text:
package com.intellij.openapi.wm.impl;

import com.intellij.ide.actions.ResizeToolWindowAction;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManagerListener;
import com.intellij.openapi.keymap.ex.KeymapManagerEx;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.ex.ToolWindowEx;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.ui.UIBundle;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.content.Content;
import com.intellij.util.Producer;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.EventListenerList;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Map;

/**
 * @author Eugene Belyaev
 * @author Vladimir Kondratyev
 */
public final class InternalDecorator extends JPanel implements Queryable, TypeSafeDataProvider {

  private static final int DIVIDER_WIDTH = UIUtil.isUnderDarcula() ? 2 : 5;

  private Project myProject;
  private WindowInfoImpl myInfo;
  private final ToolWindowImpl myToolWindow;
  private final MyDivider myDivider;
  private final EventListenerList myListenerList;
  /*
   * Actions
   */
  private final TogglePinnedModeAction myToggleAutoHideModeAction;
  private final ToggleDockModeAction myToggleDockModeAction;
  private final ToggleFloatingModeAction myToggleFloatingModeAction;
  private final ToggleSideModeAction myToggleSideModeAction;
  private final ToggleContentUiTypeAction myToggleContentUiTypeAction;

  private ActionGroup myAdditionalGearActions;
  /**
   * Catches all event from tool window and modifies decorator's appearance.
   */
  private final ToolWindowHandler myToolWindowHandler;
  private final MyKeymapManagerListener myWeakKeymapManagerListener;
  @NonNls private static final String HIDE_ACTIVE_WINDOW_ACTION_ID = "HideActiveWindow";
  @NonNls public static final String TOGGLE_PINNED_MODE_ACTION_ID = "TogglePinnedMode";
  @NonNls public static final String TOGGLE_DOCK_MODE_ACTION_ID = "ToggleDockMode";
  @NonNls public static final String TOGGLE_FLOATING_MODE_ACTION_ID = "ToggleFloatingMode";
  @NonNls public static final String TOGGLE_SIDE_MODE_ACTION_ID = "ToggleSideMode";
  @NonNls private static final String TOGGLE_CONTENT_UI_TYPE_ACTION_ID = "ToggleContentUiTypeMode";

  private ToolWindowHeader myHeader;

  InternalDecorator(final Project project, final WindowInfoImpl info, final ToolWindowImpl toolWindow) {
    super(new BorderLayout());
    myProject = project;
    myToolWindow = toolWindow;
    myToolWindow.setDecorator(this);
    myDivider = new MyDivider();

    myToggleFloatingModeAction = new ToggleFloatingModeAction();
    myToggleSideModeAction = new ToggleSideModeAction();
    myToggleDockModeAction = new ToggleDockModeAction();
    myToggleAutoHideModeAction = new TogglePinnedModeAction();
    myToggleContentUiTypeAction = new ToggleContentUiTypeAction();

    myListenerList = new EventListenerList();

    myHeader = new ToolWindowHeader(toolWindow, info, new Producer<ActionGroup>() {
      @Override
      public ActionGroup produce() {
        return createGearPopupGroup();
      }
    }) {
      @Override
      protected boolean isActive() {
        return isFocused();
      }

      @Override
      protected void hideToolWindow() {
        fireHidden();
      }

      @Override
      protected void toolWindowTypeChanged(ToolWindowType type) {
        fireTypeChanged(type);
      }

      @Override
      protected void sideHidden() {
        fireHiddenSide();
      }
    };

    MyKeymapManagerListener keymapManagerListener = new MyKeymapManagerListener();
    final KeymapManagerEx keymapManager = KeymapManagerEx.getInstanceEx();
    myWeakKeymapManagerListener = keymapManagerListener;
    keymapManager.addWeakListener(keymapManagerListener);

    init();

    myToolWindowHandler = new ToolWindowHandler();
    myToolWindow.addPropertyChangeListener(myToolWindowHandler);

    apply(info);
  }

  public boolean isFocused() {
    IdeFocusManager fm = IdeFocusManager.getInstance(myProject);
    Component component = fm.getFocusedDescendantFor(myToolWindow.getComponent());
    if (component != null) return true;

    Component owner = fm.getLastFocusedFor(WindowManager.getInstance().getIdeFrame(myProject));

    return owner != null && SwingUtilities.isDescendingFrom(owner, myToolWindow.getComponent());
  }

  /**
   * Applies specified decoration.
   */
  public final void apply(final WindowInfoImpl info) {
    if (Comparing.equal(myInfo, info) || myProject == null || myProject.isDisposed()) {
      return;
    }
    myInfo = info;

    // Anchor
    final ToolWindowAnchor anchor = myInfo.getAnchor();
    if (info.isSliding()) {
      myDivider.invalidate();
      if (ToolWindowAnchor.TOP == anchor) {
        add(myDivider, BorderLayout.SOUTH);
      }
      else if (ToolWindowAnchor.LEFT == anchor) {
        add(myDivider, BorderLayout.EAST);
      }
      else if (ToolWindowAnchor.BOTTOM == anchor) {
        add(myDivider, BorderLayout.NORTH);
      }
      else if (ToolWindowAnchor.RIGHT == anchor) {
        add(myDivider, BorderLayout.WEST);
      }
      myDivider.setPreferredSize(new Dimension(DIVIDER_WIDTH, DIVIDER_WIDTH));
    }
    else { // docked and floating windows don't have divider
      remove(myDivider);
    }

    validate();
    repaint();

    //
    updateTitle();

    // Push "apply" request forward

    if (myInfo.isFloating() && myInfo.isVisible()) {
      final FloatingDecorator floatingDecorator = (FloatingDecorator)SwingUtilities.getAncestorOfClass(FloatingDecorator.class, this);
      if (floatingDecorator != null) {
        floatingDecorator.apply(myInfo);
      }
    }

    myToolWindow.getContentUI().setType(myInfo.getContentUiType());
    setBorder(new InnerPanelBorder(myToolWindow));
  }

  @Override
  public void calcData(DataKey key, DataSink sink) {
    if (PlatformDataKeys.TOOL_WINDOW.equals(key)) {
      sink.put(PlatformDataKeys.TOOL_WINDOW, myToolWindow);
    }
  }

  final void addInternalDecoratorListener(final InternalDecoratorListener l) {
    myListenerList.add(InternalDecoratorListener.class, l);
  }

  final void removeInternalDecoratorListener(final InternalDecoratorListener l) {
    myListenerList.remove(InternalDecoratorListener.class, l);
  }

  final void dispose() {
    removeAll();
    myToolWindow.removePropertyChangeListener(myToolWindowHandler);
    KeymapManagerEx.getInstanceEx().removeWeakListener(myWeakKeymapManagerListener);

    Disposer.dispose(myHeader);
    myHeader = null;
    myProject = null;
  }

  private void fireAnchorChanged(final ToolWindowAnchor anchor) {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.anchorChanged(this, anchor);
    }
  }

  private void fireAutoHideChanged(final boolean autoHide) {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.autoHideChanged(this, autoHide);
    }
  }

  /**
   * Fires event that "hide" button has been pressed.
   */
  final void fireHidden() {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.hidden(this);
    }
  }

  /**
   * Fires event that "hide" button has been pressed.
   */
  final void fireHiddenSide() {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.hiddenSide(this);
    }
  }

  /**
   * Fires event that user performed click into the title bar area.
   */
  final void fireActivated() {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.activated(this);
    }
  }

  private void fireTypeChanged(final ToolWindowType type) {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.typeChanged(this, type);
    }
  }

  final void fireResized() {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.resized(this);
    }
  }

  private void fireSideStatusChanged(boolean isSide) {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.sideStatusChanged(this, isSide);
    }
  }

  private void fireContentUiTypeChanges(ToolWindowContentUiType type) {
    final InternalDecoratorListener[] listeners = myListenerList.getListeners(InternalDecoratorListener.class);
    for (InternalDecoratorListener listener : listeners) {
      listener.contentUiTypeChanges(this, type);
    }
  }

  private void init() {
    enableEvents(AWTEvent.COMPONENT_EVENT_MASK);

    final JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.add(myHeader, BorderLayout.NORTH);

    JPanel innerPanel = new JPanel(new BorderLayout());
    JComponent toolWindowComponent = myToolWindow.getComponent();
    innerPanel.add(toolWindowComponent, BorderLayout.CENTER);

    final NonOpaquePanel inner = new NonOpaquePanel(innerPanel);
    inner.setBorder(new EmptyBorder(0, 0, 0, 0));

    contentPane.add(inner, BorderLayout.CENTER);
    add(contentPane, BorderLayout.CENTER);
    if (SystemInfo.isMac) {
      setBackground(new JBColor(Gray._200, Gray._90));
    }

    // Add listeners
    registerKeyboardAction(new ActionListener() {
      @Override
      public void actionPerformed(final ActionEvent e) {
        ToolWindowManager.getInstance(myProject).activateEditorComponent();
      }
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
  }

  public void setTitleActions(AnAction[] actions) {
    myHeader.setAdditionalTitleActions(actions);
  }

  private class InnerPanelBorder implements Border {

    private final ToolWindow myWindow;

    private InnerPanelBorder(ToolWindow window) {
      myWindow = window;
    }

    @Override
    public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
      g.setColor(UIUtil.getPanelBackground());
      doPaintBorder(c, g, x, y, width, height);
      g.setColor(new Color(0, 0, 0, 90));
      doPaintBorder(c, g, x, y, width, height);
    }

    private void doPaintBorder(Component c, Graphics g, int x, int y, int width, int height) {
      Insets insets = getBorderInsets(c);

      if (insets.top > 0) {
        UIUtil.drawLine(g, x, y + insets.top - 1, x + width - 1, y + insets.top - 1);
      }

      if (insets.left > 0) {
        UIUtil.drawLine(g, x, y + insets.top, x, y + height - 1);
      }

      if (insets.right > 0) {
        UIUtil.drawLine(g, x + width - 1, y + insets.top, x + width - 1, y + height - 1);
      }

      if (insets.bottom > 0) {
        UIUtil.drawLine(g, x, y + height - 1, x + width - 1, y + height - 1);
       }
    }

    @Override
    public Insets getBorderInsets(final Component c) {
      if (myProject == null) return new Insets(0, 0, 0, 0);
      ToolWindowManager toolWindowManager =  ToolWindowManager.getInstance(myProject);
      if (!(toolWindowManager instanceof ToolWindowManagerImpl)
          || !((ToolWindowManagerImpl)toolWindowManager).isToolWindowRegistered(myInfo.getId())
          || myWindow.getType() == ToolWindowType.FLOATING) {
        return new Insets(0, 0, 0, 0);
      }
      ToolWindowAnchor anchor = myWindow.getAnchor();
      Component component = myWindow.getComponent();
      Container parent = component.getParent();
      while(parent != null) {
        if (parent instanceof Splitter) {
          Splitter splitter = (Splitter)parent;
          boolean isFirst = splitter.getFirstComponent() == component;
          boolean isVertical = splitter.isVertical();
          return new Insets(0,
                            anchor == ToolWindowAnchor.RIGHT || (!isVertical && !isFirst) ? 1 : 0,
                            (isVertical && isFirst) ? 1 : 0,
                            anchor == ToolWindowAnchor.LEFT || (!isVertical && isFirst) ? 1 : 0);
        }
        component = parent;
        parent = component.getParent();
      }
      return new Insets(0, anchor == ToolWindowAnchor.RIGHT ? 1 : 0, 0, anchor == ToolWindowAnchor.LEFT ? 1 : 0);
    }

    @Override
    public boolean isBorderOpaque() {
      return false;
    }
  }

  public final ActionGroup createPopupGroup() {
    final DefaultActionGroup group = createGearPopupGroup();

    group.add(myToggleContentUiTypeAction);

    final DefaultActionGroup moveGroup = new DefaultActionGroup(UIBundle.message("tool.window.move.to.action.group.name"), true);
    final ToolWindowAnchor anchor = myInfo.getAnchor();
    if (anchor != ToolWindowAnchor.TOP) {
      final AnAction topAction = new ChangeAnchorAction(UIBundle.message("tool.window.move.to.top.action.name"), ToolWindowAnchor.TOP);
      moveGroup.add(topAction);
    }
    if (anchor != ToolWindowAnchor.LEFT) {
      final AnAction leftAction = new ChangeAnchorAction(UIBundle.message("tool.window.move.to.left.action.name"), ToolWindowAnchor.LEFT);
      moveGroup.add(leftAction);
    }
    if (anchor != ToolWindowAnchor.BOTTOM) {
      final AnAction bottomAction =
        new ChangeAnchorAction(UIBundle.message("tool.window.move.to.bottom.action.name"), ToolWindowAnchor.BOTTOM);
      moveGroup.add(bottomAction);
    }
    if (anchor != ToolWindowAnchor.RIGHT) {
      final AnAction rightAction =
        new ChangeAnchorAction(UIBundle.message("tool.window.move.to.right.action.name"), ToolWindowAnchor.RIGHT);
      moveGroup.add(rightAction);
    }
    group.add(moveGroup);

    DefaultActionGroup resize = new DefaultActionGroup(ActionsBundle.groupText("ResizeToolWindowGroup"), true);
    resize.add(new ResizeToolWindowAction.Left(myToolWindow, this));
    resize.add(new ResizeToolWindowAction.Right(myToolWindow, this));
    resize.add(new ResizeToolWindowAction.Up(myToolWindow, this));
    resize.add(new ResizeToolWindowAction.Down(myToolWindow, this));

    group.add(resize);

    group.addSeparator();
    group.add(new HideAction());
    return group;
  }

  private DefaultActionGroup createGearPopupGroup() {
    final DefaultActionGroup group = new DefaultActionGroup();

    if (myAdditionalGearActions != null) {
      addSorted(group, myAdditionalGearActions);
      group.addSeparator();
    }
    if (myInfo.isDocked()) {
      group.add(myToggleAutoHideModeAction);
      group.add(myToggleDockModeAction);
      group.add(myToggleFloatingModeAction);
      group.add(myToggleSideModeAction);
    }
    else if (myInfo.isFloating()) {
      group.add(myToggleAutoHideModeAction);
      group.add(myToggleFloatingModeAction);
    }
    else if (myInfo.isSliding()) {
      group.add(myToggleDockModeAction);
      group.add(myToggleFloatingModeAction);
    }
    return group;
  }

  private static void addSorted(DefaultActionGroup main, ActionGroup group) {
    final AnAction[] children = group.getChildren(null);
    boolean hadSecondary = false;
    for (AnAction action : children) {
      if (group.isPrimary(action)) {
        main.add(action);
      } else {
        hadSecondary = true;
      }
    }
    if (hadSecondary) {
      main.addSeparator();
      for (AnAction action : children) {
        if (!group.isPrimary(action)) {
          main.addAction(action).setAsSecondary(true);
        }
      }
    }
  }

  /**
   * @return tool window associated with the decorator.
   */
  final ToolWindowImpl getToolWindow() {
    return myToolWindow;
  }

  /**
   * @return last window info applied to the decorator.
   */
  final WindowInfoImpl getWindowInfo() {
    return myInfo;
  }

  public int getHeaderHeight() {
    return myHeader.getPreferredSize().height;
  }

  @Override
  protected final void processComponentEvent(final ComponentEvent e) {
    super.processComponentEvent(e);
    if (ComponentEvent.COMPONENT_RESIZED == e.getID()) {
      fireResized();
    }
  }

  // TODO: to b removed
  private void updateTitle() {
    final StringBuffer fullTitle = new StringBuffer();
    //  Due to JDK's bug #4234645 we cannot support custom decoration on Linux platform.
    // The prblem is that Window.setLocation() doesn't work properly wjen the dialod is displayable.
    // Therefore we use native WM decoration. When the dialog has native decoration we show window ID
    // in the dialog's title and window title at the custom title panel. If the custom decoration
    // is used we show composite string at the custom title panel.
    // TODO[vova] investigate the problem under Mac OSX.
    if (SystemInfo.isWindows || !myInfo.isFloating()) {
      fullTitle.append(myInfo.getId());
      final String title = myToolWindow.getTitle();
      if (title != null && title.length() > 0) {
        fullTitle.append(" - ").append(title);
      }
    }
    else { // Unixes ans MacOSX go here when tool window is in floating mode
      final String title = myToolWindow.getTitle();
      if (title != null && title.length() > 0) {
        fullTitle.append(title);
      }
    }
  }

  private final class ChangeAnchorAction extends AnAction implements DumbAware {
    private final ToolWindowAnchor myAnchor;

    public ChangeAnchorAction(final String title, final ToolWindowAnchor anchor) {
      super(title);
      myAnchor = anchor;
    }

    @Override
    public final void actionPerformed(final AnActionEvent e) {
      fireAnchorChanged(myAnchor);
    }
  }

  private final class TogglePinnedModeAction extends ToggleAction implements DumbAware {
    public TogglePinnedModeAction() {
      copyFrom(ActionManager.getInstance().getAction(TOGGLE_PINNED_MODE_ACTION_ID));
    }

    @Override
    public final boolean isSelected(final AnActionEvent event) {
      return !myInfo.isAutoHide();
    }

    @Override
    public final void setSelected(final AnActionEvent event, final boolean flag) {
      fireAutoHideChanged(!myInfo.isAutoHide());
    }
  }

  private final class ToggleDockModeAction extends ToggleAction implements DumbAware {
    public ToggleDockModeAction() {
      copyFrom(ActionManager.getInstance().getAction(TOGGLE_DOCK_MODE_ACTION_ID));
    }

    @Override
    public final boolean isSelected(final AnActionEvent event) {
      return myInfo.isDocked();
    }

    @Override
    public final void setSelected(final AnActionEvent event, final boolean flag) {
      if (myInfo.isDocked()) {
        fireTypeChanged(ToolWindowType.SLIDING);
      }
      else if (myInfo.isSliding()) {
        fireTypeChanged(ToolWindowType.DOCKED);
      }
    }
  }

  private final class ToggleFloatingModeAction extends ToggleAction implements DumbAware {
    public ToggleFloatingModeAction() {
      copyFrom(ActionManager.getInstance().getAction(TOGGLE_FLOATING_MODE_ACTION_ID));
    }

    @Override
    public final boolean isSelected(final AnActionEvent event) {
      return myInfo.isFloating();
    }

    @Override
    public final void setSelected(final AnActionEvent event, final boolean flag) {
      if (myInfo.isFloating()) {
        fireTypeChanged(myInfo.getInternalType());
      }
      else {
        fireTypeChanged(ToolWindowType.FLOATING);
      }
    }
  }

  private final class ToggleSideModeAction extends ToggleAction implements DumbAware {
    public ToggleSideModeAction() {
      copyFrom(ActionManager.getInstance().getAction(TOGGLE_SIDE_MODE_ACTION_ID));
    }

    @Override
    public final boolean isSelected(final AnActionEvent event) {
      return myInfo.isSplit();
    }

    @Override
    public final void setSelected(final AnActionEvent event, final boolean flag) {
      fireSideStatusChanged(flag);
    }

    @Override
    public void update(final AnActionEvent e) {
      super.update(e);
    }
  }

  private final class HideAction extends AnAction implements DumbAware {
    @NonNls public static final String HIDE_ACTIVE_WINDOW_ACTION_ID = InternalDecorator.HIDE_ACTIVE_WINDOW_ACTION_ID;

    public HideAction() {
      copyFrom(ActionManager.getInstance().getAction(HIDE_ACTIVE_WINDOW_ACTION_ID));
      getTemplatePresentation().setText(UIBundle.message("tool.window.hide.action.name"));
    }

    @Override
    public final void actionPerformed(final AnActionEvent e) {
      fireHidden();
    }

    @Override
    public final void update(final AnActionEvent event) {
      final Presentation presentation = event.getPresentation();
      presentation.setEnabled(myInfo.isVisible());
    }
  }

  private final class ToggleContentUiTypeAction extends ToggleAction implements DumbAware {
    private ToggleContentUiTypeAction() {
      copyFrom(ActionManager.getInstance().getAction(TOGGLE_CONTENT_UI_TYPE_ACTION_ID));
    }

    @Override
    public boolean isSelected(AnActionEvent e) {
      return myInfo.getContentUiType() == ToolWindowContentUiType.TABBED;
    }

    @Override
    public void setSelected(AnActionEvent e, boolean state) {
      fireContentUiTypeChanges(state ? ToolWindowContentUiType.TABBED : ToolWindowContentUiType.COMBO);
    }
  }

  private final class MyDivider extends JPanel {
    private boolean myDragging;
    private Point myLastPoint;

    private MyDivider() {
      myDragging = false;
      enableEvents(MouseEvent.MOUSE_EVENT_MASK | MouseEvent.MOUSE_MOTION_EVENT_MASK);
      setBorder(new DividerBorder());
    }

    @Override
    protected final void processMouseMotionEvent(final MouseEvent e) {
      super.processMouseMotionEvent(e);
      if (MouseEvent.MOUSE_DRAGGED == e.getID()) {
        myDragging = true;
        final ToolWindowAnchor anchor = myInfo.getAnchor();
        final boolean isVerticalCursor = myInfo.isDocked() ? anchor.isSplitVertically() : anchor.isHorizontal();
        setCursor(isVerticalCursor ? Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR) : Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
        final Point point = e.getPoint();

        final Container windowPane = InternalDecorator.this.getParent();
        myLastPoint = SwingUtilities.convertPoint(this, point, windowPane);
        myLastPoint.x = Math.min(Math.max(myLastPoint.x, 0), windowPane.getWidth());
        myLastPoint.y = Math.min(Math.max(myLastPoint.y, 0), windowPane.getHeight());

        final Rectangle bounds = InternalDecorator.this.getBounds();
        if (anchor == ToolWindowAnchor.TOP) {
          if (myLastPoint.y < DIVIDER_WIDTH) {
            myLastPoint.y = DIVIDER_WIDTH;
          }
          InternalDecorator.this.setBounds(0, 0, bounds.width, myLastPoint.y);
        }
        else if (anchor == ToolWindowAnchor.LEFT) {
          if (myLastPoint.x < DIVIDER_WIDTH) {
            myLastPoint.x = DIVIDER_WIDTH;
          }
          InternalDecorator.this.setBounds(0, 0, myLastPoint.x, bounds.height);
        }
        else if (anchor == ToolWindowAnchor.BOTTOM) {
          if (myLastPoint.y > windowPane.getHeight() - DIVIDER_WIDTH) {
            myLastPoint.y = windowPane.getHeight() - DIVIDER_WIDTH;
          }
          InternalDecorator.this.setBounds(0, myLastPoint.y, bounds.width, windowPane.getHeight() - myLastPoint.y);
        }
        else if (anchor == ToolWindowAnchor.RIGHT) {
          if (myLastPoint.x > windowPane.getWidth() - DIVIDER_WIDTH) {
            myLastPoint.x = windowPane.getWidth() - DIVIDER_WIDTH;
          }
          InternalDecorator.this.setBounds(myLastPoint.x, 0, windowPane.getWidth() - myLastPoint.x, bounds.height);
        }
        InternalDecorator.this.validate();
      }
    }

    @Override
    protected final void processMouseEvent(final MouseEvent e) {
      super.processMouseEvent(e);
      final boolean isVerticalCursor = myInfo.isDocked() ? myInfo.getAnchor().isSplitVertically() : myInfo.getAnchor().isHorizontal();
      switch (e.getID()) {
        case MouseEvent.MOUSE_MOVED:
        default:
          break;
        case MouseEvent.MOUSE_ENTERED:
          setCursor(
            isVerticalCursor ? Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR) : Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
          break;
        case MouseEvent.MOUSE_EXITED:
          if (!myDragging) {
            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
          }
          break;
        case MouseEvent.MOUSE_PRESSED:
          setCursor(
            isVerticalCursor ? Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR) : Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
          break;
        case MouseEvent.MOUSE_RELEASED:
          myDragging = false;
          myLastPoint = null;
          break;
        case MouseEvent.MOUSE_CLICKED:
          break;
      }
    }

    private final class DividerBorder implements Border {
      @Override
      public final void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
        final ToolWindowAnchor anchor = myInfo.getAnchor();
        final boolean isVertical = !anchor.isSplitVertically();
        final JBColor outer = new JBColor(Color.white, Color.darkGray);
        if (isVertical) {
          if (anchor == ToolWindowAnchor.TOP) {
            g.setColor(outer);
            UIUtil.drawLine(g, x, y, x + width - 1, y);
            g.setColor(Color.darkGray);
            UIUtil.drawLine(g, x, y + height - 1, x + width - 1, y + height - 1);
          }
          else {
            g.setColor(Color.darkGray);
            UIUtil.drawLine(g, x, y, x + width - 1, y);
            g.setColor(outer);
            UIUtil.drawLine(g, x, y + height - 1, x + width - 1, y + height - 1);
          }
        }
        else {
          if (anchor == ToolWindowAnchor.LEFT) {
            g.setColor(outer);
            UIUtil.drawLine(g, x, y, x, y + height - 1);
            g.setColor(Color.darkGray);
            UIUtil.drawLine(g, x + width - 1, y, x + width - 1, y + height - 1);
          }
          else {
            g.setColor(Color.darkGray);
            UIUtil.drawLine(g, x, y, x, y + height - 1);
            g.setColor(outer);
            UIUtil.drawLine(g, x + width - 1, y, x + width - 1, y + height - 1);
          }
        }
      }

      @Override
      public final Insets getBorderInsets(final Component c) {
        if (c instanceof MyDivider) {
          return new Insets(1, 1, 1, 1);
        }
        return new Insets(0, 0, 0, 0);
      }

      @Override
      public final boolean isBorderOpaque() {
        return true;
      }
    }
  }

  /**
   * Updates tooltips.
   */
  private final class MyKeymapManagerListener implements KeymapManagerListener {
    @Override
    public final void activeKeymapChanged(final Keymap keymap) {
      if (myHeader != null) {
        myHeader.updateTooltips();
      }
    }
  }

  /**
   * Synchronizes decorator with IdeToolWindow changes.
   */
  private final class ToolWindowHandler implements PropertyChangeListener {
    @Override
    public final void propertyChange(final PropertyChangeEvent e) {
      final String name = e.getPropertyName();
      if (ToolWindowEx.PROP_TITLE.equals(name)) {
        updateTitle();
        if (myHeader != null) {
          myHeader.repaint();
        }
      }
    }
  }

  @Override
  public void putInfo(@NotNull Map<String, String> info) {
    info.put("toolWindowTitle", myToolWindow.getTitle());

    final Content selection = myToolWindow.getContentManager().getSelectedContent();
    if (selection != null) {
      info.put("toolWindowTab", selection.getTabName());
    }
  }

  public void setAdditionalGearActions(@Nullable ActionGroup additionalGearActions) {
    myAdditionalGearActions = additionalGearActions;
  }
}


text:
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

// ReSharper disable once CheckNamespace
namespace NuGet.Modules
{
    public static class JsonHelper
    {
        private static readonly JsonSerializerSettings JsonSerializerSettings =
            new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };

        public static void Serialize<T>(string path, T obj)
        {
            string directory = Path.GetDirectoryName(path);
            if (!String.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            File.WriteAllText(path, ToJson(obj));
        }

        public static T Deserialize<T>(string path)
        {
            var json = File.ReadAllText(path);
            return FromJson<T>(json);
        }

        public static string ToJson<T>(T obj)
        {
            return JsonConvert.SerializeObject(obj, JsonSerializerSettings);
        }

        public static T FromJson<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json, JsonSerializerSettings);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package net.sf.gaia.engine;

import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.persistence.EntityManagerFactory;

import net.sf.gaia.persistence.DatabaseSettings;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.dialect.Dialect;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.ejb.EntityManagerImpl;

/**
 * Classe que disponibiliza métodos para persistir entidades do Gaia no banco de dados.
 *
 * @author daniel.joppi
 *
 */
public final class HibernateEngine {

	private static final Log logger = LogFactory.getLog(HibernateEngine.class);

	private static Ejb3Configuration ejbConfiguration;

	private static String PERSISTENCE_UNIT = "gaia";

	/**
	 * Método que persiste um Object no banco de dados.
	 *
	 * @param o objeto a ser persistido no banco de dados.
	 *
	 * @author daniel.joppi
	 * @since 20/08/2010
	 */
	public final static void persist(Object o) {

		if (logger.isDebugEnabled()) {
			logger.debug("Persisting object " + o);
		}
		EntityManagerImpl manager = ((EntityManagerImpl) DatabaseSettings.getEntityManager());
		Session session = manager.getSession();
		Transaction trans = session.getTransaction();

		try {
			if (trans == null) {
				trans = session.beginTransaction();
			} else if (!trans.isActive()) {
				trans.begin();
			}

			// Persists the object
			session.saveOrUpdate(o);
			session.flush();

			trans.commit();

		} catch (RuntimeException e) {
			if (trans.isActive()) {
				trans.rollback();
			}
			logger.error("Error persisting object " + o.getClass().getName() + " #@" + o.hashCode(), e);
			throw e;
		}
	}

	/**
	 * Método que remove um Object no banco de dados.
	 *
	 * @param o objeto a ser removido no banco de dados.
	 *
	 * @author daniel.joppi
	 * @since 20/08/2010
	 */
	public final static void remove(Object o) {

		if (logger.isDebugEnabled()) {
			logger.debug("Removing object " + o);
		}
		EntityManagerImpl manager = ((EntityManagerImpl) DatabaseSettings.getEntityManager());
		Session session = manager.getSession();
		Transaction trans = session.getTransaction();

		try {
			if (trans == null) {
				trans = session.beginTransaction();
			} else if (!trans.isActive()) {
				trans.begin();
			}
			// Remove the object
			session.merge(o);
			session.delete(o);

			trans.commit();

		} catch (RuntimeException e) {
			if (trans.isActive()) {
				trans.rollback();
			}
			logger.error("Error removing object " + o.getClass().getName() + " #@" + o.hashCode(), e);
			throw e;
		}
	}

	/**
	 * Método que carrega todas os dados de uma determinada entidade.
	 *
	 * @param clazz classe da entidade que será carregada.
	 *
	 * @author daniel.joppi
	 * @since 11/12/2011
	 */
	public final static <T> List<T> load(Class<T> clazz) {
		return load(clazz, null);
	}

	/**
	 * Método que carrega todas os dados de uma determinada entidade.
	 *
	 * @param clazz classe da entidade que será carregada.
	 * @param criteria filtro que será aplicado a consulta dos dados.
	 *
	 * @author daniel.joppi
	 * @since 11/12/2011
	 */
	public final static <T> List<T> load(Class<T> clazz, Criterion criterion) {

		if (logger.isDebugEnabled()) {
			logger.debug("Load data for entity " + clazz.getName());
		}

		Criteria criteria = ((EntityManagerImpl) DatabaseSettings.getEntityManager()).getSession().createCriteria(clazz);

		if(criterion != null) {
			criteria.add(criterion);
		}
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

		return (List<T>) criteria.list();
	}

	public final static <T> EntityManagerFactory recreateEntityManagerFactory(final Set<Class<T>> classes) {
		return createEntityManagerFactory(classes, null);
	}

	public final static <T> EntityManagerFactory createEntityManagerFactory(final Set<Class<T>> classes, String unit) {
		if (unit != null) {
			PERSISTENCE_UNIT = unit;
			System.setProperty("gaia.hibernate.persitence.unit", PERSISTENCE_UNIT);
		}
		if (PERSISTENCE_UNIT == null) {
			PERSISTENCE_UNIT = System.getProperty("gaia.hibernate.persitence.unit");
		}

		System.setProperty("hibernate.bytecode.provider", "cglib");

		ejbConfiguration = new Ejb3Configuration();

		logger.debug("Adding annotated classes...");
		if (classes != null) {
			for (final Class<T> c : classes) {
				if (logger.isDebugEnabled()) {
					logger.debug("Adding annotated class " + c.getName());
				}
				ejbConfiguration.addAnnotatedClass(c);
			}
		}

		long l1 = System.currentTimeMillis();
		ejbConfiguration = ejbConfiguration.configure(PERSISTENCE_UNIT, new HashMap<Object,Object>());
		ejbConfiguration.addProperties(System.getProperties());
		final Configuration config = ejbConfiguration.getHibernateConfiguration();
		config.setProperty("hibernate.query.jpaql_strict_compliance", "false");

		if (logger.isDebugEnabled()) {
			logger.debug("cfg.configure time: " + (System.currentTimeMillis() - l1) + "ms");
		}
		l1 = System.currentTimeMillis();
		if (logger.isDebugEnabled()) {
			logger.debug("building EMF... classes: " + classes);
		}
		final EntityManagerFactory emf = ejbConfiguration.buildEntityManagerFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("cfg.buildEntityManagerFactory time: " + (System.currentTimeMillis() - l1) + "ms");
		}

		DatabaseSettings.setEntityManagerFactory(emf);
		return emf;
	}

	/**
	 *
	 * @param <T>
	 * @param classes
	 * @deprecated não funco muito bem
	 */
	public final static <T> void includeNewClasses(Set<Class<T>> classes) {
		logger.debug("Adding annotated classes...");
		if (classes != null) {
			for (final Class<T> c : classes) {
				if (logger.isDebugEnabled()) {
					logger.debug("Adding annotated class " + c.getName());
				}
				ejbConfiguration.addAnnotatedClass(c);
			}
		}

		long l1 = System.currentTimeMillis();
		if (logger.isDebugEnabled()) {
			logger.debug("building EMF... classes: " + classes);
		}
		final EntityManagerFactory emf = ejbConfiguration.buildEntityManagerFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("cfg.buildEntityManagerFactory time: " + (System.currentTimeMillis() - l1) + "ms");
		}

		DatabaseSettings.setEntityManagerFactory(emf);
	}

	public static String getPersistenceUnit() {
		return PERSISTENCE_UNIT;
	}

	public static Dialect getDialect() {
		Properties prop = ejbConfiguration.getProperties();
		return Dialect.getDialect(prop);
	}
}


text:
Advisory TFV-4 (CVE-2017-9607)
==============================

+----------------+-------------------------------------------------------------+
| Title          | Malformed Firmware Update SMC can result in copy or         |
|                | authentication of unexpected data in secure memory in       |
|                | AArch32 state                                               |
+================+=============================================================+
| CVE ID         | `CVE-2017-9607`_                                            |
+----------------+-------------------------------------------------------------+
| Date           | 20 Jun 2017                                                 |
+----------------+-------------------------------------------------------------+
| Versions       | None (only between 22 May 2017 and 14 June 2017)            |
| Affected       |                                                             |
+----------------+-------------------------------------------------------------+
| Configurations | Platforms that use AArch32 BL1 plus untrusted normal world  |
| Affected       | firmware update code executing before BL31                  |
+----------------+-------------------------------------------------------------+
| Impact         | Copy or authentication of unexpected data in the secure     |
|                | memory                                                      |
+----------------+-------------------------------------------------------------+
| Fix Version    | `Pull Request #979`_ (merged on 14 June 2017)               |
+----------------+-------------------------------------------------------------+
| Credit         | ARM                                                         |
+----------------+-------------------------------------------------------------+

The ``include/lib/utils_def.h`` header file provides the
``check_uptr_overflow()`` macro, which aims at detecting arithmetic overflows
that may occur when computing the sum of a base pointer and an offset. This
macro evaluates to 1 if the sum of the given base pointer and offset would
result in a value large enough to wrap around, which may lead to unpredictable
behaviour.

The macro code is at line 52, referring to the version of the code as of `commit
c396b73`_:

.. code:: c

    /*
     * Evaluates to 1 if (ptr + inc) overflows, 0 otherwise.
     * Both arguments must be unsigned pointer values (i.e. uintptr_t).
     */
    #define check_uptr_overflow(ptr, inc)       \
        (((ptr) > UINTPTR_MAX - (inc)) ? 1 : 0)

This macro does not work correctly for AArch32 images. It fails to detect
overflows when the sum of its two parameters fall into the ``[2^32, 2^64 - 1]``
range. Therefore, any AArch32 code relying on this macro to detect such integer
overflows is actually not protected.

The buggy code has been present in ARM Trusted Firmware (TF) since `Pull Request
#678`_ was merged (on 18 August 2016). However, the upstream code was not
vulnerable until `Pull Request #939`_ was merged (on 22 May 2017), which
introduced AArch32 support for the Trusted Board Boot (TBB) feature. Before
then, the ``check_uptr_overflow()`` macro was not used in AArch32 code.

The vulnerability resides in the BL1 FWU SMC handling code and it may be
exploited when *all* the following conditions apply:

- Platform code uses TF BL1 with the ``TRUSTED_BOARD_BOOT`` build option.

- Platform code uses the Firmware Update (FWU) code provided in
  ``bl1/bl1_fwu.c``, which is part of the TBB support.

- TF BL1 is compiled with the ``ARCH=aarch32`` build option.

In this context, the AArch32 BL1 image might fail to detect potential integer
overflows in the input validation checks while handling the
``FWU_SMC_IMAGE_COPY`` and ``FWU_SMC_IMAGE_AUTH`` SMCs.

The ``FWU_SMC_IMAGE_COPY`` SMC handler is designed to copy an image into secure
memory for subsequent authentication. This is implemented by the
``bl1_fwu_image_copy()`` function, which has the following function prototype:

.. code:: c

     static int bl1_fwu_image_copy(unsigned int image_id,
                        uintptr_t image_src,
                        unsigned int block_size,
                        unsigned int image_size,
                        unsigned int flags)

``image_src`` is an SMC argument and therefore potentially controllable by an
attacker. A very large 32-bit value, for example ``2^32 -1``, may result in the
sum of ``image_src`` and ``block_size`` overflowing a 32-bit type, which
``check_uptr_overflow()`` will fail to detect.  Depending on its implementation,
the platform-specific function ``bl1_plat_mem_check()`` might get defeated by
these unsanitized values and allow the following memory copy operation, that
would wrap around.  This may allow an attacker to copy unexpected data into
secure memory if the memory is mapped in BL1's address space, or cause a fatal
exception if it's not.

The ``FWU_SMC_IMAGE_AUTH`` SMC handler is designed to authenticate an image
resident in secure memory. This is implemented by the ``bl1_fwu_image_auth()``
function, which has the following function prototype:

.. code:: c

    static int bl1_fwu_image_auth(unsigned int image_id,
                        uintptr_t image_src,
                        unsigned int image_size,
                        unsigned int flags)

Similarly, if an attacker has control over the ``image_src`` or ``image_size``
arguments through the SMC interface and injects high values whose sum overflows,
they might defeat the ``bl1_plat_mem_check()`` function and make the
authentication module read data outside of what's normally allowed by the
platform code or crash the platform.

Note that in both cases, a separate vulnerability is required to leverage this
vulnerability; for example a way to get the system to change its behaviour based
on the unexpected secure memory accesses.  Moreover, the normal world FWU code
would need to be compromised in order to send a malformed FWU SMC that triggers
an integer overflow.

The vulnerability is known to affect all ARM standard platforms when enabling
the ``TRUSTED_BOARD_BOOT`` and ``ARCH=aarch32`` build options.  Other platforms
may also be affected if they fulfil the above conditions.

.. _CVE-2017-9607: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-9607
.. _commit c396b73: https://github.com/ARM-software/arm-trusted-firmware/commit/c396b73
.. _Pull Request #678: https://github.com/ARM-software/arm-trusted-firmware/pull/678
.. _Pull Request #939: https://github.com/ARM-software/arm-trusted-firmware/pull/939
.. _Pull Request #979: https://github.com/ARM-software/arm-trusted-firmware/pull/979


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE application SYSTEM "application.dtd">

<application xmlns:xi="http://www.w3.org/2001/XInclude">

    <copyright>
      <year>1998</year><year>2016</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      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.

    </legalnotice>
    <title>Erl_Interface Reference Manual</title>
    <prepared>Gordon Beaton</prepared>
    <docno></docno>
    <date>1998-11.30</date>
    <rev>1.2</rev>
    <file>ref_man.xml</file>

  <description>
    <note>
The support for VxWorks is deprecated as of OTP 22, and
    will be removed in OTP 23.
</note>
    <note>
The old legacy <c>erl_interface</c> library (functions
    with prefix <c>erl_</c>) is deprecated as of OTP 22, and will be
    removed in OTP 23. This does not apply to the <c>ei</c>
    library. Reasonably new <c>gcc</c> compilers will issue deprecation
    warnings. In order to disable these warnings, define the macro
    <c>EI_NO_DEPR_WARN</c>.
</note>
  </description>
  <xi:include href="ei.xml"/>
  <xi:include href="ei_connect.xml"/>
  <xi:include href="registry.xml"/>
  <xi:include href="erl_connect.xml"/>
  <xi:include href="erl_error.xml"/>
  <xi:include href="erl_eterm.xml"/>
  <xi:include href="erl_format.xml"/>
  <xi:include href="erl_global.xml"/>
  <xi:include href="erl_malloc.xml"/>
  <xi:include href="erl_marshal.xml"/>
  <xi:include href="erl_call.xml"/>
</application>


text:
package alec_wam.CrystalMod.util;

import java.util.Random;

import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.math.MathHelper;

public class CrystalColors {
	public static final PropertyEnum<Basic> COLOR_BASIC = PropertyEnum.<Basic>create("color", Basic.class);
	public static final PropertyEnum<Special> COLOR_SPECIAL = PropertyEnum.<Special>create("color", Special.class);
	public static final PropertyEnum<SuperSpecial> COLOR_SUPER = PropertyEnum.<SuperSpecial>create("color", SuperSpecial.class);

	public static enum Basic implements IStringSerializable, IEnumMeta {
		BLUE("blue"),
		RED("red"),
		GREEN("green"),
		DARK("dark");

		private final String unlocalizedName;
		public final int meta;

		Basic(String name) {
	      meta = ordinal();
	      unlocalizedName = name;
	    }

	    @Override
	    public String getName() {
	      return unlocalizedName;
	    }

	    @Override
	    public int getMeta() {
	      return meta;
	    }

		public static Basic byMetadata(int meta)
        {
            if (meta < 0 || meta >= values().length)
            {
                meta = 0;
            }

            return values()[meta];
        }

		public static Basic getRandom(Random rand){
			return byMetadata(MathHelper.getInt(rand, 0, values().length-1));
		}
	}

	public static enum Special implements IStringSerializable, IEnumMeta {
		BLUE("blue"),
		RED("red"),
		GREEN("green"),
		DARK("dark"),
		PURE("pure");

		private final String unlocalizedName;
		public final int meta;

		Special(String name) {
	      meta = ordinal();
	      unlocalizedName = name;
	    }

	    @Override
	    public String getName() {
	      return unlocalizedName;
	    }

	    @Override
	    public int getMeta() {
	      return meta;
	    }

	    public static Special byMetadata(int meta)
        {
            if (meta < 0 || meta >= values().length)
            {
                meta = 0;
            }

            return values()[meta];
        }

		public static Special convert(Basic color) {
			if(color == Basic.RED){
				return RED;
			}
			if(color == Basic.GREEN){
				return GREEN;
			}
			if(color == Basic.DARK){
				return DARK;
			}
			return BLUE;
		}
	}

	public static enum SuperSpecial implements IStringSerializable, IEnumMeta {
		BLUE("blue"),
		RED("red"),
		GREEN("green"),
		DARK("dark"),
		PURE("pure"),
		CRYSTEX("crystex");

		private final String unlocalizedName;
		public final int meta;

		SuperSpecial(String name) {
	      meta = ordinal();
	      unlocalizedName = name;
	    }

	    @Override
	    public String getName() {
	      return unlocalizedName;
	    }

	    @Override
	    public int getMeta() {
	      return meta;
	    }

		public static SuperSpecial byMetadata(int meta)
        {
            if (meta < 0 || meta >= values().length)
            {
                meta = 0;
            }

            return values()[meta];
        }

		public static SuperSpecial getRandom(Random rand, boolean basic){
			if(basic){
				return byMetadata(MathHelper.getInt(rand, 0, 3));
			}
			return byMetadata(MathHelper.getInt(rand, 0, values().length-1));
		}

		public static SuperSpecial convert(Basic color) {
			if(color == Basic.RED){
				return RED;
			}
			if(color == Basic.GREEN){
				return GREEN;
			}
			if(color == Basic.DARK){
				return DARK;
			}
			return BLUE;
		}
	}

}


text:
package com.navercorp.pinpoint.web.service.stat;

import com.navercorp.pinpoint.web.dao.stat.SampledTransactionDao;
import com.navercorp.pinpoint.web.util.TimeWindow;
import com.navercorp.pinpoint.web.vo.stat.SampledTransaction;
import com.navercorp.pinpoint.web.vo.stat.chart.StatChart;
import com.navercorp.pinpoint.web.vo.stat.chart.agent.TransactionChart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author HyunGil Jeong
 */
@Service
public class TransactionChartService implements AgentStatChartService {

    private final SampledTransactionDao sampledTransactionDao;

    public TransactionChartService(@Qualifier("sampledTransactionDaoFactory") SampledTransactionDao sampledTransactionDao) {
        this.sampledTransactionDao = Objects.requireNonNull(sampledTransactionDao, "sampledTransactionDao");
    }

    @Override
    public StatChart selectAgentChart(String agentId, TimeWindow timeWindow) {
        Objects.requireNonNull(agentId, "agentId");
        Objects.requireNonNull(timeWindow, "timeWindow");

        List<SampledTransaction> sampledTransactions = this.sampledTransactionDao.getSampledAgentStatList(agentId, timeWindow);
        return new TransactionChart(timeWindow, sampledTransactions);
    }

    @Override
    public List<StatChart> selectAgentChartList(String agentId, TimeWindow timeWindow) {
        StatChart agentStatChart = selectAgentChart(agentId, timeWindow);

        List<StatChart> result = new ArrayList<>(1);
        result.add(agentStatChart);

        return result;
    }

}


text:
<?php

namespace Surume\Container\Method;

class FactoryMethod
{
    /**
     * @var callable
     */
    protected $callback;

    /**
     * @var mixed[]
     */
    protected $args;

    /**
     * @param callable $callback
     * @param mixed[] $args
     */
    public function __construct(callable $callback, $args = [])
    {
        $this->callback = $callback;
        $this->args = $args;
    }

    /**
     * @return callable
     */
    public function getCallback()
    {
        return $this->callback;
    }

    /**
     * @return mixed[]
     */
    public function getArgs()
    {
        return $this->args;
    }
}


text:
module.exports = function(app){
	// =====================================
	// optimisation PAGE                ====
	// =====================================
var fs = require('fs');
	app.get('/realisations/optimisation', function(req, res) {
    fs.readFile('./data/realisations/optimisation.json', 'utf8', function (err, data) {
        if (err) {
          console.log(err);
        }
        var obj = JSON.parse(data);
				console.log(obj.pageTitle);
        res.render('realisation.ejs', {obj : obj}); // load the optimisation.ejs file
      });
	});
}


text:
const fs = require('fs');
import VcfParser from "../../js/variant/vcfParser.js";
import getDataWrapper from "../../js/feature/dataWrapper.js";

vcfToBed();

async function vcfToChords() {

    const input = require.resolve("../../test/data/vcf/SKBR3_Sniffles_variants_tra.vcf");
    const data = fs.readFileSync(input, 'utf-8');

    const parser = new VcfParser();
    let dataWrapper = getDataWrapper(data);
    await parser.parseHeader(dataWrapper);

    dataWrapper = getDataWrapper(data)
    const featureList = await parser.parseFeatures(dataWrapper);
    for (let v of featureList) {

        if (v.info.CHR2 && v.info.END) {
            const chr2 = v.info.CHR2;
            const pos2 = Number.parseInt(v.info.END);
            const start2 = pos2 - 100;
            const end2 = pos2 + 100;

            if(bedPE) {
                console.log(`${v.chr}\t${v.start - 100}\t${v.end + 100}\t${chr2}\t${start2}\t${end2}`);
            } else {
                console.log(`${v.chr}\t${v.start - 100}\t${v.end + 100}`);
                console.log(`${chr2}\t${start2}\t${end2}`);
            }
        }
    }

}


text:
import DS from 'ember-data';
import BackboneElement from 'ember-fhir/models/backbone-element';

const { attr } = DS;

export default BackboneElement.extend({
name: attr('string'), variable: attr()
});


text:
layout:     post
title:      OpenEars 2.504 with build fixes
date:       2016-11-15
summary:    OpenEars 2.504 with build fixes
categories: openears
---
* OpenEars 2.504 has fixes for build errors with Xcode 8.1, fixes for runtime errors with the sample app on iOS 10 and up, adds API support for running in 8k mode when using Bluetooth devices that can't support 16k mode, and contains Swift 3 examples and documentation in its header files.


text:
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using Txt.ABNF;
using Txt.Core;

namespace Http.request_line
{
    public sealed class RequestLineLexer : Lexer<RequestLine>
    {
        public RequestLineLexer([NotNull] ILexer<Concatenation> innerLexer)
        {
            if (innerLexer == null)
            {
                throw new ArgumentNullException(nameof(innerLexer));
            }
            InnerLexer = innerLexer;
        }

        [NotNull]
        public ILexer<Concatenation> InnerLexer { get; }

        protected override IEnumerable<RequestLine> ReadImpl(
            ITextScanner scanner,
            ITextContext context)
        {
            foreach (var concatenation in InnerLexer.Read(scanner, context))
            {
                yield return new RequestLine(concatenation);
            }
        }
    }
}


text:
/* Generated by ./xlat/gen.sh from ./xlat/fdflags.in; do not edit. */

static const struct xlat fdflags[] = {
#if defined(FD_CLOEXEC) || (defined(HAVE_DECL_FD_CLOEXEC) && HAVE_DECL_FD_CLOEXEC)
	XLAT(FD_CLOEXEC),
#endif
	XLAT_END
};


text:
"""hourly histogram"""
import datetime

import numpy as np
import pandas as pd
from pyiem.plot import figure_axes
from pyiem.util import get_autoplot_context, get_sqlalchemy_conn
from pyiem.exceptions import NoDataFound

PDICT = {
    "yes": "Yes, Include only Year to Date period each year",
    "no": "No, Include all available data for each year",
}
VDICT = {
    "tmpf": "Air Temperature",
    "dwpf": "Dew Point Temperature",
    "heatindex": "Heat Index",
    "windchill": "Wind Chill Index",
    "gust": "Wind Gust",
}
LEVELS = {
    "tmpf": np.arange(85, 115),
    "dwpf": np.arange(60, 85),
    "heatindex": np.arange(80, 121),
    "windchill": np.arange(-50, 1),
    "gust": np.arange(30, 71),
}
OPTDICT = {
    "no": "No, only include times when heatindex/windchill is additive",
    "yes": "Yes, include all observations",
}

def get_description():
    """Return a dict describing how to call this plotter"""
    desc = {}
    desc["data"] = True
    desc[
        "description"
    ] = """Caution: This plot takes a bit of time to
    generate. This plot displays a histogram of hourly observations.
    Only the routine hourly observations are considered,
    so specials or multiple observations per hour are not considered.
    The connecting lines between the dots are to help readability. In the
    case of wind chill, the year shown is for the winter season actual year
    with December contained within.

This form provides an option for the case of wind chill and heat index
    to only include cases that are additive.  What this means is to only
    include observations where the wind chill temperature is colder than the
    air temperature or when the heat index temperature is warmer than the
    air temperature.

This application only considers one observation per hour.  In the case
    of multiple observations within an hour, a simple average of the found
    values is used.  In the future, the hope is to limit the considered data
    to the "synoptic" observation at the top of the hour, but we are not there
    yet.

Change made 29 Aug 2018: The algorithm used here was
    updated to use greater than or equal to the given threshold.  In the case
    of wind chill, it is less than or equal to.

    """
    desc["arguments"] = [
        dict(
            type="zstation",
            name="zstation",
            default="DSM",
            network="IA_ASOS",
            label="Select Station:",
        ),
        dict(
            type="year",
            minvalue=1973,
            default=1973,
            name="syear",
            label="Start year (if data available) for plot:",
        ),
        dict(
            type="year",
            minvalue=1973,
            default=datetime.date.today().year,
            name="eyear",
            label="End year (inclusive, if data available) for plot:",
        ),
        dict(
            type="year",
            minvalue=1973,
            default=datetime.date.today().year,
            name="year",
            label="Year to Highlight:",
        ),
        dict(
            type="select",
            options=VDICT,
            name="var",
            default="heatindex",
            label="Select variable to plot:",
        ),
        dict(
            type="select",
            options=PDICT,
            name="ytd",
            default="no",
            label="Include Only Year to Date Data?",
        ),
        dict(
            type="select",
            options=OPTDICT,
            name="inc",
            default="no",
            label=(
                "Include cases where windchill or heatindex " "is not additive"
            ),
        ),
    ]
    return desc

def get_doylimit(ytd, varname):
    """Get the SQL limiter"""
    if ytd == "no":
        return ""
    if varname != "windchill":
        return "and extract(doy from valid) < extract(doy from 'TODAY'::date)"
    if datetime.date.today().month > 7:
        res = "and extract(doy from valid) < extract(doy from 'TODAY'::date) "
        if varname == "windchill":
            res += "and extract(month from valid) > 6"
        return res

    return (
        "and (extract(doy from valid) < extract(doy from 'TODAY'::date) "
        "or extract(month from valid) > 6)"
    )

def plotter(fdict):
    """Go"""
    ctx = get_autoplot_context(fdict, get_description())
    station = ctx["zstation"]
    highlightyear = ctx["year"]
    sdate = datetime.date(ctx["syear"], 1, 1)
    edate = datetime.date(ctx["eyear"] + 1, 1, 1)
    ytd = ctx["ytd"]
    varname = ctx["var"]
    inc = ctx["inc"]
    doylimiter = get_doylimit(ytd, varname)
    tmpflimit = "and tmpf >= 50" if varname != "windchill" else "and tmpf < 50"
    if varname not in ["windchill", "heatindex"]:
        tmpflimit = ""
    with get_sqlalchemy_conn("asos") as conn:
        df = pd.read_sql(
            f"""
            SELECT valid at time zone 'UTC' as valid,
            tmpf::int as tmpf, gust * 1.15 as gust,
            dwpf::int as dwpf, feel
            from alldata WHERE station = %s {tmpflimit}
            and dwpf <= tmpf and valid > %s and valid < %s
            and report_type = 3 {doylimiter}""",
            conn,
            params=(station, sdate, edate),
            index_col=None,
        )
    if df.empty:
        raise NoDataFound("No Data Found.")
    bs = ctx["_nt"].sts[station]["archive_begin"]
    if bs is None:
        raise NoDataFound("Unknown station metadata.")
    df["year"] = df["valid"].dt.year

    df2 = df
    title2 = VDICT[varname]
    compop = np.greater_equal
    inctitle = ""
    if varname == "heatindex":
        df[varname] = df["feel"]
        inctitle = " [All Obs Included]"
        if inc == "no":
            df2 = df[df["feel"] > df["tmpf"]]
            inctitle = " [Only Additive]"
        else:
            df2 = df
        maxval = int(df2["feel"].max() + 1)
        LEVELS[varname] = np.arange(80, maxval)
    elif varname == "windchill":
        df[varname] = df["feel"]
        compop = np.less_equal
        df["year"] = df["valid"].apply(
            lambda x: (x.year - 1) if x.month < 7 else x.year
        )
        inctitle = " [All Obs Included]"
        if inc == "no":
            df2 = df[df["feel"] < df["tmpf"]]
            inctitle = " [Only Additive]"
        else:
            df2 = df
        minval = int(df2["feel"].min() - 1)
        LEVELS[varname] = np.arange(minval, minval + 51)
    elif varname == "gust":
        pass
    else:
        maxval = int(df2[varname].max() + 1)
        LEVELS[varname] = np.arange(maxval - 31, maxval)

    minyear = df["year"].min()
    maxyear = df["year"].max()
    years = float((maxyear - minyear) + 1)
    x = []
    y = []
    y2 = []
    title = f"till {datetime.date.today():%-d %b}"
    title = "Entire Year" if ytd == "no" else title
    title = (
        f"{ctx['_sname']} ({minyear}-{maxyear})\n"
        f"{title2} Histogram ({title}){inctitle}"
    )
    fig, ax = figure_axes(title=title, apctx=ctx)
    ax.set_position([0.06, 0.1, 0.64, 0.8])
    yloc = 1.0
    xloc = 1.13
    yrlabel = (
        f"{highlightyear}"
        if varname != "windchill"
        else f"{highlightyear}-{highlightyear + 1}"
    )
    ax.text(
        xloc + 0.08, yloc + 0.04, "Avg:", transform=ax.transAxes, color="b"
    )
    ax.text(
        xloc + 0.21, yloc + 0.04, yrlabel, transform=ax.transAxes, color="r"
    )
    df3 = df2[df2["year"] == highlightyear]
    for level in LEVELS[varname]:
        x.append(level)
        y.append(len(df2[compop(df2[varname], level)].index) / years)
        y2.append(len(df3[compop(df3[varname], level)].index))

        if level % 2 == 0:
            ax.text(xloc, yloc, f"{level}", transform=ax.transAxes)
            ax.text(
                xloc + 0.08,
                yloc,
                f"{y[-1]:.1f}",
                transform=ax.transAxes,
                color="b",
            )
            ax.text(
                xloc + 0.21,
                yloc,
                f"{y2[-1]:.0f}",
                transform=ax.transAxes,
                color="r",
            )
            yloc -= 0.04
    ax.text(xloc, yloc, f"n={len(df2.index)}", transform=ax.transAxes)
    for x0, y0, y02 in zip(x, y, y2):
        ax.plot([x0, x0], [y0, y02], color="k")
    rdf = pd.DataFrame({"level": x, "avg": y, f"d{highlightyear}": y2})
    x = np.array(x, dtype=np.float64)
    ax.scatter(x, y, color="b", label="Avg")
    ax.scatter(x, y2, color="r", label=yrlabel)
    ax.grid(True)
    ymax = int(max([max(y), max(y2)]))
    ax.set_xlim(x[0] - 0.5, x[-1] + 0.5)
    dy = 24 * (int(ymax / 240) + 1)
    ax.set_yticks(range(0, ymax, dy))
    ax.set_ylim(-0.5, ymax + 5)
    ax2 = ax.twinx()
    ax2.set_ylim(-0.5, ymax + 5)
    ax2.set_yticks(range(0, ymax, dy))
    ax2.set_yticklabels([f"{s:.0f}" for s in np.arange(0, ymax, dy) / 24])
    ax2.set_ylabel("Expressed in 24 Hour Days")
    ax.set_ylabel("Hours Per Year")
    unit = r"$^\circ$F" if varname != "gust" else "MPH"
    ax.set_xlabel(f"{VDICT[varname]} {unit}")
    ax.legend(loc=(2 if varname == "windchill" else 1), scatterpoints=1)
    return fig, rdf

if __name__ == "__main__":
    plotter(
        dict(
            ytd="yes", network="UT_ASOS", zstation="SGU", var="dwpf", inc="yes"
        )
    )


text:
<!DOCTYPE html>
<!--

// Copyright 2011 Google Inc.
//
// 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.

-->
<html>
<head>
<title></title>
<script src="../../../third_party/closure-library/closure/goog/base.js"></script>
<script>
// NOTE: base.js and all goog.require statements must be in JS script blocks
// NOTE: because they use document.write to add new script tags in place
goog.require('goog.testing.jsunit');
</script>
<script src="../../../bin/traceur.js"></script>
</head>
<body>
<script type="text/expected-result">
var $__toObject = function(value) {
  if (value == null) throw TypeError();
  return Object(value);
}, $__spread = function() {
  var rv = [], k = 0;
  for (var i = 0; i < arguments.length; i++) {
    var value = $__toObject(arguments[i]);
    for (var j = 0; j < value.length; j++) {
      rv[k++] = value[j];
    }
  }
  return rv;
};
var a = $__spread([0, 1]);
var b = $__spread(a, [2]);
</script>
<script>

var ProjectWriter = traceur.outputgeneration.ProjectWriter;

traceur.options.reset(true);
traceur.options.spread = true;

function normalize(s) {
  return s.trim().replace(/\s+\n/g, '\n');
}

function testTwoProprams() {
  var url = location.href;
  var project = new traceur.semantics.symbols.Project(url);

  var sourceA = 'var a = [...[0, 1]];'
  var fileA = new traceur.syntax.SourceFile('a', sourceA);
  project.addFile(fileA);

  var sourceB = 'var b = [...a, 2];'
  var fileB = new traceur.syntax.SourceFile('b', sourceB);
  project.addFile(fileB);

  var reporter = new traceur.util.ErrorReporter();

  var res = traceur.codegeneration.Compiler.compile(reporter, project, false);

  var expectedResult = normalize(
      document.querySelector('[type="text/expected-result"]').textContent);
  var actualResult = normalize(ProjectWriter.write(res));

  assertEquals(expectedResult, actualResult);
}

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


text:
define([], function () {
  function extendPrototype(superClass, prototypeProperties) {
    var properties = {};
    for (var prop in prototypeProperties) {
      if (prototypeProperties.hasOwnProperty(prop)) {
        properties[prop] = {
          value: prototypeProperties[prop],
          enumerable: true,
          writable: true,
          configurable: true
        }
      }
    }
    return Object.create(superClass, properties);
  }

  return extendPrototype;
})


text:
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                // require('jQuery') returns a factory that requires window to
                // build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop
                // if it's defined (how jquery works)
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            return factory(jQuery);
        };
    } else {
        // Browser globals
        factory(window.jQuery);
    }
}(function ($) {
/**
 * Swedish
 */

$.FE.LANGUAGE['sv'] = {
  translation: {
    // Place holder
    "Type something": "Ange n\u00e5got",

    // Basic formatting
    "Bold": "Fetstil",
    "Italic": "Kursiv stil",
    "Underline": "Understruken",
    "Strikethrough": "Genomstruken",

    // Main buttons
    "Insert": "Infoga",
    "Delete": "Radera",
    "Cancel": "Avbryt",
    "OK": "Ok",
    "Back": "Tillbaka",
    "Remove": "Ta bort",
    "More": "Mer",
    "Update": "Uppdatera",
    "Style": "Stil",

    // Font
    "Font Family": "Teckensnitt",
    "Font Size": "Teckenstorlek",

    // Colors
    "Colors": "F\u00e4rger",
    "Background": "Bakgrund",
    "Text": "Text",
    "HEX Color": "Hex färg",

    // Paragraphs
    "Paragraph Format": "Format",
    "Normal": "Normal",
    "Code": "Kod",
    "Heading 1": "Rubrik 1",
    "Heading 2": "Rubrik 2",
    "Heading 3": "Rubrik 3",
    "Heading 4": "Rubrik 4",

    // Style
    "Paragraph Style": "Styckesformat",
    "Inline Style": "Infogad stil",

    // Alignment
    "Align": "Justera",
    "Align Left": "Vänsterjustera",
    "Align Center": "Centrera",
    "Align Right": "Högerjustera",
    "Align Justify": "Justera",
    "None": "Inget",

    // Lists
    "Ordered List": "Ordnad lista",
    "Default": "Standard",
    "Lower Alpha": "Lägre alfa",
    "Lower Greek": "Lägre grekiska",
    "Lower Roman": "Lägre roman",
    "Upper Alpha": "Övre alfa",
    "Upper Roman": "Övre roman",

    "Unordered List": "Oordnad lista",
    "Circle": "Cirkel",
    "Disc": "Skiva",
    "Square": "Fyrkant",

    // Line height
    "Line Height": "Radavstånd",
    "Single": "Enda",
    "Double": "Dubbel",

    // Indent
    "Decrease Indent": "Minska indrag",
    "Increase Indent": "\u00d6ka indrag",

    // Links
    "Insert Link": "Infoga l\u00e4nk",
    "Open in new tab": "\u00d6ppna i ny flik",
    "Open Link": "\u00d6ppna l\u00e4nk",
    "Edit Link": "Redigera l\u00e4nk",
    "Unlink": "Ta bort l\u00e4nk",
    "Choose Link": "V\u00e4lj l\u00e4nk",

    // Images
    "Insert Image": "Infoga bild",
    "Upload Image": "Ladda upp en bild",
    "By URL": "Genom URL",
    "Browse": "Bl\u00e4ddra",
    "Drop image": "Sl\u00e4pp bild",
    "or click": "eller klicka",
    "Manage Images": "Hantera bilder",
    "Loading": "Laddar",
    "Deleting": "Raderar",
    "Tags": "Etiketter",
    "Are you sure? Image will be deleted.": "\u00c4r du s\u00e4ker? Bild kommer att raderas.",
    "Replace": "Ers\u00e4tt",
    "Uploading": "Laddar upp",
    "Loading image": "Laddar bild",
    "Display": "Visa",
    "Inline": "I linje",
    "Break Text": "Bryt text",
    "Alternative Text": "Alternativ text",
    "Change Size": "\u00c4ndra storlek",
    "Width": "Bredd",
    "Height": "H\u00f6jd",
    "Something went wrong. Please try again.": "N\u00e5got gick fel. Var god f\u00f6rs\u00f6k igen.",
    "Image Caption": "Bildtext",
    "Advanced Edit": "Avancerad redigering",

    // Video
    "Insert Video": "Infoga video",
    "Embedded Code": "Inb\u00e4ddad kod",
    "Paste in a video URL": "Klistra in i en video url",
    "Drop video": "Släpp video",
    "Your browser does not support HTML5 video.": "Din webbläsare stöder inte html5-video.",
    "Upload Video": "Ladda upp video",

    // Tables
    "Insert Table": "Infoga tabell",
    "Table Header": "Tabell huvud",
    "Remove Table": "Ta bort tabellen",
    "Table Style": "Tabellformat",
    "Horizontal Align": "Horisontell justering",
    "Row": "Rad",
    "Insert row above": "Infoga rad f\u00f6re",
    "Insert row below": "Infoga rad efter",
    "Delete row": "Ta bort rad",
    "Column": "Kolumn",
    "Insert column before": "Infoga kolumn f\u00f6re",
    "Insert column after": "Infoga kolumn efter",
    "Delete column": "Ta bort kolumn",
    "Cell": "Cell",
    "Merge cells": "Sammanfoga celler",
    "Horizontal split": "Dela horisontellt",
    "Vertical split": "Dela vertikalt",
    "Cell Background": "Cellbakgrund",
    "Vertical Align": "Vertikal justering",
    "Top": "Överst",
    "Middle": "Mitten",
    "Bottom": "Nederst",
    "Align Top": "Justera överst",
    "Align Middle": "Justera mitten",
    "Align Bottom": "Justera nederst",
    "Cell Style": "Cellformat",

    // Files
    "Upload File": "Ladda upp fil",
    "Drop file": "Sl\u00e4pp fil",

    // Emoticons
    "Emoticons": "Uttryckssymboler",
    "Grinning face": "Grina ansikte",
    "Grinning face with smiling eyes": "Grina ansikte med leende \u00f6gon",
    "Face with tears of joy": "Face med gl\u00e4djet\u00e5rar",
    "Smiling face with open mouth": "Leende ansikte med \u00f6ppen mun",
    "Smiling face with open mouth and smiling eyes": "Leende ansikte med \u00f6ppen mun och leende \u00f6gon",
    "Smiling face with open mouth and cold sweat": "Leende ansikte med \u00f6ppen mun och kallsvett",
    "Smiling face with open mouth and tightly-closed eyes": "Leende ansikte med \u00f6ppen mun och t\u00e4tt slutna \u00f6gon",
    "Smiling face with halo": "Leende ansikte med halo",
    "Smiling face with horns": "Leende ansikte med horn",
    "Winking face": "Blinka ansikte",
    "Smiling face with smiling eyes": "Leende ansikte med leende \u00f6gon",
    "Face savoring delicious food": "Ansikte smaka uts\u00f6kt mat",
    "Relieved face": "L\u00e4ttad ansikte",
    "Smiling face with heart-shaped eyes": "Leende ansikte med hj\u00e4rtformade \u00f6gon",
    "Smiling face with sunglasses": "Leende ansikte med solglas\u00f6gon",
    "Smirking face": "Flinande ansikte",
    "Neutral face": "Neutral ansikte",
    "Expressionless face": "Uttryckslöst ansikte",
    "Unamused face": "Inte roade ansikte",
    "Face with cold sweat": "Ansikte med kallsvett",
    "Pensive face": "Eftert\u00e4nksamt ansikte",
    "Confused face": "F\u00f6rvirrad ansikte",
    "Confounded face": "F\u00f6rbryllade ansikte",
    "Kissing face": "Kyssande ansikte",
    "Face throwing a kiss": "Ansikte kasta en kyss",
    "Kissing face with smiling eyes": "Kyssa ansikte med leende \u00f6gon",
    "Kissing face with closed eyes": "Kyssa ansikte med slutna \u00f6gon",
    "Face with stuck out tongue": "Ansikte med stack ut tungan",
    "Face with stuck out tongue and winking eye": "Ansikte med stack ut tungan och blinkande \u00f6ga",
    "Face with stuck out tongue and tightly-closed eyes": "Ansikte med stack ut tungan och t\u00e4tt slutna \u00f6gon",
    "Disappointed face": "Besviken ansikte",
    "Worried face": "Orolig ansikte",
    "Angry face": "Argt ansikte",
    "Pouting face": "Sk\u00e4ggtorsk ansikte",
    "Crying face": "Gr\u00e5tande ansikte",
    "Persevering face": "Uth\u00e5llig ansikte",
    "Face with look of triumph": "Ansikte med utseendet p\u00e5 triumf",
    "Disappointed but relieved face": "Besviken men l\u00e4ttad ansikte",
    "Frowning face with open mouth": "Rynkar pannan ansikte med \u00f6ppen mun",
    "Anguished face": "\u00c5ngest ansikte",
    "Fearful face": "R\u00e4dda ansikte",
    "Weary face": "Tr\u00f6tta ansikte",
    "Sleepy face": "S\u00f6mnig ansikte",
    "Tired face": "Tr\u00f6tt ansikte",
    "Grimacing face": "Grimaserande ansikte",
    "Loudly crying face": "H\u00f6gt gr\u00e5tande ansikte",
    "Face with open mouth": "Ansikte med \u00f6ppen mun",
    "Hushed face": "D\u00e4mpade ansikte",
    "Face with open mouth and cold sweat": "Ansikte med \u00f6ppen mun och kallsvett",
    "Face screaming in fear": "Face skriker i skr\u00e4ck",
    "Astonished face": "F\u00f6rv\u00e5nad ansikte",
    "Flushed face": "Ansiktsrodnad",
    "Sleeping face": "Sovande anskite",
    "Dizzy face": "Yr ansikte",
    "Face without mouth": "Ansikte utan mun",
    "Face with medical mask": "Ansikte med medicinsk maskera",

    // Line breaker
    "Break": "Ny rad",

    // Math
    "Subscript": "Neds\u00e4nkt",
    "Superscript": "Upph\u00f6jd",

    // Full screen
    "Fullscreen": "Helsk\u00e4rm",

    // Horizontal line
    "Insert Horizontal Line": "Infoga horisontell linje",

    // Clear formatting
    "Clear Formatting": "Ta bort formatering",

    // Save
    "Save": "Spara",

    // Undo, redo
    "Undo": "\u00c5ngra",
    "Redo": "G\u00f6r om",

    // Select all
    "Select All": "Markera allt",

    // Code view
    "Code View": "Kodvy",

    // Quote
    "Quote": "Citat",
    "Increase": "\u00d6ka",
    "Decrease": "Minska",

    // Quick Insert
    "Quick Insert": "Snabbinfoga",

    // Spcial Characters
    "Special Characters": "Specialtecken",
    "Latin": "Latin",
    "Greek": "Grekisk",
    "Cyrillic": "Cyrillic",
    "Punctuation": "Skiljetecken",
    "Currency": "Valuta",
    "Arrows": "Pilar",
    "Math": "Matematik",
    "Misc": "Övrigt",

    // Print.
    "Print": "Skriva ut",

    // Spell Checker.
    "Spell Checker": "Stavningskontroll",

    // Help
    "Help": "Hjälp",
    "Shortcuts": "Genvägar",
    "Inline Editor": "Inline editor",
    "Show the editor": "Visa redigeraren",
    "Common actions": "Vanliga kommandon",
    "Copy": "Kopiera",
    "Cut": "Klipp ut",
    "Paste": "Klistra in",
    "Basic Formatting": "Grundläggande formatering",
    "Increase quote level": "Öka citatnivå",
    "Decrease quote level": "Minska citatnivå",
    "Image / Video": "Bild / video",
    "Resize larger": "Öka storlek",
    "Resize smaller": "Minska storlek",
    "Table": "Tabell",
    "Select table cell": "Markera tabellcell",
    "Extend selection one cell": "Utöka markering en cell",
    "Extend selection one row": "Utöka markering en rad",
    "Navigation": "Navigering",
    "Focus popup / toolbar": "Fokusera popup / verktygsfältet",
    "Return focus to previous position": "Byt fokus till föregående plats",

    // Embed.ly
    "Embed URL": "Bädda in url",
    "Paste in a URL to embed": "Klistra in i en url för att bädda in",

    // Word Paste.
    "The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?": "Den inklippta texten kommer från ett Microsoft Word-dokument. Vill du behålla formateringen eller städa upp det?",
    "Keep": "Behåll",
    "Clean": "Städa upp",
    "Word Paste Detected": "Urklipp från Word upptäckt"
  },
  direction: "ltr"
};

}));


text:
layout: page-fullwidth
title: Angeführt
published: true
author: mwerner
meta_description: "Jekyll kann typographische Anführungszeichen."
date: 2017-06-22
tags:
    - jekyll
    - kramdown
categories:
    - small hacks
---
Jekyll -- oder genauer der dort genutzte Markdown-Prozessor Kramdown -- kann typographische Anführungszeichen.
Wenn man also ein Zitat in Anführungszeichen (\") setzt stehen nach der Verarbeitung vor und nach dem Zitat typographische
Anführungszeichen:

   * `"Zitat"` wird zu "Zitat"

Leider entspricht das nicht der deutschen Typographie, wo vor dem Zitat das Zitatzeichen unten und danach oben (und anders herum) steht.
Durch eine zusätzliche Konfiguration kann man auf deutsche Typographie umschalten, indem man die <kbd>_config.yml</kbd> um folgende Zeilen ergänzt:

~~~ yml
kramdown:
  smart_quotes:   sbquo,lsquo,bdquo,ldquo
~~~
Nun ergibt sich der richtige Schriftsatz im Deutschen:

   * `"Zitat"` wird zu "Zitat"


text:
<?php

namespace Magento\Customer\Test\TestCase;

use Magento\Config\Test\Fixture\ConfigData;
use Magento\Customer\Test\Fixture\CustomerGroup;
use Magento\Mtf\Fixture\FixtureFactory;
use Magento\Mtf\TestCase\Injectable;
use Magento\Customer\Test\Fixture\Customer;

/**
 * Abstract class for setting up VAT ID configuration.
 */
abstract class AbstractApplyVatIdTest extends Injectable
{
    /**
     * Fixture factory instance.
     *
     * @var FixtureFactory
     */
    protected $fixtureFactory;

    /**
     * System configuration data sets.
     *
     * @var string
     */
    protected $configData;

    /**
     * Customer fixture.
     *
     * @var Customer
     */
    protected $customer;

    /**
     * Customer groups data sets for VAT ID configuration.
     *
     * @var array
     */
    protected $vatGroupDataSets = [
        'valid_domestic_group' => 'valid_vat_id_domestic',
        'valid_intra_union_group' => 'valid_vat_id_intra_union',
        'invalid_group' => 'invalid_vat_id',
        'error_group' => 'validation_error_vat_id'
    ];

    /**
     * Customer groups for VAT ID configuration.
     *
     * @var array
     */
    protected $vatGroups = [];

    /**
     * Inject fixture factory class and create customer groups.
     *
     * @param FixtureFactory $fixtureFactory
     * @return void
     */
    public function __prepare(FixtureFactory $fixtureFactory)
    {
        $this->fixtureFactory = $fixtureFactory;

        foreach ($this->vatGroupDataSets as $group => $dataset) {
            /** @var CustomerGroup $groupFixture */
            $groupFixture = $this->fixtureFactory->createByCode('customerGroup', ['dataset' => $dataset]);
            $groupFixture->persist();
            $this->vatGroups[$group] = $groupFixture;
        }
    }

    /**
     * Prepare VAT ID confguration.
     *
     * @param ConfigData $vatConfig
     * @param string $customerGroup
     * @return void
     */
    protected function prepareVatConfig(ConfigData $vatConfig, $customerGroup)
    {
        $groupConfig = [
            'customer/create_account/viv_domestic_group' => [
                'value' => $this->vatGroups['valid_domestic_group']->getCustomerGroupId()
            ],
            'customer/create_account/viv_intra_union_group' => [
                'value' => $this->vatGroups['valid_intra_union_group']->getCustomerGroupId()
            ],
            'customer/create_account/viv_invalid_group' => [
                'value' => $this->vatGroups['invalid_group']->getCustomerGroupId()
            ],
            'customer/create_account/viv_error_group' => [
                'value' => $this->vatGroups['error_group']->getCustomerGroupId()
            ]
        ];
        $vatConfig = $this->fixtureFactory->createByCode(
            'configData',
            ['data' => array_replace_recursive($vatConfig->getSection(), $groupConfig)]
        );
        $vatConfig->persist();

        $customerData = array_merge(
            $this->customer->getData(),
            ['group_id' => ['value' => $this->vatGroups[$customerGroup]->getCustomerGroupCode()]],
            ['address' => ['addresses' => $this->customer->getDataFieldConfig('address')['source']->getAddresses()]]
        );
        $this->customer = $this->fixtureFactory->createByCode('customer', ['data' => $customerData]);
    }

    /**
     * Disable VAT id configuration.
     *
     * @return void
     */
    public function tearDown()
    {
        $this->objectManager->create(
            'Magento\Config\Test\TestStep\SetupConfigurationStep',
            ['configData' => $this->configData, 'rollback' => true]
        )->run();
    }
}


text:
package contentfetcher_test

import "github.com/apoydence/blogcontentprovider/contentfetcher"

type mockCacheProvider struct {
	called chan interface{}
	cache  *mockCache
}

func newMockCacheProvider(cache *mockCache) *mockCacheProvider {
	return &mockCacheProvider{
		called: make(chan interface{}, 10),
		cache:  cache,
	}
}

func (m *mockCacheProvider) CreateCache() contentfetcher.CacheFetcher {
	m.called <- nil
	return m.cache
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBuildingTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('buildings', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->integer('CityBlock')->unsigned();

        });

        Schema::table('buildings', function ($table) {
            $table->foreign('CityBlock')->references('id')->on('cityblocks')->onDelete('cascade');
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('buildings');
    }
}


text:
var request     = require('request');
var MongoClient = require('mongodb').MongoClient;
var utils       = require('../test-utils');

describe('donations page', function() {

	beforeEach(function() {
		/* create a bunch of contacts */
		var flow = protractor.promise.controlFlow();
		var self = this;
		utils.createUserAndSignIn(browser, element);
		flow.execute(function() {
			self.contacts = [];
			for (var i = 0; i < 10; ++i) {
				var name = 'TestName'+String.fromCharCode('A'.charCodeAt(0) + i);
				var contact = {
					firstName: name,
					surname: name
				};
				self.contacts.push(contact);
			}
			return utils.db(function(db) {
				db.collection('contacts').insert(self.contacts, utils.throwIfPresent);
			});
		});

	});

	it('should be able to add a donation', function() {
		browser.get('/#!/donations');

		element.all(by.css('[href="/#!/donations/create"]')).first().click();

		// var donation = {
		//  name: this.contacts[0].id,
		//  items: []
		// };

		element(by.partialButtonText('Click')).click();
		element(by.model('searchText')).sendKeys(this.contacts[0].firstName);
		element.all(by.repeater('contact in contacts')).first().click();

		// element(by.model('donors')).sendKeys(donation.name);
		// element(by.model('dollarAmount')).sendKeys(donation.dollarAmount);
		// element(by.css('select option[value=cash]')).click();
		// element(by.css('[type=submit]')).click();

		browser.get('/#!/donations');
		expect(true).toBeTruthy();
	});
});


text:
namespace p3d {

	PhysicsTriangleMesh::PhysicsTriangleMesh(IPhysics* engine, RenderingComponent* rcomp, const f32 mass, bool ghost) : IPhysicsComponent(mass, CollisionShapes::TriangleMesh, engine, ghost)
	{
		// Build the triangle mesh from Rendering Component
		unsigned indexCount = 0;
		for (unsigned k = 0; k < rcomp->GetMeshes().size(); k++)
		{
			RenderingMesh* rc = (RenderingMesh*)rcomp->GetMeshes()[k];
			for (unsigned i = 0; i < rc->Geometry->GetIndexData().size(); i++)
			{
				index.push_back(indexCount++);
				vertex.push_back(rc->Geometry->GetVertexData()[rc->Geometry->GetIndexData()[i]]);
			}
		}
	}

	PhysicsTriangleMesh::PhysicsTriangleMesh(IPhysics* engine, const std::vector<uint32> &index, const std::vector<Vec3> &vertex, const f32 mass, bool ghost) : IPhysicsComponent(mass, CollisionShapes::TriangleMesh, engine, ghost)
	{
		// Build the triangle mesh from an index vector and vertex vector
		this->vertex = vertex;
		this->index = index;
	}

	//    void AddRendering(IRendering* rcomp)
	//    {
	//
	//    }
	//    void AddIndex(const unsigned &index)
	//    {
	//
	//    }
	//    void AddTriangle(const Vec3 &vertex1, const Vec3 &vertex2, const Vec3 &vertex4)
	//    {
	//
	//    }

	PhysicsTriangleMesh::~PhysicsTriangleMesh() {}

}


text:
/**
* cpsc101 lab 1
* date: January 2016
* Made By:
*  Kier Lindsay
**/

//import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Random;

import java.io.RandomAccessFile;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;

public class PersonTester{

  //retuens a random line(name since there is a name on each line) form a file and retuensd it as a string
  //this method is modified form a stackoverflow post.
  //link to origanal post http://stackoverflow.com/a/19850005

  //NOTE only 4080 names can be generated after that the
  //name fred will be used and filenotfound error wqill be printed
  public static String getRandomName() {
    String name = "Fred";
    try{
      RandomAccessFile f = new RandomAccessFile("namelist", "r");
      long randomLocation = (long) (Math.random() * f.length());
      f.seek(randomLocation);
      f.readLine();
      name = f.readLine();

    } catch(FileNotFoundException e) {
      System.out.println("Error: namelist File Not found");
    } catch(IOException e) {
      System.out.println("Error: IO Exeption");
    }

    return name;
  }

  public static String getFullName() {
    return getRandomName()+" "+getRandomName();
  }

  public static void main(String[] args) {

    //makes a list for the people to be in
    ArrayList<Person> people = new ArrayList<Person>();

    //decuses the population of random vile
    Random rand = new Random();
    int numberOfPeople = rand.nextInt(200) + 10;

    //create person objects in the people array
    for(int i = 0; i < numberOfPeople; i++) {
      people.add(new Person(getFullName()));
    }

    //start of the story
    System.out.print("In  small town called Random Ville there are "+Person.numberLiving()+" people living happy.\n");

    int murdererCount = rand.nextInt(10) + 1;
    System.out.print("Sadly this town has a few("+murdererCount+") murderers in it who plan to go on a rampage!\n");

    //picks the murderers
    ArrayList<Integer> murderers = new ArrayList<Integer>();
    for(int i = 0; i < murdererCount; i++) {
      int temp = 0;
      boolean alreadyMurderer = true;
      while(alreadyMurderer) {
			alreadyMurderer=false;
			temp =rand.nextInt(numberOfPeople);
			for(int j = 0; j < murderers.size(); j++) {
  				if(temp == murderers.get(j)) {
    				alreadyMurderer=true;
				}
			}
      }
      murderers.add(temp);

    }
    System.out.print("Let the murderers say Hello!\n");

    for(int i = 0; i < murderers.size(); i++) {
      people.get(murderers.get(i)).sayHello();
    }
    System.out.println();
    System.out.print("Every night each murderer plans to kill one person.\n\n");
    int day = 1;
    while(murderers.size()>0){
      System.out.print("Day: "+ day + "\n");

      for(int i = 0; i < murderers.size(); i++) {
	boolean noMurder = true;
	int temp = 0;
	while(noMurder) {
	  temp = rand.nextInt( people.size() );
	  if(people.get(temp).isAlive()) {

	    if(murderers.get( i ) == temp) {
	      System.out.print( people.get( murderers.get( i ) ).name() + " committed seppuku!\n");

	    }
	    else System.out.print( people.get( murderers.get( i ) ).name() + " murdered " + people.get( temp ).name()+"!\n");

	    people.get( murderers.get( i ) ).murder( people.get( temp ) );
	    //System.out.println(people.get(temp).name() );
	    noMurder = false;

	    for(int j = 0; j < murderers.size(); j++) {
	      if(temp == murderers.get(j)) {

		//we need to decrement the for loop as the murderer array is one smaller now and all
		//the fallowing murderers are shifted one spot down in the array
		//we only need to do this if someone bofore or at our cutrrent position is killed.
		if(murderers.get(j)<=i) {
		  murderers.remove(j);
		  i--;
		}else {
		  murderers.remove(j);
		}
		break;
	      }
	    }

	  }
	}
      }
    System.out.println();
    day++;
    }

    System.out.println( Person.numberLiving() + " People survived the killing spree.  \nAs the survivors come out form hiding they all introduce themselves.\n" );
    Person.allSayHello();

  }
}


text:
package org.apache.camel.component.reactive.streams.platforms;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.reactive.streams.api.CamelReactiveStreams;
import org.apache.camel.component.reactive.streams.api.CamelReactiveStreamsService;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 *
 */
public abstract class AbstractPlatformTestSupport extends CamelTestSupport {

    @Test
    public void testPublisher() throws Exception {

        int num = 20;

        new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:endpoint")
                        .to("reactive-streams:integers");
            }
        }.addRoutesToCamelContext(context);

        CamelReactiveStreamsService camel = CamelReactiveStreams.get(context);

        List<Integer> elements = new LinkedList<>();
        CountDownLatch latch = new CountDownLatch(num);

        this.changeSign(camel.fromStream("integers", Integer.class), i -> {
            elements.add(i);
            latch.countDown();
        });

        context.start();

        for (int i = 1; i <= num; i++) {
            template.sendBody("direct:endpoint", i);
        }

        assertTrue(latch.await(5, TimeUnit.SECONDS));

        for (Integer number : elements) {
            assertTrue(number < 0);
        }

    }

    @Test
    public void testSubscriber() throws Exception {

        int num = 20;

        new RouteBuilder() {
            @Override
            public void configure() {
                from("reactive-streams:integers")
                        .to("mock:endpoint");
            }
        }.addRoutesToCamelContext(context);

        CamelReactiveStreamsService camel = CamelReactiveStreams.get(context);

        List<Integer> elements = new LinkedList<>();
        for (int i = 1; i <= num; i++) {
            elements.add(i);
        }

        changeSign(elements, camel.streamSubscriber("integers", Integer.class));
        context.start();

        MockEndpoint mock = getMockEndpoint("mock:endpoint");
        mock.expectedMessageCount(num);
        mock.assertIsSatisfied();

        for (Exchange ex : mock.getExchanges()) {
            Integer number = ex.getIn().getBody(Integer.class);
            assertNotNull(number);
            assertTrue(number < 0);
        }

    }

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    protected abstract void changeSign(Publisher<Integer> data, Consumer<Integer> consume);

    protected abstract void changeSign(Iterable<Integer> data, Subscriber<Integer> camel);

}