text:
package com.omniti.labs;

import java.util.Date;
import java.util.Map;

public class FqClientImplDebug implements FqClientImplInterface {
  protected FqClient client = null;
  public void setClient(FqClient c) throws InUseException {
    if(client != null) throw new InUseException();
    client = c;
  }
  protected void genericError(Throwable e) {
    e.printStackTrace();
  }
  public void connectError(Throwable e) { genericError(e); }
  public void commandError(Throwable e) { genericError(e); }
  public void dataError(Throwable e) { genericError(e); }
  public void dispatch(FqMessage m) {
    byte b[] = m.getPayload();
    int len = (b == null) ? 0 : b.length;
    System.err.println("m[" + len + "] via " + m.getRoute() +
      " over " + m.getExchange() + " from " + m.getSender());
  }
  public void dispatch(FqCommand cmd) {
    System.err.println(cmd);
  }
  public void dispatchAuth(FqCommand.Auth cmd) {
    dispatch(cmd);
  }
  public void dispatchHeartbeatRequest(FqCommand.HeartbeatRequest cmd) {
    dispatch(cmd);
  }
  public void dispatchHeartbeat(FqCommand.Heartbeat cmd) { dispatch(cmd); }
  public void dispatchBindRequest(FqCommand.BindRequest cmd) {
    System.err.println(cmd.toString() + cmd.getBinding());
  }
  public void dispatchUnbindRequest(FqCommand.UnbindRequest cmd) {
    System.err.println(cmd.toString() + cmd.getBinding() + " " + cmd.getSuccess());
  }
  public void dispatchStatusRequest(FqCommand.StatusRequest cmd) {
    Date d = cmd.getDate();
    Map<String,Long> m = cmd.getMap();
    System.err.println("Status: " + d);
    for(Map.Entry<String, Long> entry : m.entrySet()) {
      System.err.println("    " + entry.getKey() + " : " + entry.getValue());
    }
  }
}


text:
module Network.TLS.Cap
    ( hasHelloExtensions
    , hasExplicitBlockIV
    ) where

import Network.TLS.Types

hasHelloExtensions, hasExplicitBlockIV :: Version -> Bool

hasHelloExtensions ver = ver >= SSL3
hasExplicitBlockIV ver = ver >= TLS11

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react'

export interface TableHeaderProps {
  adjustForCheckbox?: boolean;
  className?: string;
  displaySelectAll?: boolean;
  enableSelectAll?: boolean;
  style?: React.CSSProperties;
}

export default class TableHeader extends React.Component<TableHeaderProps, {}> {
}


text:
package jkanvas.painter.groups;

import static jkanvas.util.ArrayUtil.*;

import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import jkanvas.Camera;
import jkanvas.KanvasContext;
import jkanvas.animation.AnimatedPosition;
import jkanvas.animation.AnimationAction;
import jkanvas.animation.AnimationList;
import jkanvas.animation.AnimationTiming;
import jkanvas.animation.Animator;
import jkanvas.animation.GenericAnimated;
import jkanvas.painter.Renderpass;
import jkanvas.painter.RenderpassPainter;
import jkanvas.util.PaintUtil;
import jkanvas.util.VecUtil;

/**
 * A group of render passes. The layout of the render passes is determined by
 * subclasses. Render passes without bounding boxes may or may not be allowed
 * depending of the implementation of the subclass. Transitions between layouts
 * can be animated.
 *
 * @author Joschi <josua.krause@gmail.com>
 * @param <T> The type of layouted render passes.
 */
public class RenderGroup<T extends Renderpass> extends Renderpass {

  /**
   * The offset of a render pass as {@link AnimatedPosition}.
   *
   * @author Joschi <josua.krause@gmail.com>
   * @param <T> The type of the render pass.
   */
  public static final class RenderpassPosition<T extends Renderpass>
  extends GenericAnimated<Point2D> {

    /** The render pass. */
    public final T pass;

    /** The current render pass bounding box. */
    private final Rectangle2D bbox;

    /**
     * Creates a render pass position.
     *
     * @param pass The render pass.
     * @param list The animation list.
     */
    public RenderpassPosition(final T pass, final AnimationList list) {
      super(new Point2D.Double(pass.getOffsetX(), pass.getOffsetY()));
      bbox = new Rectangle2D.Double();
      pass.getBoundingBox(bbox);
      this.pass = pass;
      list.addAnimated(this);
      pass.setAnimationList(list);
    }

    @Override
    protected AnimationAction beforeAnimation(
        final AnimationTiming timing, final AnimationAction onFinish) {
      if(timing.duration <= 0) return onFinish;
      pass.setForceCache(true);
      // TODO #43 -- Java 8 simplification
      return new AnimationAction() {

        @Override
        public void animationFinished() {
          pass.setForceCache(false);
          if(onFinish != null) {
            onFinish.animationFinished();
          }
        }

      };
    }

    @Override
    protected Point2D interpolate(final Point2D from, final Point2D to, final double t) {
      return VecUtil.interpolate(from, to, t);
    }

    @Override
    protected void doSet(final Point2D t) {
      super.doSet(t);
      pass.setOffset(t.getX(), t.getY());
    }

    /**
     * Checks whether the bounding box has changed since the last call and sets
     * the current bounding box.
     *
     * @return Whether the bounding box has changed.
     */
    public boolean checkBBoxChange() {
      final double oldWidth = bbox.getWidth();
      final double oldHeight = bbox.getHeight();
      RenderpassPainter.getPassBoundingBox(bbox, pass);
      return bbox.getWidth() != oldWidth || bbox.getHeight() != oldHeight;
    }

    /**
     * Getter.
     *
     * @return The bounding box of the pass. The box must not be changed. The
     *         value is refreshed by calling {@link #checkBBoxChange()}.
     */
    Rectangle2D getPassBBox() {
      return bbox;
    }

    /**
     * Getter.
     *
     * @param rect When the position is in animation the resulting frame is the
     *          destination bounding-box of the render pass. Otherwise the
     *          current bounding box is used.
     */
    public void getPredictBBox(final Rectangle2D rect) {
      pass.getBoundingBox(rect);
      final Point2D pred = getPredict();
      rect.setFrame(rect.getX() + pred.getX(),
          rect.getY() + pred.getY(), rect.getWidth(), rect.getHeight());
    }

  } // RenderpassPosition

  /** If this flag is set the layout is recomputed when the group is drawn. */
  private boolean redoLayout;

  /** The list of group members. */
  private final List<RenderpassPosition<T>> members;

  /** The list of non layouted members in front of the layouted members. */
  private final List<Renderpass> nlFront = new ArrayList<>();

  /** The list of non layouted members behind the layouted members. */
  private final List<Renderpass> nlBack = new ArrayList<>();

  /** The underlying animator. */
  private final Animator animator;

  /**
   * Creates a new render pass group.
   *
   * @param animator The underlying animator.
   */
  public RenderGroup(final Animator animator) {
    this.animator = Objects.requireNonNull(animator);
    members = new ArrayList<>();
    redoLayout = true;
  }

  /**
   * Getter.
   *
   * @return The animator for this render group.
   */
  public Animator getAnimator() {
    return animator;
  }

  @Override
  public void setAnimationList(final AnimationList list) {
    if(animator.getAnimationList() != list) throw new IllegalArgumentException(
        "attempt to set group to other animation list");
  }

  /**
   * Creates a render pass position directly without adding it to the member
   * list yet. Note that if this position will not be used it must be removed
   * with {@link #remove(RenderpassPosition)}. This method is a convenience
   * method for methods that have direct access to the member list like
   * {@link #doLayout(List)}.
   *
   * @param pass The render pass.
   * @return The converted render pass position.
   */
  protected RenderpassPosition<T> create(final T pass) {
    final RenderpassPosition<T> rp = convert(pass);
    rp.checkBBoxChange();
    addedRenderpassIntern(rp);
    return rp;
  }

  /**
   * Safely removes a render pass position directly without altering the member
   * list. This method is a convenience method for methods that have direct
   * access to the member list like {@link #doLayout(List)}.
   *
   * @param rp The render pass position.
   */
  protected void remove(final RenderpassPosition<T> rp) {
    removedRenderpassIntern(rp);
  }

  /**
   * This method is called before a render pass is added. It can be used to
   * prepare the render pass to be added.
   *
   * @param pass The render pass that will be added.
   */
  protected void beforeAdding(@SuppressWarnings("unused") final T pass) {
    // nothing to do
  }

  /**
   * Converts a render pass to a render pass position.
   *
   * @param pass The render pass.
   * @return The position.
   */
  private RenderpassPosition<T> convert(final T pass) {
    if(this == pass) throw new IllegalArgumentException("cannot add itself");
    beforeAdding(Objects.requireNonNull(pass));
    return new RenderpassPosition<>(pass, animator.getAnimationList());
  }

  /**
   * This method is called after a render pass is added.
   *
   * @param rp The render pass position.
   */
  protected void addedRenderpass(
      @SuppressWarnings("unused") final RenderpassPosition<T> rp) {
    // nothing to do
  }

  /**
   * This method is always called after a render pass is added.
   *
   * @param p The render pass position.
   */
  private void addedRenderpassIntern(final RenderpassPosition<T> p) {
    p.pass.setParent(this);
    addedRenderpass(p);
  }

  /**
   * This method is called after a render pass is removed.
   *
   * @param rp The render pass position.
   */
  protected void removedRenderpass(
      @SuppressWarnings("unused") final RenderpassPosition<T> rp) {
    // nothing to do
  }

  /**
   * This method is always called after a render pass is removed.
   *
   * @param p The render pass position.
   */
  private void removedRenderpassIntern(final RenderpassPosition<T> p) {
    removedRenderpass(p);
    p.pass.setParent(null);
  }

  /**
   * Adds a render pass.
   *
   * @param pass The render pass.
   */
  public void addRenderpass(final T pass) {
    final RenderpassPosition<T> p = convert(pass);
    members.add(p);
    addedRenderpassIntern(p);
    invalidate();
  }

  /**
   * Inserts a render pass.
   *
   * @param index The index where the render pass will be inserted.
   * @param pass The render pass.
   */
  public void addRenderpass(final int index, final T pass) {
    final RenderpassPosition<T> p = convert(pass);
    members.add(index, p);
    addedRenderpassIntern(p);
    invalidate();
  }

  /**
   * Getter.
   *
   * @param r The abstract render pass to find.
   * @return The index of the given render pass or -1 if the pass
   *         could not be found. Equality is defined by identity.
   */
  public int indexOf(final T r) {
    for(int i = 0; i < members.size(); ++i) {
      final RenderpassPosition<T> rp = members.get(i);
      if(rp.pass == r) return i;
    }
    return -1;
  }

  /**
   * Removes the render pass at the given index.
   *
   * @param index The index.
   */
  public void removeRenderpass(final int index) {
    final RenderpassPosition<T> p = members.remove(index);
    removedRenderpassIntern(p);
    invalidate();
  }

  /** Clears all render passes. */
  public void clearRenderpasses() {
    final RenderpassPosition<T>[] rps = members();
    members.clear();
    for(final RenderpassPosition<T> p : rps) {
      removedRenderpassIntern(p);
    }
    invalidate();
  }

  /**
   * Getter.
   *
   * @return The number of render passes.
   */
  public int renderpassCount() {
    return members.size();
  }

  /**
   * Getter.
   *
   * @param index The index.
   * @return The render pass at the given position.
   */
  public T getRenderpass(final int index) {
    return members.get(index).pass;
  }

  /**
   * Sets the position of the given render pass and executes the given action
   * afterwards.
   *
   * @param pass The render pass.
   * @param pos The new position.
   * @param onFinish The (optional) action to execute afterwards.
   */
  public void setPosition(final T pass, final Point2D pos, final AnimationAction onFinish) {
    setPosition(indexOf(pass), pos, onFinish);
  }

  /**
   * Sets the position of the given render pass and executes the given action
   * afterwards.
   *
   * @param index The index of the render pass.
   * @param pos The new position.
   * @param onFinish The (optional) action to execute afterwards.
   */
  public void setPosition(final int index, final Point2D pos,
      final AnimationAction onFinish) {
    members.get(index).set(pos, onFinish);
  }

  /**
   * Transitions a render pass to the given position and executes the given
   * action afterwards.
   *
   * @param pass The render pass.
   * @param pos The new position.
   * @param timing The animation timing.
   * @param onFinish The (optional) action to execute afterwards.
   */
  public void setPosition(final T pass, final Point2D pos,
      final AnimationTiming timing, final AnimationAction onFinish) {
    setPosition(indexOf(pass), pos, timing, onFinish);
  }

  /**
   * Transitions a render pass to the given position and executes the given
   * action afterwards.
   *
   * @param index The index of the render pass.
   * @param pos The new position.
   * @param timing The animation timing.
   * @param onFinish The (optional) action to execute afterwards.
   */
  public void setPosition(final int index, final Point2D pos,
      final AnimationTiming timing, final AnimationAction onFinish) {
    members.get(index).startAnimationTo(pos, timing, onFinish);
  }

  /**
   * Setter.
   *
   * @param index The index.
   * @param pass The render pass.
   */
  public void setRenderpass(final int index, final T pass) {
    final RenderpassPosition<T> p = convert(pass);
    final RenderpassPosition<T> o = members.set(index, p);
    removedRenderpassIntern(o);
    addedRenderpassIntern(p);
    invalidate();
  }

  /**
   * Adds a render pass that is not used for the layout.
   *
   * @param pass The render pass.
   * @param front Whether this pass is added in front of the layouted passes.
   */
  public void addNonLayouted(final Renderpass pass, final boolean front) {
    if(front) {
      nlFront.add(pass);
    } else {
      nlBack.add(pass);
    }
    animator.quickRefresh();
  }

  /**
   * Inserts a render pass that is not used for the layout.
   *
   * @param index The index where the render pass will be inserted.
   * @param pass The render pass.
   * @param front Whether this pass is added in front of the layouted passes.
   */
  public void addNonLayouted(final int index, final Renderpass pass, final boolean front) {
    if(front) {
      nlFront.add(index, pass);
    } else {
      nlBack.add(index, pass);
    }
    animator.quickRefresh();
  }

  /**
   * Removes a render pass that is not used for the layout.
   *
   * @param index The index of the render pass.
   * @param front Whether this pass is found in front of the layouted passes.
   */
  public void removeNonLayouted(final int index, final boolean front) {
    if(front) {
      nlFront.remove(index);
    } else {
      nlBack.remove(index);
    }
    animator.quickRefresh();
  }

  /**
   * Sets the render pass that is not used for the layout at the given position.
   *
   * @param index The index.
   * @param pass The render pass.
   * @param front Whether this method addresses passes in front of the layouted
   *          passes.
   */
  public void setNonLayouted(final int index, final Renderpass pass, final boolean front) {
    if(front) {
      nlFront.set(index, pass);
    } else {
      nlBack.set(index, pass);
    }
    animator.quickRefresh();
  }

  /**
   * Getter.
   *
   * @param index The index.
   * @param front Whether this method addresses passes in front of the layouted
   *          passes.
   * @return The render pass at the given index that is not used for the layout.
   */
  public Renderpass getNonLayouted(final int index, final boolean front) {
    return front ? nlFront.get(index) : nlBack.get(index);
  }

  /** Clears all render passes that are not used for the layout. */
  public void clearNonLayouted() {
    nlFront.clear();
    nlBack.clear();
    animator.quickRefresh();
  }

  /**
   * Getter.
   *
   * @param front Whether this method addresses passes in front of the layouted
   *          passes.
   * @return The number of render passes that are not used for the layout.
   */
  public int nonLayoutedSize(final boolean front) {
    return front ? nlFront.size() : nlBack.size();
  }

  /** Invalidates the current layout, recomputes the layout, and repaints. */
  public void invalidate() {
    redoLayout = true;
    animator.quickRefresh();
  }

  /**
   * Computes the current layout. The implementation may decide whether to allow
   * render passes without bounding box.
   *
   * @param members The positions of the render passes.
   */
  protected void doLayout(final List<RenderpassPosition<T>> members) {
    if(layout != null) {
      layout.doLayout(members);
    }
  }

  /** The layout of the group. */
  private RenderpassLayout<T> layout;

  /**
   * Setter.
   *
   * @param layout The layout of the group or null if the default
   *          layout should be used.
   */
  public void setLayout(final RenderpassLayout<T> layout) {
    this.layout = layout;
    invalidate();
  }

  /**
   * Getter.
   *
   * @return The layout of the group or null if the default layout
   *         should be used.
   */
  public RenderpassLayout<T> getLayout() {
    return layout;
  }

  /** Immediately computes the current layout. */
  public void forceLayout() {
    invalidate();
    doLayout(members);
    redoLayout = false;
    animator.forceNextFrame();
  }

  /** Ensures that the layout is computed. */
  private void ensureLayout() {
    if(!redoLayout) return;
    forceLayout();
  }

  /**
   * Enables to draw between two adjacent render passes.
   *
   * @param gfx The graphics context. This context must be copied implementation
   *          side and must therefore not be altered without creating a
   *          copy.
   * @param ctx The canvas context.
   * @param left The left (first) render pass or null.
   * @param right The right (second) render pass or null.
   */
  protected void drawBetween(@SuppressWarnings("unused") final Graphics2D gfx,
      @SuppressWarnings("unused") final KanvasContext ctx,
      @SuppressWarnings("unused") final T left, @SuppressWarnings("unused") final T right) {
    // nothing to do here
  }

  @Override
  public void draw(final Graphics2D gfx, final KanvasContext ctx) {
    ensureLayout();
    if(layout != null) {
      final Graphics2D g = (Graphics2D) gfx.create();
      final Rectangle2D bbox = new Rectangle2D.Double();
      getBoundingBox(bbox);
      layout.drawBackground(g, ctx, bbox, members);
      g.dispose();
    }
    gfx.setColor(java.awt.Color.GREEN);
    RenderpassPainter.draw(nlBack, gfx, ctx);
    final Rectangle2D view = ctx.getVisibleCanvas();
    boolean changed = false;
    T last = null;
    for(final RenderpassPosition<T> p : members) {
      final T r = p.pass;
      if(!r.isVisible()) {
        continue;
      }
      if(p.checkBBoxChange()) {
        changed = true;
      }
      final Rectangle2D bbox = p.getPassBBox();
      if(!view.intersects(bbox)) {
        continue;
      }
      final Graphics2D g = (Graphics2D) gfx.create();
      g.clip(bbox);
      final double dx = r.getOffsetX();
      final double dy = r.getOffsetY();
      g.translate(dx, dy);
      final KanvasContext c = RenderpassPainter.getContextFor(r, ctx);
      r.draw(g, c);
      g.dispose();
      drawBetween(gfx, ctx, last, r);
      last = r;
    }
    drawBetween(gfx, ctx, last, null);
    if(jkanvas.Canvas.DEBUG_BBOX) {
      final Graphics2D g = (Graphics2D) gfx.create();
      PaintUtil.setAlpha(g, 0.3);
      g.setColor(java.awt.Color.BLUE);
      for(final RenderpassPosition<T> rp : members) {
        final Renderpass r = rp.pass;
        if(!r.isVisible()) {
          continue;
        }
        if(rp.checkBBoxChange()) {
          changed = true;
        }
        final Rectangle2D bbox = rp.getPassBBox();
        if(!view.intersects(bbox)) {
          continue;
        }
        g.fill(bbox);
      }
    }
    gfx.setColor(java.awt.Color.GREEN);
    RenderpassPainter.draw(nlFront, gfx, ctx);
    if(changed) {
      invalidate();
    }
  }

  /**
   * Copies the member list for iterations that allow modifications to the list.
   *
   * @return The member list as array.
   */
  private RenderpassPosition<T>[] members() {
    return members.toArray(new RenderpassPosition[members.size()]);
  }

  @Override
  public boolean click(final Camera cam, final Point2D position, final MouseEvent e) {
    if(RenderpassPainter.click(nlFront, cam, position, e)) return true;
    final Rectangle2D bbox = new Rectangle2D.Double();
    for(final RenderpassPosition<T> p : reverseArray(members())) {
      final Renderpass r = p.pass;
      if(!r.isVisible()) {
        continue;
      }
      r.getBoundingBox(bbox);
      final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position);
      if(!bbox.contains(pos)) {
        continue;
      }
      if(r.click(cam, pos, e)) return true;
    }
    return RenderpassPainter.click(nlBack, cam, position, e);
  }

  @Override
  public boolean doubleClick(final Camera cam, final Point2D position, final MouseEvent e) {
    if(RenderpassPainter.doubleClick(nlFront, cam, position, e)) return true;
    final Rectangle2D bbox = new Rectangle2D.Double();
    for(final RenderpassPosition<T> p : reverseArray(members())) {
      final Renderpass r = p.pass;
      if(!r.isVisible()) {
        continue;
      }
      r.getBoundingBox(bbox);
      final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position);
      if(!bbox.contains(pos)) {
        continue;
      }
      if(r.doubleClick(cam, pos, e)) return true;
    }
    if(RenderpassPainter.doubleClick(nlBack, cam, position, e)) return true;
    if(USE_DOUBLE_CLICK_DEFAULT) return defaultDoubleClick(this, cam, e);
    return false;
  }

  @Override
  public String getTooltip(final Point2D position) {
    final String tt = RenderpassPainter.getTooltip(nlFront, position);
    if(tt != null) return tt;
    final Rectangle2D bbox = new Rectangle2D.Double();
    for(final RenderpassPosition<T> p : reverseArray(members())) {
      final Renderpass r = p.pass;
      if(!r.isVisible()) {
        continue;
      }
      r.getBoundingBox(bbox);
      final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position);
      if(!bbox.contains(pos)) {
        continue;
      }
      final String tooltip = r.getTooltip(pos);
      if(tooltip != null) return tooltip;
    }
    return RenderpassPainter.getTooltip(nlBack, position);
  }

  @Override
  public boolean moveMouse(final Point2D cur) {
    boolean moved = RenderpassPainter.moveMouse(nlFront, cur);
    for(final RenderpassPosition<T> p : reverseArray(members())) {
      final Renderpass r = p.pass;
      if(!r.isVisible()) {
        continue;
      }
      final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, cur);
      if(r.moveMouse(pos)) {
        moved = true;
      }
    }
    return RenderpassPainter.moveMouse(nlBack, cur) || moved;
  }

  /**
   * Picks a layouted render pass.
   *
   * @param position The position.
   * @return The render pass at the given position or null if there
   *         is none.
   */
  protected Renderpass pickLayouted(final Point2D position) {
    final Rectangle2D bbox = new Rectangle2D.Double();
    for(final RenderpassPosition<T> p : reverseArray(members())) {
      final Renderpass r = p.pass;
      if(!r.isVisible()) {
        continue;
      }
      r.getBoundingBox(bbox);
      final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position);
      if(!bbox.contains(pos)) {
        continue;
      }
      return r;
    }
    return null;
  }

  /** The render pass currently responsible for dragging. */
  private Renderpass dragging = null;

  /** The start position of the drag in the render pass coordinates. */
  private Point2D start = null;

  /**
   * Checks whether the given render pass accepts the drag. When the render pass
   * accepts the drag everything is set up properly.
   *
   * @param r The render pass to check.
   * @param position The position in canvas coordinates.
   * @param e The mouse event.
   * @return Whether the drag was accepted.
   * @see #acceptDrag(Point2D, MouseEvent)
   */
  private boolean acceptDrag(
      final Renderpass r, final Point2D position, final MouseEvent e) {
    if(!r.isVisible()) return false;
    final Rectangle2D bbox = new Rectangle2D.Double();
    r.getBoundingBox(bbox);
    final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position);
    if(!bbox.contains(pos)) return false;
    if(!r.acceptDrag(pos, e)) return false;
    start = pos;
    dragging = r;
    return true;
  }

  @Override
  public final boolean acceptDrag(final Point2D position, final MouseEvent e) {
    for(final Renderpass r : reverseList(nlFront)) {
      if(acceptDrag(r, position, e)) return true;
    }
    for(final RenderpassPosition<T> p : reverseArray(members())) {
      if(acceptDrag(p.pass, position, e)) return true;
    }
    for(final Renderpass r : reverseList(nlBack)) {
      if(acceptDrag(r, position, e)) return true;
    }
    return false;
  }

  @Override
  public final void drag(final Point2D _start, final Point2D cur,
      final double dx, final double dy) {
    if(dragging == null) return;
    // dx and dy do not change
    final Point2D pos = RenderpassPainter.getPositionFromCanvas(dragging, cur);
    dragging.drag(start, pos, dx, dy);
  }

  @Override
  public final void endDrag(final Point2D _start, final Point2D end,
      final double dx, final double dy) {
    if(dragging == null) return;
    // dx and dy do not change
    final Point2D pos = RenderpassPainter.getPositionFromCanvas(dragging, end);
    dragging.endDrag(start, pos, dx, dy);
    dragging = null;
  }

  @Override
  public void getBoundingBox(final RectangularShape bbox) {
    ensureLayout();
    boolean change = false;
    RenderpassPainter.getBoundingBox(bbox, nlFront);
    final Rectangle2D rect = new Rectangle2D.Double();
    RenderpassPainter.getBoundingBox(rect, nlBack);
    RenderpassPainter.addToRect(bbox, rect);
    if(layout != null) {
      change = layout.addBoundingBox(bbox, members);
    } else {
      for(final RenderpassPosition<T> p : members) {
        if(!p.pass.isVisible()) {
          continue;
        }
        if(p.checkBBoxChange()) {
          change = true;
        }
        RenderpassPainter.addToRect(bbox, p.getPassBBox());
      }
    }
    if(change) {
      invalidate();
    }
  }

  @Override
  public boolean isChanging() {
    for(final Renderpass r : nlBack) {
      if(r.isChanging()) return true;
    }
    for(final Renderpass r : nlFront) {
      if(r.isChanging()) return true;
    }
    for(final RenderpassPosition<T> rp : members) {
      if(rp.inAnimation()) return true;
    }
    return false;
  }

  @Override
  public void processMessage(final String[] ids, final String msg) {
    super.processMessage(ids, msg);
    RenderpassPainter.processMessage(nlBack, ids, msg);
    RenderpassPainter.processMessage(nlFront, ids, msg);
    for(final RenderpassPosition<T> p : members) {
      p.pass.processMessage(ids, msg);
    }
  }

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Tevent {
    constructor(type, eventData = null, cancelable = true) {
        this.type = null;
        this.data = null;
        this.cancelable = false;
        this.currentTarget = null;
        this.cancelled = false;
        this.defaultPrevented = false;
        this.bind = null;
        this.relatedData = null;
        if (arguments.length > 0)
            this.type = type;
        if (arguments.length > 1)
            this.data = eventData;
        if (arguments.length > 2)
            this.cancelable = cancelable;
    }
    preventDefault() {
        this.defaultPrevented = true;
    }
}
exports.Tevent = Tevent;
//# sourceMappingURL=Tevent.js.map


text:
PLATFORM="$(uname -s | tr [:upper:] [:lower:])"

function is_darwin() {
  [[ "${PLATFORM}" =~ darwin ]]
}

function _log_base() {
  prefix=$1
  shift
  echo >&2 "${prefix}[$(basename "$0") $(date "+%Y-%m-%d %H:%M:%S (%z)")] $*"
}

function log_info() {
  _log_base "INFO" "$@"
}

function log_fatal() {
  _log_base "ERROR" "$@"
  exit 1
}

if ! type rlocation &> /dev/null; then
  log_fatal "rlocation() is undefined"
fi

# Set some environment variables needed on Windows.
if [[ $PLATFORM =~ msys ]]; then
  # TODO(philwo) remove this once we have a Bazel release that includes the CL
  # moving the Windows-specific TEST_TMPDIR into TestStrategy.
  TEST_TMPDIR_BASENAME="$(basename "$TEST_TMPDIR")"

  export JAVA_HOME="${JAVA_HOME:-$(ls -d C:/Program\ Files/Java/jdk* | sort | tail -n 1)}"
  export BAZEL_SH="$(cygpath -m /usr/bin/bash)"
fi

# Make the command "bazel" available for tests.
if [ -z "${BAZEL_SUFFIX:-}" ]; then
  PATH_TO_BAZEL_BIN=$(rlocation "io_bazel/src/bazel")
  PATH_TO_BAZEL_WRAPPER="$(dirname $(rlocation "io_bazel/src/test/shell/bin/bazel"))"
else
  DIR_OF_BAZEL_BIN="$(dirname $(rlocation "io_bazel/src/bazel${BAZEL_SUFFIX}"))"
  ln -s "${DIR_OF_BAZEL_BIN}/bazel${BAZEL_SUFFIX}" "${DIR_OF_BAZEL_BIN}/bazel"
  PATH_TO_BAZEL_WRAPPER="$(dirname $(rlocation "io_bazel/src/test/shell/bin/bazel${BAZEL_SUFFIX}"))"
  ln -s "${PATH_TO_BAZEL_WRAPPER}/bazel${BAZEL_SUFFIX}" "${PATH_TO_BAZEL_WRAPPER}/bazel"
  PATH_TO_BAZEL_BIN="${DIR_OF_BAZEL_BIN}/bazel"
fi
# Convert PATH_TO_BAZEL_WRAPPER to Unix path style on Windows, because it will be
# added into PATH. There's problem if PATH=C:/msys64/usr/bin:/usr/local,
# because ':' is used as both path separator and in C:/msys64/...
case "$(uname -s | tr [:upper:] [:lower:])" in
msys*|mingw*|cygwin*)
  PATH_TO_BAZEL_WRAPPER="$(cygpath -u "$PATH_TO_BAZEL_WRAPPER")"
esac
[ ! -f "${PATH_TO_BAZEL_WRAPPER}/bazel" ] \
  && log_fatal "Unable to find the Bazel binary at $PATH_TO_BAZEL_WRAPPER/bazel"
export PATH="$PATH_TO_BAZEL_WRAPPER:$PATH"

################### shell/bazel/testenv ##################################
# Setting up the environment for Bazel integration tests.
#
[ -z "$TEST_SRCDIR" ] && log_fatal "TEST_SRCDIR not set!"
BAZEL_RUNFILES="$TEST_SRCDIR/io_bazel"

# WORKSPACE file
workspace_file="${BAZEL_RUNFILES}/WORKSPACE"
distdir_bzl_file="${BAZEL_RUNFILES}/distdir.bzl"

# Java
if [[ $PLATFORM =~ msys ]]; then
  jdk_dir="$(cygpath -m $(cd $(rlocation local_jdk/bin/java.exe)/../..; pwd))"
else
  jdk_dir="${TEST_SRCDIR}/local_jdk"
fi
langtools="$(rlocation io_bazel/src/test/shell/bazel/langtools.jar)"

# Tools directory location
tools_dir="$(dirname $(rlocation io_bazel/tools/BUILD))"
langtools_dir="$(dirname $(rlocation io_bazel/third_party/java/jdk/langtools/BUILD))"

# Platforms
default_host_platform="@local_config_platform//:host"

# Sandbox tools
process_wrapper="${BAZEL_RUNFILES}/src/main/tools/process-wrapper"
linux_sandbox="${BAZEL_RUNFILES}/src/main/tools/linux-sandbox"

# Test data
testdata_path=${BAZEL_RUNFILES}/src/test/shell/bazel/testdata
python_server="$(rlocation io_bazel/src/test/shell/bazel/testing_server.py)"

# Third-party
protoc_compiler="${BAZEL_RUNFILES}/src/test/shell/integration/protoc"

# Skylib
skylib_package="@bazel_skylib//"

if [ -z ${RUNFILES_MANIFEST_ONLY+x} ]; then
  junit_jar="${BAZEL_RUNFILES}/third_party/junit/junit-*.jar"
  hamcrest_jar="${BAZEL_RUNFILES}/third_party/hamcrest/hamcrest-*.jar"
else
  junit_jar=$(rlocation io_bazel/third_party/junit/junit-.*.jar)
  hamcrest_jar=$(rlocation io_bazel/third_party/hamcrest/hamcrest-.*.jar)
fi

# This function copies the tools directory from Bazel.
function copy_tools_directory() {
  cp -RL ${tools_dir}/* tools
  if [ -f tools/jdk/BUILD ]; then
    chmod +w tools/jdk/BUILD
  fi
  if [ -f tools/build_defs/repo/BUILD.repo ]; then
      cp tools/build_defs/repo/BUILD.repo tools/build_defs/repo/BUILD
  fi
  # To support custom langtools
  cp ${langtools} tools/jdk/langtools.jar
  cat >>tools/jdk/BUILD <<'EOF'
filegroup(name = "test-langtools", srcs = ["langtools.jar"])
EOF

  mkdir -p third_party/java/jdk/langtools
  cp -R ${langtools_dir}/* third_party/java/jdk/langtools

  chmod -R +w .
}

# Report whether a given directory name corresponds to a tools directory.
function is_tools_directory() {
  case "$1" in
    third_party|tools|src)
      true
      ;;
    *)
      false
      ;;
  esac
}

# Copy the examples of the base workspace
function copy_examples() {
  EXAMPLE="$(cd $(dirname $(rlocation io_bazel/examples/cpp/BUILD))/..; pwd)"
  cp -RL ${EXAMPLE} .
  chmod -R +w .
}

#
# Find a random unused TCP port
#
pick_random_unused_tcp_port () {
    perl -MSocket -e '
sub CheckPort {
  my ($port) = @_;
  socket(TCP_SOCK, PF_INET, SOCK_STREAM, getprotobyname("tcp"))
    || die "socket(TCP): $!";
  setsockopt(TCP_SOCK, SOL_SOCKET, SO_REUSEADDR, 1)
    || die "setsockopt(TCP): $!";
  return 0 unless bind(TCP_SOCK, sockaddr_in($port, INADDR_ANY));
  socket(UDP_SOCK, PF_INET, SOCK_DGRAM, getprotobyname("udp"))
    || die "socket(UDP): $!";
  return 0 unless bind(UDP_SOCK, sockaddr_in($port, INADDR_ANY));
  return 1;
}
for (1 .. 128) {
  my ($port) = int(rand() * 27000 + 32760);
  if (CheckPort($port)) {
    print "$port\n";
    exit 0;
  }
}
print "NO_FREE_PORT_FOUND\n";
exit 1;
'
}

#
# A uniform SHA-256 command that works across platforms.
#
# sha256sum is the fastest option, but may not be available on macOS (where it
# is usually called 'gsha256sum'), so we optionally fallback to shasum.
#
if hash sha256sum 2>/dev/null; then
  :
elif hash gsha256sum 2>/dev/null; then
  function sha256sum() {
    gsha256sum "$@"
  }
elif hash shasum 2>/dev/null; then
  function sha256sum() {
    shasum -a 256 "$@"
  }
else
  echo "testenv.sh: Could not find either sha256sum or gsha256sum or shasum in your PATH."
  exit 1
fi

################### shell/bazel/test-setup ###############################
# Setup bazel for integration tests
#

# OS X has a limit in the pipe length, so force the root to a shorter one
bazel_root="${TEST_TMPDIR}/root"

# Delete stale installation directory from previously failed tests. On Windows
# we regularly get the same TEST_TMPDIR but a failed test may only partially
# clean it up, and the next time the test runs, Bazel reports a corrupt
# installation error. See https://github.com/bazelbuild/bazel/issues/3618
rm -rf "${bazel_root}"
mkdir -p "${bazel_root}"

bazel_javabase="${jdk_dir}"

log_info "bazel binary is at $PATH_TO_BAZEL_WRAPPER"

# Here we unset variable that were set by the invoking Blaze instance
unset JAVA_RUNFILES

# Runs a command, retrying if needed for a fixed timeout.
#
# Necessary to use it on Windows, typically when deleting directory trees,
# because the OS cannot delete open files, which we attempt to do when deleting
# workspaces where a Bazel server is still in the middle of shutting down.
# (Because "bazel shutdown" returns sooner than the server actually shuts down.)
function try_with_timeout() {
  for i in {1..120}; do
    if $* ; then
      break
    fi
    if (( i == 10 )) || (( i == 30 )) || (( i == 60 )) ; then
      log_info "try_with_timeout($*): no success after $i seconds" \
               "(timeout in $((120-i)) seconds)"
    fi
    sleep 1
  done
}

function setup_bazelrc() {
  cat >$TEST_TMPDIR/bazelrc <<EOF
# Set the user root properly for this test invocation.
startup --output_user_root=${bazel_root}

# Print all progress messages because we regularly grep the output in tests.
common --show_progress_rate_limit=-1

# Disable terminal-specific features.
common --color=no --curses=no

# Prevent SIGBUS during JVM actions.
build --sandbox_tmpfs_path=/tmp

build --incompatible_skip_genfiles_symlink=false

build --incompatible_use_toolchain_resolution_for_java_rules

${EXTRA_BAZELRC:-}
EOF

  if [[ -n ${TEST_REPOSITORY_HOME:-} ]]; then
    echo "testenv.sh: Using shared repositories from $TEST_REPOSITORY_HOME."

    repos=(
        "android_tools_for_testing"
        "bazel_skylib"
        "bazel_toolchains"
        "com_google_protobuf"
        "openjdk11_darwin_archive"
        "openjdk11_linux_archive"
        "openjdk11_windows_archive"
        "openjdk14_darwin_archive"
        "openjdk14_linux_archive"
        "openjdk14_windows_archive"
        "openjdk15_darwin_archive"
        "openjdk15_linux_archive"
        "openjdk15_windows_archive"
        "openjdk_linux_aarch64_minimal"
        "openjdk_linux_minimal"
        "openjdk_macos_x86_64_minimal"
        "openjdk_win_minimal"
        "remote_coverage_tools_for_testing"
        "remote_java_tools_for_testing"
        "remote_java_tools_darwin_for_testing"
        "remote_java_tools_test"
        "remote_java_tools_test_darwin"
        "remote_java_tools_test_linux"
        "remote_java_tools_test_windows"
        "remote_java_tools_linux_for_testing"
        "remote_java_tools_windows_for_testing"
        "remotejdk11_linux_for_testing"
        "remotejdk11_linux_aarch64_for_testing"
        "remotejdk11_linux_ppc64le_for_testing"
        "remotejdk11_linux_s390x_for_testing"
        "remotejdk11_macos_for_testing"
        "remotejdk11_win_for_testing"
        "remotejdk14_linux_for_testing"
        "remotejdk14_macos_for_testing"
        "remotejdk14_win_for_testing"
        "remotejdk15_linux_for_testing"
        "remotejdk15_macos_for_testing"
        "remotejdk15_win_for_testing"
        "rules_cc"
        "rules_java"
        "rules_pkg"
        "rules_proto"
        "rules_python"
    )
    for repo in "${repos[@]}"; do
      reponame="${repo%"_for_testing"}"
      echo "common --override_repository=$reponame=$TEST_REPOSITORY_HOME/$repo" >> $TEST_TMPDIR/bazelrc
    done
  fi

  if [[ -n ${REPOSITORY_CACHE:-} ]]; then
    echo "testenv.sh: Using repository cache at $REPOSITORY_CACHE."
    cat >>$TEST_TMPDIR/bazelrc <<EOF
common --repository_cache=$REPOSITORY_CACHE --experimental_repository_cache_hardlinks
EOF
  fi

  if [[ -n ${TEST_INSTALL_BASE:-} ]]; then
    echo "testenv.sh: Using shared install base at $TEST_INSTALL_BASE."
    echo "startup --install_base=$TEST_INSTALL_BASE" >> $TEST_TMPDIR/bazelrc
  fi
}

function setup_android_sdk_support() {
  # Required for runfiles library on Windows, since $(rlocation) lookups
  # can't do directories. We use android-28's android.jar as the anchor
  # for the androidsdk location.
  local android_jar=$(rlocation androidsdk/platforms/android-28/android.jar)
  local android=$(dirname $android_jar)
  local platforms=$(dirname $android)
  ANDROID_SDK=$(dirname $platforms)

cat >> WORKSPACE <<EOF
android_sdk_repository(
    name = "androidsdk",
    path = "$ANDROID_SDK",
)
register_toolchains("//tools/android:all")
EOF
}

function setup_android_ndk_support() {
  ANDROID_NDK=$PWD/android_ndk
  NDK_SRCDIR=$TEST_SRCDIR/androidndk/ndk
  mkdir -p $ANDROID_NDK
  for i in $NDK_SRCDIR/*; do
    if [[ "$(basename $i)" != "BUILD" ]]; then
      ln -s "$i" "$ANDROID_NDK/$(basename $i)"
    fi
  done
  cat >> WORKSPACE <<EOF
android_ndk_repository(
    name = "androidndk",
    path = "$ANDROID_NDK",
)
EOF
}

function setup_javatest_common() {
  # TODO(bazel-team): we should use remote repositories.
  mkdir -p third_party
  if [ ! -f third_party/BUILD ]; then
    cat <<EOF >third_party/BUILD
package(default_visibility = ["//visibility:public"])
EOF
  fi

  [ -e third_party/junit.jar ] || ln -s ${junit_jar} third_party/junit.jar
  [ -e third_party/hamcrest.jar ] \
    || ln -s ${hamcrest_jar} third_party/hamcrest.jar
}

function setup_javatest_support() {
  setup_javatest_common
  grep -q 'name = "junit4"' third_party/BUILD \
    || cat <<EOF >>third_party/BUILD
java_import(
    name = "junit4",
    jars = [
        "junit.jar",
        "hamcrest.jar",
    ],
)
EOF
}

# If the current platform is Windows, defines a Python toolchain for our
# Windows CI machines. Otherwise does nothing.
#
# Our Windows CI machines have Python 2 and 3 installed at C:\Python2 and
# C:\Python3 respectively.
#
# Since the tools directory is not cleared between test cases, this only needs
# to run once per suite. However, the toolchain must still be registered
# somehow.
#
# TODO(#7844): Delete this custom (and machine-specific) test setup once we have
# an autodetecting Python toolchain for Windows.
function maybe_setup_python_windows_tools() {
  if [[ ! $PLATFORM =~ msys ]]; then
    return
  fi

  mkdir -p tools/python/windows
  cat > tools/python/windows/BUILD << EOF
load("@bazel_tools//tools/python:toolchain.bzl", "py_runtime_pair")

py_runtime(
  name = "py2_runtime",
  interpreter_path = r"C:\Python2\python.exe",
  python_version = "PY2",
)

py_runtime(
  name = "py3_runtime",
  interpreter_path = r"C:\Python3\python.exe",
  python_version = "PY3",
)

py_runtime_pair(
  name = "py_runtime_pair",
  py2_runtime = ":py2_runtime",
  py3_runtime = ":py3_runtime",
)

toolchain(
  name = "py_toolchain",
  toolchain = ":py_runtime_pair",
  toolchain_type = "@bazel_tools//tools/python:toolchain_type",
  target_compatible_with = ["@platforms//os:windows"],
)
EOF
}

function setup_starlark_javatest_support() {
  setup_javatest_common
  grep -q "name = \"junit4-jars\"" third_party/BUILD \
    || cat <<EOF >>third_party/BUILD
filegroup(
    name = "junit4-jars",
    srcs = [
        "junit.jar",
        "hamcrest.jar",
    ],
)
EOF
}

# Sets up Objective-C tools. Mac only.
function setup_objc_test_support() {
  IOS_SDK_VERSION=$(xcrun --sdk iphoneos --show-sdk-version)
}

function setup_skylib_support() {
  # Get skylib path portably by using rlocation to locate a top-level file in
  # the repo. Use BUILD because it's in the //:test_deps target (unlike
  # WORKSPACE).
  local -r skylib_workspace="$(rlocation bazel_skylib/BUILD)"
  [[ -n "$skylib_workspace" && -e "$skylib_workspace" ]] || fail "could not find Skylib"
  local -r skylib_root="$(dirname "$skylib_workspace")"
  cat >> WORKSPACE << EOF
new_local_repository(
    name = 'bazel_skylib',
    build_file_content = '',
    path='$skylib_root',
)

load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
bazel_skylib_workspace()
EOF
}

function add_rules_cc_to_workspace() {
  cat >> "$1"<<EOF
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "rules_cc",
    sha256 = "1d4dbbd1e1e9b57d40bb0ade51c9e882da7658d5bfbf22bbd15b68e7879d761f",
    strip_prefix = "rules_cc-8bd6cd75d03c01bb82561a96d9c1f9f7157b13d0",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_cc/archive/8bd6cd75d03c01bb82561a96d9c1f9f7157b13d0.zip",
        "https://github.com/bazelbuild/rules_cc/archive/8bd6cd75d03c01bb82561a96d9c1f9f7157b13d0.zip",
    ],
)
EOF
}

function add_rules_java_to_workspace() {
  cat >> "$1"<<EOF
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "rules_java",
    sha256 = "bc81f1ba47ef5cc68ad32225c3d0e70b8c6f6077663835438da8d5733f917598",
    strip_prefix = "rules_java-7cf3cefd652008d0a64a419c34c13bdca6c8f178",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_java/archive/7cf3cefd652008d0a64a419c34c13bdca6c8f178.zip",
        "https://github.com/bazelbuild/rules_java/archive/7cf3cefd652008d0a64a419c34c13bdca6c8f178.zip",
    ],
)
EOF
}

# TODO(https://github.com/bazelbuild/bazel/issues/8986): Build this dynamically
# from //WORKSPACE
function add_rules_pkg_to_workspace() {
  cat >> "$1"<<EOF
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "rules_pkg",
    sha256 = "5bdc04987af79bd27bc5b00fe30f59a858f77ffa0bd2d8143d5b31ad8b1bd71c",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_pkg/rules_pkg-0.2.0.tar.gz",
        "https://github.com/bazelbuild/rules_pkg/releases/download/0.2.0/rules_pkg-0.2.0.tar.gz",
    ],
)
EOF
}

function add_rules_proto_to_workspace() {
  cat >> "$1"<<EOF
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "rules_proto",
    sha256 = "8e7d59a5b12b233be5652e3d29f42fba01c7cbab09f6b3a8d0a57ed6d1e9a0da",
    strip_prefix = "rules_proto-7e4afce6fe62dbff0a4a03450143146f9f2d7488",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_proto/archive/7e4afce6fe62dbff0a4a03450143146f9f2d7488.tar.gz",
        "https://github.com/bazelbuild/rules_proto/archive/7e4afce6fe62dbff0a4a03450143146f9f2d7488.tar.gz",
    ],
)
EOF
}

function create_workspace_with_default_repos() {
  write_workspace_file "${1:-WORKSPACE}" "${2:-main}"
  echo "$1"
}

# Write the default WORKSPACE file, wiping out any custom WORKSPACE setup.
function write_workspace_file() {
  cat > "$1" << EOF
workspace(name = "$2")
EOF
  add_rules_cc_to_workspace "WORKSPACE"
  add_rules_java_to_workspace "WORKSPACE"
  add_rules_pkg_to_workspace "WORKSPACE"
  add_rules_proto_to_workspace "WORKSPACE"

  maybe_setup_python_windows_workspace
}

# If the current platform is Windows, registers our custom Windows Python
# toolchain. Otherwise does nothing.
#
# Since this modifies the WORKSPACE file, it must be called between test cases.
function maybe_setup_python_windows_workspace() {
  if [[ ! $PLATFORM =~ msys ]]; then
    return
  fi

  # --extra_toolchains has left-to-right precedence semantics, but the bazelrc
  # is processed before the command line. This means that any matching
  # toolchains added to the bazelrc will always take precedence over toolchains
  # set up by test cases. Instead, we add the toolchain to WORKSPACE so that it
  # has lower priority than whatever is passed on the command line.
  cat >> WORKSPACE << EOF
register_toolchains("//tools/python/windows:py_toolchain")
EOF
}

workspaces=()
# Set-up a new, clean workspace with only the tools installed.
function create_new_workspace() {
  new_workspace_dir=${1:-$(mktemp -d ${TEST_TMPDIR}/workspace.XXXXXXXX)}
  try_with_timeout rm -fr ${new_workspace_dir} > /dev/null 2>&1
  mkdir -p ${new_workspace_dir}
  workspaces+=(${new_workspace_dir})
  cd ${new_workspace_dir}
  mkdir tools
  mkdir -p third_party/java/jdk/langtools

  copy_tools_directory

  [ -e third_party/java/jdk/langtools/javac-9+181-r4173-1.jar ] \
    || ln -s "${langtools_path}"  third_party/java/jdk/langtools/javac-9+181-r4173-1.jar

  write_workspace_file "WORKSPACE" "$WORKSPACE_NAME"

  maybe_setup_python_windows_tools
}

# Set-up a clean default workspace.
function setup_clean_workspace() {
  export WORKSPACE_DIR=${TEST_TMPDIR}/workspace
  log_info "setting up client in ${WORKSPACE_DIR}" >> $TEST_log
  try_with_timeout rm -fr ${WORKSPACE_DIR}
  create_new_workspace ${WORKSPACE_DIR}
  [ "${new_workspace_dir}" = "${WORKSPACE_DIR}" ] \
    || log_fatal "Failed to create workspace"

  if [[ $PLATFORM =~ msys ]]; then
    export BAZEL_SH="$(cygpath --windows /bin/bash)"
  fi
}

# Clean up all files that are not in tools directories, to restart
# from a clean workspace
function cleanup_workspace() {
  if [ -d "${WORKSPACE_DIR:-}" ]; then
    log_info "Cleaning up workspace" >> $TEST_log
    cd ${WORKSPACE_DIR}

    if [[ ${TESTENV_DONT_BAZEL_CLEAN:-0} == 0 ]]; then
      bazel clean >> "$TEST_log" 2>&1
    fi

    for i in *; do
      if ! is_tools_directory "$i"; then
        try_with_timeout rm -fr "$i"
      fi
    done
    write_workspace_file "WORKSPACE" "$WORKSPACE_NAME"
  fi
  for i in "${workspaces[@]}"; do
    if [ "$i" != "${WORKSPACE_DIR:-}" ]; then
      try_with_timeout rm -fr $i
    fi
  done
  workspaces=()
}

function testenv_tear_down() {
  cleanup_workspace
}

# This is called by unittest.bash upon eventual exit of the test suite.
function cleanup() {
  if [ -d "${WORKSPACE_DIR:-}" ]; then
    # Try to shutdown Bazel at the end to prevent a "Cannot delete path" error
    # on Windows when the outer Bazel tries to delete $TEST_TMPDIR.
    cd "${WORKSPACE_DIR}"
    try_with_timeout bazel shutdown || true
  fi
}

#
# Simples assert to make the tests more readable
#
function assert_build() {
  bazel build -s --verbose_failures $* || fail "Failed to build $*"
}

function assert_build_output() {
  local OUTPUT=$1
  shift
  assert_build "$*"
  test -f "$OUTPUT" || fail "Output $OUTPUT not found for target $*"
}

function assert_build_fails() {
  bazel build -s $1 >> $TEST_log 2>&1 \
    && fail "Test $1 succeed while expecting failure" \
    || true
  if [ -n "${2:-}" ]; then
    expect_log "$2"
  fi
}

function assert_test_ok() {
  bazel test --test_output=errors $* >> $TEST_log 2>&1 \
    || fail "Test $1 failed while expecting success"
}

function assert_test_fails() {
  bazel test --test_output=errors $* >> $TEST_log 2>&1 \
    && fail "Test $* succeed while expecting failure" \
    || true
  expect_log "$1.*FAILED"
}

function assert_binary_run() {
  $1 >> $TEST_log 2>&1 || fail "Failed to run $1"
  [ -z "${2:-}" ] || expect_log "$2"
}

function assert_bazel_run() {
  bazel run $1 >> $TEST_log 2>&1 || fail "Failed to run $1"
    [ -z "${2:-}" ] || expect_log "$2"

  assert_binary_run "./bazel-bin/$(echo "$1" | sed 's|^//||' | sed 's|:|/|')" "${2:-}"
}

setup_bazelrc

################### shell/integration/testenv ############################
# Setting up the environment for our legacy integration tests.
#
PRODUCT_NAME=bazel
TOOLS_REPOSITORY="@bazel_tools"
BUILTINS_PACKAGE_PATH_IN_SOURCE="src/main/starlark/builtins_bzl"
WORKSPACE_NAME=main
bazelrc=$TEST_TMPDIR/bazelrc

function put_bazel_on_path() {
  # do nothing as test-setup already does that
  true
}

function write_default_bazelrc() {
  setup_bazelrc
}

function add_to_bazelrc() {
  echo "$@" >> $bazelrc
}

function create_and_cd_client() {
  setup_clean_workspace
  touch .bazelrc
}

################### Extra ############################

# Functions that need to be called before each test.

create_and_cd_client

# Optional environment changes.

# Creates a fake Python default runtime that just outputs a marker string
# indicating which version was used, without executing any Python code.
function use_fake_python_runtimes_for_testsuite() {
  # The stub script template automatically appends ".exe" to the Python binary
  # name if it doesn't already end in ".exe", ".com", or ".bat".
  if [[ $PLATFORM =~ msys ]]; then
    PYTHON2_FILENAME="python2.bat"
    PYTHON3_FILENAME="python3.bat"
  else
    PYTHON2_FILENAME="python2.sh"
    PYTHON3_FILENAME="python3.sh"
  fi

  add_to_bazelrc "build --extra_toolchains=//tools/python:fake_python_toolchain"

  mkdir -p tools/python

  cat > tools/python/BUILD << EOF
load("@bazel_tools//tools/python:toolchain.bzl", "py_runtime_pair")

package(default_visibility=["//visibility:public"])

sh_binary(
    name = '2to3',
    srcs = ['2to3.sh']
)

py_runtime(
    name = "fake_py2_interpreter",
    interpreter = ":${PYTHON2_FILENAME}",
    python_version = "PY2",
)

py_runtime(
    name = "fake_py3_interpreter",
    interpreter = ":${PYTHON3_FILENAME}",
    python_version = "PY3",
)

py_runtime_pair(
    name = "fake_py_runtime_pair",
    py2_runtime = ":fake_py2_interpreter",
    py3_runtime = ":fake_py3_interpreter",
)

toolchain(
    name = "fake_python_toolchain",
    toolchain = ":fake_py_runtime_pair",
    toolchain_type = "@bazel_tools//tools/python:toolchain_type",
)
EOF

  # Windows .bat has uppercase ECHO and no shebang.
  if [[ $PLATFORM =~ msys ]]; then
    cat > tools/python/$PYTHON2_FILENAME << EOF
@ECHO I am Python 2
EOF
    cat > tools/python/$PYTHON3_FILENAME << EOF
@ECHO I am Python 3
EOF
  else
    cat > tools/python/$PYTHON2_FILENAME << EOF
#!/bin/sh
echo 'I am Python 2'
EOF
    cat > tools/python/$PYTHON3_FILENAME << EOF
#!/bin/sh
echo 'I am Python 3'
EOF
    chmod +x tools/python/$PYTHON2_FILENAME tools/python/$PYTHON3_FILENAME
  fi
}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns #-}
{-#  LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}

module Data.Vector.Persistent.Generic.Internal.Types where

import Data.IORef
import System.IO.Unsafe
import  Unsafe.Coerce

import GHC.Prim (RealWorld)

import qualified  Data.Vector.Generic.Mutable as GM
import qualified  Data.Vector.Generic as G

import qualified  Control.Monad.Primitive as Prim

newtype PerVect (v:: * -> *)  (a :: * ) (tok :: Threadiness) where
    PerVect :: IORef (PVect v a tok ) -> PerVect v a tok

{-NOTE:  Resulttype  will be one of  (), IORef Bool, or Mvar (),

Single -> () --- DONT USE IN THREADS
AutoRetry -> Mvar ()  --- use the GHC schedule
ManualRetry -> IORef Bool  --- you decide when retry

-}

-- | we hide the IOy bits in PVect, mwwahahahaha
--  need to make sure that tok is the SAME everywhere
data PVect  (v::  * -> *)   (a :: * ) (tok :: Threadiness )  where
    TheArray :: (TokType tok) -> !((G.Mutable v) RealWorld  a) -> PVect  v  a tok
    ArrDiff :: (TokType tok ) -> !Int -> !a -> !(PerVect v a tok ) -> PVect v a tok

data Threadiness = Single | AutoRetry | ManualRetry

class (GM.MVector (G.Mutable v ) a ) => PersistentVector (tok :: Threadiness) v a  where
    type TokType :: Threadiness -> *
    type ResultType :: Threadiness -> * -> *
    init :: Int -> (Int -> a ) -> PerVect v a tok
    get :: PerVect v a  tok -> Int -> ResultType tok a
    set  :: PerVect v a tok -> Int -> a -> ResultType tok (PerVect v a tok )
    getAndRoot :: PerVect v a tok -> Int -> ResultType tok a
    setAndRoot :: PerVect v a   tok -> Int -> a -> ResultType tok (PerVect v a tok )
    --- unsafe ones will be O(1) but you CANT ref the PerVect afterwards safely
    ---- either a) you'll have visible mutation in pure code,
    ---- or in the case of mvars, you'll block, or cas you'll always fail
    unsafeExtractM :: Prim.PrimMonad m =>PerVect v a tok  ->ResultType tok  ( m   (G.Mutable v (Prim.PrimState m) a))
    unsafeExtract :: PerVect v a tok  -> ResultType tok (v a)
    -- the safe ones will have O(1) complexity for CAS, O(n) for single and MVar
    extractM :: Prim.PrimMonad m =>PerVect v a tok  ->   m (ResultType tok     (G.Mutable v (Prim.PrimState m) a))
    extract :: PerVect v a tok  -> ResultType tok (v a)

{-
extract and extractM should have default instances
likewise not sure if the monad m should be inside or outside the resulttype constructor
-}

--instance (GM.MVector v a ) => PersistentVector Single  v a  where

-- need to sort out what the "right" return type will be.
class TokRegulator (tk :: Threadiness ) where
    --claim :: TokType tk -> IO Bool
    --release :: TokType tk -> IO Bool

    -- | withToken is a private type class api for handling the token checking logic
    withToken :: PerVect v a tk -> ( PerVect v a tk ->IO  b ) -> IO (ResultType tok b )

{- internally, i'll just have the machinery use IO rather than ST
this unsafe coerce is actually save -}
unsafeMVectorAsIOVector :: ( GM.MVector v a) => (v s) a ->  (v (RealWorld)) a
unsafeMVectorAsIOVector =  unsafeCoerce

--newPerVect :: GM.MVector v a => v s  a -> PerVect (v RealWorld) a

{- tok is our auth token, could be (), IORef Bool, or MVar () -}
newPerVect :: GM.MVector (G.Mutable v) a => (G.Mutable v) s a -> TokType tok -> PerVect v  a tok
newPerVect !v !tk  =  PerVect $! unsafePerformIO  $!  newIORef $! TheArray tk $! unsafeMVectorAsIOVector v

{-
NOTE: Thread safe version would have every constructor point at a shared
reference
    could use MVar ()  api  or a IORef Bool using CAS
    MVar would have more sensible blocking / scheduling,
    CAS approach would either succeed or Return a Nothing (retry)  operation,
        and would punt on handling the retry logic
                -}


text:
"""
Utilities for reading and writing Fortran namelists.
"""

# pylint: disable-msg=E0611,F0401
import ordereddict
from numpy import ndarray, array, append, vstack, zeros, \
    int32, int64, float32, float64
from openmdao.util.filewrap import ToFloat, ToInteger
from pyparsing import CaselessLiteral, Combine, ZeroOrMore, Literal, \
    Optional, QuotedString, Suppress, Word, alphanums, \
    oneOf, nums, TokenConverter, Group
from traits.trait_handlers import TraitListObject

def _floatfmt(val):
    """ Returns the output format for a floating point number.
    The general format is used with 16 places of accuracy, except for when
    the floating point value is an integer, in which case a decimal point
    followed by a single zero is used."""

    if int(val) == val:
        return "%.1f"
    else:
        return "%.16g"

def _intfmt(val):
    """ Returns the output format for an integer """

    return "%d"

def _strfmt(val):
    """ Returns the output format for a string """

    return "'%s'"

def _boolfmt(val):
    """ Returns the output format for a boolean """

    if val == True:
        return 'T%.0s'
    else:
        return 'F%.0s'

def _process_card_info(card):
    """ Function to extract info from a card as returned from PyParsing a
    namelist file. """

    name = card.name

    # Sometimes we have a 1D array declared by element
    if card.index:
        index = card.index[0] - 1

        # Strings go into lists, not arrays
        if isinstance(card[2], str):
            val = card[2:]
            value = [''] * (index + len(val))
            value[index:] = val
        else:
            val = array(card[2:])
            value = zeros(index + len(val))
            value[index:] = val

    # Alternate array specification
    elif card.dimension:
        dim = card.dimension
        value = zeros(dim)
        value.fill(card.value)

    # Comma-delimited arrays
    elif len(card) > 2:
        value = array(card[1:])
    else:
        value = card.value

    return name, value

class Card(object):
    """ Data object that stores the value of a single card for a namelist."""

    def __init__(self, name, value, is_comment=0):
        self.name = name
        self.value = value
        self.is_comment = is_comment

class ToBool(TokenConverter):
    """Converter for PyParsing that is used to turn a token into a Boolean."""

    def postParse(self, instring, loc, tokenlist):
        """Converter to make token into a bool."""

        if tokenlist[0] in ['T', 'True', 'TRUE', 'true', '.TRUE.', '.T.']:
            return True
        elif tokenlist[0] in ['F', 'False', 'FALSE', 'false', '.FALSE.', '.F.']:
            return False
        else:
            raise RuntimeError('Unexpected error while trying to identify a'
                               ' Boolean value in the namelist.')

class Namelist(object):
    """Utility to ease the task of constructing a formatted output file."""

    def __init__(self, comp):

        self.filename = None
        self.delimiter = ", "
        self.terminator = "/"
        self.title = ""

        self.comp = comp
        self.groups = []
        self.cards = []

        self.currentgroup = 0

    def set_filename(self, filename):
        """Set the name of the file that will be generated or parsed.

        filename: string
            Name of the file to be written."""

        self.filename = filename

    def set_title(self, title):
        """Sets the title for the namelist Note that a title is not
        required.

        title: string
            The title card in the namelist - generally optional."""

        self.title = title

    def add_group(self, name):
        """Add a new group to the namelist. Any variables added after this are
        added to this new group.

        name: string
            Group name to be added."""

        self.groups.append(name)
        self.currentgroup = len(self.groups) - 1
        self.cards.append([])

    def add_var(self, varpath):
        """Add an openmdao variable to the namelist.

        varpath: string
        varpath is the dotted path (e.g., comp1.container1.var1)."""

        paths = varpath.split('.')
        name = paths[-1]

        value = self.comp.get(varpath)

        self.cards[self.currentgroup].append(Card(name, value))

    def add_newvar(self, name, value):
        """Add a new variable to the namelist.

        name: string
            Name of the variable to be added.

        value: int, float, string, ndarray, list, bool
            Value of the variable to be added."""

        self.cards[self.currentgroup].append(Card(name, value))

    def add_container(self, varpath='', skip=None):
        """Add every variable in an OpenMDAO container to the namelist. This
        can be used it your component has containers of variables.

        varpath: string
            Dotted path of container in the data hierarchy.

        skip: list of str
            List of variables to skip printing to the file."""

        target_container = self.comp.get(varpath)

        if not skip:
            skip = []

        for name in sorted(target_container.list_vars()):
            if name not in skip:
                self.add_var("%s.%s" % (varpath, name))

    def add_comment(self, comment):
        """Add a comment in the namelist.

        comment: string
            Comment text to be added. Text should include comment character
            if one is desired. (Note that a comment character isn't always
            needed in a Namelist. It seems to figure out whether something
            is a comment without it.)"""

        self.cards[self.currentgroup].append(Card("C", comment, 1))

    def generate(self):
        """Generates the input file. This should be called after all cards
        and groups are added to the namelist."""

        data = []
        data.append("%s\n" % self.title)
        for i, group_name in enumerate(self.groups):

            # Groups get a '&', freeform cards don't.
            if self.cards[i]:
                data.append("&%s\n" % group_name)
            else:
                data.append("%s\n" % group_name)

            for card in self.cards[i]:

                if card.is_comment:
                    line = "  %s\n" % (card.value)

                elif isinstance(card.value, bool):
                    fstring = "  %s = " + _boolfmt(card.value) + "\n"
                    line = fstring % (card.name, card.value)

                elif isinstance(card.value, int):
                    fstring = "  %s = " + _intfmt(card.value) + "\n"
                    line = fstring % (card.name, card.value)

                elif isinstance(card.value, float):
                    fstring = "  %s = " + _floatfmt(card.value) + "\n"
                    line = fstring % (card.name, card.value)

                elif isinstance(card.value, str):
                    fstring = "  %s = " + _strfmt(card.value) + "\n"
                    line = fstring % (card.name, card.value)

                # Lists are mainly supported for the Enum Array
                elif isinstance(card.value, list):
                    line = "  %s = " % (card.name)
                    sep = ""
                    for val in card.value:

                        # We can have integer, real, or string lists
                        if isinstance(val, bool):
                            fmt = _boolfmt
                        elif isinstance(val, (int, int32, int64)):
                            fmt = _intfmt
                        elif isinstance(val, (float, float32, float64)):
                            fmt = _floatfmt
                        else:
                            fmt = _strfmt

                        fstring = sep + fmt(val)
                        line += fstring % val
                        sep = self.delimiter

                    line += "\n"

                elif isinstance(card.value, (ndarray)):

                    # We can have integer, real, or string arrays
                    if card.value.dtype == bool:
                        fmt = _boolfmt
                    elif card.value.dtype in (int, int32, int64):
                        fmt = _intfmt
                    elif card.value.dtype in (float, float32, float64):
                        fmt = _floatfmt
                    else:
                        fmt = _strfmt

                    # We don't need to output 0D arrays
                    if len(card.value) == 0:
                        continue

                    elif len(card.value.shape) == 1:
                        line = "  %s = " % (card.name)
                        sep = ""
                        for val in card.value:
                            fstring = "%s" + fmt(val)
                            line += fstring % (sep, val)
                            sep = self.delimiter
                        line += "\n"

                    elif len(card.value.shape) == 2:

                        line = "  "
                        for row in range(0, card.value.shape[0]):
                            line += card.name + "(1," + str(row + 1) + ") ="
                            for col in range(0, card.value.shape[1]):
                                val = card.value[row, col]
                                fstring = " " + fmt(val) + "%s"
                                line += fstring % (val, self.delimiter)
                            line += "\n"

                    else:
                        raise RuntimeError("Don't know how to handle array"
                                           " of %s dimensions"
                                           % len(card.value.shape))

                else:
                    raise RuntimeError("Error generating input file. Don't"
                                       " know how to handle data in variable"
                                       " %s in group %s." % (card.name,
                                                             group_name))

                data.append(line)

            # A group with no cards is treated like a free-form entity.
            if len(self.cards[i]) > 0:
                data.append("%s\n" % self.terminator)

        outfile = open(self.filename, 'w')
        outfile.writelines(data)
        outfile.close()

    def parse_file(self):
        """Parses an existing namelist file and creates a deck of cards to
        hold the data. After this is executed, you need to call the ``load_model()``
        method to extract the variables from this data structure."""

        infile = open(self.filename, 'r')
        data = infile.readlines()
        infile.close()

        # Lots of numerical tokens for recognizing various kinds of numbers
        digits = Word(nums)
        dot = "."
        sign = oneOf("+ -")
        ee = CaselessLiteral('E') | CaselessLiteral('D')

        num_int = ToInteger(Combine(Optional(sign) + digits))

        num_float = ToFloat(Combine(Optional(sign) +
                                    ((digits + dot + Optional(digits)) |
                                     (dot + digits)) +
                                    Optional(ee + Optional(sign) + digits)
                                    ))

        # special case for a float written like "3e5"
        mixed_exp = ToFloat(Combine(digits + ee + Optional(sign) + digits))

        # I don't suppose we need these, but just in case (plus it's easy)
        nan = ToFloat(oneOf("NaN Inf -Inf"))

        numval = num_float | mixed_exp | num_int | nan
        strval = QuotedString(quoteChar='"') | QuotedString(quoteChar="'")
        b_list = "T TRUE True true F FALSE False false .TRUE. .FALSE. .T. .F."
        boolval = ToBool(oneOf(b_list))
        fieldval = Word(alphanums)

        # Tokens for parsing a line of data
        numstr_token = numval + ZeroOrMore(Suppress(',') + numval) \
                       | strval
        data_token = numstr_token | boolval
        index_token = Suppress('(') + num_int + Suppress(')')

        card_token = Group(fieldval("name") +
                           Optional(index_token("index")) +
                           Suppress('=') +
                           Optional(num_int("dimension") + Suppress('*')) +
                           data_token("value") +
                           Optional(Suppress('*') + num_int("dimension")))
        multi_card_token = (card_token + ZeroOrMore(Suppress(',') + card_token))
        array_continuation_token = numstr_token.setResultsName("value")
        array2D_token = fieldval("name") + Suppress("(") + \
                        Suppress(num_int) + Suppress(',') + \
                        num_int("index") + Suppress(')') + \
                        Suppress('=') + numval + \
                        ZeroOrMore(Suppress(',') + numval)

        # Tokens for parsing the group head and tai
        group_end_token = Literal("/") | \
                          Literal("$END") | Literal("$end") | \
                          Literal("&END") | Literal("&end")
        group_name_token = (Literal("$") | Literal("&")) + \
                           Word(alphanums).setResultsName("name") + \
                           Optional(multi_card_token) + \
                           Optional(group_end_token)

        # Comment Token
        comment_token = Literal("!")

        # Loop through each line and parse.

        current_group = None
        for line in data:
            line_base = line
            line = line.strip()

            # blank line: do nothing
            if not line:
                continue

            if current_group:

                # Skip comment cards
                if comment_token.searchString(line):
                    pass

                # Process orindary cards
                elif multi_card_token.searchString(line):
                    cards = multi_card_token.parseString(line)

                    for card in cards:
                        name, value = _process_card_info(card)
                        self.cards[-1].append(Card(name, value))

                # Catch 2D arrays like -> X(1,1) = 3,4,5
                elif array2D_token.searchString(line):
                    card = array2D_token.parseString(line)

                    name = card[0]
                    index = card[1]
                    value = array(card[2:])

                    if index > 1:
                        old_value = self.cards[-1][-1].value
                        new_value = vstack((old_value, value))
                        self.cards[-1][-1].value = new_value
                    else:
                        self.cards[-1].append(Card(name, value))

                # Arrays can be continued on subsequent lines
                # The value of the most recent card must be turned into an
                # array and appended
                elif array_continuation_token.searchString(line):
                    card = array_continuation_token.parseString(line)

                    if len(card) > 1:
                        element = array(card[0:])
                    else:
                        element = card.value

                    if isinstance(self.cards[-1][-1].value, ndarray):
                        new_value = append(self.cards[-1][-1].value, element)
                    else:
                        new_value = array([self.cards[-1][-1].value, element])

                    self.cards[-1][-1].value = new_value

                # Lastly, look for the group footer
                elif group_end_token.searchString(line):
                    current_group = None

                # Everything else must be a pure comment
                else:
                    print "Comment ignored: %s" % line.rstrip('\n')

                # Group ending '/' can also conclude a data line.
                if line[-1] == '/':
                    current_group = None

                    # print self.cards[-1][-1].name, self.cards[-1][-1].value
            else:
                group_name = group_name_token.searchString(line)

                # Group Header
                if group_name:
                    group_name = group_name_token.parseString(line)
                    current_group = group_name.name
                    self.add_group(current_group)

                    # Sometimes, variable definitions are included on the
                    # same line as the namelist header
                    if len(group_name) > 2:
                        cards = group_name[2:]

                        for card in cards:
                            # Sometimes an end card is on the same line.
                            if group_end_token.searchString(card):
                                current_group = None
                            else:
                                name, value = _process_card_info(card)
                                self.cards[-1].append(Card(name, value))

                # If there is an ungrouped card at the start, take it as the
                # title for the analysis
                elif len(self.cards) == 0 and self.title == '':
                    self.title = line

                # All other ungrouped cards are saved as free-form (card-less)
                # groups.
                # Note that we can't lstrip because column spacing might be
                # important.
                else:
                    self.add_group(line_base.rstrip())

    def load_model(self, rules=None, ignore=None, single_group=-1):
        """Loads the current deck into an OpenMDAO component.

        rules: dict of lists of strings (optional)
             An optional dictionary of rules can be passed if the component has a
             hierarchy of containers for its input variables. If no rules dictionary
             is passed, ``load_model`` will attempt to find each namelist variable in the
             top level of the model hierarchy.

        ignore: list of strings (optional)
             List of variable names that can safely be ignored.

        single_group: integer (optional)
             Group id number to use for processing one single namelist group. Useful
             if extra processing is needed or if multiple groups have the same name.

             Returns a tuple containing the following values:
             (empty_groups, unlisted_groups, unlinked_vars). These need to be
             examined after calling ``load_model`` to make sure you loaded every
             variable into your model.

        empty_groups: ordereddict( integer : string )
             Names and ID number of groups that don't have cards. This includes
             strings found at the top level that aren't comments; these need to
             be processed by your wrapper to determine how the information fits
             into your component's variable hierarchy.

        unlisted_groups: ordereddict( integer : string )
             This dictionary includes the names and ID number of groups that have
             variables that couldn't be loaded because the group wasn't mentioned
             in the rules dictionary.

        unlinked_vars: list containing all variable names that weren't found
        in the component.

        """

        # See Pylint W0102 for why we do this
        if not ignore:
            ignore = []

        if not self.groups:
            msg = "Input file must be read with parse_file before " \
                  "load_model can be executed."
            raise RuntimeError(msg)

        if single_group > -1:
            use_group = {single_group: self.groups[single_group]}.iteritems()
        else:
            use_group = enumerate(self.groups)

        empty_groups = ordereddict.OrderedDict()
        unlisted_groups = ordereddict.OrderedDict()
        unlinked_vars = []
        used_groups = []
        for i, group_name in use_group:

            # Report all groups with no cards
            if len(self.cards[i]) == 0:
                empty_groups[i] = group_name
                continue

            # If a group_name appears twice, we really don't know where to
            # stick the variables, and there are potential data overwrite
            # issues. Those cases have to be handled individually.
            if group_name in used_groups:
                unlisted_groups[i] = group_name
                continue
            else:
                used_groups.append(group_name)

            # Process the cards in this group
            for card in self.cards[i]:

                name = card.name
                value = card.value
                found = False

                if rules:

                    # If the group isn't in the rules dict, we can't handle
                    # it now. A separate function call will be required.
                    try:
                        containers = rules[group_name]
                    except KeyError:
                        unlisted_groups[i] = group_name
                        # print "Group not found: %s" % group_name
                        break

                    for container in containers:
                        # Note: FORTRAN is case-insensitive, OpenMDAO is not
                        varpath1 = "%s.%s" % (container, name)
                        varpath2 = "%s.%s" % (container, name.lower())

                        for item in [varpath1, varpath2]:
                            if self.comp.contains(item):
                                found = True
                                varpath = item
                                break

                else:
                    for item in [name, name.lower()]:
                        if item in self.comp.list_vars():
                            found = True
                            varpath = item
                            break

                if not found:
                    if name not in ignore and name.lower() not in ignore:
                        unlinked_vars.append(name)
                        print "Variable not found: " + \
                              "%s in group %s." % (name, group_name)

                else:

                    # 1D arrays must become ndarrays
                    target = self.comp.get(varpath)

                    if isinstance(target, ndarray) and \
                            isinstance(value, (float, int)):
                        value = array([value])

                    # Enum ndarrays must become lists
                    elif isinstance(target, TraitListObject):
                        if isinstance(value, ndarray):
                            value = list(value)
                        elif isinstance(value, list):
                            pass
                        else:
                            value = [value]

                    self.comp.set(varpath, value)

                    # print varpath, value

        return empty_groups, unlisted_groups, unlinked_vars

    def find_card(self, group, name):
        """Returns the value for a given namelist variable in a given group.

        group: string
            namelist group name.

        name: string
            namelist variable name."""

        group_id = self.groups.index(group)

        for card in self.cards[group_id]:
            if card.name == name:
                return card.value

        msg = "Variable %s" % name + \
              " not found in namelist %s." % group
        raise RuntimeError(msg)


text:
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.

package elastic

import (
	"context"
	"testing"
)

func TestIndicesForcemergeBuildURL(t *testing.T) {
	client := setupTestClient(t)

	tests := []struct {
		Indices  []string
		Expected string
	}{
		{
			[]string{},
			"/_forcemerge",
		},
		{
			[]string{"index1"},
			"/index1/_forcemerge",
		},
		{
			[]string{"index1", "index2"},
			"/index1%2Cindex2/_forcemerge",
		},
	}

	for i, test := range tests {
		path, _, err := client.Forcemerge().Index(test.Indices...).buildURL()
		if err != nil {
			t.Errorf("case #%d: %v", i+1, err)
			continue
		}
		if path != test.Expected {
			t.Errorf("case #%d: expected %q; got: %q", i+1, test.Expected, path)
		}
	}
}

func TestIndicesForcemerge(t *testing.T) {
	client := setupTestClientAndCreateIndexAndAddDocs(t)

	_, err := client.Forcemerge(testIndexName).MaxNumSegments(1).Do(context.TODO())
	if err != nil {
		t.Fatal(err)
	}
	/*
		if !ok {
			t.Fatalf("expected forcemerge to succeed; got: %v", ok)
		}
	*/
}


text:
package org.mifos.application.productdefinition.business;

import org.mifos.application.master.business.MasterDataEntity;
import org.mifos.application.productdefinition.util.helpers.InterestCalcType;

public class InterestCalcTypeEntity extends MasterDataEntity {

    public InterestCalcTypeEntity(InterestCalcType interestCalcType) {
        super(interestCalcType.getValue());

    }

    protected InterestCalcTypeEntity() {
        super();
    }

}


text:
<?php

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="moviedb"; // Database name
$tbl_name="people"; // Table name

// Connect to server and select databse.
$conn = mysql_connect("$host", "$username", "$password");
$select_db = mysql_select_db("$db_name");
?>


text:
"""Tests for Unicode strings proto parser."""

from nisaba.scripts.utils import unicode_strings_pb2
from nisaba.scripts.utils import unicode_strings_util as lib
from absl.testing import absltest

class UnicodeStringsUtilTest(absltest.TestCase):

  def _proto_entries_to_string(self, uname_prefixes=(), uname=(), raw=""):
    return lib.proto_entries_to_string(uname_prefixes, uname, raw)

  def _convert_item(self, uname_prefixes=(), to_uname_prefixes=(),
                    uname=None, raw="", to_uname=None, to_raw=""):
    item = unicode_strings_pb2.UnicodeStrings.Item()
    item.raw = raw
    item.to_raw = to_raw
    if uname:
      item.uname.extend(uname)
    if to_uname:
      item.to_uname.extend(to_uname)
    return lib.convert_item(uname_prefixes, to_uname_prefixes, item)

  def testProtoEntriesToString(self):
    """Tests the internal API for parsing `uname` and `raw` fields."""
    # The Unicode names or raw Unicode codepoint sequence specification is set.
    self.assertEqual("abc", self._proto_entries_to_string(raw="abc"))
    self.assertEqual("abc", self._proto_entries_to_string(
        uname_prefixes=["Latin Small Letter"], uname=["A", "B", "C"]))
    with self.assertRaisesRegex(ValueError, "does not match a character name"):
      # Invalid Unicode character name should fail.
      self._proto_entries_to_string(uname=["AZTEC LETTER Ы"])

    # Both the unicode names or raw Unicode codepoint sequence specification is
    # set. In this case, both need to be equivalent.
    brahmi_string = "𑀅𑀞𑀪𑀸𑀕𑀺𑀬𑁂𑀘"
    brahmi_unames = ["LETTER A", "LETTER TTHA", "LETTER BHA", "VOWEL SIGN AA",
                     "LETTER GA", "VOWEL SIGN I", "LETTER YA", "VOWEL SIGN E",
                     "LETTER CA"]
    self.assertEqual(brahmi_string, self._proto_entries_to_string(
        uname_prefixes=["BRAHMI"], uname=brahmi_unames, raw=brahmi_string))

    # The Unicode name sequence mismatches the reference raw string.
    with self.assertRaisesRegex(ValueError, "uname=.* mismatch with raw"):
      self._proto_entries_to_string(
          uname_prefixes=["BRAHMI"], uname=brahmi_unames + ["LETTER A"],
          raw=brahmi_string)
    with self.assertRaisesRegex(ValueError, "uname=.* mismatch with raw"):
      self._proto_entries_to_string(
          uname_prefixes=["BRAHMI"], uname=brahmi_unames,
          raw=brahmi_string + "𑀞")
    # Both prefixes resolve different characters.
    with self.assertRaisesRegex(
        ValueError, "Above exception is for raw=.'BRAHMI LETTER I'."):
      self._proto_entries_to_string(
          uname_prefixes=["BRAHMI LETTER", "BRAHMI VOWEL SIGN"], uname=["I"],
          raw="𑀇")

    brahmi_unames = ["A", "TTHA", "BHA", "SIGN AA", "GA", "SIGN I", "YA",
                     "SIGN E", "CA"]
    self.assertEqual(brahmi_string, self._proto_entries_to_string(
        uname_prefixes=["BRAHMI LETTER", "BRAHMI VOWEL"], uname=brahmi_unames,
        raw=brahmi_string))

  def testConvertItem(self):
    """Tests the internal API for parsing UnicodeStrings.Item field."""
    # Only list items are set.
    source, dest = self._convert_item(raw="abc")
    self.assertEqual("abc", source)
    self.assertFalse(dest)
    latin_prefix = ["Latin Small Letter"]
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      uname=["A", "B", "C"])
    self.assertEqual("abc", source)
    self.assertFalse(dest)
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      raw="abc", uname=["A", "B", "C"])
    self.assertEqual("abc", source)
    self.assertFalse(dest)

    # Either `uname` or `raw` or both have to be set.
    with self.assertRaisesRegex(ValueError, "have to be defined"):
      self._convert_item(to_raw="abc")
    with self.assertRaisesRegex(ValueError, "have to be defined"):
      self._convert_item(to_uname=["A", "B", "C"])

    # Mapping items are set.
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      raw="abc", to_uname=["D", "E", "F"])
    self.assertEqual("abc", source)
    self.assertEqual("def", dest)
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      raw="abc", uname=["A", "B", "C"],
                                      to_uname=["D", "E", "F"])
    self.assertEqual("abc", source)
    self.assertEqual("def", dest)
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      uname=["A", "B", "C"],
                                      to_uname=["D", "E", "F"])
    self.assertEqual("abc", source)
    self.assertEqual("def", dest)
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      uname=["A", "B", "C"],
                                      to_raw="def", to_uname=["D", "E", "F"])
    self.assertEqual("abc", source)
    self.assertEqual("def", dest)
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      raw="abc", to_raw="def")
    self.assertEqual("abc", source)
    self.assertEqual("def", dest)
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      raw="abc", uname=["A", "B", "C"],
                                      to_raw="def", to_uname=["D", "E", "F"])
    self.assertEqual("abc", source)
    self.assertEqual("def", dest)

    latin_capital_prefix = ["Latin Capital Letter"]
    source, dest = self._convert_item(uname_prefixes=latin_prefix,
                                      to_uname_prefixes=latin_capital_prefix,
                                      raw="abc", uname=["A", "B", "C"],
                                      to_raw="DEF", to_uname=["D", "E", "F"])
    self.assertEqual("abc", source)
    self.assertEqual("DEF", dest)

    source, dest = self._convert_item(uname_prefixes=["LATIN", "LATIN LETTER"],
                                      raw="N", uname=["CAPITAL LETTER N"],
                                      to_raw="ɴ", to_uname=["SMALL CAPITAL N"])
    self.assertEqual("N", source)
    self.assertEqual("ɴ", dest)

    with self.assertRaisesRegex(
        ValueError, "resolves to more than one character"):
      self._convert_item(uname_prefixes=["LATIN", "LATIN SMALL LETTER",
                                         "LATIN CAPITAL LETTER"],
                         uname=["X"], to_uname=["Y"])

    # Check equivalence of raw and uname fields on either side.
    with self.assertRaisesRegex(ValueError, "uname=.* mismatch with raw"):
      self._convert_item(uname_prefixes=latin_prefix, raw="abc", uname=["X"])
    with self.assertRaisesRegex(ValueError, "uname=.* mismatch with raw"):
      self._convert_item(uname_prefixes=latin_prefix,
                         raw="___", to_raw="abc", to_uname=["X"])

if __name__ == "__main__":
  absltest.main()


text:
#include "FastAsset.hpp"

#include <fwklib/GsRandom.hpp>

#include <geode/DataInput.hpp>
#include <geode/DataOutput.hpp>

namespace testobject {

using apache::geode::client::testframework::GsRandom;

FastAsset::FastAsset(int idx, int maxVal) : assetId(idx) {
  value = GsRandom::getInstance().nextDouble(1, maxVal);
}

void FastAsset::toData(apache::geode::client::DataOutput& output) const {
  output.writeInt(static_cast<int32_t>(assetId));
  output.writeDouble(value);
}

void FastAsset::fromData(apache::geode::client::DataInput& input) {
  assetId = input.readInt32();
  value = input.readDouble();
}

}  // namespace testobject


text:
using System;
using System.Linq;

namespace Microsoft.Azure.Management.WebSites.Models
{
    /// <summary>
    /// The availability of a web space.
    /// </summary>
    public enum WebSpaceAvailabilityState
    {
        Normal = 0,

        Limited = 1,
    }
}


text:
// cassandra-sharp - high performance .NET driver for Apache Cassandra
// Copyright (c) 2011-2013 Pierre Chalamet
//
// 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.

namespace CassandraSharp.Extensibility
{
    using System.Collections.Generic;
    using System.Net;

    public interface IEndpointSnitch
    {
        string GetRack(IPAddress endpoint);

        string GetDatacenter(IPAddress endpoint);

        List<IPAddress> GetSortedListByProximity(IPAddress address, IEnumerable<IPAddress> unsortedAddress);

        int CompareEndpoints(IPAddress address, IPAddress a1, IPAddress a2);
    }
}