text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui;

import com.intellij.ide.lightEdit.LightEditCompatible;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonShortcuts;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.util.Couple;
import com.intellij.ui.speedSearch.SpeedSearchSupply;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * A helper class for registering Keymap aware navigation actions for lists and tables
 *
 * @author Konstantin Bulenkov
 */
public final class ScrollingUtil {
  private static final Logger LOG = Logger.getInstance(ScrollingUtil.class);
  @NonNls
  private static final String SCROLL_UP_ACTION_ID = "scrollUp";
  @NonNls
  private static final String SCROLL_DOWN_ACTION_ID = "scrollDown";
  @NonNls
  private static final String SELECT_PREVIOUS_ROW_ACTION_ID = "selectPreviousRow";
  @NonNls
  private static final String SELECT_NEXT_ROW_ACTION_ID = "selectNextRow";
  @NonNls
  private static final String SELECT_LAST_ROW_ACTION_ID = "selectLastRow";
  @NonNls
  private static final String SELECT_FIRST_ROW_ACTION_ID = "selectFirstRow";
  @NonNls
  private static final String MOVE_HOME_ID = "MOVE_HOME";
  @NonNls
  private static final String MOVE_END_ID = "MOVE_END";

  public static final int ROW_PADDING = 2;

  public static void selectItem(@NotNull JList<?> list, int index) {
    LOG.assertTrue(index >= 0);
    LOG.assertTrue(index < list.getModel().getSize());
    ensureIndexIsVisible(list, index, 0);
    list.setSelectedIndex(index);
  }

  public static void ensureSelectionExists(@NotNull JList<?> list) {
    int size = list.getModel().getSize();
    if (size == 0) {
      list.clearSelection();
      return;
    }
    int selectedIndex = list.getSelectedIndex();
    if (selectedIndex < 0 || selectedIndex >= size) { // fit index to [0, size-1] range
      selectedIndex = 0;
    }
    selectItem(list, selectedIndex);
  }

  public static <T> boolean selectItem(@NotNull JList<T> list, @NotNull T item) {
    ListModel<T> model = list.getModel();
    for (int i = 0; i < model.getSize(); i++) {
      T anItem = model.getElementAt(i);
      if (item.equals(anItem)) {
        selectItem(list, i);
        return true;
      }
    }
    return false;
  }

  public static void movePageUp(JList<?> list) {
    int visible = getVisibleRowCount(list);
    ListSelectionModel selectionModel = list.getSelectionModel();
    if (visible <= 0) {
      moveHome(list);
      return;
    }
    int size = list.getModel().getSize();
    int decrement = visible - 1;
    int index = Math.max(list.getSelectedIndex() - decrement, 0);
    int top = list.getFirstVisibleIndex() - decrement;
    if (top < 0) {
      top = 0;
    }
    int bottom = top + visible - 1;
    if (bottom >= size) {
      bottom = size - 1;
    }
    //list.clearSelection();
    Rectangle cellBounds = list.getCellBounds(top, bottom);
    if (cellBounds == null) {
      moveHome(list);
      return;
    }
    list.scrollRectToVisible(cellBounds);
    selectionModel.setSelectionInterval(index,index);
    list.ensureIndexIsVisible(index);
  }

  public static void movePageDown(@NotNull JList<?> list) {
    int visible = getVisibleRowCount(list);
    if (visible <= 0) {
      moveEnd(list);
      return;
    }
    int size = list.getModel().getSize();
    int increment = visible - 1;
    int index = Math.min(list.getSelectedIndex() + increment, size - 1);
    int top = list.getFirstVisibleIndex() + increment;
    int bottom = top + visible - 1;
    if (bottom >= size) {
      bottom = size - 1;
    }
    //list.clearSelection();
    Rectangle cellBounds = list.getCellBounds(top, bottom);
    if (cellBounds == null) {
      moveEnd(list);
      return;
    }
    list.scrollRectToVisible(cellBounds);
    list.setSelectedIndex(index);
    list.ensureIndexIsVisible(index);
  }

  public static void moveHome(@NotNull JList<?> list) {
    list.setSelectedIndex(0);
    list.ensureIndexIsVisible(0);
  }

  public static void moveEnd(@NotNull JList<?> list) {
    int index = list.getModel().getSize() - 1;
    list.setSelectedIndex(index);
    list.ensureIndexIsVisible(index);
  }

  public static void ensureIndexIsVisible(@NotNull JList<?> list, int index, int moveDirection) {
    _ensureIndexIsVisible(list, index, moveDirection, list.getModel().getSize());
  }

  public static void ensureIndexIsVisible(@NotNull JTable table, int index, int moveDirection) {
    _ensureIndexIsVisible(table, index, moveDirection, table.getRowCount());
  }

  private static void _ensureIndexIsVisible(@NotNull JComponent c, int index, int moveDirection, int size) {
    int visible = visibleRowCount(c);
    int top;
    int bottom;
    if (moveDirection == 0) {
      top = index - (visible - 1) / ROW_PADDING;
      bottom = top + visible - 1;
    }
    else if (moveDirection < 0) {
      top = index - ROW_PADDING;
      bottom = index;
    }
    else {
      top = index;
      bottom = index + ROW_PADDING;
    }
    if (top < 0) {
      top = 0;
    }
    if (bottom >= size) {
      bottom = size - 1;
    }
    _ensureRangeIsVisible(c, top, bottom);
  }

  public static void ensureRangeIsVisible(@NotNull JList<?> list, int top, int bottom) {
    int size = list.getModel().getSize();
    if (top < 0) {
      top = 0;
    }
    if (bottom >= size) {
      bottom = size - 1;
    }
    Rectangle cellBounds = list.getCellBounds(top, bottom);
    if (cellBounds != null) {
      cellBounds.x = 0;
      list.scrollRectToVisible(cellBounds);
    }
  }
  private static void _ensureRangeIsVisible(@NotNull JComponent c, int top, int bottom) {
    if (c instanceof JList) {
      ensureRangeIsVisible((JList<?>)c, top, bottom);
    }
    else if (c instanceof JTable) {
      JTable table = (JTable)c;
      Rectangle cellBounds = getCellBounds(table, top, bottom);
      cellBounds.x = 0;
      table.scrollRectToVisible(cellBounds);
    }
  }

  public static boolean isIndexFullyVisible(@NotNull JList<?> list, int index) {
    int first = list.getFirstVisibleIndex();
    int last = list.getLastVisibleIndex();

    if (index < 0 || first < 0 || last < 0 || index < first || index > last) {
      return false;
    }
    if (index > first && index < last) {
      return true;
    }

    return list.getVisibleRect().contains(list.getCellBounds(index, index));
  }

  private static int getVisibleRowCount(@NotNull JList<?> list) {
    return list.getLastVisibleIndex() - list.getFirstVisibleIndex() + 1;
  }

  public static void moveDown(@NotNull JList<?> list, @JdkConstants.InputEventMask int modifiers) {
    moveDown(list, modifiers, UISettings.getInstance().getCycleScrolling());
  }

  private static void moveDown(@NotNull JList<?> list, @JdkConstants.InputEventMask int modifiers, boolean cycleScrolling) {
    _moveDown(list, list.getSelectionModel(), modifiers, list.getModel().getSize(), cycleScrolling);
  }

  private static void selectOrAddSelection(@NotNull ListSelectionModel selectionModel,
                                           int indexToSelect,
                                           @JdkConstants.InputEventMask int modifiers) {
    if (selectionModel.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) {
      selectionModel.setSelectionInterval(indexToSelect,indexToSelect);
    }
    else {
      if ((modifiers & InputEvent.SHIFT_DOWN_MASK) == 0) {
        selectionModel.removeSelectionInterval(selectionModel.getMinSelectionIndex(), selectionModel.getMaxSelectionIndex());
      }
      selectionModel.addSelectionInterval(indexToSelect, indexToSelect);
    }
  }

  public static void installActions(@NotNull JList<?> list) {
    installActions(list, null);
  }

  public static void installActions(@NotNull JList<?> list, @Nullable JComponent focusParent) {
    installActions(list, focusParent, UISettings.getInstance().getCycleScrolling());
  }

  public static void installActions(final @NotNull JList<?> list, @Nullable JComponent focusParent, boolean cycleScrolling) {
    ActionMap actionMap = list.getActionMap();
    setupScrollingActions(list, actionMap, cycleScrolling);
    actionMap.put(MOVE_HOME_ID, new MoveAction(MOVE_HOME_ID, list));
    actionMap.put(MOVE_END_ID, new MoveAction(MOVE_END_ID, list));

    maybeInstallDefaultShortcuts(list);

    installMoveUpAction(list, focusParent, cycleScrolling);
    installMoveDownAction(list, focusParent, cycleScrolling);
    installMovePageUpAction(list, focusParent);
    installMovePageDownAction(list, focusParent);
    if (!(focusParent instanceof JTextComponent)) {
      installMoveHomeAction(list, focusParent);
      installMoveEndAction(list, focusParent);
    }
  }

  private static void setupScrollingActions(@NotNull JComponent list, ActionMap actionMap, boolean cycleScrolling) {
    actionMap.put(SCROLL_UP_ACTION_ID, new MoveAction(SCROLL_UP_ACTION_ID, list, cycleScrolling));
    actionMap.put(SCROLL_DOWN_ACTION_ID, new MoveAction(SCROLL_DOWN_ACTION_ID, list, cycleScrolling));
    actionMap.put(SELECT_PREVIOUS_ROW_ACTION_ID, new MoveAction(SELECT_PREVIOUS_ROW_ACTION_ID, list, cycleScrolling));
    actionMap.put(SELECT_NEXT_ROW_ACTION_ID, new MoveAction(SELECT_NEXT_ROW_ACTION_ID, list, cycleScrolling));
    actionMap.put(SELECT_LAST_ROW_ACTION_ID, new MoveAction(SELECT_LAST_ROW_ACTION_ID, list, cycleScrolling));
    actionMap.put(SELECT_FIRST_ROW_ACTION_ID, new MoveAction(SELECT_FIRST_ROW_ACTION_ID, list, cycleScrolling));
  }

  public static void redirectExpandSelection(@NotNull JList<?> list, @Nullable JComponent focusParent) {
    if (focusParent != null && focusParent != list) {
      focusParent.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
          if (e.isShiftDown()) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
              list.dispatchEvent(e);
              e.consume();
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
              list.dispatchEvent(e);
              e.consume();
            }
          }
        }
      });
    }
  }

  public static void installMoveEndAction(@NotNull JList<?> list, @Nullable JComponent focusParent) {
    new ListMoveEndAction(focusParent, list);
  }

  public static void installMoveHomeAction(@NotNull JList<?> list, @Nullable JComponent focusParent) {
    new ListMoveHomeAction(focusParent, list);
  }

  public static void installMovePageDownAction(@NotNull JList<?> list, @Nullable JComponent focusParent) {
    new ListMovePageDownAction(focusParent, list);
  }

  public static void installMovePageUpAction(@NotNull JList<?> list, @Nullable JComponent focusParent) {
    new ListMovePageUpAction(focusParent, list);
  }

  public static void installMoveDownAction(@NotNull JList<?> list, @Nullable JComponent focusParent) {
    installMoveDownAction(list, focusParent, UISettings.getInstance().getCycleScrolling());
  }

  private static void installMoveDownAction(@NotNull JList<?> list, @Nullable JComponent focusParent, boolean cycleScrolling) {
    new ListMoveDownAction(focusParent, list, cycleScrolling);
  }

  public static void installMoveUpAction(@NotNull JList<?> list, @Nullable JComponent focusParent) {
    installMoveUpAction(list, focusParent, UISettings.getInstance().getCycleScrolling());
  }

  private static void installMoveUpAction(@NotNull JList<?> list, @Nullable JComponent focusParent, boolean cycleScrolling) {
    new ListMoveUpAction(focusParent, list, cycleScrolling);
  }

  private static void maybeInstallDefaultShortcuts(@NotNull JComponent component) {
    InputMap map = component.getInputMap(JComponent.WHEN_FOCUSED);
    UIUtil.maybeInstall(map, SCROLL_UP_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
    UIUtil.maybeInstall(map, SCROLL_DOWN_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
    UIUtil.maybeInstall(map, SELECT_PREVIOUS_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
    UIUtil.maybeInstall(map, SELECT_NEXT_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
    UIUtil.maybeInstall(map, SELECT_FIRST_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0));
    UIUtil.maybeInstall(map, SELECT_LAST_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_END, 0));
    UIUtil.maybeInstall(map, MOVE_HOME_ID, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
    UIUtil.maybeInstall(map, MOVE_END_ID, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
  }

  public interface ScrollingAction extends DumbAware {

  }

  public static abstract class ListScrollAction extends MyScrollingAction {
    protected ListScrollAction(@NotNull ShortcutSet shortcutSet, @NotNull JComponent component) {
      super(component);
      registerCustomShortcutSet(shortcutSet, component);
    }
  }

  public static void ensureSelectionExists(@NotNull JTable table) {
    int size = table.getModel().getRowCount();
    if (size == 0) {
      table.clearSelection();
      return;
    }
    int selectedIndex = table.getSelectedRow();
    boolean reselect = false;
    if (selectedIndex < 0 || selectedIndex >= size) { // fit index to [0, size-1] range
      selectedIndex = 0;
      reselect = true;
    }
    ensureIndexIsVisible(table, selectedIndex, 0);
    if (reselect) {
      table.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex);
    }
  }

  @NotNull
  private static Rectangle getCellBounds(@NotNull JTable table, int top, int bottom) {
    return table.getCellRect(top, 0, true).union(table.getCellRect(bottom,0,true));
  }

  private static int visibleRowCount(JComponent c) {
    if (c instanceof JList) return getVisibleRowCount((JList<?>)c);
    if (c instanceof JTable) return getVisibleRowCount((JTable)c);
    return -1;
  }

  private static int getVisibleRowCount(@NotNull JTable table) {
    Rectangle visibleRect = table.getVisibleRect();
    return getTrailingRow(table, visibleRect) - getLeadingRow(table, visibleRect) + 1;
  }

  public static @NotNull Couple<Integer> getVisibleRows(@NotNull JTable table) {
    Rectangle visibleRect = table.getVisibleRect();
    return Couple.of(getLeadingRow(table, visibleRect), getTrailingRow(table, visibleRect));
  }

  private static int getLeadingRow(@NotNull JTable table, @NotNull Rectangle visibleRect) {
    int row = table.rowAtPoint(getLeadingPoint(table, visibleRect));
    if (row >= 0) return row;
    // return the first row in the table
    // if there is no any row at the given point
    return 0 < table.getRowCount() ? 0 : -1;
  }

  @NotNull
  private static Point getLeadingPoint(@NotNull JTable table, @NotNull Rectangle visibleRect) {
    if (table.getComponentOrientation().isLeftToRight()) {
        return new Point(visibleRect.x, visibleRect.y);
    }
    else {
        return new Point(visibleRect.x + visibleRect.width,
                                 visibleRect.y);
    }
  }

  public static int getReadableRow(@NotNull JTable table, int maximumHiddenPart) {
    Rectangle visibleRect = table.getVisibleRect();
    Point leadingPoint = getLeadingPoint(table, visibleRect);
    int row = table.rowAtPoint(leadingPoint);
    int column = table.columnAtPoint(leadingPoint);
    if (leadingPoint.y - table.getCellRect(row, column, true).getY() <= maximumHiddenPart) {
      return row;
    } else {
      return Math.min(row + 1, table.getRowCount() - 1); // just in case
    }
  }

  public static boolean isVisible(@NotNull JTable table, int row) {
    Rectangle visibleRect = table.getVisibleRect();
    int start = getLeadingRow(table, visibleRect);
    int end = getTrailingRow(table, visibleRect);
    return row >= start && row <= end;
  }

  private static int getTrailingRow(@NotNull JTable table, @NotNull Rectangle visibleRect) {
      Point trailingPoint;

      if (table.getComponentOrientation().isLeftToRight()) {
          trailingPoint = new Point(visibleRect.x,
                                    visibleRect.y + visibleRect.height - 1);
      }
      else {
          trailingPoint = new Point(visibleRect.x + visibleRect.width,
                                    visibleRect.y + visibleRect.height - 1);
      }
    int row = table.rowAtPoint(trailingPoint);
    if (row >= 0) return row;
    // return the last row in the table
    // if there is no any row at the given point
    return table.getRowCount() - 1;
  }

  public static void moveDown(@NotNull JTable table, @JdkConstants.InputEventMask int modifiers, boolean cycleScrolling) {
    _moveDown(table, table.getSelectionModel(), modifiers, table.getRowCount(), cycleScrolling);
  }

  public static void moveUp(@NotNull JList<?> list, @JdkConstants.InputEventMask int modifiers) {
    moveUp(list, modifiers, UISettings.getInstance().getCycleScrolling());
  }

  private static void moveUp(@NotNull JList<?> list, @JdkConstants.InputEventMask int modifiers, boolean cycleScrolling) {
    _moveUp(list, list.getSelectionModel(), list.getModel().getSize(), modifiers, cycleScrolling);
  }

  public static void moveUp(@NotNull JTable table, @JdkConstants.InputEventMask int modifiers, boolean cycleScrolling) {
    _moveUp(table, table.getSelectionModel(), table.getModel().getRowCount(), modifiers, cycleScrolling);
  }

  private static void _moveDown(@NotNull JComponent c, @NotNull ListSelectionModel selectionModel, @JdkConstants.InputEventMask final int modifiers, int size, boolean cycleScrolling) {
    _move(c, selectionModel, modifiers, size, cycleScrolling, +1);
  }

  private static void _move(@NotNull JComponent c, @NotNull ListSelectionModel selectionModel, @JdkConstants.InputEventMask final int modifiers, int size, boolean cycleScrolling, int direction) {
    if (size == 0) return;
    int index = selectionModel.getLeadSelectionIndex();
    int indexToSelect = index + direction;
    if (indexToSelect < 0 || indexToSelect >= size) {
      if (cycleScrolling) {
        indexToSelect = indexToSelect < 0 ? size - 1 : 0;
      } else {
        return;
      }
    }
    _ensureIndexIsVisible(c, indexToSelect, -1, size);
    selectOrAddSelection(selectionModel, indexToSelect, modifiers);
  }

  private static void _moveUp(@NotNull JComponent c, @NotNull ListSelectionModel selectionModel, int size, @JdkConstants.InputEventMask int modifiers, boolean cycleScrolling) {
    _move(c, selectionModel, modifiers, size, cycleScrolling, -1);
  }

  public static void moveHome(@NotNull JTable table) {
    table.getSelectionModel().setSelectionInterval(0,0);
    ensureIndexIsVisible(table, 0,0);
  }

  public static void moveEnd(@NotNull JTable table) {
    int index = table.getModel().getRowCount() - 1;
    table.getSelectionModel().setSelectionInterval(index, index);
    ensureIndexIsVisible(table, index, 0);
  }

  public static void movePageUp(@NotNull JTable table) {
    int visible = getVisibleRowCount(table);
    if (visible <= 0) {
      moveHome(table);
      return;
    }
    int step = visible - 1;
    ListSelectionModel selectionModel = table.getSelectionModel();
    int index = Math.max(selectionModel.getMinSelectionIndex() - step, 0);
    int visibleIndex = getLeadingRow(table, table.getVisibleRect());
    int top = visibleIndex - step;
    if (top < 0) {
      top = 0;
    }
    int bottom = top + visible - 1;
    _scrollAfterPageMove(table, top, bottom, index);
  }

  public static void movePageDown(@NotNull JTable table) {
    int visible = getVisibleRowCount(table);
    if (visible <= 0) {
      moveEnd(table);
      return;
    }
    ListSelectionModel selectionModel = table.getSelectionModel();
    int step = visible - 1;
    int firstVisibleRow = getLeadingRow(table, table.getVisibleRect());
    int top = firstVisibleRow + step;
    int bottom = top + visible - 1;
    int size = table.getModel().getRowCount();
    int index = Math.min(selectionModel.getMinSelectionIndex() + step, size - 1);
    _scrollAfterPageMove(table, top, bottom, index);
  }

  private static void _scrollAfterPageMove(@NotNull JTable table, int top, int bottom, int index) {
    int size = table.getModel().getRowCount();
    if (bottom >= size) {
      bottom = size - 1;
    }
    Rectangle cellBounds = getCellBounds(table, top, bottom);
    table.scrollRectToVisible(cellBounds);
    table.getSelectionModel().setSelectionInterval(index, index);
    ensureIndexIsVisible(table, index, 0);
  }

  public static void installActions(@NotNull JTable table) {
    installActions(table, UISettings.getInstance().getCycleScrolling());
  }

  private abstract static class MyScrollingAction extends DumbAwareAction implements ScrollingAction, LightEditCompatible {
    private final JComponent myComponent;

    MyScrollingAction(@NotNull JComponent component) {
      myComponent = component;
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
      e.getPresentation().setEnabled(isEnabled());
    }

    protected boolean isEnabled() {
      return SpeedSearchSupply.getSupply(myComponent) == null && !isEmpty(myComponent);
    }
  }

  public static boolean isEmpty(JComponent component) {
    if (component instanceof JTable) return ((JTable)component).getRowCount() < 1;
    if (component instanceof JList) return ((JList<?>)component).getModel().getSize() <1;
    return false;
  }

  public static void installActions(@NotNull JTable table, final boolean cycleScrolling) {
    installActions(table, cycleScrolling, null);
  }

  public static void installActions(final @NotNull JTable table, final boolean cycleScrolling, @Nullable JComponent focusParent) {
    ActionMap actionMap = table.getActionMap();
    setupScrollingActions(table, actionMap, cycleScrolling);

    maybeInstallDefaultShortcuts(table);
    JComponent target = focusParent == null ? table : focusParent;

    new TableMoveHomeAction(table).registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)), table);
    new TableMoveEndAction(table).registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0)), table);
    if (!(focusParent instanceof JTextComponent)) {
      new TableMoveHomeAction(table).registerCustomShortcutSet(CommonShortcuts.getMoveHome(), target);
      new TableMoveEndAction(table).registerCustomShortcutSet(CommonShortcuts.getMoveEnd(), target);
    }
    new TableMoveDownAction(table, cycleScrolling, target).registerCustomShortcutSet(CommonShortcuts.getMoveDown(), target);
    new TableMoveUpAction(table, cycleScrolling, target).registerCustomShortcutSet(CommonShortcuts.getMoveUp(), target);
    new TableMovePageUpAction(table).registerCustomShortcutSet(CommonShortcuts.getMovePageUp(), target);
    new TableMovePageDownAction(table).registerCustomShortcutSet(CommonShortcuts.getMovePageDown(), target);
  }

  private static boolean isMultiline(@NotNull JComponent component) {
    return component instanceof JTextArea && ((JTextArea)component).getText().contains("\n");
  }

  static class MoveAction extends AbstractAction {
    private final String myId;
    private final JComponent myComponent;
    private final Boolean myCycleScrolling;

    MoveAction(@NotNull String id, @NotNull JComponent component, @Nullable Boolean cycleScrolling) {
      myId = id;
      myComponent = component;
      myCycleScrolling = cycleScrolling;
    }

    MoveAction(@NotNull String id, @NotNull JComponent component) {
      this(id, component, null);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
      final int modifiers = e.getModifiers();
        if (SCROLL_UP_ACTION_ID.equals(myId)) doPageUp();
        else if (SCROLL_DOWN_ACTION_ID.equals(myId)) doPageDown();
        else if (SELECT_PREVIOUS_ROW_ACTION_ID.equals(myId)) doMoveUp(modifiers);
        else if (SELECT_NEXT_ROW_ACTION_ID.equals(myId)) doMoveDown(modifiers);
        else if (SELECT_LAST_ROW_ACTION_ID.equals(myId)) doMoveEnd();
        else if (SELECT_FIRST_ROW_ACTION_ID.equals(myId)) doMoveHome();
        else if (MOVE_END_ID.equals(myId)) doMoveEnd();
        else if (MOVE_HOME_ID.equals(myId)) doMoveHome();
    }

    private void doMoveEnd() {
      if (myComponent instanceof JList) moveEnd((JList<?>)myComponent);
      else if (myComponent instanceof JTable) moveEnd((JTable)myComponent);
      else throw new IllegalArgumentException("MoveEnd is not implemented for " + myComponent.getClass());
    }

    private void doMoveHome() {
      if (myComponent instanceof JList) moveHome((JList<?>)myComponent);
      else if (myComponent instanceof JTable) moveHome((JTable)myComponent);
      else throw new IllegalArgumentException("MoveHome is not implemented for " + myComponent.getClass());
    }

    private void doMoveUp(@JdkConstants.InputEventMask int modifiers) {
      if (myComponent instanceof JList) moveUp((JList<?>)myComponent, modifiers, isCycleScrolling());
      else if (myComponent instanceof JTable) moveUp((JTable)myComponent, modifiers, isCycleScrolling());
      else throw new IllegalArgumentException("MoveUp is not implemented for " + myComponent.getClass());
    }

    private void doMoveDown(@JdkConstants.InputEventMask int modifiers) {
      if (myComponent instanceof JList) moveDown((JList<?>)myComponent, modifiers, isCycleScrolling());
      else if (myComponent instanceof JTable) moveDown((JTable)myComponent, modifiers, isCycleScrolling());
      else throw new IllegalArgumentException("MoveDown is not implemented for " + myComponent.getClass());
    }

    private void doPageUp() {
      if (myComponent instanceof JList) movePageUp((JList<?>)myComponent);
      else if (myComponent instanceof JTable) movePageUp((JTable)myComponent);
      else throw new IllegalArgumentException("PageUp is not implemented for " + myComponent.getClass());
    }

    private void doPageDown() {
      if (myComponent instanceof JList) movePageDown((JList<?>)myComponent);
      else if (myComponent instanceof JTable) movePageDown((JTable)myComponent);
      else throw new IllegalArgumentException("PageDown is not implemented for " + myComponent.getClass());
    }

    private boolean isCycleScrolling() {
      return myCycleScrolling == null ? UISettings.getInstance().getCycleScrolling() : myCycleScrolling.booleanValue();
    }
  }

  private static class ListMoveUpAction extends ListScrollAction {
    private @NotNull final JList<?> myList;
    private final boolean myCycleScrolling;

    private ListMoveUpAction(@Nullable JComponent focusParent, @NotNull JList<?> list, boolean cycleScrolling) {
      super(CommonShortcuts.getMoveUp(),
            focusParent == null
            ? list
            : focusParent);
      myList = list;
      myCycleScrolling = cycleScrolling;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      moveUp(myList, 0, myCycleScrolling);
    }
  }

  private static class ListMoveEndAction extends ListScrollAction {
    private @NotNull final JList<?> myList;

    private ListMoveEndAction(@Nullable JComponent focusParent, @NotNull JList<?> list) {
      super(CommonShortcuts.getMoveEnd(), focusParent == null ? list : focusParent);
      myList = list;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      moveEnd(myList);
    }
  }

  private static class ListMoveHomeAction extends ListScrollAction {
    private @NotNull final JList<?> myList;

    private ListMoveHomeAction(@Nullable JComponent focusParent, @NotNull JList<?> list) {
      super(CommonShortcuts.getMoveHome(), focusParent == null ? list : focusParent);
      myList = list;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      moveHome(myList);
    }
  }

  private static class ListMovePageDownAction extends ListScrollAction {
    private @NotNull final JList<?> myList;

    private ListMovePageDownAction(@Nullable JComponent focusParent, @NotNull JList<?> list) {
      super(CommonShortcuts.getMovePageDown(), focusParent == null ? list : focusParent);
      myList = list;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      movePageDown(myList);
    }
  }

  private static class ListMovePageUpAction extends ListScrollAction {
    private @NotNull final JList<?> myList;

    private ListMovePageUpAction(@Nullable JComponent focusParent, @NotNull JList<?> list) {
      super(CommonShortcuts.getMovePageUp(), focusParent == null ? list : focusParent);
      myList = list;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      movePageUp(myList);
    }
  }

  private static class ListMoveDownAction extends ListScrollAction {
    private @NotNull final JList<?> myList;
    private final boolean myCycleScrolling;

    private ListMoveDownAction(@Nullable JComponent focusParent, @NotNull JList<?> list, boolean cycleScrolling) {
      super(CommonShortcuts.getMoveDown(),
            focusParent == null
            ? list
            : focusParent);
      myList = list;
      myCycleScrolling = cycleScrolling;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      moveDown(myList, 0, myCycleScrolling);
    }
  }

  private static class TableMoveHomeAction extends MyScrollingAction {
    private @NotNull final JTable myTable;

    private TableMoveHomeAction(@NotNull JTable table) {
      super(table);
      myTable = table;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      moveHome(myTable);
    }
  }

  private static class TableMoveEndAction extends MyScrollingAction {
    private @NotNull final JTable myTable;

    private TableMoveEndAction(@NotNull JTable table) {
      super(table);
      myTable = table;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      moveEnd(myTable);
    }
  }

  private static class TableMoveDownAction extends MyScrollingAction {
    private @NotNull final JTable myTable;
    private final boolean myCycleScrolling;
    private final JComponent myTarget;

    private TableMoveDownAction(@NotNull JTable table, boolean cycleScrolling, JComponent target) {
      super(table);
      myTable = table;
      myCycleScrolling = cycleScrolling;
      myTarget = target;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      moveDown(myTable, e.getModifiers(), myCycleScrolling);
    }

    @Override
    protected boolean isEnabled() {
      return super.isEnabled() && !isMultiline(myTarget);
    }
  }

  private static class TableMoveUpAction extends MyScrollingAction {
    private @NotNull final JTable myTable;
    private final boolean myCycleScrolling;
    private final JComponent myTarget;

    private TableMoveUpAction(@NotNull JTable table, boolean cycleScrolling, JComponent target) {
      super(table);
      myTable = table;
      myCycleScrolling = cycleScrolling;
      myTarget = target;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      moveUp(myTable, e.getModifiers(), myCycleScrolling);
    }

    @Override
    protected boolean isEnabled() {
      return super.isEnabled() && !isMultiline(myTarget);
    }
  }

  private static class TableMovePageUpAction extends MyScrollingAction {
    private @NotNull final JTable myTable;

    private TableMovePageUpAction(@NotNull JTable table) {
      super(table);
      myTable = table;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      movePageUp(myTable);
    }
  }

  private static class TableMovePageDownAction extends MyScrollingAction {
    private @NotNull final JTable myTable;

    public TableMovePageDownAction(@NotNull JTable table) {
      super(table);
      myTable = table;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      movePageDown(myTable);
    }
  }
}


text:
/*
 * Created on 07-Mar-2005
 */
package sim.net.overlay.dht;
/**
 * @author Andrew Brampton
 */
public class RegTestMessage extends Message {

	/**
	 * @param fromAddress
	 * @param fromID
	 * @param toID
	 */
	public RegTestMessage(int fromAddress, long fromID, long toID) {
		super(fromAddress, fromID, toID);
	}

}

redpajama_set_name: RedPajamaGithub


text: int Dotfile::autoNumbering = 0;


text:
define(function(){

    var form = {

        dependencies: {
            'validation': 'utils/validation'
        },

        /**
         * Configuration for form validation
         */

        validation_config: {
            // Events to bind auto-validation
            events: ['keyup','blur'],

            // Rules for fields based on input's name param
            rules: {
                fname: {
                    required: true,
                    minlength: 2,
                    maxlength: 32
                },
                lname: {
                    required: true,
                    minlength: 2,
                    maxlength: 32
                },
                email: {
                    //required: true,
                    email: true
                },
                password: {
                    required: true,
                    minlength: 6
                },
                password_confirm: {
                    required: true,
                    matches: 'password'
                }
            },

            // Messages displayed on validation error
            messages: {
                required: "This field is required",
                minlength: "This field must contain at least {{minlength}} characters",
                maxlength: "This field must not contain more than {{maxlength}} characters",
                email: "This field must contain a valid email address",
                matches: "This field must match {{matches}}"
            }
        },

        events: {
            'submit form': 'processForm'
        },

        routes: {
            'form': 'renderForm'
        },

        /**
         * Loads up this modules main view
         */
        renderForm: function(){
            // Render template
            Colt.render(this);
            this.validation.bind(this);
        },

        processForm: function(event){
            var check_all = this.validation.check_all(this);
            if(!check_all){
                alert('Please fill out all required fields');
            }
        }

    };

    return form;

});


text:
layout: compress
---

{% include base_path %}

<!doctype html>
<script type="text/javascript"
  src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<html lang="{{ site.locale | slice: 0,2 }}" class="no-js">
  <head>
    {% include head.html %}
    {% include head/custom.html %}
  </head>

  <body>

    {% include browser-upgrade.html %}
    {% include masthead.html %}

    {{ content }}

    </script>

    <div class="page__footer">
      <footer>
        {% include footer/custom.html %}
        {% include footer.html %}
      </footer>
    </div>

    {% include scripts.html %}

  </body>
</html>


text:
<?php

declare(strict_types=1);

namespace JMS\Serializer\Metadata\Driver;

use Doctrine\Common\Annotations\Reader;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\AccessorOrder;
use JMS\Serializer\Annotation\AccessType;
use JMS\Serializer\Annotation\Discriminator;
use JMS\Serializer\Annotation\Exclude;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\Inline;
use JMS\Serializer\Annotation\MaxDepth;
use JMS\Serializer\Annotation\PostDeserialize;
use JMS\Serializer\Annotation\PostSerialize;
use JMS\Serializer\Annotation\PreSerialize;
use JMS\Serializer\Annotation\ReadOnlyProperty;
use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\Since;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Until;
use JMS\Serializer\Annotation\VirtualProperty;
use JMS\Serializer\Annotation\XmlAttribute;
use JMS\Serializer\Annotation\XmlAttributeMap;
use JMS\Serializer\Annotation\XmlDiscriminator;
use JMS\Serializer\Annotation\XmlElement;
use JMS\Serializer\Annotation\XmlKeyValuePairs;
use JMS\Serializer\Annotation\XmlList;
use JMS\Serializer\Annotation\XmlMap;
use JMS\Serializer\Annotation\XmlNamespace;
use JMS\Serializer\Annotation\XmlRoot;
use JMS\Serializer\Annotation\XmlValue;
use JMS\Serializer\Exception\InvalidMetadataException;
use JMS\Serializer\Expression\CompilableExpressionEvaluatorInterface;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\ExpressionPropertyMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Metadata\VirtualPropertyMetadata;
use JMS\Serializer\Naming\PropertyNamingStrategyInterface;
use JMS\Serializer\Type\Parser;
use JMS\Serializer\Type\ParserInterface;
use Metadata\ClassMetadata as BaseClassMetadata;
use Metadata\Driver\DriverInterface;
use Metadata\MethodMetadata;

class AnnotationDriver implements DriverInterface
{
    use ExpressionMetadataTrait;

    /**
     * @var Reader
     */
    private $reader;

    /**
     * @var ParserInterface
     */
    private $typeParser;
    /**
     * @var PropertyNamingStrategyInterface
     */
    private $namingStrategy;

    public function __construct(Reader $reader, PropertyNamingStrategyInterface $namingStrategy, ?ParserInterface $typeParser = null, ?CompilableExpressionEvaluatorInterface $expressionEvaluator = null)
    {
        $this->reader = $reader;
        $this->typeParser = $typeParser ?: new Parser();
        $this->namingStrategy = $namingStrategy;
        $this->expressionEvaluator = $expressionEvaluator;
    }

    public function loadMetadataForClass(\ReflectionClass $class): ?BaseClassMetadata
    {
        $classMetadata = new ClassMetadata($name = $class->name);
        $fileResource =  $class->getFilename();
        if (false !== $fileResource) {
            $classMetadata->fileResources[] = $fileResource;
        }

        $propertiesMetadata = [];
        $propertiesAnnotations = [];

        $exclusionPolicy = ExclusionPolicy::NONE;
        $excludeAll = false;
        $classAccessType = PropertyMetadata::ACCESS_TYPE_PROPERTY;
        $readOnlyClass = false;
        foreach ($this->reader->getClassAnnotations($class) as $annot) {
            if ($annot instanceof ExclusionPolicy) {
                $exclusionPolicy = $annot->policy;
            } elseif ($annot instanceof XmlRoot) {
                $classMetadata->xmlRootName = $annot->name;
                $classMetadata->xmlRootNamespace = $annot->namespace;
                $classMetadata->xmlRootPrefix = $annot->prefix;
            } elseif ($annot instanceof XmlNamespace) {
                $classMetadata->registerNamespace($annot->uri, $annot->prefix);
            } elseif ($annot instanceof Exclude) {
                if (null !== $annot->if) {
                    $classMetadata->excludeIf = $this->parseExpression($annot->if);
                } else {
                    $excludeAll = true;
                }
            } elseif ($annot instanceof AccessType) {
                $classAccessType = $annot->type;
            } elseif ($annot instanceof ReadOnlyProperty) {
                $readOnlyClass = true;
            } elseif ($annot instanceof AccessorOrder) {
                $classMetadata->setAccessorOrder($annot->order, $annot->custom);
            } elseif ($annot instanceof Discriminator) {
                if ($annot->disabled) {
                    $classMetadata->discriminatorDisabled = true;
                } else {
                    $classMetadata->setDiscriminator($annot->field, $annot->map, $annot->groups);
                }
            } elseif ($annot instanceof XmlDiscriminator) {
                $classMetadata->xmlDiscriminatorAttribute = (bool) $annot->attribute;
                $classMetadata->xmlDiscriminatorCData = (bool) $annot->cdata;
                $classMetadata->xmlDiscriminatorNamespace = $annot->namespace ? (string) $annot->namespace : null;
            } elseif ($annot instanceof VirtualProperty) {
                $virtualPropertyMetadata = new ExpressionPropertyMetadata(
                    $name,
                    $annot->name,
                    $this->parseExpression($annot->exp)
                );
                $propertiesMetadata[] = $virtualPropertyMetadata;
                $propertiesAnnotations[] = $annot->options;
            }
        }

        foreach ($class->getMethods() as $method) {
            if ($method->class !== $name) {
                continue;
            }

            $methodAnnotations = $this->reader->getMethodAnnotations($method);

            foreach ($methodAnnotations as $annot) {
                if ($annot instanceof PreSerialize) {
                    $classMetadata->addPreSerializeMethod(new MethodMetadata($name, $method->name));
                    continue 2;
                } elseif ($annot instanceof PostDeserialize) {
                    $classMetadata->addPostDeserializeMethod(new MethodMetadata($name, $method->name));
                    continue 2;
                } elseif ($annot instanceof PostSerialize) {
                    $classMetadata->addPostSerializeMethod(new MethodMetadata($name, $method->name));
                    continue 2;
                } elseif ($annot instanceof VirtualProperty) {
                    $virtualPropertyMetadata = new VirtualPropertyMetadata($name, $method->name);
                    $propertiesMetadata[] = $virtualPropertyMetadata;
                    $propertiesAnnotations[] = $methodAnnotations;
                    continue 2;
                }
            }
        }

        if (!$excludeAll) {
            foreach ($class->getProperties() as $property) {
                if ($property->class !== $name || (isset($property->info) && $property->info['class'] !== $name)) {
                    continue;
                }

                $propertiesMetadata[] = new PropertyMetadata($name, $property->getName());
                $propertiesAnnotations[] = $this->reader->getPropertyAnnotations($property);
            }

            foreach ($propertiesMetadata as $propertyKey => $propertyMetadata) {
                $isExclude = false;
                $isExpose = $propertyMetadata instanceof VirtualPropertyMetadata
                    || $propertyMetadata instanceof ExpressionPropertyMetadata;
                $propertyMetadata->readOnly = $propertyMetadata->readOnly || $readOnlyClass;
                $accessType = $classAccessType;
                $accessor = [null, null];

                $propertyAnnotations = $propertiesAnnotations[$propertyKey];

                foreach ($propertyAnnotations as $annot) {
                    if ($annot instanceof Since) {
                        $propertyMetadata->sinceVersion = $annot->version;
                    } elseif ($annot instanceof Until) {
                        $propertyMetadata->untilVersion = $annot->version;
                    } elseif ($annot instanceof SerializedName) {
                        $propertyMetadata->serializedName = $annot->name;
                    } elseif ($annot instanceof SkipWhenEmpty) {
                        $propertyMetadata->skipWhenEmpty = true;
                    } elseif ($annot instanceof Expose) {
                        $isExpose = true;
                        if (null !== $annot->if) {
                            $propertyMetadata->excludeIf = $this->parseExpression('!(' . $annot->if . ')');
                        }
                    } elseif ($annot instanceof Exclude) {
                        if (null !== $annot->if) {
                            $propertyMetadata->excludeIf = $this->parseExpression($annot->if);
                        } else {
                            $isExclude = true;
                        }
                    } elseif ($annot instanceof Type) {
                        $propertyMetadata->setType($this->typeParser->parse($annot->name));
                    } elseif ($annot instanceof XmlElement) {
                        $propertyMetadata->xmlAttribute = false;
                        $propertyMetadata->xmlElementCData = $annot->cdata;
                        $propertyMetadata->xmlNamespace = $annot->namespace;
                    } elseif ($annot instanceof XmlList) {
                        $propertyMetadata->xmlCollection = true;
                        $propertyMetadata->xmlCollectionInline = $annot->inline;
                        $propertyMetadata->xmlEntryName = $annot->entry;
                        $propertyMetadata->xmlEntryNamespace = $annot->namespace;
                        $propertyMetadata->xmlCollectionSkipWhenEmpty = $annot->skipWhenEmpty;
                    } elseif ($annot instanceof XmlMap) {
                        $propertyMetadata->xmlCollection = true;
                        $propertyMetadata->xmlCollectionInline = $annot->inline;
                        $propertyMetadata->xmlEntryName = $annot->entry;
                        $propertyMetadata->xmlEntryNamespace = $annot->namespace;
                        $propertyMetadata->xmlKeyAttribute = $annot->keyAttribute;
                    } elseif ($annot instanceof XmlKeyValuePairs) {
                        $propertyMetadata->xmlKeyValuePairs = true;
                    } elseif ($annot instanceof XmlAttribute) {
                        $propertyMetadata->xmlAttribute = true;
                        $propertyMetadata->xmlNamespace = $annot->namespace;
                    } elseif ($annot instanceof XmlValue) {
                        $propertyMetadata->xmlValue = true;
                        $propertyMetadata->xmlElementCData = $annot->cdata;
                    } elseif ($annot instanceof AccessType) {
                        $accessType = $annot->type;
                    } elseif ($annot instanceof ReadOnlyProperty) {
                        $propertyMetadata->readOnly = $annot->readOnly;
                    } elseif ($annot instanceof Accessor) {
                        $accessor = [$annot->getter, $annot->setter];
                    } elseif ($annot instanceof Groups) {
                        $propertyMetadata->groups = $annot->groups;
                        foreach ((array) $propertyMetadata->groups as $groupName) {
                            if (false !== strpos($groupName, ',')) {
                                throw new InvalidMetadataException(sprintf(
                                    'Invalid group name "%s" on "%s", did you mean to create multiple groups?',
                                    implode(', ', $propertyMetadata->groups),
                                    $propertyMetadata->class . '->' . $propertyMetadata->name
                                ));
                            }
                        }
                    } elseif ($annot instanceof Inline) {
                        $propertyMetadata->inline = true;
                    } elseif ($annot instanceof XmlAttributeMap) {
                        $propertyMetadata->xmlAttributeMap = true;
                    } elseif ($annot instanceof MaxDepth) {
                        $propertyMetadata->maxDepth = $annot->depth;
                    }
                }

                if ($propertyMetadata->inline) {
                    $classMetadata->isList = $classMetadata->isList || PropertyMetadata::isCollectionList($propertyMetadata->type);
                    $classMetadata->isMap = $classMetadata->isMap || PropertyMetadata::isCollectionMap($propertyMetadata->type);

                    if ($classMetadata->isMap && $classMetadata->isList) {
                        throw new InvalidMetadataException('Can not have an inline map and and inline map on the same class');
                    }
                }

                if (!$propertyMetadata->serializedName) {
                    $propertyMetadata->serializedName = $this->namingStrategy->translateName($propertyMetadata);
                }

                foreach ($propertyAnnotations as $annot) {
                    if ($annot instanceof VirtualProperty && null !== $annot->name) {
                        $propertyMetadata->name = $annot->name;
                    }
                }

                if (
                    (ExclusionPolicy::NONE === $exclusionPolicy && !$isExclude)
                    || (ExclusionPolicy::ALL === $exclusionPolicy && $isExpose)
                ) {
                    $propertyMetadata->setAccessor($accessType, $accessor[0], $accessor[1]);
                    $classMetadata->addPropertyMetadata($propertyMetadata);
                }
            }
        }

        return $classMetadata;
    }
}


text:
class PerconaXtrabackup < Formula
  desc "Open source hot backup tool for InnoDB and XtraDB databases"
  homepage "https://www.percona.com/software/mysql-database/percona-xtrabackup"
  url "https://www.percona.com/downloads/XtraBackup/Percona-XtraBackup-2.4.12/source/tarball/percona-xtrabackup-2.4.12.tar.gz"
  sha256 "de02cfd5bde96ddbf50339ef3a4646004dde52239698df45c19ed3e8ee40738e"

  bottle do
    sha256 "7f69dd77c9d2fa2f7d2b3634eca30bcbd083f426b033a049394c7c804bf788df" => :high_sierra
    sha256 "afe400789cd164fc668d888f8c0e0e7ca5a861aad7df9291648bf932a2ac8225" => :sierra
    sha256 "39b82780d9716d07186228027a09feb53ded26e25e671abcf463273687d45750" => :el_capitan
  end

  option "without-docs", "Build without man pages (which requires python-sphinx)"
  option "without-mysql-client", "Build without bundled Perl DBD::mysql module, to use the database of your choice."

  deprecated_option "without-mysql" => "without-mysql-client"

  depends_on "cmake" => :build
  depends_on "sphinx-doc" => :build if build.with? "docs"
  depends_on "mysql-client" => :recommended
  depends_on "libev"
  depends_on "libgcrypt"
  depends_on "openssl"

  resource "DBD::mysql" do
    url "https://cpan.metacpan.org/authors/id/C/CA/CAPTTOFU/DBD-mysql-4.046.tar.gz"
    sha256 "6165652ec959d05b97f5413fa3dff014b78a44cf6de21ae87283b28378daf1f7"
  end

  resource "boost" do
    url "https://downloads.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.bz2"
    sha256 "727a932322d94287b62abb1bd2d41723eec4356a7728909e38adb65ca25241ca"
  end

  def install
    cmake_args = %w[
      -DBUILD_CONFIG=xtrabackup_release
      -DCOMPILATION_COMMENT=Homebrew
    ]

    if build.with? "docs"
      cmake_args.concat %w[
        -DWITH_MAN_PAGES=ON
        -DINSTALL_MANDIR=share/man
      ]

      # macOS has this value empty by default.
      # See https://bugs.python.org/issue18378#msg215215
      ENV["LC_ALL"] = "en_US.UTF-8"
    else
      cmake_args << "-DWITH_MAN_PAGES=OFF"
    end

    # 1.59.0 specifically required. Detailed in cmake/boost.cmake
    (buildpath/"boost_1_59_0").install resource("boost")
    cmake_args << "-DWITH_BOOST=#{buildpath}/boost_1_59_0"

    cmake_args.concat std_cmake_args

    system "cmake", *cmake_args
    system "make"
    system "make", "install"

    share.install "share/man" if build.with? "docs"

    rm_rf prefix/"xtrabackup-test" # Remove unnecessary files
    # remove conflicting libraries that are already installed by mysql
    rm lib/"libmysqlservices.a"
    rm lib/"plugin/keyring_file.so"

    if build.with? "mysql-client"
      ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5"
      resource("DBD::mysql").stage do
        system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}"
        system "make", "install"
      end
      bin.env_script_all_files(libexec/"bin", :PERL5LIB => ENV["PERL5LIB"])
    end
  end

  test do
    assert_match version.to_s, shell_output("#{bin}/xtrabackup --version 2>&1")
  end
end


text:
package eu.com.cwsfe.cms.dao;

import eu.com.cwsfe.cms.DaoTestsConfiguration;
import eu.com.cwsfe.cms.domains.CmsUserStatus;
import eu.com.cwsfe.cms.model.CmsRole;
import eu.com.cwsfe.cms.model.CmsUser;
import eu.com.cwsfe.cms.model.CmsUserRole;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@Rollback
@ContextConfiguration(classes = {DaoTestsConfiguration.class, CmsUsersDAO.class, CmsRolesDAO.class, CmsUserRolesDAO.class})
@IfProfileValue(name = "test-groups", values = {"integration-tests-local"})
public class CmsUserRolesDAOTest extends AbstractTransactionalJUnit4SpringContextTests {

    @Autowired
    private CmsUsersDAO usersDao;
    @Autowired
    private CmsRolesDAO rolesDao;

    @Autowired
    private CmsUserRolesDAO dao;

    @Test
    public void testListForUser() throws Exception {
        //given
        //when
        List<CmsUserRole> cmsUserRoles = dao.listForUser(1L);
        //then
        assertNotNull("Roles for any user should not return null", cmsUserRoles);
    }

    @Test
    public void testAdd() throws Exception {
        //given
        String username = "test";
        String hash = "hash";
        CmsUser cmsUser = new CmsUser();
        cmsUser.setUserName(username);
        cmsUser.setStatus(CmsUserStatus.NEW);
        cmsUser.setPasswordHash(hash);
        Long userId = usersDao.add(cmsUser);
        CmsRole role = rolesDao.getByCode("ROLE_CWSFE_CMS_ADMIN");
        CmsUserRole cmsUserRole = new CmsUserRole(userId, role.getId());

        //when
        dao.add(cmsUserRole);

        //then
        List<CmsUserRole> results = dao.listForUser(userId);
        assertNotNull(results);
        assertEquals("User has one role assigned", 1, results.size());
    }

    @Test
    public void testDeleteForUser() throws Exception {
        //given
        String username = "test";
        String hash = "hash";
        CmsUser cmsUser = new CmsUser();
        cmsUser.setUserName(username);
        cmsUser.setStatus(CmsUserStatus.NEW);
        cmsUser.setPasswordHash(hash);
        Long userId = usersDao.add(cmsUser);
        CmsRole role = rolesDao.getByCode("ROLE_CWSFE_CMS_ADMIN");
        CmsUserRole cmsUserRole = new CmsUserRole(userId, role.getId());
        dao.add(cmsUserRole);

        //when
        dao.deleteForUser(userId);

        //then
        List<CmsUserRole> results = dao.listForUser(userId);
        assertNotNull(results);
        assertEquals("User should not have role assigned", 0, results.size());
    }

    @Test
    public void testDeleteForUserByUserRole() throws Exception {
        //given
        String username = "test";
        String hash = "hash";
        CmsUser cmsUser = new CmsUser();
        cmsUser.setUserName(username);
        cmsUser.setStatus(CmsUserStatus.NEW);
        cmsUser.setPasswordHash(hash);
        Long userId = usersDao.add(cmsUser);
        CmsRole role = rolesDao.getByCode("ROLE_CWSFE_CMS_ADMIN");
        CmsUserRole cmsUserRole = new CmsUserRole(userId, role.getId());
        dao.add(cmsUserRole);

        //when
        dao.deleteForUser(cmsUserRole);

        //then
        List<CmsUserRole> results = dao.listForUser(userId);
        assertNotNull(results);
        assertEquals("User should not have role assigned", 0, results.size());
    }

}


text:
//
//  AppointProgressDetailController.h
//  TiJian
//
//  Created by lichaowei on 16/3/8.
//  Copyright © 2016年 lcw. All rights reserved.

/**
 *  预约进度详情
 */
#import "MyViewController.h"

@interface AppointProgressDetailController : MyViewController

@property(nonatomic,retain)NSString *appointId;

@end


text:
Repository Commands
===================
The files in this directory are intended to be run as command line commands.
Some are Bash scripts, while others are Node scripts which depend on Node to be
installed before use.

If you have not run `bin/init` (see below) you will not see anything in this
directory other than this README and the init script.

Also, if you are viewing this README remotely, you will not see the other
scripts since they are created locally by the init script and are *not* tracked
by git.

### init

    bin/init

`bin/init` Is a Bash script which will initialize the project repository. If
this is a fresh clone of the repository, don't expect anything to work until
`bin/init` is run.

### cake

    bin/cake

`bin/cake` is the CoffeeScript driven build tool which is configured by the
`Cakefile` in the project root. Your current working directory must be the
project root (where the Cakefile is located) for `bin/cake` to do anything. Run
`bin/cake` to see the usage help screen.

### coffee

    bin/coffee

`bin/coffee` is used to compile CoffeeScript files into JS and can be used to
do this whenever you have the need to build something. Run `bin/coffee` to see
the usage help screen.

### nave

    bin/nave

`nave` provides several commands for you to manage your virtual Node.js
environment.  Run `bin/nave` to see the usage help and checkout the
[docs](https://github.com/isaacs/nave) for more info.


text:
namespace v8 {
namespace internal {

// LayoutDescriptor is a bit vector defining which fields contain non-tagged
// values. It could either be a fixed typed array (slow form) or a Smi
// if the length fits (fast form).
// Each bit in the layout represents a FIELD. The bits are referenced by
// field_index which is a field number. If the bit is set then the corresponding
// field contains a non-tagged value and therefore must be skipped by GC.
// Otherwise the field is considered tagged. If the queried bit lays "outside"
// of the descriptor then the field is also considered tagged.
// Once a layout descriptor is created it is allowed only to append properties
// to it. GC uses layout descriptors to iterate objects. Avoid heap pointers
// in a layout descriptor because they can lead to data races in GC when
// GC moves objects in parallel.
class V8_EXPORT_PRIVATE LayoutDescriptor : public ByteArray {
 public:
  V8_INLINE bool IsTagged(int field_index);

  // Queries the contiguous region of fields that are either tagged or not.
  // Returns true if the given field is tagged or false otherwise and writes
  // the length of the contiguous region to |out_sequence_length|.
  // If the sequence is longer than |max_sequence_length| then
  // |out_sequence_length| is set to |max_sequence_length|.
  bool IsTagged(int field_index, int max_sequence_length,
                int* out_sequence_length);

  // Returns true if this is a layout of the object having only tagged fields.
  V8_INLINE bool IsFastPointerLayout();
  V8_INLINE static bool IsFastPointerLayout(Object layout_descriptor);

  // Returns true if the layout descriptor is in non-Smi form.
  V8_INLINE bool IsSlowLayout();

  DECL_CAST(LayoutDescriptor)

  V8_INLINE static LayoutDescriptor cast_gc_safe(Object object);

  // Builds layout descriptor optimized for given |map| by |num_descriptors|
  // elements of given descriptors array. The |map|'s descriptors could be
  // different.
  static Handle<LayoutDescriptor> New(Isolate* isolate, Handle<Map> map,
                                      Handle<DescriptorArray> descriptors,
                                      int num_descriptors);

  // Modifies |map|'s layout descriptor or creates a new one if necessary by
  // appending property with |details| to it.
  static Handle<LayoutDescriptor> ShareAppend(Isolate* isolate, Handle<Map> map,
                                              PropertyDetails details);

  // Creates new layout descriptor by appending property with |details| to
  // |map|'s layout descriptor and if it is still fast then returns it.
  // Otherwise the |full_layout_descriptor| is returned.
  static Handle<LayoutDescriptor> AppendIfFastOrUseFull(
      Isolate* isolate, Handle<Map> map, PropertyDetails details,
      Handle<LayoutDescriptor> full_layout_descriptor);

  // Layout descriptor that corresponds to an object all fields of which are
  // tagged (FastPointerLayout).
  V8_INLINE static LayoutDescriptor FastPointerLayout();

  // Check that this layout descriptor corresponds to given map.
  bool IsConsistentWithMap(Map map, bool check_tail = false);

  // Trims this layout descriptor to given number of descriptors. This happens
  // only when corresponding descriptors array is trimmed.
  // The layout descriptor could be trimmed if it was slow or it could
  // become fast.
  LayoutDescriptor Trim(Heap* heap, Map map, DescriptorArray descriptors,
                        int num_descriptors);

#ifdef OBJECT_PRINT
  // For our gdb macros, we should perhaps change these in the future.
  void Print();

  void ShortPrint(std::ostream& os);
  void Print(std::ostream& os);  // NOLINT
#endif

  // Capacity of layout descriptors in bits.
  V8_INLINE int capacity();

  static Handle<LayoutDescriptor> NewForTesting(Isolate* isolate, int length);
  LayoutDescriptor SetTaggedForTesting(int field_index, bool tagged);

 private:
  // Exclude sign-bit to simplify encoding.
  static constexpr int kBitsInSmiLayout =
      SmiValuesAre32Bits() ? 32 : kSmiValueSize - 1;

  static const int kBitsPerLayoutWord = 32;

  V8_INLINE int number_of_layout_words();
  V8_INLINE uint32_t get_layout_word(int index) const;
  V8_INLINE void set_layout_word(int index, uint32_t value);

  V8_INLINE static Handle<LayoutDescriptor> New(Isolate* isolate, int length);
  V8_INLINE static LayoutDescriptor FromSmi(Smi smi);

  V8_INLINE static bool InobjectUnboxedField(int inobject_properties,
                                             PropertyDetails details);

  // Calculates minimal layout descriptor capacity required for given
  // |map|, |descriptors| and |num_descriptors|.
  V8_INLINE static int CalculateCapacity(Map map, DescriptorArray descriptors,
                                         int num_descriptors);

  // Calculates the length of the slow-mode backing store array by given layout
  // descriptor length.
  V8_INLINE static int GetSlowModeBackingStoreLength(int length);

  // Fills in clean |layout_descriptor| according to given |map|, |descriptors|
  // and |num_descriptors|.
  V8_INLINE static LayoutDescriptor Initialize(
      LayoutDescriptor layout_descriptor, Map map, DescriptorArray descriptors,
      int num_descriptors);

  static Handle<LayoutDescriptor> EnsureCapacity(
      Isolate* isolate, Handle<LayoutDescriptor> layout_descriptor,
      int new_capacity);

  // Returns false if requested field_index is out of bounds.
  V8_INLINE bool GetIndexes(int field_index, int* layout_word_index,
                            int* layout_bit_index);

  V8_INLINE V8_WARN_UNUSED_RESULT LayoutDescriptor SetRawData(int field_index);

  V8_INLINE V8_WARN_UNUSED_RESULT LayoutDescriptor SetTagged(int field_index,
                                                             bool tagged);

  OBJECT_CONSTRUCTORS(LayoutDescriptor, ByteArray);
};

// LayoutDescriptorHelper is a helper class for querying layout descriptor
// about whether the field at given offset is tagged or not.
class LayoutDescriptorHelper {
 public:
  inline explicit LayoutDescriptorHelper(Map map);

  bool all_fields_tagged() { return all_fields_tagged_; }
  inline bool IsTagged(int offset_in_bytes);

  // Queries the contiguous region of fields that are either tagged or not.
  // Returns true if fields starting at |offset_in_bytes| are tagged or false
  // otherwise and writes the offset of the end of the contiguous region to
  // |out_end_of_contiguous_region_offset|. The |end_offset| value is the
  // upper bound for |out_end_of_contiguous_region_offset|.
  V8_EXPORT_PRIVATE bool IsTagged(int offset_in_bytes, int end_offset,
                                  int* out_end_of_contiguous_region_offset);

 private:
  bool all_fields_tagged_;
  int header_size_;
  LayoutDescriptor layout_descriptor_;
};
}  // namespace internal
}  // namespace v8

#include "src/objects/object-macros-undef.h"

#endif  // V8_OBJECTS_LAYOUT_DESCRIPTOR_H_


text:
id: 587d781b367417b2b2512abb
title: Create a Horizontal Line Using the hr Element
challengeType: 0
videoUrl: 'https://scrimba.com/c/c3bR8t7'
forumTopicId: 301049
---

## Description

You can use the hr tag to add a horizontal line across the width of its containing element. This can be used to define a change in topic or to visually separate groups of content.

## Instructions

Add an hr tag underneath the h4 which contains the card title.
Note: In HTML, hr is a self-closing tag, and therefore doesn't need a separate closing tag.

## Tests

```yml
tests:
  - text: Your code should add an <code>hr</code> tag to the markup.
    testString: assert($('hr').length == 1);
  - text: The <code>hr</code> tag should come between the title and the paragraph.
    testString: assert(code.match(/<\/h4>\s*?<hr(>|\s*?\/>)\s*?<p>/gi));

```

## Challenge Seed

```html
<style>
  h4 {
    text-align: center;
    height: 25px;
  }
  p {
    text-align: justify;
  }
  .links {
    text-align: left;
    color: black;
  }
  .fullCard {
    width: 245px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin: 10px 5px;
    padding: 4px;
  }
  .cardContent {
    padding: 10px;
  }
  .cardText {
    margin-bottom: 30px;
  }
</style>
<div class="fullCard">
  <div class="cardContent">
    <div class="cardText">
      <h4><s>Google</s>Alphabet</h4>

      <p><em>Google was founded by Larry Page and Sergey Brin while they were <u>Ph.D. students</u> at <strong>Stanford University</strong>.</em></p>
    </div>
    <div class="cardLinks">
      <a href="https://en.wikipedia.org/wiki/Larry_Page" target="_blank" class="links">Larry Page</a><br><br>
      <a href="https://en.wikipedia.org/wiki/Sergey_Brin" target="_blank" class="links">Sergey Brin</a>
    </div>
  </div>
</div>
```

## Solution

```html
<style>
  h4 {
    text-align: center;
    height: 25px;
  }
  p {
    text-align: justify;
  }
  .links {
    text-align: left;
    color: black;
  }
  .fullCard {
    width: 245px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin: 10px 5px;
    padding: 4px;
  }
  .cardContent {
    padding: 10px;
  }
  .cardText {
    margin-bottom: 30px;
  }
</style>
<div class="fullCard">
  <div class="cardContent">
    <div class="cardText">
      <h4><s>Google</s>Alphabet</h4>
      <hr>
      <p><em>Google was founded by Larry Page and Sergey Brin while they were <u>Ph.D. students</u> at <strong>Stanford University</strong>.</em></p>
    </div>
    <div class="cardLinks">
      <a href="https://en.wikipedia.org/wiki/Larry_Page" target="_blank" class="links">Larry Page</a><br><br>
      <a href="https://en.wikipedia.org/wiki/Sergey_Brin" target="_blank" class="links">Sergey Brin</a>
    </div>
  </div>
</div>
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using LanguageHelpers.Localization.Data;
using LanguageHelpers.Localization.Models;

namespace LanguageHelpers.Localization.Services
{
    public class LanguageService : ILanguageService
    {
        private readonly IUnitOfWork _unitOfWork;

        public LanguageService(IUnitOfWork unitOfWork)
        {
            this._unitOfWork = unitOfWork;
        }

        public bool AddLanguage(Language language)
        {
            _unitOfWork.LanguageRepository.Add(language);
            var texts = _unitOfWork.LocalizedTextRepository.FindBy(m=>m.LanguageCode=="EN");
            foreach (var localizedText in texts)
            {
                var newText = new LocalizedText()
                    {
                        LanguageCode = language.LanguageCode,
                        TextKey = localizedText.TextKey
                    };
                _unitOfWork.LocalizedTextRepository.Add(newText);
            }
            _unitOfWork.Save();
            return true;
        }

        public bool DeleteLanguage(Language language)
        {
            if (language == null) return false;
            _unitOfWork.LanguageRepository.Delete(language);
            _unitOfWork.Save();
            return true;
        }

        public bool DeleteById(int id)
        {
            var entity = _unitOfWork.LanguageRepository.FindById(id);
            if (entity == null) return false;
            _unitOfWork.LanguageRepository.Delete(entity);
            _unitOfWork.Save();
            return true;
        }

        public bool EditLanguage(Language language)
        {
            _unitOfWork.LanguageRepository.Edit(language);
            _unitOfWork.Save();
            return true;
        }

        public Language FindById(int id)
        {
            return _unitOfWork.LanguageRepository.FindById(id);
        }

        public List<Language> GetAllLanguage()
        {
            return _unitOfWork.LanguageRepository.GetAll();
        }

        public List<Language> FindBy(System.Linq.Expressions.Expression<Func<Language, bool>> predicate)
        {
            return _unitOfWork.LanguageRepository.FindBy(predicate);
        }

        public IEnumerable<Language> Get(System.Linq.Expressions.Expression<Func<Language, bool>> filter = null, Func<IQueryable<Language>, IOrderedQueryable<Language>> orderBy = null, string includeProperties = "")
        {
            return _unitOfWork.LanguageRepository.Get(filter, orderBy, includeProperties);
        }

        public bool Save()
        {
            _unitOfWork.Save();
            return true;
        }
    }
}


text:
Function New-XmlDocument
{
    <#
        .Synopsis

        .Description

        .Parameter x

        .Outputs

        .Example

    #>
    [CmdletBinding()]
    Param
    (
		[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
		[string]$DocumentElementName
    )

    Begin
    {
    }

    Process
    {
        $xml = New-Object System.Xml.XmlDocument
        [Void]$xml.AppendChild($xml.CreateXmlDeclaration('1.0', 'UTF-8', $null))
        [Void]$xml.AppendChild($xml.CreateElement($DocumentElementName))
		Write-Output $xml
    }

    End
    {
    }
}


text:
.csstransitions.csstransforms .deck-container {
  overflow-y: hidden;
}
.csstransitions.csstransforms .deck-container > .slide {
  -webkit-transition: -webkit-transform 500ms ease-in-out;
  -moz-transition: -moz-transform 500ms ease-in-out;
  -ms-transition: -ms-transform 500ms ease-in-out;
  -o-transition: -o-transform 500ms ease-in-out;
  transition: transform 500ms ease-in-out;
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide {
  position: absolute;
  top: 0;
  left: 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  width: 100%;
  padding: 0 48px;
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .slide {
  position: relative;
  left: 0;
  top: 0;
  -webkit-transition: -webkit-transform 500ms ease-in-out, opacity 500ms ease-in-out;
  -moz-transition: -moz-transform 500ms ease-in-out, opacity 500ms ease-in-out;
  -ms-transition: -ms-transform 500ms ease-in-out, opacity 500ms ease-in-out;
  -o-transition: -o-transform 500ms ease-in-out, opacity 500ms ease-in-out;
  transition: -webkit-transform 500ms ease-in-out, opacity 500ms ease-in-out;
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .deck-next, .csstransitions.csstransforms .deck-container:not(.deck-menu) > .slide .deck-after {
  visibility: visible;
  -webkit-transform: translate3d(0, 1600px, 0);
  -moz-transform: translate(0, 1600px);
  -ms-transform: translate(0, 1600px);
  -o-transform: translate(0, 1600px);
  transform: translate3d(0, 1600px, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-previous {
  -webkit-transform: translate3d(0, -200%, 0);
  -moz-transform: translate(0, -200%);
  -ms-transform: translate(0, -200%);
  -o-transform: translate(0, -200%);
  transform: translate3d(0, -200%, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-before {
  -webkit-transform: translate3d(0, -400%, 0);
  -moz-transform: translate(0, -400%);
  -ms-transform: translate(0, -400%);
  -o-transform: translate(0, -400%);
  transform: translate3d(0, -400%, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-next {
  -webkit-transform: translate3d(0, 200%, 0);
  -moz-transform: translate(0, 200%);
  -ms-transform: translate(0, 200%);
  -o-transform: translate(0, 200%);
  transform: translate3d(0, 200%, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-after {
  -webkit-transform: translate3d(0, 400%, 0);
  -moz-transform: translate(0, 400%);
  -ms-transform: translate(0, 400%);
  -o-transform: translate(0, 400%);
  transform: translate3d(0, 400%, 0);
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-before .slide, .csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-previous .slide {
  visibility: visible;
}
.csstransitions.csstransforms .deck-container:not(.deck-menu) > .deck-child-current {
  -webkit-transform: none;
  -moz-transform: none;
  -ms-transform: none;
  -o-transform: none;
  transform: none;
}
.csstransitions.csstransforms .deck-prev-link {
  left: auto;
  right: 8px;
  top: 59px;
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  -o-transform: rotate(90deg);
  transform: rotate(90deg);
}
.csstransitions.csstransforms .deck-next-link {
  top: 99px;
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  -o-transform: rotate(90deg);
  transform: rotate(90deg);
}


text:
{-|
Copyright   : (c) Dave Laing, 2017
License     : BSD3
Maintainer  : dave.laing.80@gmail.com
Stability   : experimental
Portability : non-portable
-}
{-# LANGUAGE ConstraintKinds #-}
module Fragment.Pair.Rules.Kind.Infer.SyntaxDirected (
    PairInferKindContext
  , pairInferKindRules
  ) where

import Control.Lens (review, preview)
import Control.Monad.Except (MonadError)
import Data.Functor.Classes (Eq1)

import Ast.Kind
import Ast.Type
import Ast.Error.Common
import Rules.Kind.Infer.SyntaxDirected

import Fragment.KiBase.Ast.Kind
import Fragment.Pair.Ast.Type

inferTyPair :: (MonadError e m, AsUnexpectedKind e ki, Eq1 ki, AsKiBase ki, AsTyPair ki ty)
            => (Type ki ty a -> m (Kind ki))
            -> Type ki ty a
            -> Maybe (m (Kind ki))
inferTyPair inferFn ty = do
  (ty1, ty2) <- preview _TyPair ty
  return $ do
    let ki = review _KiBase()
    mkCheckKind inferFn ty1 ki
    mkCheckKind inferFn ty2 ki
    return . review _KiBase $ ()

type PairInferKindContext e w s r m ki ty a = (MonadError e m, AsUnexpectedKind e ki, Eq1 ki, AsKiBase ki, AsTyPair ki ty)

pairInferKindRules :: PairInferKindContext e w s r m ki ty a
                   => InferKindInput e w s r m ki ty a
pairInferKindRules =
  InferKindInput
    [InferKindRecurse inferTyPair]


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Validation extends CI_Controller {

    public function __construct() {
        parent::__construct();
        //DEFINIMOS EL NOMBRE DEL MODULO
        $this->module_sigla = 'VAL';

        $this->load->helper('miscellaneous');
        $this->load->helper('security');

        $this->load->model('validation_model');
        validate_login($this->session->userdata('logged_in'));
    }

    public function insert($COMPONENTE_ID, $PREGUNTA_NIVELPREGUNTA) {
        $insert = $this->validation_model->update_question_validate();
        if ($insert) {
            $this->session->set_flashdata(array('message' => 'Pregunta Actualizada con Exito.', 'message_type' => 'info'));
            redirect('index.php/question/view/' . $COMPONENTE_ID . '/' . $PREGUNTA_NIVELPREGUNTA, 'refresh');
        } else {
            $this->session->set_flashdata(array('message' => 'Error al Actualizar la Pregunta.', 'message_type' => 'error'));
            redirect('index.php/selection/view/' . $COMPONENTE_ID . '/' . $PREGUNTA_NIVELPREGUNTA, 'refresh');
        }
    }

}


text:
[![Build Status](https://travis-ci.org/verdigris-cookbooks/opsworks-logstash.svg)](https://travis-ci.org/verdigris-cookbooks/opsworks-logstash)

This is a wrapper cookbook which utilizes the [logstash cookbook](https://github.com/lusis/chef-logstash)
for installing [Logstash](http://logstash.net/) on AWS OpsWorks.

## Requirements

### Platforms

* Amazon Linux
* Ubuntu 12.04 LTS
* Ubuntu 14.04 LTS

### Cookbooks

* **logstash** (~> 0.11)

## Attributes

| Key                                      |  Type  | Description                                                                | Default                                                 |
|:-----------------------------------------|:------:|:---------------------------------------------------------------------------|:--------------------------------------------------------|
| `['opsworks_logstash']['instance_name']` | String | Instance name for Logstash; used for setting up directory and service name | EC2 instance name in AWS OpsWorks, `"server"` otherwise |

## Recipes

### default

Installs Logstash and sets up configuration and pattern files.

## License

This cookbook is licensed and distributed under the Simplified BSD license.
See [LICENSE](https://github.com/verdigris-cookbooks/opsworks-rabbitmq/blob/master/LICENSE)
for more details.


text:
import React from 'react'
import ReactDOM from 'react-dom';
import ShToast from '../src/sh-toast-service'
import '../node_modules/sh-core/bin/main.css';
import '../node_modules/sh-icons/bin/main.css';
import '../node_modules/sh-buttons/bin/main.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            toast: null
        };
        this.openMe = this.openMe.bind(this);
    }

    componentDidMount() {
        this.setState({
            toast: new ShToast('Your content has been saved and is now available to be seen on the interwebbs, how does that make you feel?', 'success', 'icon-envelope', 1000000,'from-top right error')
        })
    }

    simulate() {
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log('make request to save');
                resolve();
            }, 3000)
        });
    }

    openMe() {
        this.state.toast.open().then(() => {
            return this.simulate();
        }).then(() => {
            return this.state.toast.close();
        })
    }

    render() {
        return (
            <div>
                <button className="sh-btn sh-btn-default" onClick={this.openMe}>Toast Me</button>
            </div>
        )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'));


text:
<!DOCTYPE html>
<title>iframe for #target and scroll-snap-padding with snapping off (y</title>

FAIL

FAIL


text:
<?php
	// soft dependency
	use_helper('sfMooDiaBox');
	plgContentDiaBoxActivate();

	use_helper('sfMooNoobSlide');
	plgContentNoobSlideActivate();
	plgContentNoobSlide(array(
		'title' => 'AlumniBook Screenshot',
		'subtitle' => 'Any related AlumniBook ports.',
		'lightbox_type' => 3,	// use diabox
		// picasa mode
		'picasa_user'	=> 'epsi.rns',
		'picasa_album'	=> 'AlumniBook'
	));


text:
using SqlFu;
using SqlFu.Builders.CreateTable;
using SqlFu.Providers.Sqlite;
using SqlFu.Providers.SqlServer;

namespace DomainBus.Sql.Processor
{
    public class ProcessorMessagesRowCreator : ATypedStorageCreator<ProcessorMessagesRow>
    {
        public ProcessorMessagesRowCreator(IDbFactory db) : base(db)
        {
        }

        protected override void Configure(IConfigureTable<ProcessorMessagesRow> cfg)
        {
            cfg.ColumnSize(d => d.Processor, 75)
                .Column(d => d.ArrivalId, c => c.AutoIncrement())

                .Index(pk=>pk.OnColumns(d=>d.MessageId,d=>d.Processor).Unique());
            if (this._db.Provider.IsSqlite())
            {
                cfg.ColumnDbType(d => d.MessageId, SqliteType.Text)

                    //.PrimaryKey(pk => pk.OnColumns(d => d.ArrivalId))
                    ;

            }
            if (this._db.Provider.IsSqlserver())
            {
                cfg.ColumnSize(d => d.Data, "max")
                    .PrimaryKey(pk => pk.OnColumns(d => d.ArrivalId))
                    //.Column(d => d.ArrivalId, c => c.AutoIncrement())
                ;
            }
        }
    }
}


text:
int main (int argnum, char **argv)
{
	if (argnum < 3) {
		printf("Usage: %s <input interface> <output interface>\n", argv[0]);
		exit(-1);
	}

	printf("Reading broadcast packets from %s and relaying to %s..\n",
			argv[1],argv[2]);

    //Create a raw socket of type IPPROTO
	int s_in = socket (AF_INET, SOCK_RAW, IPPROTO_UDP);
	int s_out = socket (AF_INET, SOCK_RAW, IPPROTO_UDP);

    if(s_out == -1)
    {
        //socket creation failed, may be because of non-root privileges
        perror("Failed to create raw socket");
        exit(1);
    }

    // Bind to our actual interface
	struct ifreq ifr_in;
	struct ifreq ifr_out;
	memset(&ifr_in, 0, sizeof(ifr_in));
	memset(&ifr_out, 0, sizeof(ifr_out));

	//
	// Input binding
	//
	strncpy(ifr_in.ifr_name, argv[1], sizeof(ifr_in.ifr_name));

	// Bind to interface
	if (setsockopt(s_in, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr_in, sizeof(ifr_in)) < 0) {
		perror("Could not bind to interface.");
		// If something wrong just exit
		exit(-1);
	}

	// Get our ip
	if (ioctl(s_out, SIOCGIFADDR, &ifr_in) < 0)
		perror("SIOCGIFADDR");

	// display result
	struct in_addr ip_in = ((struct sockaddr_in *)&ifr_in.ifr_addr)->sin_addr;

	//
	// Output binding
	//
	strncpy(ifr_out.ifr_name, argv[2], sizeof(ifr_out.ifr_name));
	if (setsockopt(s_out, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr_out, sizeof(ifr_out)) < 0) {
		perror("Could not bind to interface.");
		// If something wrong just exit
		exit(-1);
	}

	// allow broadcast messages for the socket
	int true = 1;
	if (setsockopt(s_out, SOL_SOCKET, SO_BROADCAST, &true, sizeof(true))) {
		printf ("Could not set SO_BROADCAST (%s)\n", strerror(errno));
		exit (-1);
	}

	// Don't include headers by default.
//	int hdrincl=1;
//	if (setsockopt(s_out,IPPROTO_IP,IP_HDRINCL,&hdrincl,sizeof(hdrincl))==-1) {
//	    printf("%s",strerror(errno));
//	    exit(-1);
//	}

	// Get our ip
	if (ioctl(s_out, SIOCGIFADDR, &ifr_out) < 0)
		perror("SIOCGIFADDR");

	// display result
	struct in_addr ip_out = ((struct sockaddr_in *)&ifr_out.ifr_addr)->sin_addr;

	printf("Bound input to: %s\n", inet_ntoa(ip_in));
	printf("Bound output to: %s\n", inet_ntoa(ip_out));

    //Datagram to represent the packet
    char datagram[MAX_UDP];
//    char *data;

    //zero out the packet buffer
    memset (datagram, 0, 4096);

    //IP header
    struct iphdr *iph = (struct iphdr *) datagram;

    //UDP header
    struct udphdr *udph = (struct udphdr *) (datagram + sizeof(struct iphdr));

    //Data part
//    data = datagram + sizeof(struct iphdr) + sizeof(struct udphdr);

    // What ip do we forward to?
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(FORWARD_PORT);
    sin.sin_addr.s_addr = inet_addr ("255.255.255.255");

    // Receive data
    struct sockaddr_in recv_sa;
    int read_bytes = 0;
    int recvlen = sizeof(recv_sa);

    // Loop forever
    while (1)
    {
    	//Recieve a packet
    	read_bytes = recvfrom(s_in, datagram, sizeof(datagram), 0,
                (struct sockaddr *)&recv_sa, (socklen_t*)&recvlen);
    	if (read_bytes < 0){
			perror("recvfrom failed");
			break;
		}

    	if (VERBOSE && iph->saddr != ip_out.s_addr && iph->saddr != ip_in.s_addr) {
    		printf("Read %d bytes.", read_bytes);
    		printf("Dest IP: %08X, Port: %04X\n",iph->daddr, udph->dest);
    	}

    	//printf("%08X == %08X or %08X?\n", iph->saddr, ip_out.s_addr, ip_in.s_addr);
    	if (iph->saddr == ip_out.s_addr ||
    		iph->saddr == ip_in.s_addr) {
    		if (VERBOSE) {
    			printf("Received a loopback packet, ignoring.\n");
    		}
    		continue;
    	}

    	// Check to see if this is a packet that should be forwarded
    	if ((iph->daddr & FORWARD_MASK) == FORWARD_MASK
    			&& ntohs(udph->dest) == FORWARD_PORT) {

    		if (VERBOSE)
    			printf("Forwarding broadcast packet.\n");

			//Send the packet
		int data_len = ntohs(udph->len);
			if (sendto (s_out,
					udph,
					data_len,
					0, (struct sockaddr *) &sin,
					sizeof (sin)) < 0)
			{
				perror("sendto failed");
				break;
			}
			//Data send successfully
			else if (VERBOSE) {
				printf ("Packet Send. Length : %d \n" , iph->tot_len);
			}
    	}
    }

    return 0;
}


text:
// This file exists for the convenience of QxtBoundCFunction.
// It is not part of the public API and is subject to change.
//
// We mean it.

#ifndef QXTBOUNDFUNCTIONBASE_H
#define QXTBOUNDFUNCTIONBASE_H

#include <QObject>
#include <QMetaObject>
#include <QGenericArgument>
#include <qxtmetaobject.h>
#include <qxtboundfunction.h>

#ifndef QXT_DOXYGEN_RUN

#define QXT_10_UNUSED Q_UNUSED(p1) Q_UNUSED(p2) Q_UNUSED(p3) Q_UNUSED(p4) Q_UNUSED(p5) Q_UNUSED(p6) Q_UNUSED(p7) Q_UNUSED(p8) Q_UNUSED(p9) Q_UNUSED(p10)

class QXT_CORE_EXPORT QxtBoundFunctionBase : public QxtBoundFunction
{
public:
    QByteArray bindTypes[10];
    QGenericArgument arg[10], p[10];
    void* data[10];

    QxtBoundFunctionBase(QObject* parent, QGenericArgument* params[10], QByteArray types[10]);
    virtual ~QxtBoundFunctionBase();

    int qt_metacall(QMetaObject::Call _c, int _id, void **_a);
    bool invokeBase(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_PROTO_10ARGS(QGenericArgument));
};

#define QXT_ARG(i) ((argCount>i)?QGenericArgument(p ## i .typeName(), p ## i .constData()):QGenericArgument())
#define QXT_VAR_ARG(i) (p ## i .isValid())?QGenericArgument(p ## i .typeName(), p ## i .constData()):QGenericArgument()
#endif
#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <!--40% opacity to 0% opacity, as Material Design Spec suggests-->
            <gradient android:startColor="#00000000" android:endColor="#66000000" android:angle="270" />
        </shape>
    </item>
</selector>