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

#include "ui/display/manager/display_configurator.h"

#include <cstddef>
#include <utility>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/time/time.h"
#include "chromeos/system/devicemode.h"
#include "ui/display/display.h"
#include "ui/display/display_features.h"
#include "ui/display/display_switches.h"
#include "ui/display/manager/content_protection_manager.h"
#include "ui/display/manager/display_layout_manager.h"
#include "ui/display/manager/display_util.h"
#include "ui/display/manager/managed_display_info.h"
#include "ui/display/manager/update_display_configuration_task.h"
#include "ui/display/types/display_mode.h"
#include "ui/display/types/display_snapshot.h"
#include "ui/display/types/gamma_ramp_rgb_entry.h"
#include "ui/display/types/native_display_delegate.h"
#include "ui/display/util/display_util.h"

namespace display {

namespace {

typedef std::vector<const DisplayMode*> DisplayModeList;

struct DisplayState {
  DisplaySnapshot* display = nullptr;  // Not owned.

  // User-selected mode for the display.
  const DisplayMode* selected_mode = nullptr;

  // Mode used when displaying the same desktop on multiple displays.
  const DisplayMode* mirror_mode = nullptr;
};

// This is used for calling either SetColorMatrix() or SetGammaCorrection()
// depending on the given |color_correction_closure| which is run synchronously.
// If |reset_color_space_on_success| is true and running
// |color_correction_closure| returns true, then the color space of the display
// with |display_id| will be reset.
bool RunColorCorrectionClosureSync(
    int64_t display_id,
    const DisplayConfigurator::DisplayStateList& cached_displays,
    bool reset_color_space_on_success,
    base::OnceCallback<bool(void)> color_correction_closure) {
  for (DisplaySnapshot* display : cached_displays) {
    if (display->display_id() != display_id)
      continue;

    const bool success = std::move(color_correction_closure).Run();

    // Nullify the |display|s ColorSpace to avoid correcting colors twice, if
    // we have successfully configured something.
    if (success && reset_color_space_on_success)
      display->reset_color_space();

    return success;
  }

  return false;
}

// Returns true if a platform native |mode| is equal to a |managed_mode|.
bool AreModesEqual(const DisplayMode& mode,
                   const ManagedDisplayMode& managed_mode) {
  return mode.size() == managed_mode.size() &&
         mode.refresh_rate() == managed_mode.refresh_rate() &&
         mode.is_interlaced() == managed_mode.is_interlaced();
}

// Finds and returns a pointer to a platform native mode in the given |display|
// snapshot's modes which exactly matches the given |managed_mode|. Returns
// nullptr if nothing was found.
const DisplayMode* FindExactMatchingMode(
    const DisplaySnapshot& display,
    const ManagedDisplayMode& managed_mode) {
  if (managed_mode.native()) {
    return display.native_mode() &&
                   AreModesEqual(*display.native_mode(), managed_mode)
               ? display.native_mode()
               : nullptr;
  }

  for (const std::unique_ptr<const DisplayMode>& mode : display.modes()) {
    if (AreModesEqual(*mode, managed_mode))
      return mode.get();
  }

  return nullptr;
}

}  // namespace

const int DisplayConfigurator::kSetDisplayPowerNoFlags = 0;
const int DisplayConfigurator::kSetDisplayPowerForceProbe = 1 << 0;
const int DisplayConfigurator::kSetDisplayPowerOnlyIfSingleInternalDisplay =
    1 << 1;

bool DisplayConfigurator::TestApi::TriggerConfigureTimeout() {
  if (configurator_->configure_timer_.IsRunning()) {
    configurator_->configure_timer_.FireNow();
    return true;
  } else {
    return false;
  }
}

base::TimeDelta DisplayConfigurator::TestApi::GetConfigureDelay() const {
  return configurator_->configure_timer_.IsRunning()
             ? configurator_->configure_timer_.GetCurrentDelay()
             : base::TimeDelta();
}

////////////////////////////////////////////////////////////////////////////////
// DisplayConfigurator::DisplayLayoutManagerImpl implementation

class DisplayConfigurator::DisplayLayoutManagerImpl
    : public DisplayLayoutManager {
 public:
  explicit DisplayLayoutManagerImpl(DisplayConfigurator* configurator);
  ~DisplayLayoutManagerImpl() override;

  // DisplayLayoutManager:
  SoftwareMirroringController* GetSoftwareMirroringController() const override;
  StateController* GetStateController() const override;
  MultipleDisplayState GetDisplayState() const override;
  chromeos::DisplayPowerState GetPowerState() const override;
  bool GetDisplayLayout(
      const std::vector<DisplaySnapshot*>& displays,
      MultipleDisplayState new_display_state,
      chromeos::DisplayPowerState new_power_state,
      std::vector<DisplayConfigureRequest>* requests) const override;
  DisplayStateList GetDisplayStates() const override;
  bool IsMirroring() const override;

 private:
  // Parses the |displays| into a list of DisplayStates. This effectively adds
  // |mirror_mode| and |selected_mode| to the returned results.
  // TODO(dnicoara): Break this into GetSelectedMode() and GetMirrorMode() and
  // remove DisplayState.
  std::vector<DisplayState> ParseDisplays(
      const std::vector<DisplaySnapshot*>& displays) const;

  const DisplayMode* GetUserSelectedMode(const DisplaySnapshot& display) const;

  // Return true if all displays are on the same device.
  bool AllDisplaysOnSameDevice(
      const std::vector<DisplayState*>& displays) const;

  // Return true if all displays have display mode.
  bool AllDisplaysHaveDisplayMode(
      const std::vector<DisplayState*>& displays) const;

  // Return true if |mode| has the same aspect ratio as the native mode of
  // |display|.
  bool HasSameAspectRatioAsNativeMode(const DisplaySnapshot* display,
                                      const DisplayMode* mode) const;

  // Helper method for ParseDisplays() that initializes the passed-in displays'
  // |mirror_mode| fields by looking for a matching mode among these displays'
  // mode list. |preserve_native_aspect_ratio| limits the search only to the
  // modes having the native aspect ratio of each external display.
  bool FindExactMatchingMirrorMode(const std::vector<DisplayState*>& displays,
                                   bool preserve_native_aspect_ratio) const;

  DisplayConfigurator* configurator_;  // Not owned.

  DISALLOW_COPY_AND_ASSIGN(DisplayLayoutManagerImpl);
};

DisplayConfigurator::DisplayLayoutManagerImpl::DisplayLayoutManagerImpl(
    DisplayConfigurator* configurator)
    : configurator_(configurator) {}

DisplayConfigurator::DisplayLayoutManagerImpl::~DisplayLayoutManagerImpl() {}

DisplayConfigurator::SoftwareMirroringController*
DisplayConfigurator::DisplayLayoutManagerImpl::GetSoftwareMirroringController()
    const {
  return configurator_->mirroring_controller_;
}

DisplayConfigurator::StateController*
DisplayConfigurator::DisplayLayoutManagerImpl::GetStateController() const {
  return configurator_->state_controller_;
}

MultipleDisplayState
DisplayConfigurator::DisplayLayoutManagerImpl::GetDisplayState() const {
  return configurator_->current_display_state_;
}

chromeos::DisplayPowerState
DisplayConfigurator::DisplayLayoutManagerImpl::GetPowerState() const {
  return configurator_->current_power_state_;
}

std::vector<DisplayState>
DisplayConfigurator::DisplayLayoutManagerImpl::ParseDisplays(
    const std::vector<DisplaySnapshot*>& snapshots) const {
  std::vector<DisplayState> cached_displays;
  for (auto* snapshot : snapshots) {
    DisplayState display_state;
    display_state.display = snapshot;
    display_state.selected_mode = GetUserSelectedMode(*snapshot);
    cached_displays.push_back(display_state);
  }

  // Hardware mirroring doesn't work on desktop-linux Chrome OS's fake displays.
  // Skip mirror mode setup in that case to fall back on software mirroring.
  if (!chromeos::IsRunningAsSystemCompositor())
    return cached_displays;

  if (cached_displays.size() <= 1)
    return cached_displays;

  std::vector<DisplayState*> displays;
  int num_internal_displays = 0;
  for (auto& display : cached_displays) {
    if (display.display->type() == DISPLAY_CONNECTION_TYPE_INTERNAL)
      ++num_internal_displays;
    displays.emplace_back(&display);
  }
  CHECK_LT(num_internal_displays, 2);
  LOG_IF(WARNING, num_internal_displays >= 2)
      << "At least two internal displays detected.";

  // Hardware mirroring doesn't work among displays on different devices. In
  // this case we revert to software mirroring.
  if (!AllDisplaysOnSameDevice(displays))
    return cached_displays;

  // Hardware mirroring doesn't work for displays that do not have display
  // mode. In this case we revert to software mirroring.
  if (!AllDisplaysHaveDisplayMode(displays))
    return cached_displays;

  bool can_mirror = false;
  for (int attempt = 0; !can_mirror && attempt < 2; ++attempt) {
    // Try preserving external display's aspect ratio on the first attempt.
    // If that fails, fall back to the highest matching resolution.
    bool preserve_aspect = attempt == 0;
    can_mirror = FindExactMatchingMirrorMode(displays, preserve_aspect);
  }
  return cached_displays;
}

bool DisplayConfigurator::DisplayLayoutManagerImpl::GetDisplayLayout(
    const std::vector<DisplaySnapshot*>& displays,
    MultipleDisplayState new_display_state,
    chromeos::DisplayPowerState new_power_state,
    std::vector<DisplayConfigureRequest>* requests) const {
  std::vector<DisplayState> states = ParseDisplays(displays);
  std::vector<bool> display_power;
  int num_on_displays =
      GetDisplayPower(displays, new_power_state, &display_power);
  VLOG(1) << "EnterState: display="
          << MultipleDisplayStateToString(new_display_state)
          << " power=" << DisplayPowerStateToString(new_power_state);

  // Framebuffer dimensions.
  gfx::Size size;

  for (size_t i = 0; i < displays.size(); ++i) {
    requests->push_back(DisplayConfigureRequest(
        displays[i], displays[i]->current_mode(), gfx::Point()));
  }

  switch (new_display_state) {
    case MULTIPLE_DISPLAY_STATE_INVALID:
      NOTREACHED() << "Ignoring request to enter invalid state with "
                   << displays.size() << " connected display(s)";
      return false;
    case MULTIPLE_DISPLAY_STATE_HEADLESS:
      if (displays.size() != 0) {
        LOG(WARNING) << "Ignoring request to enter headless mode with "
                     << displays.size() << " connected display(s)";
        return false;
      }
      break;
    case MULTIPLE_DISPLAY_STATE_SINGLE: {
      // If there are multiple displays connected, only one should be turned on.
      if (displays.size() != 1 && num_on_displays != 1) {
        LOG(WARNING) << "Ignoring request to enter single mode with "
                     << displays.size() << " connected displays and "
                     << num_on_displays << " turned on";
        return false;
      }

      for (size_t i = 0; i < states.size(); ++i) {
        const DisplayState* state = &states[i];
        (*requests)[i].mode = display_power[i] ? state->selected_mode : NULL;

        if (display_power[i] || states.size() == 1) {
          const DisplayMode* mode_info = state->selected_mode;
          if (!mode_info) {
            LOG(WARNING) << "No selected mode when configuring display: "
                         << state->display->ToString();
            return false;
          }
          if (mode_info->size() == gfx::Size(1024, 768)) {
            VLOG(1) << "Potentially misdetecting display(1024x768):"
                    << " displays size=" << states.size()
                    << ", num_on_displays=" << num_on_displays
                    << ", current size:" << size.width() << "x" << size.height()
                    << ", i=" << i << ", display=" << state->display->ToString()
                    << ", display_mode=" << mode_info->ToString();
          }
          size = mode_info->size();
        }
      }
      break;
    }
    case MULTIPLE_DISPLAY_STATE_MULTI_MIRROR: {
      if (configurator_->mirroring_controller_->IsSoftwareMirroringEnforced()) {
        LOG(WARNING) << "Ignoring request to enter hardware mirror mode "
                        "because software mirroring is enforced";
        return false;
      }

      const bool can_set_mirror_mode =
          states.size() > 1 && num_on_displays != 1;
      if (!can_set_mirror_mode) {
        LOG(WARNING) << "Ignoring request to enter mirrored mode with "
                     << states.size() << " connected display(s) and "
                     << num_on_displays << " turned on";
        return false;
      }

      const DisplayMode* mode_info = states[0].mirror_mode;
      if (!mode_info) {
        LOG(WARNING) << "No mirror mode when configuring display: "
                     << states[0].display->ToString();
        return false;
      }
      size = mode_info->size();

      for (size_t i = 0; i < states.size(); ++i) {
        const DisplayState* state = &states[i];
        (*requests)[i].mode = display_power[i] ? state->mirror_mode : NULL;
      }
      break;
    }
    case MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED: {
      if (states.size() < 2) {
        LOG(WARNING) << "Ignoring request to enter extended mode with "
                     << states.size() << " connected display(s) and "
                     << num_on_displays << " turned on";
        return false;
      }

      for (size_t i = 0; i < states.size(); ++i) {
        const DisplayState* state = &states[i];
        (*requests)[i].origin.set_y(size.height() ? size.height() + kVerticalGap
                                                  : 0);
        (*requests)[i].mode = display_power[i] ? state->selected_mode : NULL;

        // Retain the full screen size even if all displays are off so the
        // same desktop configuration can be restored when the displays are
        // turned back on.
        const DisplayMode* mode_info = states[i].selected_mode;
        if (!mode_info) {
          LOG(WARNING) << "No selected mode when configuring display: "
                       << state->display->ToString();
          return false;
        }

        size.set_width(std::max<int>(size.width(), mode_info->size().width()));
        size.set_height(size.height() + (size.height() ? kVerticalGap : 0) +
                        mode_info->size().height());
      }
      break;
    }
  }
  DCHECK(new_display_state == MULTIPLE_DISPLAY_STATE_HEADLESS ||
         !size.IsEmpty());
  return true;
}

DisplayConfigurator::DisplayStateList
DisplayConfigurator::DisplayLayoutManagerImpl::GetDisplayStates() const {
  return configurator_->cached_displays();
}

bool DisplayConfigurator::DisplayLayoutManagerImpl::IsMirroring() const {
  if (GetDisplayState() == MULTIPLE_DISPLAY_STATE_MULTI_MIRROR)
    return true;

  return GetSoftwareMirroringController() &&
         GetSoftwareMirroringController()->SoftwareMirroringEnabled();
}

const DisplayMode*
DisplayConfigurator::DisplayLayoutManagerImpl::GetUserSelectedMode(
    const DisplaySnapshot& display) const {
  const DisplayMode* selected_mode = nullptr;
  auto* state_controller = GetStateController();
  if (state_controller) {
    ManagedDisplayMode mode;
    const bool mode_found = state_controller->GetSelectedModeForDisplayId(
        display.display_id(), &mode);
    if (display::features::IsListAllDisplayModesEnabled()) {
      // When selecting any arbitrary display mode is enabled, we don't try to
      // be smart about finding the best mode matching the user-selected display
      // size, rather we find an exact match to the selected display mode.
      selected_mode =
          mode_found ? FindExactMatchingMode(display, mode) : nullptr;
    } else {
      selected_mode = mode_found
                          ? FindDisplayModeMatchingSize(display, mode.size())
                          : nullptr;
    }
  }

  // Fall back to native mode.
  return selected_mode ? selected_mode : display.native_mode();
}

bool DisplayConfigurator::DisplayLayoutManagerImpl::AllDisplaysOnSameDevice(
    const std::vector<DisplayState*>& displays) const {
  DisplayState* first_display = displays.front();
  for (auto it = displays.begin() + 1; it != displays.end(); ++it) {
    if (first_display->display->sys_path() != (*it)->display->sys_path())
      return false;
  }
  return true;
}

bool DisplayConfigurator::DisplayLayoutManagerImpl::AllDisplaysHaveDisplayMode(
    const std::vector<DisplayState*>& displays) const {
  for (const auto* display : displays) {
    if (display->display->modes().empty())
      return false;
  }
  return true;
}

bool DisplayConfigurator::DisplayLayoutManagerImpl::
    HasSameAspectRatioAsNativeMode(const DisplaySnapshot* display,
                                   const DisplayMode* mode) const {
  return display->native_mode()->size().width() * mode->size().height() ==
         display->native_mode()->size().height() * mode->size().width();
}

bool DisplayConfigurator::DisplayLayoutManagerImpl::FindExactMatchingMirrorMode(
    const std::vector<DisplayState*>& displays,
    bool preserve_native_aspect_ratio) const {
  DCHECK(displays.size() > 0);

  // Put each display's display modes in |mode_lists| and sort the display modes
  // for each display by size area and refresh rate.
  std::vector<std::vector<const DisplayMode*>> mode_lists;
  for (auto* d : displays) {
    std::vector<const DisplayMode*> mode_list;
    for (auto& mode : d->display->modes()) {
      if (d->display->type() != DISPLAY_CONNECTION_TYPE_INTERNAL &&
          preserve_native_aspect_ratio &&
          !HasSameAspectRatioAsNativeMode(d->display, mode.get())) {
        // Only preserve aspect ratio for external displays.
        continue;
      }
      mode_list.emplace_back(mode.get());
    }
    std::sort(
        mode_list.begin(), mode_list.end(),
        [](const DisplayMode* const& a, const DisplayMode* const& b) -> bool {
          if (a->size().GetArea() > b->size().GetArea())
            return true;
          if (a->size().GetArea() < b->size().GetArea())
            return false;
          return a->refresh_rate() > b->refresh_rate();
        });
    mode_lists.emplace_back(mode_list);
  }

  std::vector<std::vector<const DisplayMode*>::iterator> it_list;
  for (auto& mode_list : mode_lists)
    it_list.emplace_back(mode_list.begin());

  // Find matching display modes among all displays and use them as mirror
  // mirror modes.
  for (; it_list[0] != mode_lists[0].end(); ++it_list[0]) {
    bool found = true;
    for (size_t i = 1; i < mode_lists.size(); ++i) {
      while (it_list[i] != mode_lists[i].end() &&
             (*it_list[i])->size().GetArea() >=
                 (*it_list[0])->size().GetArea()) {
        if ((*it_list[i])->size() == (*it_list[0])->size() &&
            (*it_list[i])->is_interlaced() == (*it_list[0])->is_interlaced()) {
          displays[i]->mirror_mode = *it_list[i];
          break;
        }
        ++it_list[i];
      }
      if (!displays[i]->mirror_mode) {
        found = false;
        break;
      }
    }
    if (found) {
      displays[0]->mirror_mode = *it_list[0];
      return true;
    }
    for (auto* d : displays)
      d->mirror_mode = nullptr;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
// DisplayConfigurator implementation

// static
const DisplayMode* DisplayConfigurator::FindDisplayModeMatchingSize(
    const DisplaySnapshot& display,
    const gfx::Size& size) {
  const DisplayMode* best_mode = NULL;
  for (const std::unique_ptr<const DisplayMode>& mode : display.modes()) {
    if (mode->size() != size)
      continue;

    if (mode.get() == display.native_mode()) {
      best_mode = mode.get();
      break;
    }

    if (!best_mode) {
      best_mode = mode.get();
      continue;
    }

    if (mode->is_interlaced()) {
      if (!best_mode->is_interlaced())
        continue;
    } else {
      // Reset the best rate if the non interlaced is
      // found the first time.
      if (best_mode->is_interlaced()) {
        best_mode = mode.get();
        continue;
      }
    }
    if (mode->refresh_rate() < best_mode->refresh_rate())
      continue;

    best_mode = mode.get();
  }

  return best_mode;
}

DisplayConfigurator::DisplayConfigurator()
    : state_controller_(NULL),
      mirroring_controller_(NULL),
      is_panel_fitting_enabled_(false),
      configure_display_(chromeos::IsRunningAsSystemCompositor()),
      current_display_state_(MULTIPLE_DISPLAY_STATE_INVALID),
      current_power_state_(chromeos::DISPLAY_POWER_ALL_ON),
      current_internal_display_(nullptr),
      requested_display_state_(MULTIPLE_DISPLAY_STATE_INVALID),
      pending_power_state_(chromeos::DISPLAY_POWER_ALL_ON),
      has_pending_power_state_(false),
      pending_power_flags_(kSetDisplayPowerNoFlags),
      force_configure_(false),
      display_externally_controlled_(false),
      display_control_changing_(false),
      displays_suspended_(false),
      layout_manager_(new DisplayLayoutManagerImpl(this)),
      content_protection_manager_(new ContentProtectionManager(
          layout_manager_.get(),
          base::BindRepeating(&DisplayConfigurator::configurator_disabled,
                              base::Unretained(this)))),
      has_unassociated_display_(false) {
  AddObserver(content_protection_manager_.get());
}

DisplayConfigurator::~DisplayConfigurator() {
  RemoveObserver(content_protection_manager_.get());

  if (native_display_delegate_)
    native_display_delegate_->RemoveObserver(this);

  CallAndClearInProgressCallbacks(false);
  CallAndClearQueuedCallbacks(false);
}

void DisplayConfigurator::SetDelegateForTesting(
    std::unique_ptr<NativeDisplayDelegate> display_delegate) {
  DCHECK(!native_display_delegate_);

  native_display_delegate_ = std::move(display_delegate);
  configure_display_ = true;
}

void DisplayConfigurator::SetInitialDisplayPower(
    chromeos::DisplayPowerState power_state) {
  if (requested_power_state_) {
    // A new power state has alreday been requested so ignore the initial state.
    return;
  }

  // Set the initial requested power state.
  requested_power_state_ = power_state;

  if (current_display_state_ == MULTIPLE_DISPLAY_STATE_INVALID) {
    // DisplayConfigurator::OnConfigured has not been called yet so just set
    // the current state and notify observers.
    current_power_state_ = power_state;
    NotifyPowerStateObservers();
    return;
  }

  // DisplayConfigurator::OnConfigured has been called so update the current
  // and pending states.
  UpdatePowerState(power_state);
}

void DisplayConfigurator::InitializeDisplayPowerState() {
  SetInitialDisplayPower(chromeos::DISPLAY_POWER_ALL_ON);
}

void DisplayConfigurator::Init(
    std::unique_ptr<NativeDisplayDelegate> display_delegate,
    bool is_panel_fitting_enabled) {
  is_panel_fitting_enabled_ = is_panel_fitting_enabled;
  if (configurator_disabled())
    return;

  // If the delegate is already initialized don't update it (For example, tests
  // set their own delegates).
  if (!native_display_delegate_)
    native_display_delegate_ = std::move(display_delegate);

  native_display_delegate_->AddObserver(this);

  content_protection_manager_->set_native_display_delegate(
      native_display_delegate_.get());
}

void DisplayConfigurator::TakeControl(DisplayControlCallback callback) {
  if (display_control_changing_) {
    std::move(callback).Run(false);
    return;
  }

  if (!display_externally_controlled_) {
    std::move(callback).Run(true);
    return;
  }

  display_control_changing_ = true;
  native_display_delegate_->TakeDisplayControl(
      base::BindOnce(&DisplayConfigurator::OnDisplayControlTaken,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void DisplayConfigurator::OnDisplayControlTaken(DisplayControlCallback callback,
                                                bool success) {
  display_control_changing_ = false;
  display_externally_controlled_ = !success;
  if (success) {
    // Force a configuration since the display configuration may have changed.
    force_configure_ = true;
    if (requested_power_state_) {
      // Restore the requested power state before releasing control.
      SetDisplayPower(*requested_power_state_, kSetDisplayPowerNoFlags,
                      base::DoNothing());
    }
  }

  std::move(callback).Run(success);
}

void DisplayConfigurator::RelinquishControl(DisplayControlCallback callback) {
  if (display_control_changing_) {
    std::move(callback).Run(false);
    return;
  }

  if (display_externally_controlled_) {
    std::move(callback).Run(true);
    return;
  }

  // For simplicity, just fail if in the middle of a display configuration.
  if (configuration_task_) {
    std::move(callback).Run(false);
    return;
  }

  display_control_changing_ = true;

  // Turn off the displays before releasing control since we're no longer using
  // them for output.
  SetDisplayPowerInternal(
      chromeos::DISPLAY_POWER_ALL_OFF, kSetDisplayPowerNoFlags,
      base::BindOnce(&DisplayConfigurator::SendRelinquishDisplayControl,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void DisplayConfigurator::SendRelinquishDisplayControl(
    DisplayControlCallback callback,
    bool success) {
  if (success) {
    // Set the flag early such that an incoming configuration event won't start
    // while we're releasing control of the displays.
    display_externally_controlled_ = true;
    native_display_delegate_->RelinquishDisplayControl(
        base::BindOnce(&DisplayConfigurator::OnDisplayControlRelinquished,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  } else {
    display_control_changing_ = false;
    std::move(callback).Run(false);
  }
}

void DisplayConfigurator::OnDisplayControlRelinquished(
    DisplayControlCallback callback,
    bool success) {
  display_control_changing_ = false;
  display_externally_controlled_ = success;
  if (!success) {
    force_configure_ = true;
    RunPendingConfiguration();
  }

  std::move(callback).Run(success);
}

void DisplayConfigurator::ForceInitialConfigure() {
  if (configurator_disabled())
    return;

  DCHECK(native_display_delegate_);
  native_display_delegate_->Initialize();

  // ForceInitialConfigure should be the first configuration so there shouldn't
  // be anything scheduled.
  DCHECK(!configuration_task_);

  configuration_task_ = std::make_unique<UpdateDisplayConfigurationTask>(
      native_display_delegate_.get(), layout_manager_.get(),
      requested_display_state_, GetRequestedPowerState(),
      kSetDisplayPowerForceProbe, /*force_configure=*/true,
      base::BindOnce(&DisplayConfigurator::OnConfigured,
                     weak_ptr_factory_.GetWeakPtr()));
  configuration_task_->Run();
}

bool DisplayConfigurator::SetColorMatrix(
    int64_t display_id,
    const std::vector<float>& color_matrix) {
  return RunColorCorrectionClosureSync(
      display_id, cached_displays_,
      !color_matrix.empty() /* reset_color_space_on_success */,
      base::BindOnce(&NativeDisplayDelegate::SetColorMatrix,
                     base::Unretained(native_display_delegate_.get()),
                     display_id, color_matrix));
}

bool DisplayConfigurator::SetGammaCorrection(
    int64_t display_id,
    const std::vector<GammaRampRGBEntry>& degamma_lut,
    const std::vector<GammaRampRGBEntry>& gamma_lut) {
  const bool reset_color_space_on_success =
      !degamma_lut.empty() || !gamma_lut.empty();
  return RunColorCorrectionClosureSync(
      display_id, cached_displays_, reset_color_space_on_success,
      base::BindOnce(&NativeDisplayDelegate::SetGammaCorrection,
                     base::Unretained(native_display_delegate_.get()),
                     display_id, degamma_lut, gamma_lut));
}

bool DisplayConfigurator::IsPrivacyScreenSupportedOnInternalDisplay() const {
  return current_internal_display_ &&
         current_internal_display_->privacy_screen_state() != kNotSupported;
}

bool DisplayConfigurator::SetPrivacyScreenOnInternalDisplay(bool enabled) {
  if (!current_internal_display_) {
    LOG(ERROR) << "This device does not have an internal display.";
    return false;
  }

  if (!IsPrivacyScreenSupportedOnInternalDisplay()) {
    LOG(ERROR) << "The internal display of this device does not support "
                  "privacy screeny.";
    return false;
  }

  native_display_delegate_->SetPrivacyScreen(
      current_internal_display_->display_id(), enabled);
  return true;
}

chromeos::DisplayPowerState DisplayConfigurator::GetRequestedPowerState()
    const {
  return requested_power_state_.value_or(chromeos::DISPLAY_POWER_ALL_ON);
}

void DisplayConfigurator::UpdateInternalDisplayCache() {
  for (DisplaySnapshot* display : cached_displays_) {
    if (display->type() == DISPLAY_CONNECTION_TYPE_INTERNAL) {
      current_internal_display_ = display;
      return;
    }
  }
  current_internal_display_ = nullptr;
}

void DisplayConfigurator::PrepareForExit() {
  configure_display_ = false;
}

void DisplayConfigurator::SetDisplayPowerInternal(
    chromeos::DisplayPowerState power_state,
    int flags,
    ConfigurationCallback callback) {
  // Only skip if the current power state is the same and the latest requested
  // power state is the same. If |pending_power_state_ != current_power_state_|
  // then there is a current task pending or the last configuration failed. In
  // either case request a new configuration to make sure the state is
  // consistent with the expectations.
  if (power_state == current_power_state_ &&
      power_state == pending_power_state_ &&
      !(flags & kSetDisplayPowerForceProbe)) {
    std::move(callback).Run(true);
    return;
  }

  pending_power_state_ = power_state;
  has_pending_power_state_ = true;
  pending_power_flags_ = flags;
  queued_configuration_callbacks_.push_back(std::move(callback));

  if (configure_timer_.IsRunning()) {
    // If there is a configuration task scheduled, avoid performing
    // configuration immediately. Instead reset the timer to wait for things to
    // settle.
    configure_timer_.Reset();
    return;
  }

  RunPendingConfiguration();
}

void DisplayConfigurator::SetDisplayPower(
    chromeos::DisplayPowerState power_state,
    int flags,
    ConfigurationCallback callback) {
  if (configurator_disabled()) {
    std::move(callback).Run(false);
    return;
  }

  VLOG(1) << "SetDisplayPower: power_state="
          << DisplayPowerStateToString(power_state) << " flags=" << flags
          << ", configure timer="
          << (configure_timer_.IsRunning() ? "Running" : "Stopped");

  requested_power_state_ = power_state;
  SetDisplayPowerInternal(*requested_power_state_, flags, std::move(callback));
}

void DisplayConfigurator::SetDisplayMode(MultipleDisplayState new_state) {
  if (configurator_disabled())
    return;

  VLOG(1) << "SetDisplayMode: state="
          << MultipleDisplayStateToString(new_state);
  if (current_display_state_ == new_state) {
    // Cancel software mirroring if the state is moving from
    // MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED to
    // MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED.
    if (mirroring_controller_ &&
        new_state == MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED)
      mirroring_controller_->SetSoftwareMirroring(false);
    NotifyDisplayStateObservers(true, new_state);
    return;
  }

  requested_display_state_ = new_state;

  RunPendingConfiguration();
}

void DisplayConfigurator::OnConfigurationChanged() {
  // Don't do anything if the displays are currently suspended.  Instead we will
  // probe and reconfigure the displays if necessary in ResumeDisplays().
  if (displays_suspended_) {
    VLOG(1) << "Displays are currently suspended.  Not attempting to "
            << "reconfigure them.";
    return;
  }

  // Configure displays with |kConfigureDelayMs| delay,
  // so that time-consuming ConfigureDisplays() won't be called multiple times.
  configure_timer_.Start(FROM_HERE,
                         base::TimeDelta::FromMilliseconds(kConfigureDelayMs),
                         this, &DisplayConfigurator::ConfigureDisplays);
}

void DisplayConfigurator::OnDisplaySnapshotsInvalidated() {
  VLOG(1) << "Display snapshots invalidated.";
  cached_displays_.clear();
}

void DisplayConfigurator::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void DisplayConfigurator::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void DisplayConfigurator::SuspendDisplays(ConfigurationCallback callback) {
  if (configurator_disabled()) {
    std::move(callback).Run(false);
    return;
  }

  displays_suspended_ = true;

  // Stop |configure_timer_| because we will force probe and configure all the
  // displays at resume time anyway.
  configure_timer_.Stop();

  // Turn off the displays for suspend. This way, if we wake up for lucid sleep,
  // the displays will not turn on (all displays should be off for lucid sleep
  // unless explicitly requested by lucid sleep code). Use
  // SetDisplayPowerInternal so requested_power_state_ is maintained.
  SetDisplayPowerInternal(chromeos::DISPLAY_POWER_ALL_OFF,
                          kSetDisplayPowerNoFlags, std::move(callback));
}

void DisplayConfigurator::ResumeDisplays() {
  if (configurator_disabled())
    return;

  displays_suspended_ = false;

  if (current_display_state_ == MULTIPLE_DISPLAY_STATE_MULTI_MIRROR ||
      current_display_state_ == MULTIPLE_DISPLAY_STATE_MULTI_EXTENDED) {
    // When waking up from suspend while being in a multi display mode, we
    // schedule a delayed forced configuration, which will make
    // SetDisplayPowerInternal() avoid performing the configuration immediately.
    // This gives a chance to wait for all displays to be added and detected
    // before configuration is performed, so we won't immediately resize the
    // desktops and the windows on it to fit on a single display.
    configure_timer_.Start(
        FROM_HERE,
        base::TimeDelta::FromMilliseconds(kResumeConfigureMultiDisplayDelayMs),
        this, &DisplayConfigurator::ConfigureDisplays);
  }

  // TODO(crbug.com/794831): Solve the issue of mirror mode on display resume.

  // If requested_power_state_ is ALL_OFF due to idle suspend, powerd will turn
  // the display power on when it enables the backlight.
  if (requested_power_state_) {
    SetDisplayPower(*requested_power_state_, kSetDisplayPowerNoFlags,
                    base::DoNothing());
  }
}

void DisplayConfigurator::ConfigureDisplays() {
  if (configurator_disabled())
    return;

  force_configure_ = true;
  RunPendingConfiguration();
}

void DisplayConfigurator::RunPendingConfiguration() {
  // Configuration task is currently running. Do not start a second
  // configuration.
  if (configuration_task_)
    return;

  if (!ShouldRunConfigurationTask()) {
    LOG(ERROR) << "Called RunPendingConfiguration without any changes"
                  " requested";
    CallAndClearQueuedCallbacks(true);
    return;
  }

  configuration_task_ = std::make_unique<UpdateDisplayConfigurationTask>(
      native_display_delegate_.get(), layout_manager_.get(),
      requested_display_state_, pending_power_state_, pending_power_flags_,
      force_configure_,
      base::BindOnce(&DisplayConfigurator::OnConfigured,
                     weak_ptr_factory_.GetWeakPtr()));

  // Reset the flags before running the task; otherwise it may end up scheduling
  // another configuration.
  force_configure_ = false;
  pending_power_flags_ = kSetDisplayPowerNoFlags;
  has_pending_power_state_ = false;
  requested_display_state_ = MULTIPLE_DISPLAY_STATE_INVALID;

  DCHECK(in_progress_configuration_callbacks_.empty());
  in_progress_configuration_callbacks_.swap(queued_configuration_callbacks_);

  configuration_task_->Run();
}

void DisplayConfigurator::OnConfigured(
    bool success,
    const std::vector<DisplaySnapshot*>& displays,
    const std::vector<DisplaySnapshot*>& unassociated_displays,
    MultipleDisplayState new_display_state,
    chromeos::DisplayPowerState new_power_state) {
  VLOG(1) << "OnConfigured: success=" << success << " new_display_state="
          << MultipleDisplayStateToString(new_display_state)
          << " new_power_state=" << DisplayPowerStateToString(new_power_state);

  cached_displays_ = displays;
  has_unassociated_display_ = unassociated_displays.size();

  if (success) {
    current_display_state_ = new_display_state;
    UpdatePowerState(new_power_state);
    UpdateInternalDisplayCache();
  } else {
    current_internal_display_ = nullptr;
  }

  configuration_task_.reset();
  NotifyDisplayStateObservers(success, new_display_state);
  CallAndClearInProgressCallbacks(success);

  if (success && !configure_timer_.IsRunning() &&
      ShouldRunConfigurationTask()) {
    configure_timer_.Start(FROM_HERE,
                           base::TimeDelta::FromMilliseconds(kConfigureDelayMs),
                           this, &DisplayConfigurator::RunPendingConfiguration);
  } else {
    // If a new configuration task isn't scheduled respond to all queued
    // callbacks (for example if requested state is current state).
    if (!configure_timer_.IsRunning())
      CallAndClearQueuedCallbacks(success);
  }
}

void DisplayConfigurator::UpdatePowerState(
    chromeos::DisplayPowerState new_power_state) {
  chromeos::DisplayPowerState old_power_state = current_power_state_;
  current_power_state_ = new_power_state;

  // Don't notify observers of |current_power_state_| when there is a pending
  // power state. Notifying the observers may confuse them because they may
  // already know the up-to-date state via PowerManagerClient. Please refer to
  // b/134459602 for details.
  if (has_pending_power_state_)
    return;

  // If the pending power state hasn't changed then make sure that value gets
  // updated as well since the last requested value may have been dependent on
  // certain conditions (ie: if only the internal monitor was present).
  pending_power_state_ = new_power_state;
  if (old_power_state != current_power_state_)
    NotifyPowerStateObservers();
}

bool DisplayConfigurator::ShouldRunConfigurationTask() const {
  if (force_configure_)
    return true;

  // Schedule if there is a request to change the display state.
  if (requested_display_state_ != current_display_state_ &&
      requested_display_state_ != MULTIPLE_DISPLAY_STATE_INVALID)
    return true;

  // Schedule if there is a request to change the power state.
  if (has_pending_power_state_)
    return true;

  return false;
}

void DisplayConfigurator::CallAndClearInProgressCallbacks(bool success) {
  for (auto& callback : in_progress_configuration_callbacks_)
    std::move(callback).Run(success);

  in_progress_configuration_callbacks_.clear();
}

void DisplayConfigurator::CallAndClearQueuedCallbacks(bool success) {
  for (auto& callback : queued_configuration_callbacks_)
    std::move(callback).Run(success);

  queued_configuration_callbacks_.clear();
}

void DisplayConfigurator::NotifyDisplayStateObservers(
    bool success,
    MultipleDisplayState attempted_state) {
  if (success) {
    for (Observer& observer : observers_)
      observer.OnDisplayModeChanged(cached_displays_);
  } else {
    for (Observer& observer : observers_)
      observer.OnDisplayModeChangeFailed(cached_displays_, attempted_state);
  }
}

void DisplayConfigurator::NotifyPowerStateObservers() {
  for (Observer& observer : observers_)
    observer.OnPowerStateChanged(current_power_state_);
}

bool DisplayConfigurator::IsDisplayOn() const {
  return current_power_state_ != chromeos::DISPLAY_POWER_ALL_OFF;
}

}  // namespace display


text:
using UnityEngine;
using System.Collections;
using System.Reflection;

namespace NewtonVR
{
    public class NVRHelpers
    {
        private static Shader standardShader;
        private static Shader StandardShader
        {
            get
            {
                if (standardShader == null)
                {
                    standardShader = Shader.Find("Standard");
                }
                return standardShader;
            }
        }

        public static void SetTransparent(Material material, Color? newcolor = null)
        {
            if (material.shader != StandardShader)
                Debug.LogWarning("Trying to set transparent mode on non-standard shader. Please use the Standard Shader instead or modify this method.");

            material.SetOverrideTag("RenderType", "Transparent");
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            material.SetInt("_ZWrite", 0);
            material.DisableKeyword("_ALPHATEST_ON");
            material.DisableKeyword("_ALPHABLEND_ON");
            material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
            material.SetFloat("_Metallic", 0f);
            material.SetFloat("_Glossiness", 0f);
            material.renderQueue = 3000;
            material.mainTexture = null;

            if (newcolor != null)
            {
                material.color = newcolor.Value;
            }
        }

        public static void SetOpaque(Material material)
        {
            if (material.shader != StandardShader)
                Debug.LogWarning("Trying to set opaque mode on non-standard shader. Please use the Standard Shader instead or modify this method.");

            material.SetOverrideTag("RenderType", "");
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
            material.SetInt("_ZWrite", 1);
            material.DisableKeyword("_ALPHATEST_ON");
            material.DisableKeyword("_ALPHABLEND_ON");
            material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            material.renderQueue = -1;
        }

        public static void SetProperty(object obj, string propertyName, object value, bool isPublic)
        {
            BindingFlags flags = BindingFlags.Instance;
            if (isPublic)
                flags = flags | BindingFlags.Public;
            else
                flags = flags | BindingFlags.NonPublic;

            PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName, flags);
            propertyInfo.SetValue(obj, value, null);
        }

        public static void SetField(object obj, string fieldName, object value, bool isPublic)
        {
            BindingFlags flags = BindingFlags.Instance;
            if (isPublic)
                flags = flags | BindingFlags.Public;
            else
                flags = flags | BindingFlags.NonPublic;

            FieldInfo fieldInfo = obj.GetType().GetField(fieldName, flags);
            fieldInfo.SetValue(obj, value);
        }

        public static void LineRendererSetColor(LineRenderer lineRenderer, Color startColor, Color endColor)
        {
            #if UNITY_5_5_OR_NEWER
            lineRenderer.startColor = startColor;
            lineRenderer.endColor = endColor;
            #else
            lineRenderer.SetColors(startColor, endColor);
            #endif
        }

        public static void LineRendererSetWidth(LineRenderer lineRenderer, float startWidth, float endWidth)
        {
            #if UNITY_5_5_OR_NEWER
            lineRenderer.startWidth = startWidth;
            lineRenderer.endWidth = endWidth;
            #else
            lineRenderer.SetWidth(startWidth, endWidth);
            #endif
        }

        //Get an average (mean) from more than two quaternions (with two, slerp would be used).
        //Note: this only works if all the quaternions are relatively close together.
        //Usage:
        //-Cumulative is an external Vector4 which holds all the added x y z and w components.
        //-newRotation is the next rotation to be added to the average pool
        //-firstRotation is the first quaternion of the array to be averaged
        //-addAmount holds the total amount of quaternions which are currently added
        //This function returns the current average quaternion
        public static Quaternion AverageQuaternion(ref Vector4 cumulative, Quaternion newRotation, Quaternion firstRotation, int addAmount)
        {
            float w = 0.0f;
            float x = 0.0f;
            float y = 0.0f;
            float z = 0.0f;

            //Before we add the new rotation to the average (mean), we have to check whether the quaternion has to be inverted. Because
            //q and -q are the same rotation, but cannot be averaged, we have to make sure they are all the same.
            if (!AreQuaternionsClose(newRotation, firstRotation))
            {

                newRotation = InverseSignQuaternion(newRotation);
            }

            //Average the values
            float addDet = 1f / (float)addAmount;
            cumulative.w += newRotation.w;
            w = cumulative.w * addDet;
            cumulative.x += newRotation.x;
            x = cumulative.x * addDet;
            cumulative.y += newRotation.y;
            y = cumulative.y * addDet;
            cumulative.z += newRotation.z;
            z = cumulative.z * addDet;

            //note: if speed is an issue, you can skip the normalization step
            return NormalizeQuaternion(x, y, z, w);
        }

        public static Quaternion NormalizeQuaternion(float x, float y, float z, float w)
        {
            float lengthD = 1.0f / (w * w + x * x + y * y + z * z);
            w *= lengthD;
            x *= lengthD;
            y *= lengthD;
            z *= lengthD;

            return new Quaternion(x, y, z, w);
        }

        //Changes the sign of the quaternion components. This is not the same as the inverse.
        public static Quaternion InverseSignQuaternion(Quaternion q)
        {
            return new Quaternion(-q.x, -q.y, -q.z, -q.w);
        }

        //Returns true if the two input quaternions are close to each other. This can
        //be used to check whether or not one of two quaternions which are supposed to
        //be very similar but has its component signs reversed (q has the same rotation as
        //-q)
        public static bool AreQuaternionsClose(Quaternion q1, Quaternion q2)
        {
            float dot = Quaternion.Dot(q1, q2);

            if (dot < 0.0f)
            {
                return false;
            }

            else
            {
                return true;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'mail/fields/common_address_field'

module Mail
  # = Reply-To Field
  #
  # The Reply-To field inherits reply-to StructuredField and handles the Reply-To: header
  # field in the email.
  #
  # Sending reply_to to a mail message will instantiate a Mail::Field object that
  # has a ReplyToField as its field type.  This includes all Mail::CommonAddress
  # module instance metods.
  #
  # Only one Reply-To field can appear in a header, though it can have multiple
  # addresses and groups of addresses.
  #
  # == Examples:
  #
  #  mail = Mail.new
  #  mail.reply_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
  #  mail.reply_to    #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
  #  mail[:reply_to]  #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
  #  mail['reply-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
  #  mail['Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
  #
  #  mail[:reply_to].encoded   #=> 'Reply-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
  #  mail[:reply_to].decoded   #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
  #  mail[:reply_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
  #  mail[:reply_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
  class ReplyToField < CommonAddressField #:nodoc:
    NAME = 'Reply-To'
  end
end


text:
import App from "../app";
import {pubsub} from "../helpers/subscriptionManager";
import uuid from "uuid";

function performAction(id, action) {
  const sys = App.systems.find(s => s.id === id);
  if (sys) {
    action(sys);
  }
  pubsub.publish(
    "thxUpdate",
    App.systems.filter(s => s.class === "Thx"),
  );
}

App.on("chargeThx", ({id, clientId, charge}) => {
  performAction(id, sys => sys.chargeClient(clientId, charge));
});

App.on("lockThx", ({id, clientId}) => {
  performAction(id, sys => sys.lockClient(clientId));
  // Also black out the client.
  // const client = App.clients.find(c => c.id === clientId);
  // client.setOfflineState("blackout");
  // pubsub.publish("clientChanged", App.clients);
});

App.on("activateThx", ({id}) => {
  performAction(id, sys => {
    sys.activate();
    pubsub.publish("notify", {
      id: uuid.v4(),
      simulatorId: sys.simulatorId,
      type: "THX",
      station: "Core",
      title: `${sys.name} Activated`,
      body: "",
      color: "info",
    });
    App.handleEvent(
      {
        simulatorId: sys.simulatorId,
        title: `${sys.name} Activated`,
        component: "ThxCore",
        body: null,
        color: "info",
      },
      "addCoreFeed",
    );
  });
});

App.on("deactivateThx", ({id}) => {
  performAction(id, sys => {
    sys.deactivate();
    pubsub.publish("notify", {
      id: uuid.v4(),
      simulatorId: sys.simulatorId,
      type: "THX",
      station: "Core",
      title: `${sys.name} Deactivated`,
      body: "",
      color: "info",
    });
    App.handleEvent(
      {
        simulatorId: sys.simulatorId,
        title: `${sys.name} Deactivated`,
        component: "ThxCore",
        body: null,
        color: "info",
      },
      "addCoreFeed",
    );
  });
});

App.on("resetThx", ({id}) => {
  performAction(id, sys => sys.reset());
});


text:
<?php

namespace Madeyski\EpuapBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MadeyskiEpuapBundle extends Bundle
{

}


text:
var Cheerio   = require('cheerio'),
    JsonFile  = require('jsonfile'),
    UrlUtil   = require('./url'),
    Puid      = require('puid');

function HtmlParser(postData) {
  this.postData = postData;
  this._linkSchema = JsonFile.readFileSync(__dirname+'/../data/linkSchema.json');
  this.$ = Cheerio.load(postData.content);
}

module.exports = HtmlParser;

HtmlParser.prototype.getLinkSchemaTemplate = function() {
  return JSON.parse(JSON.stringify(this._linkSchema));
};

HtmlParser.prototype.processTag = function(querySelector, linkType, urlSelectorCb, labelSelectorCB) {
  var linkContainer = Array(),
      puid = new Puid(),
      _this = this;

  this.$(querySelector).each(function() {
    var elementUrl,
        linkSchema;

    elementUrl = UrlUtil.process(urlSelectorCb(this));

    if (!elementUrl) return;

    linkSchema = _this.getLinkSchemaTemplate();
    linkSchema.id = puid.generate();
    linkSchema.url = elementUrl;
    linkSchema.link.type = linkType;
    linkSchema.link.label = labelSelectorCB(this);
    linkSchema.source.title = _this.postData.title;
    linkSchema.source.file = _this.postData.source;

    linkContainer.push(linkSchema);
  });

  return linkContainer;
};

HtmlParser.prototype.processATags = function() {
  var $ = this.$;

  return this.processTag('a', 'Text', function(elem) {
    return $(elem).attr('href');
  }, function(elem) {
    return $(elem).text();
  });
};

HtmlParser.prototype.processImgTags = function() {
  var $ = this.$;

  return this.processTag('img', 'Image', function(elem) {
    return $(elem).attr('src');
  }, function(elem) {
    var alt,
        title,
        returnStr;

    alt = $(elem).attr('alt');
    title = $(elem).attr('title');

    returnStr = alt || title || '';

    return returnStr;
  });
};

HtmlParser.prototype.processYouTube = function() {
  var $ = this.$;

  return this.processTag('iframe[src*="youtube.com"]', 'YouTube', function(elem) {
    return $(elem).attr('src');
  }, function(elem) {
    return 'YouTube Video';
  });
};


text:
namespace DigitalRune.Windows.TextEditor.Document
{
  /// <summary>
  /// This interface is used to describe a segment (span) inside a text sequence.
  /// </summary>
  public interface ISegment
  {
    /// <summary>
    /// Gets or sets the offset.
    /// </summary>
    /// <value>The offset where the span begins</value>
    int Offset
    {
      get;
      set;
    }

    /// <summary>
    /// Gets or sets the length.
    /// </summary>
    /// <value>The length of the span</value>
    int Length
    {
      get;
      set;
    }
  }
}


text:
log( "PoNG-List", "load module");

// This uses heavily pong-table.js functions!!

function pongListDivHTML( divId, resourceURL, params ) {
	log( "PoNG-List",  "divId="+divId+" resourceURL="+resourceURL );
	pongTableInit( divId, "PongList"  );

	if ( moduleConfig[ divId ] != null ) {
		renderPongListDivHTML( divId, resourceURL, params, moduleConfig[ divId ] );
	} else {

		$.getJSON(
			resourceURL+"/pong-list",
			function( tbl ) {
				renderPongListDivHTML( divId, resourceURL, params, tbl );
			}
		);
	}
}

function renderPongListDivHTML( divId, resourceURL, params, tbl ) {
	log( "PoNG-List", "create HTML" );

	var dataUrl = resourceURL;
	if ( tbl.dataURL != null ) {
		dataUrl = dataUrl+"/"+tbl.dataURL;
	}
	poTbl[ divId ].pongTableDef = tbl;
	poTbl[ divId ].resourceURL = resourceURL;
	poTbl[ divId ].pongTableDef.dataUrlFull = dataUrl;
	poTbl[ divId ].sortCol = '';
	poTbl[ divId ].pongTableDef.cols = tbl.divs;

	poTbl[ divId ].pongTableEndRow = tbl.maxRows;
	var contentItems = [];

	// create form, if required:
	contentItems = pongTableRenderFilterHTML( divId, resourceURL, params, tbl );

	contentItems.push( '
' );
	// cread table head
  if ( tbl.maxRows ) {
  	for ( var r = 0; r < tbl.maxRows; r ++ ) {
  	  log( "PoNG-List", 'row '+r );
  		contentItems.push( '
' );
  		renderPongListDivHTMLsub( contentItems, divId, tbl.divs, r, '' );
  		contentItems.push( "
" );
  	}
  	contentItems.push( "
" );
  }

	// paginator buttons:
  var paginatorJS = [];
  if ( tbl.maxRows ) {
    paginatorJS = pongTableGenPaginator( divId, tbl, 'pongListCells' );
  }

	// AJAX functions:
	var ajacCommitsJS = pongTableAjaxCommits( divId, resourceURL, params, tbl );

	// create HTML
	$( "#"+divId ).html( contentItems.join( "\n" ) );
	$( "#"+divId ).append( paginatorJS.join("\n") );
	$( "#"+divId ).append( ajacCommitsJS.join("\n") );

  var tHeight = $( "#"+divId ).height();
	if ( $( '#'+divId+'SrchFrmDiv' ).height() ) {
		tHeight -= $( '#'+divId+'SrchFrmDiv' ).height();
	}
	if ( $( '#'+divId+'Pagin' ).height() ) {
		tHeight -= $( '#'+divId+'Pagin' ).height();
	}
	//alert( $( "#"+divId ).height() +' - '+ $( '#'+divId+'SrchFrmDiv' ).height() );
	$( "#"+divId+'PongList' ).height( tHeight );

	// if there is no paginator:
  if ( ! tbl.maxRows ) {
    $( '#'+divId+'PongList' ).css( 'overflow', 'auto' );
  }

	if ( params != null  && params.filter != null ) {
		for ( var i = 0; i < params.filter.length; i++ ) {
			if ( i == 0 ) {
				dataUrl += "?"+params.filter[i].field+'='+params.filter[i].value;
			} else {
				dataUrl += "&"+params.filter[i].field+'='+params.filter[i].value;
			}
		}
	}
  if ( tbl.pollDataSec ) {
    var t = parseInt( tbl.pollDataSec );
    if  ( ! isNaN( t ) ) {
      poTbl[ divId ].polling = true;
      var pollHTML = [];
      pollHTML.push( '' );
      $( "#"+divId ).append( pollHTML.join("\n") );
      log( "PoNG-List", ">>>>> create pongTableUpdateTimer t="+t );
      poolDataTimerId = setInterval( "pongListUpdateTimer"+divId+"()", t*1000 );
      log( "PoNG-List", ">>>>> startet pongTableUpdateTimer"+divId+"()" );

//      // toggle pulling action button
//      var html = "";
//      html += '<button id="'+divId+'TableBt">'+$.i18n( 'Start/stop reload' )+'</button>';
//      html += '';
//      $( "#"+divId+"ActionBtn" ).html( html );

    } //else alert( "no parseInt tbl.pollDataSec" );
  } //else alert( "no tbl.pollDataSec" );

	pongListUpdateData( divId, params.get );

}

/** update data call back hook */
function pongListUpdateData( divId, paramsObj ) {
  log( "PoNG-List",  'update '+divId );
  var tblDef = poTbl[ divId ].pongTableDef;

  if ( poTbl[ divId ].resourceURL != '-' ) {

    $.getJSON( tblDef.dataUrlFull, paramsObj ,
      function( data ) {
        log( "PoNG-List",  JSON.stringify( data ) );
        var subdata = getSubData( data, tblDef.dataDocSubPath );
        pongListSetData( divId, subdata );
        publishEvent( 'feedback', {'text':'List data loaded sucessfully'} )
      }
    ).fail(
        function() { publishEvent( 'feedback', {'text':'List service offline? Config OK?'} ) }
    );

  }
}

/** hook and used by update hook */
function pongListSetData( divId, data, dataDocSubPath ) {
  log( "PoNG-List",  'set data hook: '+divId+ " "+dataDocSubPath );
  if ( dataDocSubPath != null ) {
    poTbl[ divId ].pongTableData = getSubData( data, tblDef.dataDocSubPath );
  } else {
    //log( "Pong-Table", "set: "+JSON.stringify( data )  )
    poTbl[ divId ].pongTableData = data;
  }
  pongListCells( divId );

  pongTableResize( divId );

  if ( poTbl[ divId ].setData ) {
    if ( poTbl[ divId ].setData.setData ) {
      var setDta =  poTbl[ divId ].setData.setData
      for ( var i = 0; i < setDta.length; i++ ) {
        //alert( setDta[i].resId )
        setModuleData( setDta[i].resId+'Content', poTbl[ divId ].pongTableData, null );
      }
    }
  }
}

/** render table cells */
function pongListCells( divId ) {
  var dtaArr = poTbl[ divId ].pongTableData;
  var rowSt  = 0;
  var rowEn  = dtaArr.length;
  var i = 0;

  if ( poTbl[ divId ].sortCol != '' ) {
    pongTable_sc      = poTbl[ divId ].sortCol;
    pongTable_sort_up = poTbl[ divId ].sortUp;
    //alert( "Sort "+poTbl[ divId ].sortCol );
    dtaArr.sort( pongTableCmpFields );
  }

  // if pagination is required, by a maxRow defintion:
  if ( poTbl[ divId ].pongTableDef.maxRows ) {
    rowSt = parseInt( poTbl[ divId ].pongTableStartRow );
    rowEn = parseInt( poTbl[ divId ].pongTableEndRow );
    log( "PoNG-List", "update paginator label" );
    var rPP = parseInt( poTbl[ divId ].pongTableDef.maxRows );
    var maxP = Math.ceil( dtaArr.length / rPP );
    var curP = Math.round( rowEn / rPP );
    $( "#"+divId+'PaginLbl' ).html( $.i18n( "page" )+" "+curP+"/"+maxP+ " ("+dtaArr.length+" "+$.i18n("rows")+")" );
  } else {
    // need to create empty table rows and cells
    // del all rows, except 1st
    $( '#'+divId+'PongList' ).find( ".pongListRow" ).remove();

    var contentItems = [];
    for ( var r = 0; r < rowEn; r ++ ) {
      var tbl = poTbl[ divId ].pongTableDef;
      log( "PoNG-List", 'row '+r );
      contentItems.push( '
' );
      // Render empty data cells as nested structure:
      // >>>>>>>>>>>>>>>>>>
      renderPongListDivHTMLsub( contentItems, divId, tbl.divs, r, '' );
      // <<<<<<<<<<<<<<<<<< moved to pong-table.js
      contentItems.push( "
" );

    }
    $( '#'+divId+'PongList' ).append( contentItems.join( '\n' ) );
  }

  log( "PoNG-List", "tblCells: divId="+divId+"Data #"+poTbl[ divId ].pongTableData.length + " rowSt="+rowSt + " rowEn="+rowEn );

  // fill empty cells with data:
  log( "PoNG-List", "row loop" );
  var i = 0;
  $( ".pongListValCell" ).html( ' ' );
  for ( var r = rowSt; r < rowEn; r++ ) {
    log( "PoNG-List", "row loop" );
    if ( r < dtaArr.length ) {
      log( "PoNG-List", "row "+r );
      var rowDta = dtaArr[r];
      // >>>>>>>>>>>>>>>>>>>>
      // pongListUpdateRow() is moved to pong-table.js
      pongListUpdateRow( divId, poTbl[ divId ].pongTableDef.divs, rowDta, r, '', i, divId );
      // <<<<<<<<<<<<<<<<<<<<
    }
    i++;
  }
}


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

namespace TwitchLib.Exceptions.API.UploadVideo.UploadVideoPart
{
    /// Thrown when Twitch reports a failure of the upload.
    public class UploadFailedException : Exception
    {
        /// Exception constructor
        public UploadFailedException(string apiData)
            : base(apiData)
        {
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
PreparedStatementSetter (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.springframework.jdbc.core

Interface PreparedStatementSetter

public interface PreparedStatementSetter

General callback interface used by the JdbcTemplate class.

This interface sets values on a PreparedStatement provided
 by the JdbcTemplate class, for each of a number of updates in a batch using the
 same SQL. Implementations are responsible for setting any necessary parameters.
 SQL with placeholders will already have been supplied.

It's easier to use this interface than PreparedStatementCreator:
 The JdbcTemplate will create the PreparedStatement, with the callback
 only being responsible for setting parameter values.

Implementations do not need to concern themselves with
 SQLExceptions that may be thrown from operations they attempt.
 The JdbcTemplate class will catch and handle SQLExceptions appropriately.

Since:

March 2, 2003

Author:

Rod Johnson

See Also:
JdbcTemplate.update(String, PreparedStatementSetter),
JdbcTemplate.query(String, PreparedStatementSetter, ResultSetExtractor)

Method Summary

 void
setValues(PreparedStatement ps)

          Set parameter values on the given PreparedStatement.

Method Detail

setValues

void setValues(PreparedStatement ps)
               throws SQLException

Set parameter values on the given PreparedStatement.

Parameters:
ps - the PreparedStatement to invoke setter methods on

Throws:

SQLException - if a SQLException is encountered
 (i.e. there is no need to catch SQLException)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2002-2007 The Spring Framework.


text:
require 'json'
require 'json-schema'

module FlipTheSwitch
  module Reader
    class Features
      def initialize(input, environment)
        @input = input
        @environment = environment
      end

      def features
        raise Error::InvalidFile.new(input_file) unless valid_file?
        raise Error::InvalidEnvironment.new(environment) unless environments_by_name.has_key?(environment)
        inherited_environment(environment).features
      end

      private
      attr_reader :input, :environment

      INHERITS_KEY = 'inherits_from'
      ENABLED_KEY = 'enabled'
      DESCRIPTION_KEY = 'description'

      def inherited_environment(env_name)
        inherited_env = environments_by_name[env_name]
        if inherited_env.has_parent?
          merge_environments(inherited_env, inherited_environment(inherited_env.parent_name))
        else
          inherited_env
        end
      end

      def merge_environments(overriding_env, parent_env)
        Environment.new(
          overriding_env.name,
          merge_features(parent_env.features, overriding_env.features),
          overriding_env.parent_name
        )
      end

      def merge_features(parent_features, overriding_features)
        parent_features.inject([]) { |merged_features, parent_feature|
          overriding_feature = overriding_features.detect { |feature| feature.name == parent_feature.name }
          if overriding_feature
            merged_features.push(merge_feature(parent_feature, overriding_feature))
          else
            merged_features.push(parent_feature)
          end
        }
      end

      def merge_feature(parent_feature, child_feature)
        Feature.new(parent_feature.name,
          (child_feature.enabled != nil) ? child_feature.enabled : parent_feature.enabled,
          child_feature.description ? child_feature.description : parent_feature.description,
          sub_features(child_feature, parent_feature),
          child_feature.parent_name
        )
      end

      def sub_features(child_feature, parent_feature)
        if !child_feature.sub_features.empty?
          merge_sub_features(parent_feature.sub_features, child_feature.sub_features)
        else
          parent_feature.sub_features
        end
      end

      def merge_sub_features(parent_feature_sub_features, child_feature_sub_features)
        child_feature_sub_features.inject([]) { |merged_sub_features, child_sub_feature|
          merged_sub_features.push(merge_feature(related_parents_sub_feature(parent_feature_sub_features, child_sub_feature.name), child_sub_feature))
        }
      end

      def related_parents_sub_feature(parent_feature_sub_features, sub_feature_name)
        parent_feature_sub_features.detect { |parent_sub_feature|
          parent_sub_feature.name == sub_feature_name
        }
      end

      def environments_by_name
        parse.inject({}) { |hash, env|
          hash[env.name] = env
          hash
        }
      end

      def parse
        @parse ||= json.map { |env_name, env_info|
          parse_environment(env_name, env_info)
        }
      end

      def parse_environment(name, info)
        Environment.new(name, parse_environment_features(info), info[INHERITS_KEY])
      end

      def parse_environment_features(info)
        info.select { |key, _|
          key != INHERITS_KEY
        }.map { |feature_name, feature_info|
          parse_feature(feature_name, feature_info, nil)
        }
      end

      def parse_feature(name, info, parent_name)
        Feature.new(name, info.fetch(ENABLED_KEY), info[DESCRIPTION_KEY], parse_sub_features(info, name), parent_name)
      end

      def parse_sub_features(info, parent_name)
        info.select { |key, _| ![ENABLED_KEY, DESCRIPTION_KEY].include?(key) }.map { |sub_name, sub_info|
          parse_feature(sub_name, sub_info, parent_name)
        }
      end

      def json
        JSON.parse(input_file)
      end

      def input_file
        File.read(input)
      rescue SystemCallError => e
        raise Error::UnreadableFile.new(e)
      end

      def valid_file?
        JSON::Validator.validate(expected_schema, input_file)
      end

      def expected_schema
        {
          type: :object,
          additionalProperties: {
            type: :object,
            additionalProperties: {
              properties: {
                enabled: {
                  type: :boolean
                },
                description: {
                  type: :string
                },
                additionalProperties: {
                  properties: {
                    enabled: {
                      type: :boolean
                    },
                    description: {
                      type: :string
                    },
                    required: [
                      :enabled
                    ]
                  }
                }
              },
              required: [
                :enabled
              ]
            }
          }
        }
      end
    end
  end
end


text:
import {
  findIndex,
  flatMap,
  isArray,
  isFunction,
  isObject,
  isString,
  keys,
  union,
  upperFirst,
  values,
} from "lodash";

// Doesn't work well with uglify unless its --keep-fnames is used.
function isProbablyClass (value) {
  return isFunction(value) && startsUppercase(value.name);
}

function keysUnion (...objects) {
  return union(flatMap(objects, obj => keys(obj)));
}

function onlyHasStrings (value) {
  let array = isArray(value) ? value
  : isObject(value) ? values(value)
  : undefined;

  return findIndex(array, i => !isString(i)) === -1;
}

function startsUppercase (value) {
  return isString(value) && value.length >= 1 && value === upperFirst(value);
}

module.exports = {
  isProbablyClass,
  keysUnion,
  onlyHasStrings,
  startsUppercase,
};


text:
require 'rails_helper'

RSpec.describe Identity, type: :model do
  it { should belong_to(:user) }

  it { should validate_presence_of(:provider) }
  it { should validate_presence_of(:uid) }
end


text:
using System;
using Chiro.Cdf.Ioc;
using Chiro.CiviCrm.Api;
using Chiro.CiviCrm.Api.DataContracts;
using Chiro.CiviCrm.Api.DataContracts.Entities;
using Chiro.CiviCrm.Api.DataContracts.Requests;
using Chiro.CiviSync.Services.Test;
using Chiro.Gap.UpdateApi.Client;
using Moq;
using NUnit.Framework;

namespace Chiro.CiviSync.Workers.Test
{
    [TestFixture]
    public class ContactWorkerTest: SyncTest
    {
        private readonly DateTime _vandaagZogezegd = new DateTime(2015, 2, 6);

        /// <summary>
        /// Persoon met recentste lid mag niet crashen als de API geen persoon
        /// oplevert.
        /// </summary>
        [Test]
        public void PersoonMetRecentsteLidOngeldigAd()
        {
            // ARRANGE

            Mock<ICiviCrmApi> civiApiMock;
            Mock<IGapUpdateClient> updateHelperMock;

            using (var factory = TestHelper.IocOpzetten(_vandaagZogezegd, out civiApiMock, out updateHelperMock))
            {

                civiApiMock.Setup(
                        src => src.ContactGet(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ContactRequest>()))
                    .Returns(new ApiResultValues<Contact>());

                // ContactHelper vraagt de API-keys bij constructie. Dat is misschien niet
                // zo'n goed idee. Maar voorlopig doe ik het zo dus ook in deze test.

                var contactWorker = factory.Maak<ContactWorker>();

                // ACT

                var result = contactWorker.PersoonMetRecentsteLid(2, 3);

                // ASSERT

                Assert.IsNull(result);
            }
        }

        /// <summary>
        /// Persoon met recentste membership mag niet crashen als de API geen persoon
        /// oplevert.
        /// </summary>
        [Test]
        public void PersoonMetRecentsteMembershipOngeldigAd()
        {
            // ARRANGE
            Mock<ICiviCrmApi> civiApiMock;
            Mock<IGapUpdateClient> updateHelperMock;
            using (var factory = TestHelper.IocOpzetten(_vandaagZogezegd, out civiApiMock, out updateHelperMock))
            {

                civiApiMock.Setup(
                        src => src.ContactGet(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ContactRequest>()))
                    .Returns(new ApiResultValues<Contact>());

                // ContactHelper vraagt de API-keys bij constructie. Dat is misschien niet
                // zo'n goed idee. Maar voorlopig doe ik het zo dus ook in deze test.
                var contactWorker = factory.Maak<ContactWorker>();

                // ACT
                var result = contactWorker.PersoonMetRecentsteMembership(2, MembershipType.Aansluiting);

                // ASSERT
                Assert.IsNull(result);
            }
        }

        /// <summary>
        /// Workers worden per call opnieuw geinstantieerd. Als er een nieuwe ContactWorker
        /// wordt gemaakt, dan is het de bedoeling dat dezelfde cache blijft gebruiken.
        /// </summary>
        [Test]
        public void AdNrCiviIdCacheTest()
        {
            // In principe is deze unit test niet helemaal juist, omdat het 2 dingen door elkaar
            // test: het aanroepen van de cache, en de werking van de cache. Ze zou dus beter
            // opgesplitst worden.

            // ARRANGE

            Mock<ICiviCrmApi> civiApiMock;
            Mock<IGapUpdateClient> updateHelperMock;
            using (var factory = TestHelper.IocOpzetten(_vandaagZogezegd, out civiApiMock, out updateHelperMock))
            {

                // Vervang de gemockte cache (uit IocOpzetten) opnieuw door de echte cache.
                factory.InstantieRegistreren<ICiviCache>(new CiviCache());

                var myContact = new Contact
                {
                    Id = 1,
                    FirstName = "Johan",
                    LastName = "Vervloet",
                    ExternalIdentifier = "2"
                };

                civiApiMock.Setup(
                        src =>
                            src.ContactGet(It.IsAny<string>(), It.IsAny<string>(),
                                It.Is<ContactRequest>(r => r.ExternalIdentifier == myContact.ExternalIdentifier)))
                    .Returns(new ApiResultValues<Contact>(myContact))
                    .Verifiable();

                var contactWorker1 = factory.Maak<ContactWorker>();
                var contactWorker2 = factory.Maak<ContactWorker>();

                // ACT

                // vraag twee keer op, via aparte worker
                int? civiId1 = contactWorker1.ContactIdGet(myContact.ExternalIdentifier);
                int? civiId2 = contactWorker2.ContactIdGet(myContact.ExternalIdentifier);

                // ASSERT

                civiApiMock.Verify(src =>
                        src.ContactGet(It.IsAny<string>(), It.IsAny<string>(),
                            It.Is<ContactRequest>(r => r.ExternalIdentifier == myContact.ExternalIdentifier)),
                    Times.Exactly(1));
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:res="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@color/gray_light_very"
    tools:context=".SumFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/TYPE_NUMBERS"
        android:textColor="@color/gray_dark_very_transparent_light"
        style="@style/AtlanticTextMedium"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_default"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/firstNumberEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="@string/FIRST"
            android:textColor="@color/gray_dark_very_transparent_light"
            android:inputType="number"
            style="@style/AtlanticTextMedium"/>

        <EditText
            android:id="@+id/secondNumberEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="@string/SECOND"
            android:textColor="@color/gray_dark_very_transparent_light"
            android:inputType="number"
            style="@style/AtlanticTextMedium"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_default"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="@dimen/element_icon_size"
            android:layout_height="@dimen/element_icon_size"
            android:layout_marginRight="@dimen/margin_default"
            android:src="@drawable/ic_set_timer"/>

        <EditText
            android:id="@+id/timerDelayEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="@dimen/margin_default"
            android:layout_weight="1"
            android:hint="@string/TIMER_DELAY"
            android:textColor="@color/gray_dark_very_transparent_light"
            android:inputType="number"
            style="@style/AtlanticTextMedium"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_default"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="@dimen/element_icon_size"
            android:layout_height="@dimen/element_icon_size"
            android:layout_marginRight="@dimen/margin_default"
            android:src="@drawable/ic_sum_result"/>

        <TextView
            android:id="@+id/sumResultTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_default"
            android:layout_gravity="center"
            android:text="@string/SUM_RESULT"
            android:textColor="@color/gray_dark_very_transparent_light"
            style="@style/AtlanticTextMedium"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">

        <Button
            android:id="@+id/startCounterButton"
            android:layout_width="@dimen/counter_size"
            android:layout_height="@dimen/counter_size"
            android:background="@drawable/round_button"
            android:text="10000"
            android:singleLine="true"
            android:textColor="@color/white_transparent_light"
            android:textSize="48sp"/>

        <ImageView
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/ic_up"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/PUSH_BUTTON_HINT"
            android:gravity="center"
            android:textColor="@color/gray_dark_very_transparent_very"/>

    </LinearLayout>

</LinearLayout>


text:
package com.orientechnologies.orient.server.network.protocol.http.multipart;

import java.io.IOException;
import java.util.Map;

import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.server.network.protocol.http.OHttpRequest;

/**
 * @author luca.molino
 *
 */
public class OHttpMultipartContentBaseParser implements OHttpMultipartContentParser<String> {

  @Override
  public String parse(OHttpRequest iRequest, Map<String, String> headers, OHttpMultipartContentInputStream in,
      ODatabaseRecord database) throws IOException {
    StringBuilder builder = new StringBuilder();
    int b;
    while ((b = in.read()) > 0)
      builder.append((char) b);

    return builder.toString();
  }

}


text:
libroot=$SHCF_PLATFORM_ROOT/repo
docsroot=$SHCF_PLATFORM_ROOT/docs

docfile=$docsroot/lib.txt

rm $docfile
for each_libdir in xx1 xx2 xx3; do
  for each_libfile in $(ls -1 $libroot/$each_libdir/*.bash.inc); do
      echo "Library file: lib/$each_libdir/$(basename $each_libfile)"
      echo
      grep ^##\| $each_libfile | sed 's/##| //g'
      echo '---------- END ------------------'
      echo
  done  >> $docsroot/lib.txt
done


text:
package de.windelknecht.stup.utils.io.pack.archive

object ArchiveError
  extends Enumeration {
  type ArchiveError = Value

  val UnsupportedArchive = Value
  val NoFilesGiven = Value
  val CannotUnpackToAFile = Value
}


text:
/*
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_AEAD_SIV)
   #include <botan/siv.h>
   #include <botan/block_cipher.h>
   #include <botan/parsing.h>
#endif

namespace Botan_Tests {

namespace {

#if defined(BOTAN_HAS_AEAD_SIV)

class SIV_Tests final : public Text_Based_Test
   {
   public:
      SIV_Tests() : Text_Based_Test("siv_ad.vec", "Key,Nonce,ADs,In,Out") {}

      Test::Result run_one_test(const std::string& algo, const VarMap& vars) override
         {
         const std::vector<uint8_t> key      = get_req_bin(vars, "Key");
         const std::vector<uint8_t> nonce    = get_opt_bin(vars, "Nonce");
         const std::vector<uint8_t> input    = get_req_bin(vars, "In");
         const std::vector<uint8_t> expected = get_req_bin(vars, "Out");
         const std::vector<std::string> ad_list =
            Botan::split_on(get_req_str(vars, "ADs"), ',');

         Test::Result result(algo + "/SIV");

         std::unique_ptr<Botan::SIV_Mode> siv(
            new Botan::SIV_Encryption(Botan::BlockCipher::create(algo).release()));

         siv->set_key(key);

         for(size_t i = 0; i != ad_list.size(); ++i)
            {
            std::vector<uint8_t> ad = Botan::hex_decode(ad_list[i]);
            siv->set_associated_data_n(i, ad.data(), ad.size());
            }

         Botan::secure_vector<uint8_t> buf(input.begin(), input.end());
         siv->start(nonce);
         siv->finish(buf, 0);

         result.test_eq("SIV ciphertext", buf, expected);

         return result;
         }

   };

BOTAN_REGISTER_TEST("siv_ad", SIV_Tests);

#endif

}

}


text:
package it.prisma.utils.mailer.content.accounting;

import it.prisma.utils.mailer.content.ContentFactory;
import it.prisma.utils.mailer.content.ContentFactorySkeleton;
import it.prisma.utils.mailer.exceptions.MailContentException;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

public class AccountToConfirmContentFactory extends ContentFactorySkeleton implements ContentFactory {

	private static final String ENCODE = "UTF-8";
	private static final String TEMPLATE_NAME = "AccountConfirmation.vm";

	private final String uriScheme;
	private final String uriAuthority;
	private final String confirmationPageURI;
	private final String route;
	private final String from;
	private final String support;
	private final String subject;

	public AccountToConfirmContentFactory(Properties properties) throws URISyntaxException {
		uriScheme = properties.getProperty("prisma.webui.uri.scheme");
		uriAuthority = properties.getProperty("prisma.webui.uri.authority");
		route = new StringBuilder()
			.append("/")
			.append(properties.getProperty("prisma.webui.accounting.signup.confirm.route"))
			.toString();
		confirmationPageURI = new URI(uriScheme, uriAuthority, route, null).toASCIIString();
		from = new StringBuilder()
			.append(properties.getProperty("prisma.mailconfig.accounting.address"))
			.append("@").append(uriAuthority)
			.toString();
		subject = properties.getProperty("prisma.mailconfig.accounting.signup.confirm.subject");
		support = new StringBuilder()
			.append(properties.getProperty("prisma.mailconfig.accounting.support.address"))
			.append("@").append(uriAuthority)
			.toString();
	}

	@Override
	protected String createSubject() {
		return this.subject;
	}

	@Override
	protected String createFrom() {
		return this.from;
	}

	@Override
	protected Template createTemplate() {
		return super.getTemplateEngine()
				.getTemplate(ContentFactorySkeleton.TEMPLATES_PATH + TEMPLATE_NAME,
						ContentFactorySkeleton.ENCODING);
	}

	@Override
	protected VelocityContext createContext(Map<String, String> data) throws MailContentException {
		VelocityContext context = new VelocityContext();
		try {

			String confirmationRequestURI = new URI(uriScheme, uriAuthority,
					route,
					"&email=" + URLEncoder.encode(data.get("email"), ENCODE) +
					"&code=" + URLEncoder.encode(data.get("token"), ENCODE),
					null).toASCIIString();
			context.put("email", data.get("email"));
			context.put("fullName", data.get("fullName"));
			context.put("token", data.get("token"));
			context.put("confirmationRequestURI", confirmationRequestURI);
			context.put("confirmationPageURI", confirmationPageURI);
			context.put("support", support);
		} catch (Exception e) {
			context = null;
			throw new MailContentException(MailContentException.CONTEXT_ERROR_MSG);
		}
		return context;
	}

}


text:
class CreateSnippets < ActiveRecord::Migration
  def change
    create_table :snippets do |t|
      t.string :title
      t.belongs_to :language
      t.text :contents

      t.timestamps
    end
  end
end


text:
<?php

namespace SMW\Tests\Deserializers;

use SMW\Deserializers\ExpDataDeserializer;
use SMW\Serializers\ExpDataSerializer;
use SMW\Exporter\Element\ExpResource;
use SMW\Exporter\Element\ExpNsResource;
use SMW\Exporter\Element\ExpLiteral;
use SMWExpData as ExpData;
use SMWDIBlob as DIBlob;

/**
 * @covers \SMW\Deserializers\ExpDataDeserializer
 *
 * @group semantic-mediawiki
 *
 * @license GNU GPL v2+
 * @since 2.2
 *
 * @author mwjames
 */
class ExpDataDeserializerTest extends \PHPUnit_Framework_TestCase {

	public function testCanConstructor() {

		$this->assertInstanceOf(
			'\SMW\Deserializers\ExpDataDeserializer',
			new ExpDataDeserializer()
		);
	}

	public function testInvalidSerializerObjectThrowsException() {

		$instance = new ExpDataDeserializer();

		$this->setExpectedException( 'OutOfBoundsException' );
		$instance->deserialize( 'Foo' );
	}

	public function testVersionMismatchThrowsException() {

		$instance = new ExpDataDeserializer();

		$this->setExpectedException( 'OutOfBoundsException' );
		$instance->deserialize( array( 'version' => 0.2 ) );
	}

	/**
	 * @dataProvider expDataProvider
	 */
	public function testDeserialize( $seralization, $expected ) {

		$instance = new ExpDataDeserializer();

		$this->assertEquals(
			$expected,
			$instance->deserialize( $seralization )
		);
	}

	/**
	 * @dataProvider expDataProvider
	 */
	public function testDeserializeToCompareHash( $seralization, $expected ) {

		$instance = new ExpDataDeserializer();

		$this->assertEquals(
			$expected->getHash(),
			$instance->deserialize( $seralization )->getHash()
		);
	}

	public function expDataProvider() {

		$serializier = new ExpDataSerializer();

		#0
		$expData = new ExpData(
			new ExpNsResource( 'Foo', 'Bar', 'Mo', null )
		);

		$provider[] = array(
			$serializier->serialize( $expData ),
			$expData
		);

		#1
		$expData = new ExpData(
			new ExpNsResource( 'Foo', 'Bar', 'Mo', null )
		);

		$expData->addPropertyObjectValue(
			new ExpNsResource( 'Li', 'La', 'Lu', null ),
			new ExpLiteral( 'Foo', 'Bar' )
		);

		$provider[] = array(
			$serializier->serialize( $expData ),
			$expData
		);

		#2 Nested
		$expData = new ExpData(
			new ExpNsResource( 'Foo', 'Bar', 'Mo', null )
		);

		$expData->addPropertyObjectValue(
			new ExpNsResource( 'Li', 'La', 'Lu', new DIBlob( 'SomeText' ) ),
			new ExpLiteral( 'Foo', 'Bar' )
		);

		$expData->addPropertyObjectValue(
			new ExpNsResource( 'Li', 'La', 'Lu', null ),
			new ExpData( new ExpNsResource( 'Foo', 'Bar', 'Mo', new DIBlob( 'SomeOtherText' ) ) )
		);

		$provider[] = array(
			$serializier->serialize( $expData ),
			$expData
		);

		#2 Nested level 2+3

		$expDataLevel2 = new ExpData(
			new ExpNsResource( 'Foo', 'Bar', 'Mo', new DIBlob( 'SomeOtherText' ) )
		);

		$expDataLevel2->addPropertyObjectValue(
			new ExpNsResource( 'Li', 'La', 'Lu', new DIBlob( 'SomeText' ) ),
			new ExpLiteral( 'Foo', 'Bar' )
		);

		$expDataLevel2->addPropertyObjectValue(
			new ExpNsResource( 'Li', 'La', 'Lu', null ),
			new ExpData( new ExpNsResource( 'Foo', 'Bar', 'Mo', null ) ) // 3
		);

		$expData = new ExpData(
			new ExpNsResource( 'Foo', 'Bar', 'Mo', null )
		);

		$expData->addPropertyObjectValue(
			new ExpNsResource( 'Li', 'La', 'Lu', new DIBlob( 'SomeText' ) ),
			new ExpLiteral( 'Foo', 'Bar' )
		);

		$expData->addPropertyObjectValue(
			new ExpNsResource( 'Li', 'La', 'Lu', null ),
			$expDataLevel2
		);

		$provider[] = array(
			$serializier->serialize( $expData ),
			$expData
		);

		return $provider;
	}

}


text: Repositorio para talleres de git en CITT Viña del Mar


text:
export default Ember.View.extend({
  affixNav: function () {
    // we have to wait until the template updates.
    Ember.run.later(function () {
      this.$('[data-spy=affix]').affix();
    }.bind(this), 10);
  },
  didInsertElement: function () {
    this.get('controller').addObserver('isEditing', this, this.affixNav);
    this.affixNav();
  },
  willDestroyElement: function () {
    this.get('controller').removeObserver('isEditing', this, this.affixNav);
  }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="RemoteRepositoriesConfiguration">
    <remote-repository>
      <option name="id" value="central" />
      <option name="name" value="Maven Central repository" />
      <option name="url" value="https://repo1.maven.org/maven2" />
    </remote-repository>
    <remote-repository>
      <option name="id" value="jboss.community" />
      <option name="name" value="JBoss Community repository" />
      <option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
    </remote-repository>
    <remote-repository>
      <option name="id" value="maven2" />
      <option name="name" value="maven2" />
      <option name="url" value="https://storage.googleapis.com/download.flutter.io" />
    </remote-repository>
    <remote-repository>
      <option name="id" value="BintrayJCenter" />
      <option name="name" value="BintrayJCenter" />
      <option name="url" value="https://jcenter.bintray.com/" />
    </remote-repository>
    <remote-repository>
      <option name="id" value="Google" />
      <option name="name" value="Google" />
      <option name="url" value="https://dl.google.com/dl/android/maven2/" />
    </remote-repository>
    <remote-repository>
      <option name="id" value="maven" />
      <option name="name" value="maven" />
      <option name="url" value="https://dl.bintray.com/microsoftazuremobile/SDK" />
    </remote-repository>
  </component>
</project>


text:
package config

import (
	"fmt"
	"io"
	"time"

	"github.com/scionproto/scion/go/lib/config"
	"github.com/scionproto/scion/go/lib/daemon"
	"github.com/scionproto/scion/go/lib/env"
	"github.com/scionproto/scion/go/lib/log"
	"github.com/scionproto/scion/go/lib/serrors"
	"github.com/scionproto/scion/go/lib/util"
	"github.com/scionproto/scion/go/pkg/api"
	"github.com/scionproto/scion/go/pkg/storage"
	trustengine "github.com/scionproto/scion/go/pkg/trust/config"
)

var (
	DefaultQueryInterval = 5 * time.Minute
)

var _ config.Config = (*Config)(nil)

type Config struct {
	General     env.General        `toml:"general,omitempty"`
	Features    env.Features       `toml:"features,omitempty"`
	Logging     log.Config         `toml:"log,omitempty"`
	Metrics     env.Metrics        `toml:"metrics,omitempty"`
	API         api.Config         `toml:"api,omitempty"`
	Tracing     env.Tracing        `toml:"tracing,omitempty"`
	TrustDB     storage.DBConfig   `toml:"trust_db,omitempty"`
	PathDB      storage.DBConfig   `toml:"path_db,omitempty"`
	DRKeyLvl2DB storage.DBConfig   `toml:"drkey_lvl2_db,omitempty"`
	SD          SDConfig           `toml:"sd,omitempty"`
	TrustEngine trustengine.Config `toml:"trustengine,omitempty"`
}

func (cfg *Config) InitDefaults() {
	config.InitAll(
		&cfg.General,
		&cfg.Features,
		&cfg.Logging,
		&cfg.Metrics,
		&cfg.API,
		&cfg.Tracing,
		cfg.TrustDB.WithDefault(fmt.Sprintf(storage.DefaultTrustDBPath, "sd")),
		cfg.PathDB.WithDefault(fmt.Sprintf(storage.DefaultPathDBPath, "sd")),
		&cfg.SD,
		&cfg.TrustEngine,
	)
}

func (cfg *Config) Validate() error {
	return config.ValidateAll(
		&cfg.General,
		&cfg.Features,
		&cfg.Logging,
		&cfg.Metrics,
		&cfg.API,
		&cfg.TrustDB,
		&cfg.PathDB,
		&cfg.DRKeyLvl2DB,
		&cfg.SD,
		&cfg.TrustEngine,
	)
}

func (cfg *Config) Sample(dst io.Writer, path config.Path, _ config.CtxMap) {
	config.WriteSample(dst, path, config.CtxMap{config.ID: idSample},
		&cfg.General,
		&cfg.Features,
		&cfg.Logging,
		&cfg.Metrics,
		&cfg.API,
		&cfg.Tracing,
		config.OverrideName(
			config.FormatData(
				&cfg.TrustDB,
				fmt.Sprintf(storage.DefaultTrustDBPath, "sd"),
			),
			"trust_db",
		),
		config.OverrideName(
			config.FormatData(
				&cfg.PathDB,
				fmt.Sprintf(storage.DefaultPathDBPath, "sd"),
			),
			"path_db",
		),
		config.OverrideName(
			config.FormatData(
				&cfg.DRKeyLvl2DB,
				fmt.Sprintf(storage.DefaultDRKeyLvl2DBPath, "sd"),
			),
			"drkey_lvl2_db",
		),
		&cfg.SD,
		&cfg.TrustEngine,
	)
}

var _ config.Config = (*SDConfig)(nil)

type SDConfig struct {
	// Address is the local address to listen on for SCION messages, and to send out messages to
	// other nodes.
	Address string `toml:"address,omitempty"`
	// BindDialerToAddress forces the daemon to dial
	// using the local IP address specified in Address.
	BindDialerToAddress bool `toml:"bind_dialer_to_address,omitempty"`
	// DisableSegVerification indicates that segment verification should be
	// disabled.
	DisableSegVerification bool `toml:"disable_seg_verification,omitempty"`
	// QueryInterval specifies after how much time segments
	// for a destination should be refetched.
	QueryInterval util.DurWrap `toml:"query_interval,omitempty"`
	// HiddenPathGroup is a file that contains the hiddenpath groups.
	// If HiddenPathGroups begins with http:// or https://, it will be fetched
	// over the network from the specified URL instead.
	HiddenPathGroups string `toml:"hidden_path_groups,omitempty"`
}

func (cfg *SDConfig) InitDefaults() {
	if cfg.Address == "" {
		cfg.Address = daemon.DefaultAPIAddress
	}
	if cfg.QueryInterval.Duration == 0 {
		cfg.QueryInterval.Duration = DefaultQueryInterval
	}
}

func (cfg *SDConfig) Validate() error {
	if cfg.QueryInterval.Duration == 0 {
		return serrors.New("QueryInterval must not be zero")
	}
	return nil
}

func (cfg *SDConfig) Sample(dst io.Writer, path config.Path, ctx config.CtxMap) {
	config.WriteString(dst, sdSample)
}

func (cfg *SDConfig) ConfigName() string {
	return "sd"
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Storage.Table;
using Microsoft.WindowsAzure.Storage.Table;

namespace Microsoft.Azure.WebJobs.Host.FunctionalTests.TestDoubles
{
    internal class FakeStorageTable : IStorageTable
    {
        private readonly MemoryTableStore _store;
        private readonly string _tableName;
        private readonly CloudTable _sdkObject;

        public FakeStorageTable(MemoryTableStore store, string tableName)
        {
            _store = store;
            _tableName = tableName;
            _sdkObject = new CloudTable(new Uri("http://localhost:10000/fakeaccount/" + tableName));
        }

        public string Name
        {
            get { return _tableName; }
        }

        public CloudTable SdkObject
        {
            get { return _sdkObject; }
        }

        public IStorageTableBatchOperation CreateBatch()
        {
            return new FakeStorageTableBatchOperation();
        }

        public Task CreateIfNotExistsAsync(CancellationToken cancellationToken)
        {
            _store.CreateIfNotExists(_tableName);
            return Task.FromResult(0);
        }

        public IStorageTableOperation CreateInsertOperation(ITableEntity entity)
        {
            return FakeStorageTableOperation.Insert(entity);
        }

        public IStorageTableOperation CreateInsertOrReplaceOperation(ITableEntity entity)
        {
            throw new NotImplementedException();
        }

        public IQueryable<TElement> CreateQuery<TElement>() where TElement : ITableEntity, new()
        {
            return _store.CreateQuery<TElement>(_tableName);
        }

        public IStorageTableOperation CreateReplaceOperation(ITableEntity entity)
        {
            return FakeStorageTableOperation.Replace(entity);
        }

        public IStorageTableOperation CreateRetrieveOperation<TElement>(string partitionKey, string rowKey)
            where TElement : ITableEntity, new()
        {
            return FakeStorageTableOperation.Retrieve<TElement>(partitionKey, rowKey);
        }

        public Task<TableResult> ExecuteAsync(IStorageTableOperation operation, CancellationToken cancellationToken)
        {
            return Task.FromResult(_store.Execute(_tableName, operation));
        }

        public Task<IList<TableResult>> ExecuteBatchAsync(IStorageTableBatchOperation batch,
            CancellationToken cancellationToken)
        {
            return Task.FromResult(_store.ExecuteBatch(_tableName, batch));
        }

        public Task<bool> ExistsAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(_store.Exists(_tableName));
        }
    }
}


text:
Hello "world"...

            The three wise monkeys [. . .] sometimes called the three mystic apes--are a pictorial maxim.
            Together they embody the proverbial principle to ("see no evil, hear no evil, speak no evil").
            The three monkeys are Mizaru (:see_no_evil:), covering his eyes, who sees no evil;
            Kikazaru (:hear_no_evil:), covering his ears, who hears no evil;
            and Iwazaru (:speak_no_evil:), covering his mouth, who speaks no evil.