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

#include "ash/wm/desks/desk_preview_view.h"

#include <memory>
#include <utility>

#include "ash/public/cpp/window_properties.h"
#include "ash/shell.h"
#include "ash/style/ash_color_provider.h"
#include "ash/wallpaper/wallpaper_base_view.h"
#include "ash/wm/desks/desk_mini_view.h"
#include "ash/wm/desks/desk_name_view.h"
#include "ash/wm/desks/desks_bar_view.h"
#include "ash/wm/desks/desks_controller.h"
#include "ash/wm/desks/desks_util.h"
#include "ash/wm/float/float_controller.h"
#include "ash/wm/mru_window_tracker.h"
#include "ash/wm/overview/overview_utils.h"
#include "ash/wm/window_state.h"
#include "ash/wm/window_util.h"
#include "ash/wm/wm_highlight_item_border.h"
#include "ash/wm/workspace/backdrop_controller.h"
#include "ash/wm/workspace/workspace_layout_manager.h"
#include "ash/wm/workspace_controller.h"
#include "base/containers/contains.h"
#include "base/containers/flat_map.h"
#include "base/containers/flat_set.h"
#include "base/cxx17_backports.h"
#include "base/ranges/algorithm.h"
#include "chromeos/ui/wm/features.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/compositor/layer_type.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/gfx/skia_paint_util.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/border.h"

namespace ash {

namespace {

// In non-compact layouts, the height of the preview is a percentage of the
// total display height, with a max of |kDeskPreviewMaxHeight| dips and a min of
// |kDeskPreviewMinHeight| dips.
constexpr int kRootHeightDivider = 12;
constexpr int kRootHeightDividerForSmallScreen = 8;
constexpr int kDeskPreviewMaxHeight = 140;
constexpr int kDeskPreviewMinHeight = 48;
constexpr int kUseSmallerHeightDividerWidthThreshold = 600;

// The corner radius of the border in dips.
constexpr int kBorderCornerRadius = 6;

// The rounded corner radii, also in dips.
constexpr int kCornerRadius = 4;
constexpr gfx::RoundedCornersF kCornerRadii(kCornerRadius);

// Used for painting the highlight when the context menu is open.
constexpr float kHighlightTransparency = 0.3f * 0xFF;

// Holds data about the original desk's layers to determine what we should do
// when we attempt to mirror those layers.
struct LayerData {
  // If true, the layer won't be mirrored in the desk's mirrored contents. For
  // example windows created by overview mode to hold the OverviewItemView,
  // or minimized windows' layers, should all be skipped.
  bool should_skip_layer = false;

  // If true, we will force the mirror layers to be visible even if the source
  // layers are not, and we will disable visibility change synchronization
  // between the source and mirror layers.
  // This is used, for example, for the desks container windows whose mirrors
  // should always be visible (even for inactive desks) to be able to see their
  // contents in the mini_views.
  bool should_force_mirror_visible = false;

  // If true, transformations will be cleared for this layer. This is used,
  // for example, for visible on all desk windows to clear their overview
  // transformation since they don't belong to inactive desks.
  bool should_clear_transform = false;
};

// Returns true if |window| can be shown in the desk's preview according to its
// multi-profile ownership status (i.e. can only be shown if it belongs to the
// active user).
bool CanShowWindowForMultiProfile(aura::Window* window) {
  aura::Window* window_to_check = window;
  // If |window| is a backdrop, check the window which has this backdrop
  // instead.
  WorkspaceController* workspace_controller =
      GetWorkspaceControllerForContext(window_to_check);
  if (workspace_controller) {
    BackdropController* backdrop_controller =
        workspace_controller->layout_manager()->backdrop_controller();
    if (backdrop_controller->backdrop_window() == window_to_check)
      window_to_check = backdrop_controller->window_having_backdrop();
  }

  return window_util::ShouldShowForCurrentUser(window_to_check);
}

// Returns the LayerData entry for |target_layer| in |layer_data|. Returns an
// empty LayerData struct if not found.
const LayerData GetLayerDataEntry(
    const base::flat_map<ui::Layer*, LayerData>& layers_data,
    ui::Layer* target_layer) {
  const auto iter = layers_data.find(target_layer);
  return iter == layers_data.end() ? LayerData{} : iter->second;
}

// Get the z-order of all-desk `window` in `desk` for `root`. If it does not
// exist, then nullopt is returned. Please note, the z-order information is
// retrieved from the stored stacking data of `desk` for all-desk windows.
absl::optional<size_t> GetWindowZOrderForDeskAndRoot(const aura::Window* window,
                                                     const Desk* desk,
                                                     const aura::Window* root) {
  const auto& adw_by_root = desk->all_desk_window_stacking();

  if (auto it = adw_by_root.find(root); it != adw_by_root.end()) {
    for (auto& adw : it->second) {
      if (adw.window == window)
        return adw.order;
    }
  }

  return absl::nullopt;
}

// Appends clones of all the visible on all desks windows' layers to
// `out_desk_container_children`. Should only be called if
// `visible_on_all_desks_windows` is not empty.
void AppendVisibleOnAllDesksWindowsToDeskLayer(
    const base::flat_set<aura::Window*>& visible_on_all_desks_windows,
    const base::flat_map<ui::Layer*, LayerData>& layers_data,
    std::vector<ui::Layer*>* out_desk_container_children,
    aura::Window* desk_container) {
  DCHECK(!visible_on_all_desks_windows.empty());
  auto mru_windows =
      Shell::Get()->mru_window_tracker()->BuildMruWindowList(kAllDesks);
  const Desk* desk = desks_util::GetDeskForContext(desk_container);
  aura::Window* root = desk_container->GetRootWindow();

  for (auto* window : visible_on_all_desks_windows) {
    const LayerData layer_data =
        GetLayerDataEntry(layers_data, window->layer());
    if (layer_data.should_skip_layer)
      continue;

    auto window_iter = base::ranges::find(mru_windows, window);
    if (window_iter == mru_windows.end())
      continue;

    auto insertion_point_iter = out_desk_container_children->end();
    auto desk_windows = desk_container->children();

    // Find z order of `window`. If `features::IsPerDeskZOrderEnabled()` is not
    // on, default value of zero will be used so `window` would be put on top.
    size_t window_order =
        GetWindowZOrderForDeskAndRoot(window, desk, root).value_or(0);

    // If `desk` has no child window, or `window` has lowest z order, use
    // default `insertion_point_iter` to put it on top.
    if (!desk_windows.empty() && window_order) {
      // Find the nearest window that should be on top of `window`.
      size_t order = 0, target_idx = desk_windows.size();
      for (int i = desk_windows.size() - 1; i >= 0 && order < window_order;
           i--) {
        if (desks_util::IsZOrderTracked(window)) {
          target_idx = static_cast<size_t>(i);
          ++order;
        }
      }

      // Move to the next nearest window until its layer is in the
      // `out_desk_container_children`.
      for (size_t i = target_idx; i < desk_windows.size(); i++) {
        if (base::Contains(*out_desk_container_children,
                           desk_windows[i]->layer())) {
          insertion_point_iter = base::ranges::find(
              *out_desk_container_children, desk_windows[i]->layer());
          break;
        }
      }
    }

    out_desk_container_children->insert(insertion_point_iter, window->layer());
  }
}

// Recursively mirrors `source_layer` and its children and adds them as children
// of `parent`, taking into account the given |layers_data|. If the layer data
// of `source_layer` has `should_clear_transform` set to true, the transforms of
// its mirror layers will be reset to identity.
void MirrorLayerTree(
    ui::Layer* source_layer,
    ui::Layer* parent,
    const base::flat_map<ui::Layer*, LayerData>& layers_data,
    const base::flat_set<aura::Window*>& visible_on_all_desks_windows_to_mirror,
    aura::Window* desk_container) {
  const LayerData layer_data = GetLayerDataEntry(layers_data, source_layer);
  if (layer_data.should_skip_layer)
    return;

  auto* mirror = source_layer->Mirror().release();
  parent->Add(mirror);

  std::vector<ui::Layer*> children = source_layer->children();
  if (!visible_on_all_desks_windows_to_mirror.empty()) {
    // Windows that are visible on all desks should show up in each desk
    // preview so for inactive desks, we need to append the layers of visible on
    // all desks windows.
    AppendVisibleOnAllDesksWindowsToDeskLayer(
        visible_on_all_desks_windows_to_mirror, layers_data, &children,
        desk_container);
  }
  for (auto* child : children) {
    // Visible on all desks windows only needed to be added to the subtree once
    // so use an empty set for subsequent calls.
    MirrorLayerTree(child, mirror, layers_data, base::flat_set<aura::Window*>(),
                    desk_container);
  }

  mirror->set_sync_bounds_with_source(true);
  if (layer_data.should_force_mirror_visible) {
    mirror->SetVisible(true);
    mirror->SetOpacity(1);
    mirror->set_sync_visibility_with_source(false);
  }

  if (layer_data.should_clear_transform)
    mirror->SetTransform(gfx::Transform());
}

// Gathers the needed data about the layers in the subtree rooted at the layer
// of the given |window|, and fills |out_layers_data|.
void GetLayersData(aura::Window* window,
                   base::flat_map<ui::Layer*, LayerData>* out_layers_data) {
  auto& layer_data = (*out_layers_data)[window->layer()];

  // Windows may be explicitly set to be skipped in mini_views such as those
  // created for overview mode purposes.
  // TODO(afakhry): Exclude exo's root surface, since it's a place holder and
  // doesn't have any content. See `exo::SurfaceTreeHost::SetRootSurface()`.
  if (window->GetProperty(kHideInDeskMiniViewKey)) {
    layer_data.should_skip_layer = true;
    return;
  }

  // Minimized windows should not show up in the mini_view.
  auto* window_state = WindowState::Get(window);
  if (window_state && window_state->IsMinimized()) {
    layer_data.should_skip_layer = true;
    return;
  }

  if (!CanShowWindowForMultiProfile(window)) {
    layer_data.should_skip_layer = true;
    return;
  }

  // Windows transformed into position in the overview mode grid should be
  // mirrored and the transforms of the mirrored layers should be reset to
  // identity.
  if (window->GetProperty(kForceVisibleInMiniViewKey))
    layer_data.should_force_mirror_visible = true;

  // Since floated window is not stored in desk container and will be hidden
  // when the desk is inactive, we need to make sure it's visible in the desk
  // mini view at anytime, except when it's minimized (which has been handled
  // above).
  if (window_state && window_state->IsFloated() && !window->IsVisible())
    layer_data.should_force_mirror_visible = true;

  // Visible on all desks windows and floated windows aren't children of
  // inactive desk's container so mark them explicitly to clear overview
  // transforms. Additionally, windows in overview mode are transformed into
  // their positions in the grid, but we want to show a preview of the windows
  // in their untransformed state.
  if (desks_util::IsWindowVisibleOnAllWorkspaces(window) ||
      (window_state && window_state->IsFloated()) ||
      desks_util::IsDeskContainer(window->parent())) {
    layer_data.should_clear_transform = true;
  }

  for (auto* child : window->children())
    GetLayersData(child, out_layers_data);
}

}  // namespace

// -----------------------------------------------------------------------------
// DeskPreviewView

DeskPreviewView::DeskPreviewView(PressedCallback callback,
                                 DeskMiniView* mini_view)
    : views::Button(std::move(callback)),
      mini_view_(mini_view),
      wallpaper_preview_(new DeskWallpaperPreview),
      desk_mirrored_contents_view_(new views::View),
      force_occlusion_tracker_visible_(
          std::make_unique<aura::WindowOcclusionTracker::ScopedForceVisible>(
              mini_view->GetDeskContainer())) {
  DCHECK(mini_view_);

  SetFocusPainter(nullptr);
  views::InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::OFF);
  SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
  SetPaintToLayer(ui::LAYER_TEXTURED);
  layer()->SetFillsBoundsOpaquely(false);
  layer()->SetMasksToBounds(false);

  wallpaper_preview_->SetPaintToLayer();
  auto* wallpaper_preview_layer = wallpaper_preview_->layer();
  wallpaper_preview_layer->SetFillsBoundsOpaquely(false);
  wallpaper_preview_layer->SetRoundedCornerRadius(kCornerRadii);
  wallpaper_preview_layer->SetIsFastRoundedCorner(true);
  AddChildView(wallpaper_preview_);

  shadow_ = SystemShadow::CreateShadowOnNinePatchLayerForView(
      wallpaper_preview_, kDefaultShadowType);
  shadow_->SetRoundedCornerRadius(kCornerRadius);

  desk_mirrored_contents_view_->SetPaintToLayer(ui::LAYER_NOT_DRAWN);
  ui::Layer* contents_view_layer = desk_mirrored_contents_view_->layer();
  contents_view_layer->SetMasksToBounds(true);
  contents_view_layer->SetName("Desk mirrored contents view");
  contents_view_layer->SetRoundedCornerRadius(kCornerRadii);
  contents_view_layer->SetIsFastRoundedCorner(true);
  AddChildView(desk_mirrored_contents_view_);

  if (features::IsDesksCloseAllEnabled()) {
    highlight_overlay_ = AddChildView(std::make_unique<views::View>());
    highlight_overlay_->SetPaintToLayer(ui::LAYER_SOLID_COLOR);
    highlight_overlay_->SetVisible(false);
    ui::Layer* highlight_overlay_layer = highlight_overlay_->layer();
    highlight_overlay_layer->SetName("DeskPreviewView highlight overlay");
    highlight_overlay_layer->SetRoundedCornerRadius(kCornerRadii);
    highlight_overlay_layer->SetIsFastRoundedCorner(true);
  }

  auto border = std::make_unique<WmHighlightItemBorder>(kBorderCornerRadius);
  border_ptr_ = border.get();
  SetBorder(std::move(border));
  // Do not install the default focus ring on the button since we have `border`.
  SetInstallFocusRingOnFocus(false);

  RecreateDeskContentsMirrorLayers();
}

DeskPreviewView::~DeskPreviewView() = default;

// static
int DeskPreviewView::GetHeight(aura::Window* root) {
  DCHECK(root);
  DCHECK(root->IsRootWindow());

  const int height_divider =
      root->bounds().width() <= kUseSmallerHeightDividerWidthThreshold
          ? kRootHeightDividerForSmallScreen
          : kRootHeightDivider;
  return base::clamp(root->bounds().height() / height_divider,
                     kDeskPreviewMinHeight, kDeskPreviewMaxHeight);
}

void DeskPreviewView::SetBorderColor(SkColor color) {
  border_ptr_->set_color(color);
  SchedulePaint();
}

void DeskPreviewView::SetHighlightOverlayVisibility(bool visible) {
  DCHECK(highlight_overlay_);
  highlight_overlay_->SetVisible(visible);
}

void DeskPreviewView::RecreateDeskContentsMirrorLayers() {
  auto* desk_container = mini_view_->GetDeskContainer();
  DCHECK(desk_container);
  DCHECK(desk_container->layer());

  // Mirror the layer tree of the desk container.
  auto mirrored_content_root_layer =
      std::make_unique<ui::Layer>(ui::LAYER_NOT_DRAWN);
  mirrored_content_root_layer->SetName("mirrored contents root layer");
  base::flat_map<ui::Layer*, LayerData> layers_data;
  GetLayersData(desk_container, &layers_data);

  // If there is a floated window that belongs to this desk, since it doesn't
  // belong to `desk_container`, we need to add it separately.
  aura::Window* floated_window = nullptr;
  if (chromeos::wm::features::IsFloatWindowEnabled() &&
      (floated_window =
           Shell::Get()->float_controller()->FindFloatedWindowOfDesk(
               mini_view_->desk()))) {
    GetLayersData(floated_window, &layers_data);
  }

  base::flat_set<aura::Window*> visible_on_all_desks_windows_to_mirror;
  if (!desks_util::IsActiveDeskContainer(desk_container)) {
    // Since visible on all desks windows reside on the active desk, only mirror
    // them in the layer tree if |this| is not the preview view for the active
    // desk.
    visible_on_all_desks_windows_to_mirror =
        Shell::Get()->desks_controller()->GetVisibleOnAllDesksWindowsOnRoot(
            mini_view_->root_window());
    for (auto* window : visible_on_all_desks_windows_to_mirror)
      GetLayersData(window, &layers_data);
  }

  auto* desk_container_layer = desk_container->layer();
  MirrorLayerTree(desk_container_layer, mirrored_content_root_layer.get(),
                  layers_data, visible_on_all_desks_windows_to_mirror,
                  desk_container);

  // Since floated window is not stored in desk container, we need to mirror it
  // separately.
  if (floated_window) {
    auto* floated_window_layer = floated_window->layer();
    MirrorLayerTree(floated_window_layer, mirrored_content_root_layer.get(),
                    layers_data, /*visible_on_all_desks_windows_to_mirror=*/{},
                    desk_container);
  }

  // Add the root of the mirrored layer tree as a child of the
  // |desk_mirrored_contents_view_|'s layer.
  ui::Layer* contents_view_layer = desk_mirrored_contents_view_->layer();
  contents_view_layer->Add(mirrored_content_root_layer.get());

  // Take ownership of the mirrored layer tree.
  desk_mirrored_contents_layer_tree_owner_ =
      std::make_unique<ui::LayerTreeOwner>(
          std::move(mirrored_content_root_layer));

  Layout();
}

const char* DeskPreviewView::GetClassName() const {
  return "DeskPreviewView";
}

void DeskPreviewView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
  // Avoid failing accessibility checks if we don't have a name.
  views::Button::GetAccessibleNodeData(node_data);
  if (GetAccessibleName().empty())
    node_data->SetNameExplicitlyEmpty();
}

void DeskPreviewView::Layout() {
  const gfx::Rect bounds = GetContentsBounds();
  wallpaper_preview_->SetBoundsRect(bounds);
  desk_mirrored_contents_view_->SetBoundsRect(bounds);

  if (features::IsDesksCloseAllEnabled())
    highlight_overlay_->SetBoundsRect(bounds);

  // The desk's contents mirrored layer needs to be scaled down so that it fits
  // exactly in the center of the view.
  const auto root_size = mini_view_->root_window()->layer()->size();
  const gfx::Vector2dF scale{
      static_cast<float>(bounds.width()) / root_size.width(),
      static_cast<float>(bounds.height()) / root_size.height()};
  wallpaper_preview_->set_centered_layout_image_scale(scale);
  gfx::Transform transform;
  transform.Scale(scale.x(), scale.y());
  ui::Layer* desk_mirrored_contents_layer =
      desk_mirrored_contents_layer_tree_owner_->root();
  DCHECK(desk_mirrored_contents_layer);
  desk_mirrored_contents_layer->SetTransform(transform);

  Button::Layout();
}

bool DeskPreviewView::OnMousePressed(const ui::MouseEvent& event) {
  // If we have a right click and the `kDesksCloseAll` feature is enabled, we
  // should open the context menu.
  if (features::IsDesksCloseAllEnabled() && event.IsRightMouseButton()) {
    DeskNameView::CommitChanges(GetWidget());
    mini_view_->OpenContextMenu(ui::MENU_SOURCE_MOUSE);
  } else {
    mini_view_->owner_bar()->HandlePressEvent(mini_view_, event);
  }

  return Button::OnMousePressed(event);
}

bool DeskPreviewView::OnMouseDragged(const ui::MouseEvent& event) {
  mini_view_->owner_bar()->HandleDragEvent(mini_view_, event);
  return Button::OnMouseDragged(event);
}

void DeskPreviewView::OnMouseReleased(const ui::MouseEvent& event) {
  if (!mini_view_->owner_bar()->HandleReleaseEvent(mini_view_, event))
    Button::OnMouseReleased(event);
}

void DeskPreviewView::OnGestureEvent(ui::GestureEvent* event) {
  DesksBarView* owner_bar = mini_view_->owner_bar();

  switch (event->type()) {
    // Only long press can trigger drag & drop.
    case ui::ET_GESTURE_LONG_PRESS:
      owner_bar->HandleLongPressEvent(mini_view_, *event);
      event->SetHandled();
      break;
    case ui::ET_GESTURE_SCROLL_BEGIN:
      [[fallthrough]];
    case ui::ET_GESTURE_SCROLL_UPDATE:
      owner_bar->HandleDragEvent(mini_view_, *event);
      if (owner_bar->IsDraggingDesk())
        event->SetHandled();
      break;
    case ui::ET_GESTURE_END:
      if (owner_bar->HandleReleaseEvent(mini_view_, *event))
        event->SetHandled();
      break;
    default:
      break;
  }

  if (!event->handled())
    Button::OnGestureEvent(event);
}

void DeskPreviewView::OnThemeChanged() {
  views::Button::OnThemeChanged();

  if (features::IsDesksCloseAllEnabled()) {
    highlight_overlay_->layer()->SetColor(
        SkColorSetA(AshColorProvider::Get()->GetControlsLayerColor(
                        AshColorProvider::ControlsLayerType::kHighlightColor1),
                    kHighlightTransparency));
  }
}

void DeskPreviewView::OnFocus() {
  UpdateOverviewHighlightForFocusAndSpokenFeedback(this);
  mini_view_->UpdateBorderColor();
  View::OnFocus();
}

void DeskPreviewView::OnBlur() {
  mini_view_->UpdateBorderColor();
  View::OnBlur();
}

views::View* DeskPreviewView::GetView() {
  return this;
}

void DeskPreviewView::MaybeActivateHighlightedView() {
  DesksController::Get()->ActivateDesk(mini_view_->desk(),
                                       DesksSwitchSource::kMiniViewButton);
}

void DeskPreviewView::MaybeCloseHighlightedView(bool primary_action) {
  // The primary action (Ctrl + W) is to remove the desk and not close the
  // windows (combine the desk with one on the right or left). The secondary
  // action (Ctrl + Shift + W) is to close the desk and all its applications.
  mini_view_->OnRemovingDesk(primary_action
                                 ? DeskCloseType::kCombineDesks
                                 : DeskCloseType::kCloseAllWindowsAndWait);
}

void DeskPreviewView::MaybeSwapHighlightedView(bool right) {
  const int old_index = mini_view_->owner_bar()->GetMiniViewIndex(mini_view_);
  DCHECK_NE(old_index, -1);

  const bool mirrored = mini_view_->owner_bar()->GetMirrored();
  // If mirrored, flip the swap direction.
  int new_index = mirrored ^ right ? old_index + 1 : old_index - 1;
  if (new_index < 0 ||
      new_index ==
          static_cast<int>(mini_view_->owner_bar()->mini_views().size())) {
    return;
  }

  auto* desks_controller = DesksController::Get();
  desks_controller->ReorderDesk(old_index, new_index);
  desks_controller->UpdateDesksDefaultNames();
}

bool DeskPreviewView::MaybeActivateHighlightedViewOnOverviewExit(
    OverviewSession* overview_session) {
  MaybeActivateHighlightedView();
  return true;
}

void DeskPreviewView::OnViewHighlighted() {
  mini_view_->UpdateBorderColor();
  mini_view_->owner_bar()->ScrollToShowMiniViewIfNecessary(mini_view_);
}

void DeskPreviewView::OnViewUnhighlighted() {
  mini_view_->UpdateBorderColor();
}

}  // namespace ash


text:
#include "OgreGLES2Texture.h"
#include "OgreGLES2PixelFormat.h"
#include "OgreGLES2HardwarePixelBuffer.h"
#include "OgreGLES2StateCacheManager.h"
#include "OgreRoot.h"
#include "OgreBitwise.h"
#include "OgreTextureManager.h"
#include "OgreLogManager.h"

namespace Ogre {
    GLES2Texture::GLES2Texture(ResourceManager* creator, const String& name,
                             ResourceHandle handle, const String& group, bool isManual,
                             ManualResourceLoader* loader, GLES2RenderSystem* renderSystem)
        : GLTextureCommon(creator, name, handle, group, isManual, loader),
          mRenderSystem(renderSystem)
    {
    }

    GLES2Texture::~GLES2Texture()
    {
        // have to call this here rather than in Resource destructor
        // since calling virtual methods in base destructors causes crash
        unload();
    }

    GLenum GLES2Texture::getGLES2TextureTarget(void) const
    {
        switch(mTextureType)
        {
            case TEX_TYPE_1D:
            case TEX_TYPE_2D:
                return GL_TEXTURE_2D;
            case TEX_TYPE_CUBE_MAP:
                return GL_TEXTURE_CUBE_MAP;
            case TEX_TYPE_3D:
                return GL_TEXTURE_3D_OES;
            case TEX_TYPE_2D_ARRAY:
                return GL_TEXTURE_2D_ARRAY;
            case TEX_TYPE_EXTERNAL_OES:
                return GL_TEXTURE_EXTERNAL_OES;
            default:
                return 0;
        };
    }

    void GLES2Texture::_createGLTexResource()
    {
        const RenderSystemCapabilities *renderCaps =
                Root::getSingleton().getRenderSystem()->getCapabilities();

        const bool nonPowerOfTwoSupported = renderCaps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES) ||
                                            ( renderCaps->getNonPOW2TexturesLimited() &&
                                              mNumRequestedMipmaps == 0 );

        if( !nonPowerOfTwoSupported )
        {
            // Convert to nearest power-of-two size if required
            mWidth = Bitwise::firstPO2From(mWidth);
            mHeight = Bitwise::firstPO2From(mHeight);
            mDepth = Bitwise::firstPO2From(mDepth);
        }

        // set HardwareBuffer::Usage for TU_RENDERTARGET if nothing else specified
        if((mUsage & TU_RENDERTARGET) && (mUsage & ~TU_RENDERTARGET) == 0)
            mUsage |= HardwareBuffer::HBU_DYNAMIC;

        // Adjust format if required
        mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage);
        GLenum texTarget = getGLES2TextureTarget();

        // Generate texture name
        OGRE_CHECK_GL_ERROR(glGenTextures(1, &mTextureID));

        // Set texture type
        mRenderSystem->_getStateCacheManager()->bindGLTexture(texTarget, mTextureID);

        if (renderCaps->hasCapability(RSC_DEBUG))
            OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_TEXTURE, mTextureID, -1, mName.c_str()));

        // If we can do automip generation and the user desires this, do so
        mMipmapsHardwareGenerated = !PixelUtil::isCompressed(mFormat);

        // glGenerateMipmap require all mip levels to be prepared. So override how many this texture has.
        if((mUsage & TU_AUTOMIPMAP) && mMipmapsHardwareGenerated && mNumRequestedMipmaps)
            mNumMipmaps = getMaxMipmaps();

        if(mRenderSystem->hasMinGLVersion(3, 0) || mRenderSystem->checkExtension("GL_APPLE_texture_max_level"))
            mRenderSystem->_getStateCacheManager()->setTexParameteri(texTarget, GL_TEXTURE_MAX_LEVEL_APPLE, mNumRequestedMipmaps ? mNumMipmaps + 1 : 0);

        if(mTextureType == TEX_TYPE_EXTERNAL_OES && mNumRequestedMipmaps > 0) {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Mipmaps are not available for TEX_TYPE_EXTERNAL_OES", "GLES2Texture::_createGLTexResource");
        }

        bool hasGLES30 = mRenderSystem->hasMinGLVersion(3, 0);

        // Set up texture swizzling (not available in WebGL2)
        if (hasGLES30 && (OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN))
        {
            if(PixelUtil::isLuminance(mFormat))
            {
                if (PixelUtil::getComponentCount(mFormat) == 2)
                {
                    OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED));
                    OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_RED));
                    OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_RED));
                    OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_GREEN));
                }
                else
                {
                    OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED));
                    OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_RED));
                    OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_RED));
                    OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_ONE));
                }
            }
            else if(mFormat == PF_A8)
            {
                OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_ZERO));
                OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_ZERO));
                OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_ZERO));
                OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_RED));
            }
        }

        // Allocate internal buffer so that glTexSubImageXD can be used
        // Internal format
        GLenum format = GLES2PixelUtil::getGLOriginFormat(mFormat);
        GLenum internalformat = GLES2PixelUtil::getGLInternalFormat(mFormat, mHwGamma);
        uint32 width = mWidth;
        uint32 height = mHeight;
        uint32 depth = mDepth;

        if (PixelUtil::isCompressed(mFormat))
        {
            // Compressed formats
            GLsizei size = static_cast<GLsizei>(PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat));

            // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not
            // accept a 0 pointer like normal glTexImageXD
            // Run through this process for every mipmap to pregenerate mipmap pyramid

            std::vector<uint8> tmpdata(size);
            for (uint32 mip = 0; mip <= mNumMipmaps; mip++)
            {
#if OGRE_DEBUG_MODE
                LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) +
                                                      " Width: " + StringConverter::toString(width) +
                                                      " Height: " + StringConverter::toString(height) +
                                                      " Internal Format: " + StringUtil::format("%x", internalformat) +
                                                      " Format: " + StringUtil::format("%x", format)
                                                       );
#endif
                size = static_cast<GLsizei>(PixelUtil::getMemorySize(width, height, depth, mFormat));

                switch(mTextureType)
                {
                    case TEX_TYPE_1D:
                    case TEX_TYPE_2D:
                        OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_2D,
                                               mip,
                                               internalformat,
                                               width, height,
                                               0,
                                               size,
                                               &tmpdata[0]));
                        break;
                    case TEX_TYPE_CUBE_MAP:
                        for(int face = 0; face < 6; face++) {
                            OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat,
                                width, height, 0,
                                size, &tmpdata[0]));
                        }
                        break;
                    case TEX_TYPE_2D_ARRAY:
                        if(!hasGLES30)
                            break;
                        OGRE_FALLTHROUGH;
                    case TEX_TYPE_3D:
                        glCompressedTexImage3DOES(texTarget, mip, format,
                            width, height, depth, 0,
                            size, &tmpdata[0]);
                        break;
                    case TEX_TYPE_EXTERNAL_OES:
                        OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attempt to create mipmap for TEX_TYPE_EXTERNAL_OES, should never happen", "GLES2Texture::_createGLTexResource");
                };

                if(width > 1)
                {
                    width = width / 2;
                }
                if(height > 1)
                {
                    height = height / 2;
                }
                if(depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY)
                {
                    depth = depth / 2;
                }
            }
            return;
        }

        if(hasGLES30)
        {
#if OGRE_DEBUG_MODE
            LogManager::getSingleton().logMessage("GLES2Texture::create - Name: " + mName +
                                                      " ID: " + StringConverter::toString(mTextureID) +
                                                      " Width: " + StringConverter::toString(width) +
                                                      " Height: " + StringConverter::toString(height) +
                                                      " Internal Format: " + StringUtil::format("%x", internalformat));
#endif
            switch(mTextureType)
            {
                case TEX_TYPE_1D:
                case TEX_TYPE_2D:
                case TEX_TYPE_CUBE_MAP:
                    OGRE_CHECK_GL_ERROR(glTexStorage2D(texTarget, GLsizei(mNumMipmaps+1), internalformat, GLsizei(width), GLsizei(height)));
                    break;
                case TEX_TYPE_2D_ARRAY:
                case TEX_TYPE_3D:
                    OGRE_CHECK_GL_ERROR(glTexStorage3D(texTarget, GLsizei(mNumMipmaps+1), internalformat, GLsizei(width), GLsizei(height), GLsizei(depth)));
                    break;
                case TEX_TYPE_EXTERNAL_OES:
                    // Not available for TEX_TYPE_EXTERNAL_OES
                    break;
            }
            return;
        }
        GLenum datatype = GLES2PixelUtil::getGLOriginDataType(mFormat);

        // Run through this process to pregenerate mipmap pyramid
        for(uint32 mip = 0; mip <= mNumMipmaps; mip++)
        {
#if OGRE_DEBUG_MODE
            LogManager::getSingleton().logMessage("GLES2Texture::create - Mip: " + StringConverter::toString(mip) +
                                                  " Name: " + mName +
                                                  " ID: " + StringConverter::toString(mTextureID) +
                                                  " Width: " + StringConverter::toString(width) +
                                                  " Height: " + StringConverter::toString(height) +
                                                  " Internal Format: " + StringUtil::format("%x", internalformat) +
                                                  " Format: " + StringUtil::format("%x", format) +
                                                  " Datatype: " + StringUtil::format("%x", datatype)
                                                  );
#endif
            // Normal formats
            switch(mTextureType)
            {
                case TEX_TYPE_1D:
                case TEX_TYPE_2D:
                    OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_2D,
                                 mip,
                                 internalformat,
                                 width, height,
                                 0,
                                 format,
                                 datatype, 0));
                    break;
                case TEX_TYPE_2D_ARRAY:
                    if(!hasGLES30)
                        break;
                    OGRE_FALLTHROUGH;
                case TEX_TYPE_3D:
                    OGRE_CHECK_GL_ERROR(glTexImage3DOES(texTarget,
                                 mip,
                                 internalformat,
                                 width, height, depth,
                                 0,
                                 format,
                                 datatype, 0));
                    break;
                case TEX_TYPE_CUBE_MAP:
                    for(int face = 0; face < 6; face++) {
                        OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat,
                            width, height, 0,
                            format, datatype, 0));
                    }
                    break;
                default:
                    break;
            };

            if (width > 1)
            {
                width = Bitwise::firstPO2From(width / 2);
            }
            if (height > 1)
            {
                height = Bitwise::firstPO2From(height / 2);
            }
        }
    }

    // Creation / loading methods
    void GLES2Texture::createInternalResourcesImpl(void)
    {
        _createGLTexResource();

        _createSurfaceList();

        // Get final internal format
        mFormat = getBuffer(0,0)->getFormat();
    }

    void GLES2Texture::freeInternalResourcesImpl()
    {
        if (GLES2StateCacheManager* stateCacheManager = mRenderSystem->_getStateCacheManager())
        {
            OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &mTextureID));
            stateCacheManager->invalidateStateForTexture(mTextureID);
        }
        mTextureID = 0;
    }

#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
    void GLES2Texture::notifyOnContextLost()
    {
        if (!isManuallyLoaded())
        {
            freeInternalResources();
        }
        else
        {
            OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &mTextureID));
            mTextureID = 0;
        }
    }

    void GLES2Texture::notifyOnContextReset()
    {
        if (!isManuallyLoaded())
        {
            reload();
        }
        else
        {
            preLoadImpl();

            _createGLTexResource();

            for(size_t i = 0; i < mSurfaceList.size(); i++)
            {
                static_cast<GLES2TextureBuffer*>(mSurfaceList[i].get())->updateTextureId(mTextureID);
            }

            if (mLoader)
            {
                mLoader->loadResource(this);
            }

            postLoadImpl();
        }
    }
#endif

    void GLES2Texture::_createSurfaceList()
    {
        mSurfaceList.clear();

        uint32 depth = mDepth;

        // For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr
        for (size_t face = 0; face < getNumFaces(); face++)
        {
            uint32 width = mWidth;
            uint32 height = mHeight;

            for (uint32 mip = 0; mip <= getNumMipmaps(); mip++)
            {
                auto buf = std::make_shared<GLES2TextureBuffer>(this, int(face), mip, width, height, depth);
                mSurfaceList.push_back(buf);

                if (width > 1)
                    width = width / 2;
                if (height > 1)
                    height = height / 2;
                if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY)
                    depth = depth / 2;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.zookeeper.inspector.manager;

import java.util.Map;

/**
 * A Listener for Events on zookeeper nodes
 */
public interface NodeListener {
    /**
     * @param nodePath
     *            - the path of the node
     * @param eventType
     *            - the event type
     * @param eventInfo
     *            - a {@link Map} containing any other information about this
     *            event
     */
    public void processEvent(String nodePath, String eventType,
            Map<String, String> eventInfo);
}


text:
/**
 * Watches for changes to files, rebuilds if necessary, the reloads or restarts the electron-connect client
 */
let ecServerRunning = false;

export default (gulp, plugins, conf, isProd) => {
	if (isProd) {
		console.log('Cannot run watch with --production. Exiting...');
		return;
	}

	return () => {
		let ecServer = plugins.electronConnect.server.create({ stopOnClose: true });
		serverAction('start', ecServer);

		// watches for changes to the main.js and restarts the electron-connect browser
		gulp.watch(`${conf.paths.absRoot}index.html`, ['build', () => serverAction('restart', ecServer)])
			.on('change', reportChange);
		gulp.watch(`${conf.paths.absRoot}main.js`, ['build', () => serverAction('restart', ecServer)])
			.on('change', reportChange);

		// watches for changes to the css, hbs, or js and reloads the electron-connect renderer
		gulp.watch(conf.paths.js, ['build-js', () => serverAction('reload', ecServer)])
			.on('change', reportChange);
		gulp.watch(conf.paths.css, ['build-css', () => serverAction('reload', ecServer)])
			.on('change', reportChange);
		gulp.watch(conf.paths.hbs, ['build-hbs', () => serverAction('reload', ecServer)])
			.on('change', reportChange);
	};
};

//////////////////
// helpers

// listener for electron process changes, sent as callback to ecServer
function listener(state) {
	switch (state) {
		case 'stopped':
			ecServerRunning = false;
			break;

		case 'started':
			ecServerRunning = true;

		// no default
	}
}

// outputs changes to files to the console
function reportChange(event) {
	console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
}

// performs a server action (reload, restart, or start)
function serverAction(action, ecServer) {
	switch (action) {
		case 'reload':
		case 'restart':
			if (ecServerRunning) {
				ecServer[action]();
			} else {
				ecServer.start(listener);
			}
			break;

		case 'start':
			ecServer.start(listener);
			break;

		// 	no default
	}
}


text:
using namespace Exomnium;

Object * PostProcessing::m_screenFillingQuad           = nullptr;
SceneID  PostProcessing::m_screenFillingQuadShaderID   = 0;

//BLUR SHADER
SceneID  PostProcessing::m_gaussianBlur7x1ShaderID = 0;

//FXAA
SceneID  PostProcessing::m_fxaaShaderID = 0;

//SCREEN SPACE AMVIENT OCCLUSION
FBO *PostProcessing::m_ssaoFBO = nullptr;
SceneID PostProcessing::m_ssaoGenerationShaderID = 0;
SceneID PostProcessing::m_ssaoCompositingShaderID = 0;
std::vector<float> *PostProcessing::m_ssaoFlatKernel = nullptr;
Texture *PostProcessing::m_ssaoNoiseTexture = nullptr;
int PostProcessing::m_currentSsaoKernelSize = 0;

//SCREEN SPACE REFLECTIONS
SceneID PostProcessing::m_ssReflectionsShaderID        = 0;

void PostProcessing::applyTextureToTarget(Texture * textureSource, RenderTarget &destination)
{
    if (m_screenFillingQuadShaderID == 0)
    {
        m_screenFillingQuadShaderID = Scene::addShader(new Shader("PostProcessing/screenFillingQuad", 2, Exomnium::VERTEX_SHADER, Exomnium::FRAGMENT_SHADER));
    }

    if (!m_screenFillingQuad)
    {
        initSFQ();
    }

    destination.bindAsRenderTarget();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    Scene::activateShader(m_screenFillingQuadShaderID);

    Scene::getActiveShader().sendUniformTexture("renderTexture", textureSource, 0);
    m_screenFillingQuad->render();
}

//This method just does the rendering of the screen filling quad
//If this method should be used, the shader has to bound somewhere else and the uniforms have to be send from there too
void PostProcessing::renderScreenFillingQuad(RenderTarget &destination)
{
    if (!m_screenFillingQuad)
    {
        initSFQ();
    }

    destination.bindAsRenderTarget();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    m_screenFillingQuad->render();
}

void PostProcessing::applyGaussianBlur7x1(glm::fvec3 const & blurDirection, Texture * textureSource, RenderTarget & destination)
{
    if (m_gaussianBlur7x1ShaderID == 0)
    {
        m_gaussianBlur7x1ShaderID = Scene::addShader(new Shader("PostProcessing/gaussianBlur7x1", 2, Exomnium::VERTEX_SHADER, Exomnium::FRAGMENT_SHADER));
    }

    Scene::activateShader(m_gaussianBlur7x1ShaderID);
    Scene::getActiveShader().sendUniformTexture("renderTexture", textureSource, 0);
    Scene::getActiveShader().sendUniformVec3("blurDirection", blurDirection);

    renderScreenFillingQuad(destination);
}

void PostProcessing::applyFXAA(Texture * textureSource, RenderTarget &destination, float const & fxaaSpan, float const & fxaaMin, float const & fxaaMax)
{
    if (m_fxaaShaderID == 0)
    {
        m_fxaaShaderID = Scene::addShader(new Shader("PostProcessing/fxaa", 2, Exomnium::VERTEX_SHADER, Exomnium::FRAGMENT_SHADER));
    }

    if (!m_screenFillingQuad)
    {
        initSFQ();
    }

    destination.bindAsRenderTarget();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    Scene::activateShader(m_fxaaShaderID);

    Scene::getActiveShader().sendUniformTexture("inputTexture", textureSource, 0);
    Scene::getActiveShader().sendUniformVec3("inputTextureSize", glm::fvec3(
            1.0f / static_cast<float>(textureSource->getWidth()),
            1.0f / static_cast<float>(textureSource->getHeight()),
            0.0f)
        );

    Scene::getActiveShader().sendUniformFloat("fxaaSpanMax", fxaaSpan);
    Scene::getActiveShader().sendUniformFloat("fxaaReduceMin", fxaaMin);
    Scene::getActiveShader().sendUniformFloat("fxaaReduceMul", fxaaMax);

    m_screenFillingQuad->render();
}

void PostProcessing::applySSAO(glm::mat4 const & projection, Texture *positionTexture, Texture *normalTexture, Texture * depthTexture, Texture *colorTexture, RenderTarget &destination, SSAO_QUALITY quality)
{
    float kernelSize;
    float radius;

    if (quality == SSAO_QUALITY_LOW)
    {
        kernelSize = 8;
        radius = 0.5f;
    }

    else if (quality == SSAO_QUALITY_MEDIUM)
    {
        kernelSize = 16;
        radius = 0.5f;
    }

    else if (quality == SSAO_QUALITY_HIGH)
    {
        kernelSize = 32;
        radius = 0.5f;
    }

    if (m_ssaoGenerationShaderID == 0)
    {
        m_currentSsaoKernelSize = static_cast<unsigned int>(kernelSize);
        if (m_currentSsaoKernelSize > MAX_SSAO_KERNEL_SIZE)
        {
            m_currentSsaoKernelSize = MAX_SSAO_KERNEL_SIZE;
        }

        initSSAO(destination.getWidth(), destination.getHeight());
    }

    //Recreate the kernel, if the kernel size has changed
    else if(m_currentSsaoKernelSize != kernelSize)
    {
        m_currentSsaoKernelSize = static_cast<unsigned int>(kernelSize);
        if (m_currentSsaoKernelSize > MAX_SSAO_KERNEL_SIZE)
        {
            m_currentSsaoKernelSize = MAX_SSAO_KERNEL_SIZE;
        }

        int index = 0;
        m_ssaoFlatKernel->resize(m_currentSsaoKernelSize * 3);
        for (int i = 0; i < m_currentSsaoKernelSize; i++)
        {
            //sample positions only in unit hemisphere
            //sample position density higher at origin, so occlusion contribution is more intense from objects near to the origin of the current sample point
            glm::fvec3 newRandomVector = glm::normalize(glm::fvec3(
                glm::linearRand(-1.0f, 1.0f),
                glm::linearRand(-1.0f, 1.0f),
                glm::linearRand(0.0f, 1.0f)
                ));

            //scale current random vector distance from the origin. Distance falls of the more sample points are created
            float scale = static_cast<float>(i) / static_cast<float>(m_currentSsaoKernelSize);

            newRandomVector *= glm::fvec3(glm::lerp(0.1f, 1.0f, scale * scale));

            m_ssaoFlatKernel->at(index++) = newRandomVector.x;
            m_ssaoFlatKernel->at(index++) = newRandomVector.y;
            m_ssaoFlatKernel->at(index++) = newRandomVector.z;
        }
    }

    if (!m_screenFillingQuad)
        initSFQ();

    m_ssaoFBO->bindAsRenderTarget();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    Scene::activateShader(m_ssaoGenerationShaderID);
    Scene::getActiveShader().sendUniformTexture("positionTexture", positionTexture, 0);
    Scene::getActiveShader().sendUniformTexture("normalTexture", normalTexture, 1);
    Scene::getActiveShader().sendUniformTexture("noiseTexture", m_ssaoNoiseTexture, 2);

    Scene::getActiveShader().sendUniformVec2("noiseScale", glm::fvec2(
        static_cast<float>(destination.getWidth()) / static_cast<float>(m_ssaoNoiseTexture->getWidth()),
        static_cast<float>(destination.getHeight()) / static_cast<float>(m_ssaoNoiseTexture->getHeight())
        ));

    Scene::getActiveShader().sendUniformFloat("kernelSize", static_cast<float>(m_currentSsaoKernelSize));
    Scene::getActiveShader().sendUniformVec3FlatArray("sampleKernel", *m_ssaoFlatKernel);

    Scene::getActiveShader().sendUniformFloat("radius", radius);

    Scene::getActiveShader().sendUniformMat4("projectionMatrix", projection);

    m_screenFillingQuad->render();

    //DEBUG
    //applyTextureToTarget(m_ssaoFBO->getColorTexture(0), destination);

    destination.bindAsRenderTarget();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    Scene::activateShader(m_ssaoCompositingShaderID);

    Scene::getActiveShader().sendUniformTexture("colorTexture", colorTexture, 0);
    Scene::getActiveShader().sendUniformTexture("ssaoTexture", m_ssaoFBO->getColorTexture(0), 1);

    int width = m_ssaoNoiseTexture->getWidth();
    Scene::getActiveShader().sendUniformInt("blurSize", width);
    Scene::getActiveShader().sendUniformFloat("blurSizeSquared", static_cast<float>(width*width));

    m_screenFillingQuad->render();

}

void PostProcessing::applyScreenSpaceReflections(Texture *positionTexture, Texture *normalTexture, Texture * depthTexture, Texture *colorTexture, Texture * materialTexture, glm::mat4 const & projection, float const & zNear, float const & zFar, RenderTarget &destination, SSR_QUALITY quality)
{
    if (m_ssReflectionsShaderID == 0)
    {
        m_ssReflectionsShaderID = Scene::addShader(new Shader("PostProcessing/screenSpaceReflections", 2, Exomnium::VERTEX_SHADER, Exomnium::FRAGMENT_SHADER));
    }

    if (!m_screenFillingQuad)
    {
        initSFQ();
    }

    destination.bindAsRenderTarget();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    Scene::activateShader(m_ssReflectionsShaderID);

    Scene::getActiveShader().sendUniformTexture("positionTexture", positionTexture, 0);
    Scene::getActiveShader().sendUniformTexture("normalTexture", normalTexture, 1);
    Scene::getActiveShader().sendUniformTexture("depthTexture", depthTexture, 3);
    Scene::getActiveShader().sendUniformTexture("colorTexture", colorTexture, 2);
    Scene::getActiveShader().sendUniformTexture("materialTexture", materialTexture, 4);

    Scene::getActiveShader().sendUniformInt("windowWidth", positionTexture->getWidth());
    Scene::getActiveShader().sendUniformInt("windowHeight", positionTexture->getHeight());

    Scene::getActiveShader().sendUniformMat4("projectionMatrix", projection);
    Scene::getActiveShader().sendUniformFloat("zNear", zNear);
    Scene::getActiveShader().sendUniformFloat("zFar", zFar);

    float stepSize, stepRefine;
    int maxDepth, maxRefine;

    if (quality == SSR_QUALITY_LOW)
    {
        stepSize = 0.04f;
        stepRefine = 0.7f;
        maxDepth = 3;
        maxRefine = 10;
    }

    else if (quality == SSR_QUALITY_MEDIUM)
    {
        stepSize = 0.02f;
        stepRefine = 0.7f;
        maxDepth = 3;
        maxRefine = 10;
    }

    else if (quality == SSR_QUALITY_HIGH)
    {
        stepSize = 0.004f;
        stepRefine = 0.7f;
        maxDepth = 3;
        maxRefine = 10;
    }

    else
    {
        stepSize = 0.02f;
        stepRefine = 0.7f;
        maxDepth = 3;
        maxRefine = 10;
    }

    Scene::getActiveShader().sendUniformFloat("stepSize", stepSize);
    Scene::getActiveShader().sendUniformFloat("stepRefine", stepRefine);
    Scene::getActiveShader().sendUniformInt("maxDepth", maxDepth);
    Scene::getActiveShader().sendUniformInt("maxRefine", maxRefine);

    m_screenFillingQuad->render();
}

void PostProcessing::initSFQ()
{
    m_screenFillingQuad = new Object();

    //Create screen filling quad geometry
    Mesh *sfq_mesh = new Mesh();

    sfq_mesh->addVertex(glm::vec3(-1.f, -1.f, 0.f));
    sfq_mesh->addVertex(glm::vec3( 1.f, -1.f, 0.f));
    sfq_mesh->addVertex(glm::vec3( 1.f,  1.f, 0.f));
    sfq_mesh->addVertex(glm::vec3(-1.f,  1.f, 0.f));

    sfq_mesh->addTextureCoord(glm::vec2(0.f, 0.f));
    sfq_mesh->addTextureCoord(glm::vec2(1.f, 0.f));
    sfq_mesh->addTextureCoord(glm::vec2(1.f, 1.f));
    sfq_mesh->addTextureCoord(glm::vec2(0.f, 1.f));

    sfq_mesh->addIndex(0);
    sfq_mesh->addIndex(1);
    sfq_mesh->addIndex(2);

    sfq_mesh->addIndex(2);
    sfq_mesh->addIndex(3);
    sfq_mesh->addIndex(0);

    m_screenFillingQuad->Geometry(sfq_mesh);
}

void PostProcessing::initSSAO(unsigned int const & renderTargetWidth, unsigned int const & renderTargetHeight)
{
    m_ssaoFBO = new FBO(renderTargetWidth, renderTargetHeight, 1, true,false,true,GL_RGBA32F,GL_RGBA,FILTER_LINEAR,DATA_UNSIGNED_BYTE);

    //Create SSAO generation Shader
    m_ssaoGenerationShaderID = Scene::addShader(new Shader("PostProcessing/ssaoGeneration", 2, Exomnium::VERTEX_SHADER, Exomnium::FRAGMENT_SHADER));
    m_ssaoCompositingShaderID = Scene::addShader(new Shader("PostProcessing/ssaoCompositing", 2, Exomnium::VERTEX_SHADER, Exomnium::FRAGMENT_SHADER));
    m_ssaoFlatKernel = new std::vector<float>();

    unsigned int index = 0;
    m_ssaoFlatKernel->resize(m_currentSsaoKernelSize * 3);
    for (int i = 0; i < m_currentSsaoKernelSize; i++)
    {
        //sample positions only in unit hemisphere
        //sample position density higher at origin, so occlusion contribution is more intense from objects near to the origin of the current sample point
        glm::fvec3 newRandomVector = glm::normalize(glm::fvec3(
            glm::linearRand(-1.0f, 1.0f),
            glm::linearRand(-1.0f, 1.0f),
            glm::linearRand(0.0f, 1.0f)
            ));

        //scale current random vector distance from the origin. Distance falls of the more sample points are created
        float scale = static_cast<float>(i) / static_cast<float>(m_currentSsaoKernelSize);

        newRandomVector *= glm::fvec3(glm::lerp(0.1f, 1.0f, scale * scale));

        m_ssaoFlatKernel->at(index++) = newRandomVector.x;
        m_ssaoFlatKernel->at(index++) = newRandomVector.y;
        m_ssaoFlatKernel->at(index++) = newRandomVector.z;
    }

    //generate noise texture to rotate the sample kernel
    //Trick to "increase" the sample count and reduce bandwith artifacts
    const int NOISE_SIZE = 4;
    const int NOISE_SIZE_SQUARED = 16;

    std::vector<float> ssaoNoise = std::vector<float>();

    index = 0;
    for(int i = 0; i < NOISE_SIZE_SQUARED; i++)
    {
        glm::fvec3 newNoiseVector = glm::normalize(glm::fvec3(
                glm::linearRand(-1.0f,1.0f),
                glm::linearRand(-1.0f,1.0f),
                0.0f
            ));

        ssaoNoise.push_back(newNoiseVector.x);
        ssaoNoise.push_back(newNoiseVector.y);
        ssaoNoise.push_back(newNoiseVector.z);

    }

    //create texture - tile is repeated across the texture
    m_ssaoNoiseTexture = new Texture(GL_TEXTURE_2D, NOISE_SIZE, NOISE_SIZE,0,&ssaoNoise[0],GL_RGB8,GL_RGB,GL_NEAREST,GL_NEAREST,false,GL_FLOAT);
}


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

<title>tp</title>
<meta name="date" content="2017-11-13">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

tp

Classes

Tp


text:
<?
	$logRep = new KLogger('/var/www/yoursite/http/log/report/', KLogger::INFO);
?>
<?= getBoxTopImg("Edit Ladder Games", $boxheight, true, null, $box3Img, $box3Align); ?>
<? if (!isset($_POST['game_id0'])) { ?>

Please enter the teams used in these ladder games. If you're unsure, leave the team field empty.

<form method="post" name="editGames" action="<?= $_SERVER['PHP_SELF'] ?>">

<?

$sql = "SELECT * FROM $gamestable ".
  "WHERE sixGameId IS NOT NULL ".
  "AND edited=0 ".
  "AND deleted=0 ".
  "AND (winner='$cookie_name' OR loser='$cookie_name' OR winner2='$cookie_name' OR loser2='$cookie_name') ".
  "AND (winnerteam=0 OR loserteam=0) ".
  "AND season=".$season." ".
  "ORDER BY game_id ASC";

$logRep->logInfo('sixgamesForLadder: sql='.$sql);

$res = mysql_query($sql);
$index = 0;
while ($row = mysql_fetch_array($res)) {
  $id = $row['game_id'];
  $gamedate = formatTime($row['date']);
  $winner = $row['winner'];
  $winner2 = $row['winner2'];
  $loser = $row['loser'];
  $loser2 = $row['loser2'];
  $winnerteam = $row['winnerteam'];
  $loserteam = $row['loserteam'];
  $winnerresult = $row['winnerresult'];
  $loserresult = $row['loserresult'];
  $winnerTeamName = getTeamNameForId($winnerteam);
  $loserTeamName = getTeamNameForId($loserteam);
  $winTeamAlign = '';
  if ($winnerteam == 0) {
    $winnerTeamDisplay = '<input type="text" align="right" class="width150" style="font-size:10px" id="winTeam'.$index.'" name="winTeam'.$index.'" '.
      'value="'.$winnerTeamName.'" autocomplete="off">'.
      '
'."\n".
      ''."\n";
  } else {
    $winnerTeamDisplay = $winnerTeamName.'<input type="hidden" id="winTeam'.$index.'" name="winTeam'.$index.'" '.
      'value="'.$winnerTeamName.'">';
    $winTeamAlign = ' align="right"';
  }
  if ($loserteam == 0) {
    $loserTeamDisplay = '<input type="text" align="right" class="width150" style="font-size:10px" id="loseTeam'.$index.'" name="loseTeam'.$index.'" '.
      'value="'.$loserTeamName.'" autocomplete="off">'.
      '
'."\n".
      ''."\n";
  } else {
    $loserTeamDisplay = $loserTeamName.'<input type="hidden" id="loseTeam'.$index.'" name="loseTeam'.$index.'" '.
      'value="'.$loserTeamName.'">';
  }

  if (!empty($winner2)) {
    $winnerdisplay = ''.$winner.''.
      '–'.
      ''.$winner2.'';
  } else {
    $winnerdisplay = ''.$winner.'';
  }
  if (!empty($loser2)) {
    $loserdisplay = ''.$loser.''.
      '–'.
      ''.$loser2.'';
  } else {
    $loserdisplay = ''.$loser.'';
  }
  ?>

    <?= $gamedate ?>
    <?= $winnerdisplay ?>
    <td class="shrink"<?= $winTeamAlign ?>><?= $winnerTeamDisplay ?>
    <?= $winnerresult ?>
    -
    <?= $loserresult ?>
    <?= $loserTeamDisplay ?>

      <?= $loserdisplay ?>
      <input type="hidden" name="game_id<?= $index ?>" value="<?= $id ?>" />

  <?
  $index++;
} // while
?>

  <input type="Submit" class="width100" name="submit" value="Save this!" />

</form>
<?
} else {
  $index = 0;
  while (isset($_POST['game_id'.$index])) {
    $game_id = mysql_real_escape_string($_POST['game_id'.$index]);
    $winTeamName = mysql_real_escape_string($_POST['winTeam'.$index]);
    $loseTeamName = mysql_real_escape_string($_POST['loseTeam'.$index]);

    $logRep->logInfo('index='.$index.' game_id='.$game_id.' winTeamName='.$winTeamName.' loseTeamName='.$loseTeamName);

    // get ladder team id for selected name
    $result = mysql_query("SELECT id FROM ".$teamstable." WHERE name = '".mysql_real_escape_string($winTeamName)."'");
		if (mysql_num_rows($result) != 1) {
       $winTeamId = 0;
    } else {
      $row = mysql_fetch_array($result);
      $winTeamId = $row[0];
    }

    // get ladder team id for selected name
    $result = mysql_query("SELECT id FROM ".$teamstable." WHERE name = '".mysql_real_escape_string($loseTeamName)."'");
		if (mysql_num_rows($result) != 1) {
       $loseTeamId = 0;
    } else {
      $row = mysql_fetch_array($result);
      $loseTeamId = $row[0];
    }

    // update current ladder game
    $sql = "UPDATE $gamestable SET winnerteam='$winTeamId', loserteam='$loseTeamId', edited=1 WHERE game_id = $game_id";
    $result = mysql_query($sql);

    $logRep->logInfo('sql='.$sql.' affected='.mysql_affected_rows());

    UpdateLadderGamePoints($game_id, $logRep);

    // Insert teams
    if ($winTeamId > 0 || $loseTeamId > 0) {
      $sql = "SELECT sm.*, sp1.id AS patchIdHome, sp2.id AS patchIdAway, wg.winner, wg.winner2, wg.sixGameId ".
        "FROM weblm_games wg ".
        "LEFT JOIN six_matches sm ON sm.id=wg.sixGameId ".
        "LEFT JOIN six_patches sp1 ON sp1.hash=sm.hashHome ".
        "LEFT JOIN six_patches sp2 ON sp2.hash=sm.hashAway ".
        "WHERE wg.game_id=".$game_id;
      $row = mysql_fetch_array(mysql_query($sql));

      $logRep->logInfo('sql='.$sql.' affected='.mysql_affected_rows());

      $scoreHome = $row['score_home'];
      $scoreAway = $row['score_away'];

      if ($scoreHome < $scoreAway) {
        $sixTeamIdWinner = $row['team_id_away'];
        $sixTeamIdLoser = $row['team_id_home'];
        $patchIdWinner = $row['patchIdAway'];
        $patchIdLoser = $row['patchIdHome'];
      } elseif ($scoreHome > $scoreAway) {
        $sixTeamIdWinner = $row['team_id_home'];
        $sixTeamIdLoser = $row['team_id_away'];
        $patchIdWinner = $row['patchIdHome'];
        $patchIdLoser = $row['patchIdAway'];
      } else {
        // draw could have been flipped
        $winner = $row['winner'];
        $winner2 = $row['winner2'];
        $sixGameId = $row['sixGameId'];

        $winnerIsHome = false;

        $sql = "SELECT wp.name FROM weblm_players wp ".
          "LEFT JOIN six_profiles sp ON sp.user_id=wp.player_id ".
          "LEFT JOIN six_matches_played smp ON smp.profile_id=sp.id ".
          "WHERE smp.match_id=".$sixGameId." AND smp.home=1";
        $drawRes = mysql_query($sql);

        $logRep->logInfo('DrawFlip: sql='.$sql.' affected='.mysql_affected_rows());

        while ($drawRow = mysql_fetch_array($drawRes)) {
          $homeName = $drawRow['name'];
          if ($homeName == $winner || $homeName == $winner2) {
            $winnerIsHome = true;
          }
        }

        $logRep->logInfo('DrawFlip: winnerIsHome='.$winnerIsHome);

        if ($winnerIsHome) {
          $sixTeamIdWinner = $row['team_id_home'];
          $sixTeamIdLoser = $row['team_id_away'];
          $patchIdWinner = $row['patchIdHome'];
          $patchIdLoser = $row['patchIdAway'];
        } else {
          $sixTeamIdWinner = $row['team_id_away'];
          $sixTeamIdLoser = $row['team_id_home'];
          $patchIdWinner = $row['patchIdAway'];
          $patchIdLoser = $row['patchIdHome'];
        }
      }

      $logRep->logInfo('sixTeamIdWinner='.$sixTeamIdWinner.' sixTeamIdLoser='.$sixTeamIdLoser.' patchIdWinner='.$patchIdWinner.' patchIdLoser='.$patchIdLoser);

      if ($winTeamId > 0) {
        InsertTeamAndUpdate($patchIdWinner, $sixTeamIdWinner, $winTeamId, $logRep, $season, $cookie_name);
      }
      if ($loseTeamId > 0) {
        InsertTeamAndUpdate($patchIdLoser, $sixTeamIdLoser, $loseTeamId, $logRep, $season, $cookie_name);
      }
    } // if: insert teams
    $index++;
  } // while: next game
  echo '
Updated '.($index).' ladder game(s).  [Close]
';
} // else: form submitted

?>
<?= getBoxBottom() ?>
<?

function UpdateLadderGamePoints($game_id, $logRep) {

  $logRep->logInfo('UpdateLadderGamePoints: game_id='.$game_id);

  $sql = "SELECT * FROM weblm_games WHERE game_id = '$game_id'";

  $logRep->logInfo('UpdateLadderGamePoints: sql='.$sql);

  $result = mysql_query($sql);
  $row = mysql_fetch_array($result);

  $draw = $row['isDraw'];
  $teamBonusOld = $row['teamBonus'];
  $winpoints = $row['winpoints'];
  $winner = $row['winner'];
  $winner2 = $row['winner2'];
  $sixGameId = $row['sixGameId'];
  $winTeamId = $row['winnerteam'];
  $loseTeamId = $row['loserteam'];

  $teamBonusNewArray = getTeamBonus($winTeamId, $loseTeamId, $draw, $winpoints-$teamBonusOld);
  $teamBonusNew = $teamBonusNewArray['bonusWinner'];

  $logRep->logInfo('UpdateLadderGamePoints: teamBonusNewArray[msg]='.$teamBonusNewArray['msg'].' teamBonusOld='.$teamBonusOld.' teamBonusNew='.$teamBonusNew);

  if ($teamBonusOld != $teamBonusNew) {
    $teamBonusDiff = $teamBonusNew - $teamBonusOld;

    $sql = "UPDATE weblm_games SET winpoints=winpoints+$teamBonusDiff, ".
      "teamBonus='$teamBonusNew' WHERE game_id=$game_id";
    $result = mysql_query($sql);

    $logRep->logInfo('UpdateLadderGamePoints: sql='.$sql.' affected='.mysql_affected_rows());

    $pointsField = getPointsFieldForVersion('H'); // PES6 PC

    $sql = "SELECT $pointsField from weblm_players where name = '$winner'";
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
    $pointsOld = $row[$pointsField];
    $pointsNew = $pointsOld + $teamBonusDiff;
    if ($pointsNew < 0) {
      $pointsNew = 0;
    }

    $sql = "UPDATE weblm_players SET $pointsField = $pointsNew WHERE name = '$winner'";
    $result = mysql_query($sql);

    $logRep->logInfo('UpdateLadderGamePoints: sql='.$sql.' affected='.mysql_affected_rows());

    if (!empty($winner2)) {
      $sql = "SELECT $pointsField FROM weblm_players WHERE name = '$winner2'";
      $result = mysql_query($sql);
      $row = mysql_fetch_array($result);
      $pointsOld = $row[$pointsField];
      $pointsNew = $pointsOld + $teamBonusDiff;
      if ($pointsNew < 0) {
        $pointsNew = 0;
      }

      $sql = "UPDATE weblm_players SET $pointsField=$pointsNew WHERE name='$winner2'";
      $result = mysql_query($sql);

      $logRep->logInfo('UpdateLadderGamePoints: sql='.$sql.' affected='.mysql_affected_rows());
    }
  }
}

?>


text:
require 'test_helper'

class GameplayTest < ActionDispatch::IntegrationTest
  def login_user(user = users(:default))
    visit new_user_session_url

    within 'form#new_user' do
      fill_in 'user_email', with: user.email
      fill_in 'user_password', with: '1234567890'
      click_on 'Sign in'
    end
  end

  test "After being logged in, you can view all games" do
    login_user
    visit games_url

    assert 200 == page.status_code
    assert has_link? 'Start a New Game', 'Should have a link to create a new game'
  end

  test "If not logged in, redirect to login page" do
    visit games_url

    assert 200 == page.status_code
    assert has_selector? 'body .container h2', text: 'Sign in'
  end

  teardown do
    visit root_url
    click_link 'Sign Out' if has_link? 'Sign Out'
  end
end


text:
namespace PokerTell.Statistics.Interfaces
{
    using System.Collections.Generic;

    using PokerTell.Infrastructure.Interfaces.Statistics;

    using Tools.Interfaces;

    public interface IStatisticsTableViewModel : IDetailedStatisticsAnalyzerContentViewModel
    {
        /// <summary>
        ///   Indicates the values in the the columnheaders
        /// </summary>
        string ColumnHeaderTitle { get; }

        IEnumerable<IStatisticsTableRowViewModel> Rows { get; }

        IList<ITuple<int, int>> SelectedCells { get; }

        /// <summary>
        /// Describes the situation and player of the statistics
        /// </summary>
        string StatisticsDescription { get; }

        List<ITuple<int, int>> SavedSelectedCells { get; }

        /// <summary>
        /// Gives a hint on how to interpret the statistics, e.g. what the RaiseSizes indicate
        /// </summary>
        string StatisticsHint { get; }

        bool ShowStatisticsInformationPanel { get; set; }

        IStatisticsTableViewModel AddToSelection(int row, int column);

        void ClearSelection();

        /// <summary>
        /// Saves the selected cells into SavedSelectedCells e.g. when the data grid is unloading
        /// </summary>
        void SaveSelectedCells();
    }
}


text:
/*----------------------------------------------------------------
 *  Author:        Samuel Miravet-Verde
 *  Written:       09/25/2015
 *  Last updated:  09/25/2015
 *
 *  Compilation:   javac ex22.java
 *  Execution:     java ex22 x0 v0 t
 *
 *  Program that takes three double values x0, v0, and t from the command
 *  line and prints the value of x0 + v0*t + 1/2 gt^2, where g is the constant
 *  9.800722 m/s^2. (Note : This value the displacement in meters after t seconds
 *  when an object is thrown straight up from initial position x0 at velocity
 *  v0 meters per second.)
 *
 *  ****************************************************************************/

public class ex22 {

    public static void main(String[] args) {

        double x0 = Double.parseDouble(args[0]);
        double v0 = Double.parseDouble(args[1]);
        double t = Double.parseDouble(args[2]);
        double g = 9.80665;

        System.out.println( x0 + v0*t + (1/2) * g * (Math.pow(t, 2)));
    }
}


text:
function EmailChooserChange(select)
{
	var visibility = select.options[select.selectedIndex].className;
	var children = document.getElementById(select.id + "_children");

	children.style.display = visibility;
}

window.addEvent('domready',
function()
{
	selects = document.getElementsByTagName('select');

	for (var i = 0; i < selects.length; ++i)
	{
		var select = selects[i];
		if (select.getAttribute('class') == 'b2jemailchooser')
		{
			select.onchange(select);
		}
	}
});


text:
@interface FSTPoultryChickenBoneInSousVideRecipe : FSTPoultrySousVideRecipe

@end


text:
namespace downgrade {

namespace {

bool g_snapshots_enabled_for_testing = false;

// Moves the contents of a User Data directory at |source| to |target|, with the
// exception of files/directories that should be left behind for a full data
// wipe. Returns no value if the target directory could not be created, or the
// number of items that could not be moved.
void MoveUserData(const base::FilePath& source, const base::FilePath& target) {
  // Returns true to exclude a file.
  auto exclusion_predicate =
      base::BindRepeating([](const base::FilePath& name) -> bool {
        // TODO(ydago): Share constants instead of hardcoding values here.
        static constexpr base::FilePath::StringPieceType kFilesToKeep[] = {
            FILE_PATH_LITERAL("browsermetrics"),
            FILE_PATH_LITERAL("crashpad"),
            FILE_PATH_LITERAL("first run"),
            FILE_PATH_LITERAL("last version"),
            FILE_PATH_LITERAL("lockfile"),
            FILE_PATH_LITERAL("snapshots"),
            FILE_PATH_LITERAL("stability"),
        };
        // Don't try to move the dir into which everything is being moved.
        if (name.FinalExtension() == kDowngradeDeleteSuffix)
          return true;
        return std::find_if(std::begin(kFilesToKeep), std::end(kFilesToKeep),
                            [&name](const auto& keep) {
                              return base::EqualsCaseInsensitiveASCII(
                                  name.value(), keep);
                            }) != std::end(kFilesToKeep);
      });
  auto result = MoveContents(source, target, std::move(exclusion_predicate));

  // Move the Last Version file last so that any crash before this point results
  // in a retry on the next launch.
  if (!result ||
      !MoveWithoutFallback(source.Append(kDowngradeLastVersionFile),
                           target.Append(kDowngradeLastVersionFile))) {
    // Attempt to delete Last Version if all else failed so that Chrome does not
    // continually attempt to perform a migration.
    base::DeleteFile(source.Append(kDowngradeLastVersionFile));
    // Inform system administrators that things have gone awry.
    SYSLOG(ERROR) << "Failed to perform User Data migration following a Chrome "
                     "version downgrade. Chrome will run with User Data from a "
                     "higher version and may behave unpredictably.";
    // At this point, Chrome will relaunch with --user-data-migrated. This
    // switch suppresses downgrade processing, so that launch will go through
    // normal startup.
  }
}

// Renames |disk_cache_dir| in its containing folder. If that fails, an attempt
// is made to move its contents.
void MoveCache(const base::FilePath& disk_cache_dir) {
  // A cache dir at the root of a volume is not supported.
  const base::FilePath parent = disk_cache_dir.DirName();
  if (parent == disk_cache_dir)
    return;

  // Move the cache within its parent directory from, for example, CacheDir
  // to CacheDir.CHROME_DELETE.
  const base::FilePath target =
      GetTempDirNameForDelete(parent, disk_cache_dir.BaseName());

  // A simple move succeeds in approx 2/3 of attempts.
  if (MoveWithoutFallback(disk_cache_dir, target))
    return;

  // The directory couldn't be moved whole-hog. Attempt a recursive move of its
  // contents. This succeeds in nearly all cases.
  MoveContents(disk_cache_dir, target, ExclusionPredicate());
}

// Deletes all subdirectories in |dir| named |name|*.CHROME_DELETE.
void DeleteAllRenamedUserDirectories(const base::FilePath& dir,
                                     const base::FilePath& name) {
  base::FilePath::StringType pattern = base::StrCat(
      {name.value(), FILE_PATH_LITERAL("*"), kDowngradeDeleteSuffix});
  base::FileEnumerator enumerator(dir, false, base::FileEnumerator::DIRECTORIES,
                                  pattern);
  for (base::FilePath to_delete = enumerator.Next(); !to_delete.empty();
       to_delete = enumerator.Next()) {
    base::DeletePathRecursively(to_delete);
  }
}

// Deletes all moved User Data, Snapshots and Cache directories for the given
// dirs.
void DeleteMovedUserData(const base::FilePath& user_data_dir,
                         const base::FilePath& disk_cache_dir) {
  DeleteAllRenamedUserDirectories(user_data_dir, user_data_dir.BaseName());
  DeleteAllRenamedUserDirectories(user_data_dir, base::FilePath(kSnapshotsDir));

  // Prior to Chrome M78, User Data was moved to a new name under its parent. In
  // that case, User Data at a volume's root was unsupported.
  base::FilePath parent = user_data_dir.DirName();
  if (parent != user_data_dir)
    DeleteAllRenamedUserDirectories(parent, user_data_dir.BaseName());

  if (!disk_cache_dir.empty()) {
    // Cache dir at a volume's root is unsupported.
    parent = disk_cache_dir.DirName();
    if (parent != disk_cache_dir)
      DeleteAllRenamedUserDirectories(parent, disk_cache_dir.BaseName());
  }
}

bool UserDataSnapshotEnabled() {
  return g_snapshots_enabled_for_testing ||
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
         base::IsEnterpriseDevice() ||
#endif
         policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().is_valid();
}

#if BUILDFLAG(IS_WIN)
bool IsAdministratorDrivenDowngrade(uint16_t current_milestone) {
  const auto downgrade_version = InstallUtil::GetDowngradeVersion();
  return downgrade_version &&
         downgrade_version->components()[0] > current_milestone;
}
#endif

}  // namespace

bool DowngradeManager::PrepareUserDataDirectoryForCurrentVersion(
    const base::FilePath& user_data_dir) {
  DCHECK_EQ(type_, Type::kNone);
  DCHECK(!user_data_dir.empty());

  // Do not attempt migration if this process is the product of a relaunch from
  // a previous in which migration was attempted/performed.
  auto& command_line = *base::CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kUserDataMigrated)) {
    // Strip the switch from the command line so that it does not propagate to
    // any subsequent relaunches.
    command_line.RemoveSwitch(switches::kUserDataMigrated);
    return false;
  }

  absl::optional<base::Version> last_version = GetLastVersion(user_data_dir);
  if (!last_version)
    return false;

  const base::Version& current_version = version_info::GetVersion();

  const bool user_data_snapshot_enabled = UserDataSnapshotEnabled();

  if (!user_data_snapshot_enabled) {
    if (current_version >= *last_version)
      return false;  // Same version or upgrade.

    type_ = GetDowngradeType(user_data_dir, current_version, *last_version);
    DCHECK(type_ == Type::kAdministrativeWipe || type_ == Type::kUnsupported);
    base::UmaHistogramEnumeration("Downgrade.Type", type_);
    return type_ == Type::kAdministrativeWipe;
  }

  if (current_version == *last_version)
    return false;  // Nothing to do if the version has not changed.

  if (current_version < *last_version) {
    type_ = GetDowngradeTypeWithSnapshot(user_data_dir, current_version,
                                         *last_version);
    if (type_ != Type::kNone)
      base::UmaHistogramEnumeration("Downgrade.Type", type_);

    return type_ == Type::kAdministrativeWipe ||
           type_ == Type::kSnapshotRestore;
  }

  auto current_milestone = current_version.components()[0];
  int max_number_of_snapshots = g_browser_process->local_state()->GetInteger(
      prefs::kUserDataSnapshotRetentionLimit);
  absl::optional<uint32_t> purge_milestone;
  if (current_milestone == last_version->components()[0]) {
    // Mid-milestone snapshots are only taken on canary installs.
    if (chrome::GetChannel() != version_info::Channel::CANARY)
      return false;
    // Keep one snapshot in this milestone unless snapshots are disabled.
    max_number_of_snapshots = std::min(max_number_of_snapshots, 1);
    purge_milestone = current_milestone;
  }
  SnapshotManager snapshot_manager(user_data_dir);
  snapshot_manager.TakeSnapshot(*last_version);
  snapshot_manager.PurgeInvalidAndOldSnapshots(max_number_of_snapshots,
                                               purge_milestone);
  return false;
}

void DowngradeManager::UpdateLastVersion(const base::FilePath& user_data_dir) {
  DCHECK(!user_data_dir.empty());
  DCHECK_NE(type_, Type::kAdministrativeWipe);
  const base::StringPiece version(PRODUCT_VERSION);
  base::WriteFile(GetLastVersionFile(user_data_dir), version.data(),
                  version.size());
}

void DowngradeManager::DeleteMovedUserDataSoon(
    const base::FilePath& user_data_dir) {
  DCHECK(!user_data_dir.empty());
  // IWYU note: base/location.h and base/task/task_traits.h are guaranteed to be
  // available via base/task/thread_pool.h.
  content::BrowserThread::PostBestEffortTask(
      FROM_HERE,
      base::ThreadPool::CreateTaskRunner(
          {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
           base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}),
      base::BindOnce(&DeleteMovedUserData, user_data_dir, GetDiskCacheDir()));
}

void DowngradeManager::ProcessDowngrade(const base::FilePath& user_data_dir) {
  DCHECK(type_ == Type::kAdministrativeWipe || type_ == Type::kSnapshotRestore);
  DCHECK(!user_data_dir.empty());

  const base::FilePath disk_cache_dir(GetDiskCacheDir());
  if (!disk_cache_dir.empty())
    MoveCache(disk_cache_dir);

  // User Data requires special treatment, as certain files/directories should
  // be left behind. Furthermore, User Data is moved to a new directory within
  // itself (for example, to User Data/User Data.CHROME_DELETE) to guarantee
  // that the movement isn't across volumes.
  // This has a 95% success rate according to the histogram
  // "Downgrade.UserDataDirMove.Result" which is acceptable in this case since
  // the files (usually under 5 files according to
  // "Downgrade.UserDataDirMove.FailureCount") left behind 5% of the time might
  // be overridden by `SnapshotManager::RestoreSnapshot` or updated following a
  // version upgrade.
  MoveUserData(user_data_dir, GetTempDirNameForDelete(
                                  user_data_dir, user_data_dir.BaseName()));

  if (type_ == Type::kSnapshotRestore) {
    SnapshotManager snapshot_manager(user_data_dir);
    snapshot_manager.RestoreSnapshot(version_info::GetVersion());
  }

  // Add the migration switch to the command line so that it is propagated to
  // the relaunched process. This is used to prevent a relaunch bomb in case of
  // pathological failure.
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kUserDataMigrated);
}

// static
void DowngradeManager::EnableSnapshotsForTesting(bool enable) {
  g_snapshots_enabled_for_testing = enable;
}

// static
DowngradeManager::Type DowngradeManager::GetDowngradeType(
    const base::FilePath& user_data_dir,
    const base::Version& current_version,
    const base::Version& last_version) {
  DCHECK(!user_data_dir.empty());
  DCHECK_LT(current_version, last_version);

#if BUILDFLAG(IS_WIN)
  // Move User Data aside for a clean launch if it follows an
  // administrator-driven downgrade.
  if (IsAdministratorDrivenDowngrade(current_version.components()[0]))
    return Type::kAdministrativeWipe;
#endif
    return Type::kUnsupported;
}

// static
DowngradeManager::Type DowngradeManager::GetDowngradeTypeWithSnapshot(
    const base::FilePath& user_data_dir,
    const base::Version& current_version,
    const base::Version& last_version) {
  DCHECK(!user_data_dir.empty());
  DCHECK_LT(current_version, last_version);

  const uint16_t milestone = current_version.components()[0];

  // Move User Data and restore from a snapshot if there is a candidate
  // snapshot to restore.
  const auto snapshot_to_restore =
      GetSnapshotToRestore(current_version, user_data_dir);

#if BUILDFLAG(IS_WIN)
  // Move User Data aside for a clean launch if it follows an
  // administrator-driven downgrade when no snapshot is found.
  if (!snapshot_to_restore && IsAdministratorDrivenDowngrade(milestone))
    return Type::kAdministrativeWipe;
#endif

  const uint16_t last_milestone = last_version.components()[0];
  if (last_milestone > milestone)
    return snapshot_to_restore ? Type::kSnapshotRestore : Type::kUnsupported;

  return Type::kMinorDowngrade;
}

}  // namespace downgrade


text:
package com.door.coolweather.util;

/**
 * Created by Door on 2015/10/17.
 */
public interface HttpCallbackListner {
    void onFinish(String response);
    void onError(Exception e);
}


text:
<?php

class Foo_Bar_Issue684Test extends PHPUnit_Framework_TestCase
{

}


text:
package org.hibernate.engine.jdbc.batch.internal;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

import org.hibernate.engine.jdbc.batch.spi.BatchKey;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.internal.CoreMessageLogger;
import org.jboss.logging.Logger;

/**
 * An implementation of {@link org.hibernate.engine.jdbc.batch.spi.Batch} which does not perform batching.  It simply
 * executes each statement as it is encountered.
 *
 * @author Steve Ebersole
 */
public class NonBatchingBatch extends AbstractBatchImpl {

	private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, NonBatchingBatch.class.getName() );

	private JdbcCoordinator jdbcCoordinator;

	protected NonBatchingBatch(BatchKey key, JdbcCoordinator jdbcCoordinator) {
		super( key, jdbcCoordinator );
		this.jdbcCoordinator = jdbcCoordinator;
	}

	@Override
	public void addToBatch() {
		notifyObserversImplicitExecution();
		for ( Map.Entry<String,PreparedStatement> entry : getStatements().entrySet() ) {
			try {
				final PreparedStatement statement = entry.getValue();
				final int rowCount = jdbcCoordinator.getResultSetReturn().executeUpdate( statement );
				getKey().getExpectation().verifyOutcome( rowCount, statement, 0 );
				jdbcCoordinator.release( statement );
			}
			catch ( SQLException e ) {
				LOG.debug( "SQLException escaped proxy", e );
				throw sqlExceptionHelper().convert( e, "could not execute batch statement", entry.getKey() );
			}
		}
		getStatements().clear();
	}

	@Override
	protected void doExecuteBatch() {
		// nothing to do
	}
}


text:
<html>
	<head>
		<title>TestSuite for sap.ui.core: GTP testcase CORE/BOOTSTRAP</title>
		<script src="../../../../../../resources/sap/ui/qunit/qunit-redirect.js"></script>
		<script>

		/**
		 * Add test pages to this test suite function.
		 * Please order alphabetically
		 */
		function suite() {
			var suite = new parent.jsUnitTestSuite();
			var contextPath = "/" + window.location.pathname.split("/")[1];
			suite.addTestPage(contextPath + "/test-resources/sap/ui/core/qunit/jquery.sap.global-compat.qunit.html");
			suite.addTestPage(contextPath + "/test-resources/sap/ui/core/qunit/jquery.sap.stubs.qunit.html");
			suite.addTestPage(contextPath + "/test-resources/sap/ui/core/qunit/jquery.sap.stubs-async.qunit.html");
			return suite;
		}

		</script>
	</head>
	<body>
	</body>
</html>


text:
{-# LANGUAGE CPP, RecordWildCards #-}

{-|
Module      : Language.C.Preprocessor.Remover.Internal.Preprocess
Description : Call GHC.preprocess at the Cpp phase
Copyright   : (c) Carlo Nucera, 2016
License     : BSD3
Maintainer  : meditans@gmail.com
Stability   : experimental
Portability : POSIX
-}

module Language.C.Preprocessor.Remover.Internal.Preprocess
   (
   -- * Entry point for parsing
     parseModuleWithCpp
   -- * Wrapper around GHC's preprocess
   , getPreprocessedSrcDirect
   ) where

import Control.Monad               (void)
import Data.Tuple.Extra            (fst3)
import Lens.Micro
import Language.C.Preprocessor.Remover.Internal.Types

#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>))
#endif

import qualified DriverPhases   as GHC
import qualified DriverPipeline as GHC
import qualified DynFlags       as GHC
import qualified GHC
import qualified GHC.Paths      as GHC
import qualified HeaderInfo     as GHC
import qualified HscTypes       as GHC
import qualified MonadUtils     as GHC

# if __GLASGOW_HASKELL__ >= 800
import qualified Language.Haskell.TH.LanguageExtensions as LE
# endif

--------------------------------------------------------------------------------
-- Entry point for parsing
--------------------------------------------------------------------------------

-- | Parse a module with specific instructions for the C pre-processor.
parseModuleWithCpp :: CppOptions -> FilePath -> IO String
parseModuleWithCpp cppOptions file = GHC.runGhc (Just GHC.libdir) $ do
  dflags <- initDynFlags file
#if __GLASGOW_HASKELL__ >= 800
  let useCpp = GHC.xopt LE.Cpp dflags
#else
  let useCpp = GHC.xopt GHC.Opt_Cpp dflags
#endif
  if useCpp
    then getPreprocessedSrcDirect cppOptions file
    else GHC.liftIO (readFile file)

-- | Given a config and a file, this function returns the correct dynFlags. For
-- now, this is only used to check if the Cpp extension is enabled (see the test
-- in parseModuleWithCpp), and thus it could be implemented differently. I'm
-- keeping this version to have all the flags, in case I decide later to offer
-- an entry point for ghc-api based analysis.
initDynFlags :: GHC.GhcMonad m => FilePath -> m GHC.DynFlags
initDynFlags file = do
  dflags0  <- GHC.getSessionDynFlags
  src_opts <- GHC.liftIO $ GHC.getOptionsFromFile dflags0 file
  dflags1  <- fst3 <$> GHC.parseDynamicFilePragma dflags0 src_opts
  let dflags2 = dflags1 {GHC.log_action = GHC.defaultLogAction}
  void $ GHC.setSessionDynFlags dflags2
  return dflags2

--------------------------------------------------------------------------------
-- Wrapper around GHC's preprocess
--------------------------------------------------------------------------------

-- | Invoke GHC's 'GHC.preprocess' function at the cpp phase, adding the
-- options specified in the first argument.
getPreprocessedSrcDirect :: GHC.GhcMonad m => CppOptions -> FilePath -> m String
getPreprocessedSrcDirect cppOptions file = do
  hscEnv <- injectCppOptions cppOptions <$> GHC.getSession
  (_, tempFile) <- GHC.liftIO $ GHC.preprocess hscEnv (file, cppPhase)
  GHC.liftIO (readFile tempFile)
  where
    cppPhase = Just (GHC.Cpp GHC.HsSrcFile)

injectCppOptions :: CppOptions -> GHC.HscEnv -> GHC.HscEnv
injectCppOptions CppOptions{..} = over (_hsc_dflags . _settings . _sOpt_P)
                                       (encodedOptions ++)
  where
    encodedOptions = map ("-D" ++) cppDefine
                  ++ map ("-I" ++) cppInclude
                  ++ map ("-include" ++) cppFile

--------------------------------------------------------------------------------
-- Some lenses to manipulate conveniently a HscEnv value
--------------------------------------------------------------------------------

_hsc_dflags :: Lens' GHC.HscEnv GHC.DynFlags
_hsc_dflags = lens GHC.hsc_dflags
                   (\hscEnv dynFlags -> hscEnv {GHC.hsc_dflags = dynFlags})

_settings :: Lens' GHC.DynFlags GHC.Settings
_settings = lens GHC.settings
                 (\dynFlags setting -> dynFlags {GHC.settings = setting})

_sOpt_P :: Lens' GHC.Settings [String]
_sOpt_P = lens GHC.sOpt_P
               (\setting strings -> setting {GHC.sOpt_P = strings})


text:
/*jshint globalstrict:false, strict:false, maxlen: 500 */
/*global assertEqual, assertTrue, AQL_EXPLAIN, AQL_EXECUTE, AQL_EXECUTEJSON */

////////////////////////////////////////////////////////////////////////////////
/// @brief tests for optimizer rules
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");
var helper = require("@arangodb/aql-helper");
var isEqual = helper.isEqual;
var db = require("@arangodb").db;
var _ = require("lodash");

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function optimizerRuleTestSuite () {
  var ruleName = "interchange-adjacent-enumerations";

  // various choices to control the optimizer:
  var paramNone     = { optimizer: { rules: [ "-all" ] } };
  var paramEnabled  = { optimizer: { rules: [ "-all", "+" + ruleName ] } };
  var paramDisabled = { optimizer: { rules: [ "+all", "-" + ruleName ] } };

  var collection = null;
  var collectionName = "UnitTestsAhuacatlOptimizer";

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUpAll : function () {
      db._drop(collectionName);
      collection = db._create(collectionName);

      for (var i = 0; i < 10; ++i) {
        collection.save({ value: i });
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDownAll : function () {
      db._drop(collectionName);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test that rule has no effect when explicitly disabled
////////////////////////////////////////////////////////////////////////////////

    testRuleDisabled : function () {
      var queries = [
        "FOR i IN " + collectionName + " FOR j IN " + collectionName + " RETURN 1",
        "FOR j IN " + collectionName + " FILTER j.i == 1 FOR i IN " + collectionName + " RETURN j"
      ];

      var opts = _.clone(paramNone);
      opts.allPlans = true;
      opts.verbosePlans = true;

      queries.forEach(function(query) {
        var result = AQL_EXPLAIN(query, { }, opts);
        result.plans.forEach(function(plan) {
          assertEqual([ "scatter-in-cluster" ], plan.rules);
        });
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test that rule has no effect
////////////////////////////////////////////////////////////////////////////////

    testRuleNoEffect : function () {
      var queries = [
        "FOR i IN 1..10 RETURN i",
        "FOR i IN " + collectionName + " RETURN i",
        "FOR i IN " + collectionName + " FILTER i == 1 FOR j IN " + collectionName + " RETURN i",
        "FOR i IN " + collectionName + " LIMIT 1 FOR j IN " + collectionName + " RETURN i",
        "FOR i IN " + collectionName + " RETURN (FOR j IN " + collectionName + " RETURN j)"
      ];

      var opts = _.clone(paramEnabled);
      opts.allPlans = true;
      opts.verbosePlans = true;

      queries.forEach(function(query) {
        var result = AQL_EXPLAIN(query, { }, opts);
        result.plans.forEach(function(plan) {
          assertTrue(plan.rules.indexOf(ruleName) === -1, query);
        });
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test that rule has an effect
////////////////////////////////////////////////////////////////////////////////

    testRuleHasEffect : function () {
      var queries = [
        [ "FOR i IN " + collectionName + " FOR j IN " + collectionName + " RETURN i", 1 ],
        [ "FOR i IN 1..10 FOR j IN " + collectionName + " FOR k IN " + collectionName + " RETURN i", 5 ],
        [ "FOR i IN " + collectionName + " FOR j IN " + collectionName + " FOR k IN " + collectionName + " RETURN i", 5 ],
        [ "FOR i IN " + collectionName + " FOR j IN " + collectionName + " FOR k IN " + collectionName + " FOR l IN " + collectionName + " RETURN i", 23 ],
        [ "FOR x IN (FOR i IN " + collectionName + " FOR j IN " + collectionName + " RETURN i) RETURN x", 1 ],
        [ "FOR x IN (FOR i IN " + collectionName + " FOR j IN " + collectionName + " FOR k IN " + collectionName + " RETURN i) RETURN x", 5 ],
        [ "FOR x IN (FOR i IN " + collectionName + " FOR j IN " + collectionName + " FOR k IN " + collectionName + " RETURN i) FOR y IN (FOR i IN " + collectionName + " FOR j IN " + collectionName + " RETURN i) RETURN x", 11 ]
      ];

      var opts = _.clone(paramEnabled);
      opts.allPlans = true;
      opts.verbosePlans = true;

      queries.forEach(function(query) {
        var withRule = 0;
        var withoutRule = 0;

        var result = AQL_EXPLAIN(query[0], { }, opts);
        result.plans.forEach(function(plan) {
          if (plan.rules.indexOf(ruleName) === -1) {
            withoutRule++;
          }
          else {
            withRule++;
          }
        });

        // there should still be the original plan
        assertEqual(1, withoutRule, query[0]);

        // put there should also be permuted plans
        assertEqual(query[1], withRule, query[0]);
      });
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test results
////////////////////////////////////////////////////////////////////////////////

    testResults : function () {
      var queries = [
        [ "FOR i IN " + collectionName + " FOR j IN " + collectionName + " SORT i.value, j.value FILTER i.value == j.value RETURN i.value", [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ],
        [ "FOR j IN " + collectionName + " FOR i IN " + collectionName + " SORT i.value, j.value FILTER i.value == j.value RETURN i.value", [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ],
        [ "FOR x IN (FOR i IN " + collectionName + " FOR j IN " + collectionName + " RETURN { i: i.value, j: j.value }) FILTER x.i == x.j SORT x.i RETURN x.i", [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ]
      ];

      var opts = _.clone(paramEnabled);
      opts.allPlans = true;
      opts.verbosePlans = true;

      queries.forEach(function(query) {
        var planDisabled   = AQL_EXPLAIN(query[0], { }, paramDisabled);
        var plansEnabled    = AQL_EXPLAIN(query[0], { }, opts);
        var resultDisabled = AQL_EXECUTE(query[0], { }, paramDisabled).json;

        assertTrue(planDisabled.plan.rules.indexOf(ruleName) === -1, query[0]);
        assertEqual(resultDisabled, query[1]);

        assertTrue(plansEnabled.plans.length > 1);

        // iterate over all plans
        var withRule = 0;
        plansEnabled.plans.forEach(function(plan) {
          var resultEnabled = AQL_EXECUTEJSON(plan).json;
          assertTrue(isEqual(resultDisabled, resultEnabled), query[0]);
          if (plan.rules.indexOf(ruleName) !== -1) {
            withRule++;
          }
          assertEqual(resultEnabled, query[1]);
        });

        assertTrue(withRule > 0);

      });
    }

  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

jsunity.run(optimizerRuleTestSuite);

return jsunity.done();


text:
package com.kakai.android.autopreferences.compiler.generator.type;
import com.kakai.android.autopreferences.annotations.PreferenceGetter;
import com.kakai.android.autopreferences.compiler.AutoPreferencesAnnotatedClass;
import com.kakai.android.autopreferences.compiler.PreferenceAnnotatedField;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;

class EnumTypeGenerator extends BaseTypeGenerator implements TypeGenerator {

    EnumTypeGenerator(AutoPreferencesAnnotatedClass clazz, PreferenceAnnotatedField field) {
        super(clazz, field);
    }

    @Override
    public MethodSpec generateGetter(FieldSpec context, FieldSpec helper) {
        MethodSpec.Builder builder = baseGetterBuilder()
                .addStatement("return $N.$L($N.getString($L), $L, $T.class)",
                        helper, getterHelperMethodName(), context, field.getStringRes(), field.getVariable(), field.getTypeName());

        if(clazz.annotateMethods()) {
            builder = builder.addAnnotation(generateAnnotation(PreferenceGetter.class));
        }

        return builder.build();
    }

    @Override
    protected String getterHelperMethodName() {
        return "getEnum";
    }

    @Override
    protected String setterHelperMethodName() {
        return "putEnum";
    }
}