text:
function escapeCE(s) { // escape for contenteditable
    return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '
');
}

// rust syntax highlighter
function rustSH(input, selectionStart, selectionEnd) {

    function span_to_snippet(sp) {
        return rdr.src.substring(byte_offset(rdr, sp.lo), byte_offset(rdr, sp.hi));
    }

    var result = [];
    var rdr = new_low_level_string_reader(null, {src: input, start_pos: 0, next_line: function(){}});
    var last_hi = rdr.last_pos;
    while (rdr.peek_tok.k !== token.EOF.k) {
        string_advance_token(rdr);
        if (rdr.peek_tok.k !== token.EOF.k) {

            // space and comments are skipped by lexer
            if (last_hi < rdr.peek_span.lo) {
                result.push("" + escapeCE(span_to_snippet(mk_sp(last_hi, rdr.peek_span.lo))) + "");
            }

            result.push("" + escapeCE(span_to_snippet(rdr.peek_span)) + "");
            last_hi = rdr.peek_span.hi;
        } else {

            // space and comments at the end
            if (last_hi < rdr.last_pos) {
                result.push("" + escapeCE(span_to_snippet(mk_sp(last_hi, rdr.last_pos))) + "");
            }
        }
    }
    return result.join('');
}

// js syntax highlighter
function jsSH(input, selectionStart, selectionEnd) {
    selectionStart = selectionStart || 0;
    selectionEnd = selectionEnd || 0;

    if (selectionStart > selectionEnd) { // swap
        var tmp = selectionStart;
        selectionStart = selectionEnd;
        selectionEnd = tmp;
    }

    if (selectionStart === selectionEnd) {
        return "" + escapeCE(input) + "";
    }

    var result = [];
    result.push("" + escapeCE(input.substring(0, selectionStart)) + "");
    result.push("" + escapeCE(input.substring(selectionStart, selectionEnd)) + "");
    result.push("" + escapeCE(input.substring(selectionEnd)) + "");
    return result.join('');
}

function Backlit(id, content, sh) {
    this.id = id;
    this.el = document.getElementById(id);
    this.content = content;
    this.selectionStart = 0;
    this.selectionEnd = 0;
    this.sh = sh; // syntax highlighter function (str -> html)
}

Backlit.prototype.render = function () {
    this.el.innerHTML = this.sh(this.content, this.selectionStart, this.selectionEnd);
};

Backlit.prototype.renderWithSelection = function (a, b) {
    this.selectionStart = a;
    this.selectionEnd = b;
    this.render();
    this.setSelectionRange(this.selectionStart, this.selectionEnd);
};

Backlit.prototype.visit = function (f) { // apply function f to see if visitor should proceed
    var q = [this.el]; // depth first search

    var node;
    while (q.length > 0) {
        node = q.pop();
        if (!f(node)) break;

        if (node.childNodes.length === 0) {
            continue;
        }

        for (var i = node.childNodes.length - 1; i >= 0; i--) {
            q.push(node.childNodes[i]);
        }
    }
};

// - reads latest content
// - updates selectionStart and selectionEnd if selection is within the element
// - normalizes innerHTML
Backlit.prototype.noticeChanges = function () {
    var newContent = ""; // to be computed

    var selection = document.getSelection();

    var anchorNode = selection.anchorNode;
    var anchorOffset = selection.anchorOffset;
    if (anchorNode.nodeType !== document.TEXT_NODE) { // in this case, offset is the child number
        if (anchorNode.childNodes.length > 0) { // it points to

            anchorNode = anchorNode.childNodes[anchorOffset];
            anchorOffset = 0;
        }
    }

    var focusNode = selection.focusNode;
    var focusOffset = selection.focusOffset;
    if (focusNode.nodeType !== document.TEXT_NODE) { // in this case, offset is the child number
        if (focusNode.childNodes.length > 0) { // it points to

            focusNode = focusNode.childNodes[focusOffset];
            focusOffset = 0;
        }
    }

    var selectionStart = 0; // not that in this case `selectionStart > selectionEnd` is possible
    var selectionEnd = 0;

    var anchorFound = false;
    var focusFound = false;

    var lastVisited = null;
    this.visit(function(curr){
        if (curr.nodeType === document.TEXT_NODE) {
            if (!anchorFound) {
                if (curr === anchorNode) {
                    anchorFound = true;
                    selectionStart += anchorOffset;
                } else {
                    selectionStart += curr.textContent.length;
                }
            }
            if (!focusFound) {
                if (curr === focusNode) {
                    focusFound = true;
                    selectionEnd += focusOffset;
                } else {
                    selectionEnd += curr.textContent.length;
                }
            }
            newContent += curr.textContent;
        } else if (curr.nodeName === 'BR') {
            if (!anchorFound) {
                if (curr === anchorNode) {
                    anchorFound = true;
                    selectionStart += anchorOffset;
                } else {
                    selectionStart += 1;
                }
            }
            if (!focusFound) {
                if (curr === focusNode) {
                    focusFound = true;
                    selectionEnd += focusOffset;
                } else {
                    selectionEnd += 1;
                }
            }
            newContent += "\n";
        } else { // intermediate node; do not add to selection or content
            if (!anchorFound) {
                if (curr === anchorNode) {
                    anchorFound = true;
                    selectionStart += anchorOffset;
                }
            }
            if (!focusFound) {
                if (curr === focusNode) {
                    focusFound = true;
                    selectionEnd += focusOffset;
                }
            }
            if (lastVisited !== null && lastVisited.nodeName !== 'BR' && curr.nodeName === 'DIV') {
                if (!anchorFound) selectionStart += 1;
                if (!focusFound) selectionEnd += 1;
                newContent += "\n";
            }
        }
        lastVisited = curr;
        return true;
    });

    if (anchorNode === undefined) { // TODO points to end of a childnode, assume lastVisited for the time being
        anchorFound = true;
        anchorNode = lastVisited;
    }

    if (focusNode === undefined) { // TODO points to end of a childnode, assume lastVisited for the time being
        focusFound = true;
        focusNode = lastVisited;
    }

    if (!anchorFound || !focusFound) { // selection was outside el
        return;
    }

    // update selection range
    this.selectionStart = selectionStart;
    this.selectionEnd = selectionEnd;

    if (newContent === this.content) {
        return;
    }

    // some change has happened, update content
    this.content = newContent;
    this.render();
    this.setSelectionRange(this.selectionStart, this.selectionEnd);
};

// restores caret
Backlit.prototype.setSelectionRange = function (selectionStart, selectionEnd) {
    var selectionStartCounter = 0; // will count up to selectionStart (lesser)
    var selectionEndCounter = 0;

    var newAnchorNode = null;
    var newAnchorOffset = 0;
    var newFocusNode = null;
    var newFocusOffset = 0;

    this.visit(function(curr){
        if (curr.nodeType === document.TEXT_NODE) {
            if (newAnchorNode === null) {
                if (selectionStartCounter + curr.textContent.length >= selectionStart) {
                    newAnchorNode = curr;
                    newAnchorOffset = selectionStart - selectionStartCounter;
                } else {
                    selectionStartCounter += curr.textContent.length;
                }
            }
            if (newFocusNode === null) {
                if (selectionEndCounter + curr.textContent.length >= selectionEnd) {
                    newFocusNode = curr;
                    newFocusOffset = selectionEnd - selectionEndCounter;
                } else {
                    selectionEndCounter += curr.textContent.length;
                }
            }
        } else if (curr.nodeName === 'BR') {
            if (newAnchorNode === null) {
                if (selectionStartCounter + 1 > selectionStart) { // only less than here
                    newAnchorNode = curr.parentNode;
                    for (var i = 0; i < newAnchorNode.childNodes.length; i++) {
                        if (newAnchorNode.childNodes[i] === curr) {
                            newAnchorOffset = i;
                            break;
                        }
                    }
                } else {
                    selectionStartCounter += 1;
                }
            }
            if (newFocusNode === null) {
                if (selectionEndCounter + 1 > selectionEnd) { // only less than here
                    newFocusNode = curr.parentNode;
                    for (var i = 0; i < newFocusNode.childNodes.length; i++) {
                        if (newFocusNode.childNodes[i] === curr) {
                            newFocusOffset = i;
                            break;
                        }
                    }
                } else {
                    selectionEndCounter += 1;
                }
            }
        } else { // ignore
        }
        return true;
    });

    if (newAnchorNode === null) throw 'new selection anchor node not found in backlit';
    if (newFocusNode === null) throw 'new selection focus node not found in backlit';

    // update selection
    this.selectionStart = selectionStart;
    this.selectionEnd = selectionEnd;

    // everything sane
    var selection = document.getSelection();
    var range = document.createRange();
    range.setStart(newAnchorNode, newAnchorOffset);
    range.setEnd(newFocusNode, newFocusOffset);
    selection.removeAllRanges();
    selection.addRange(range);
};


text:
<ng-form name="$ctrl.productVersionForm" novalidate>

    Product
    <pnc-product-combobox name="product" ng-change="$ctrl.checkVersionData()" ng-model="$ctrl.data.product">
    </pnc-product-combobox>

    Version
    <pnc-product-version-combobox name="version" product="$ctrl.data.product" ng-model="$ctrl.data.version" required>
    </pnc-product-version-combobox>

      Version is a required field if you selected any product.

</ng-form>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace FSi\Component\DataSource\Driver\Doctrine\Extension\Core\Field;

use FSi\Component\DataSource\Driver\Doctrine\DoctrineFieldInterface;
use FSi\Component\DataSource\Driver\Doctrine\ORM\Extension\Core\Field\Number as BaseNumber;

/**
 * Number field.
 * @deprecated since version 1.4
 */
class Number extends BaseNumber implements DoctrineFieldInterface
{
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>Dialog API Events</title>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../../styles/styles.css">

Dialog API Events

main |
Dialog API |
Messages

Event	Description

DN_CLOSE
Sent before the dialog is closed.

DN_BTNCLICK
Sent after a button, radiobutton or checkbox was clicked.

DN_CTLCOLORDIALOG
Sent before the dialog background is drawn, for changing its color.

DN_CTLCOLORDLGITEM
Sent before a dialog item is drawn, for changing its color.

DN_CTLCOLORDLGLIST
Sent before a list is drawn, for changing its color.

DN_DRAGGED
Notification of dialog dragging.

DN_DRAWDIALOG
Sent before the dialog is drawn.

DN_DRAWDIALOGDONE
Sent after the dialog has been drawn.

DN_DRAWDLGITEM
Sent before a dialog item is drawn.

DN_EDITCHANGE
Sent when the text in the dialog edit control has changed.

DN_GOTFOCUS
Sent when the dialog item gets input focus.

DN_HELP
Sent before a help topic is displayed.

DN_HOTKEY
Sent after the user has pressed an hotkey (Alt-<letter>).

DN_INITDIALOG
Sent before initializing the dialog.

DN_KEY
Sent after the user has pressed a key in the dialog.

DN_KILLFOCUS
Sent before a dialog item loses the input focus.

DN_LISTCHANGE
Sent when a list item is changed.

DN_LISTHOTKEY
Sent after the user has pressed an hotkey (Alt-<letter>) inside a list.

DN_MOUSECLICK
Sent after the user has clicked one of the dialog items with the mouse.

DN_MOUSEEVENT
Sent before a mouse event is handled by the dialog kernel.

DN_RESIZECONSOLE
Sent after the size of the console window has changed.

See also:

Dialog API Messages


text:
package tests.api.java.lang.ref;

import dalvik.annotation.TestTargets;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargetClass;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

@TestTargetClass(WeakReference.class)
public class WeakReferenceTest extends junit.framework.TestCase {
    static Boolean bool;

    protected void doneSuite() {
        bool = null;
    }

    /**
     * @tests java.lang.ref.WeakReference#WeakReference(java.lang.Object,
     *        java.lang.ref.ReferenceQueue)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "WeakReference",
        args = {java.lang.Object.class, java.lang.ref.ReferenceQueue.class}
    )
    public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
        ReferenceQueue rq = new ReferenceQueue();
        bool = new Boolean(true);
        try {
            // Allow the finalizer to run to potentially enqueue
            WeakReference wr = new WeakReference(bool, rq);
            assertTrue("Initialization failed.", ((Boolean) wr.get())
                    .booleanValue());
        } catch (Exception e) {
            fail("Exception during test : " + e.getMessage());
        }
        // need a reference to bool so the jit does not optimize it away
        assertTrue("should always pass", bool.booleanValue());

        boolean exception = false;
        try {
            new WeakReference(bool, null);
        } catch (NullPointerException e) {
            exception = true;
        }
        assertTrue("Should not throw NullPointerException", !exception);
    }

    /**
     * @tests java.lang.ref.WeakReference#WeakReference(java.lang.Object)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "WeakReference",
        args = {java.lang.Object.class}
    )
    public void test_ConstructorLjava_lang_Object() {
        bool = new Boolean(true);
        try {
            WeakReference wr = new WeakReference(bool);
            // Allow the finalizer to run to potentially enqueue
            Thread.sleep(1000);
            assertTrue("Initialization failed.", ((Boolean) wr.get())
                    .booleanValue());
        } catch (Exception e) {
            fail("Exception during test : " + e.getMessage());
        }
        // need a reference to bool so the jit does not optimize it away
        assertTrue("should always pass", bool.booleanValue());
    }

    protected void setUp() {
    }

    protected void tearDown() {
    }
}


text:
import os
import sys
import subprocess

catchPath = os.path.dirname(os.path.realpath( os.path.dirname(sys.argv[0])))

def getBuildExecutable():
    if os.name == 'nt':
        dir = os.environ.get('CATCH_DEV_OUT_DIR', "cmake-build-debug/projects/SelfTest.exe")
        return dir
    else:
        dir = os.environ.get('CATCH_DEV_OUT_DIR', "cmake-build-debug/projects/SelfTest")
        return dir

def runAndCapture( args ):
    child = subprocess.Popen(" ".join( args ), shell=True, stdout=subprocess.PIPE)
    lines = []
    line = ""
    while True:
        out = child.stdout.read(1)
        if out == '' and child.poll():
            break
        if out != '':
            if out == '\n':
                lines.append( line )
                line = ""
            else:
                line = line + out
    return lines


text:
export * from './num';
export * from './vec2';
export * from './vec3';
export * from './vec4';
export * from './quat';
export * from './mat3';
export * from './mat4';
export * from './noise';
export * from './curve';

/**
 * TypedArray
 * @typedef {Float64Array|Float32Array|Uint32Array|Uint16Array|Uint8Array|Uint8ClampedArray|Int32Array|Int16Array|Int8Array} TypedArray
 */


text:
<?php

namespace Github\HttpClient\Plugin;

use Http\Client\Common\Plugin;
use Http\Promise\Promise;
use Psr\Http\Message\RequestInterface;

/**
 * Prepend the URI with a string.
 *
 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
 */
final class PathPrepend implements Plugin
{
    /**
     * @var string
     */
    private $path;

    /**
     * @param string $path
     */
    public function __construct(string $path)
    {
        $this->path = $path;
    }

    /**
     * @param RequestInterface $request
     * @param callable         $next
     * @param callable         $first
     *
     * @return Promise
     */
    public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
    {
        $currentPath = $request->getUri()->getPath();
        if (strpos($currentPath, $this->path) !== 0) {
            $uri = $request->getUri()->withPath($this->path.$currentPath);
            $request = $request->withUri($uri);
        }

        return $next($request);
    }
}


text:
package org.jhaws.common.web.wicket.resteasy.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.annotations.GZIP;
import org.jhaws.common.web.resteasy.Pretty;
import org.jhaws.common.web.resteasy.RestResource;

@Path("/googlelogin")
@Pretty
@GZIP
public interface GoogleLoginResource extends RestResource {
    @GET
    @Path("/ping" + D + TEXT_EXTENSION)
    @Produces(TEXT)
    public String ping();

    @POST
    @Path("/tokensignin")
    @Consumes(FORM_URLENCODED)
    @Produces(HTML)
    public Response tokensignin(@FormParam("idtoken") String id_token);
}


text:
/*
# Kalei - Style guide

This project aims at making sure your style sheets are fully documented whilst being synchronized with your webpages styles. To do this it actually uses your live stylesheets in so that at anytime you can review how your styleguide looks.

*/

@import url("../../assets/application.css");

/* ### Example Buttons ### */

@import url("buttons.css");
@import url("fixie-demo.css");


text:
/**
 * @typedef {{
 *   top: number,
 *   right: number,
 *   bottom: number,
 *   left: number
 * }}
 */
let AnchorMargin;

/* eslint-disable no-unused-vars */
/**
 * @typedef {{
 *   viewport: { width: number, height: number },
 *   viewportDistance: {top: number, right: number, bottom: number, left: number},
 *   anchorHeight: number,
 *   anchorWidth: number,
 *   menuHeight: number,
 *   menuWidth: number,
 * }}
 */
let AutoLayoutMeasurements;
/* eslint-enable no-unused-vars */

import MDCFoundation from '@material/base/foundation';
import {MDCSimpleMenuAdapter} from './adapter';
import {cssClasses, strings, numbers, Corner, CornerBit} from './constants';

/**
 * @extends {MDCFoundation<!MDCSimpleMenuAdapter>}
 */
class MDCSimpleMenuFoundation extends MDCFoundation {
  /** @return enum{cssClasses} */
  static get cssClasses() {
    return cssClasses;
  }

  /** @return enum{strings} */
  static get strings() {
    return strings;
  }

  /** @return enum{numbers} */
  static get numbers() {
    return numbers;
  }

  /** @return enum{number} */
  static get Corner() {
    return Corner;
  }

  /**
   * {@see MDCSimpleMenuAdapter} for typing information on parameters and return
   * types.
   * @return {!MDCSimpleMenuAdapter}
   */
  static get defaultAdapter() {
    return /** @type {!MDCSimpleMenuAdapter} */ ({
      addClass: () => {},
      removeClass: () => {},
      hasClass: () => false,
      hasNecessaryDom: () => false,
      getAttributeForEventTarget: () => {},
      eventTargetHasClass: () => {},
      getInnerDimensions: () => ({}),
      hasAnchor: () => false,
      getAnchorDimensions: () => ({}),
      getWindowDimensions: () => ({}),
      getNumberOfItems: () => 0,
      registerInteractionHandler: () => {},
      deregisterInteractionHandler: () => {},
      registerBodyClickHandler: () => {},
      deregisterBodyClickHandler: () => {},
      getIndexForEventTarget: () => 0,
      notifySelected: () => {},
      notifyCancel: () => {},
      saveFocus: () => {},
      restoreFocus: () => {},
      isFocused: () => false,
      focus: () => {},
      getFocusedItemIndex: () => -1,
      focusItemAtIndex: () => {},
      isRtl: () => false,
      setTransformOrigin: () => {},
      setPosition: () => {},
      setMaxHeight: () => {},
    });
  }

  /** @param {!MDCSimpleMenuAdapter} adapter */
  constructor(adapter) {
    super(Object.assign(MDCSimpleMenuFoundation.defaultAdapter, adapter));

    /** @private {function(!Event)} */
    this.clickHandler_ = (evt) => this.handlePossibleSelected_(evt);
    /** @private {function(!Event)} */
    this.keydownHandler_ = (evt) => this.handleKeyboardDown_(evt);
    /** @private {function(!Event)} */
    this.keyupHandler_ = (evt) => this.handleKeyboardUp_(evt);
    /** @private {function(!Event)} */
    this.documentClickHandler_ = (evt) => this.handleDocumentClick_(evt);
    /** @private {boolean} */
    this.isOpen_ = false;
    /** @private {number} */
    this.openAnimationEndTimerId_ = 0;
    /** @private {number} */
    this.closeAnimationEndTimerId_ = 0;
    /** @private {number} */
    this.selectedTriggerTimerId_ = 0;
    /** @private {number} */
    this.animationRequestId_ = 0;
    /** @private {!{ width: number, height: number }} */
    this.dimensions_;
    /** @private {number} */
    this.itemHeight_;
    /** @private {Corner} */
    this.anchorCorner_ = Corner.TOP_START;
    /** @private {AnchorMargin} */
    this.anchorMargin_ = {top: 0, right: 0, bottom: 0, left: 0};
    /** @private {?AutoLayoutMeasurements} */
    this.measures_ = null;
  }

  init() {
    const {ROOT, OPEN} = MDCSimpleMenuFoundation.cssClasses;

    if (!this.adapter_.hasClass(ROOT)) {
      throw new Error(`${ROOT} class required in root element.`);
    }

    if (!this.adapter_.hasNecessaryDom()) {
      throw new Error(`Required DOM nodes missing in ${ROOT} component.`);
    }

    if (this.adapter_.hasClass(OPEN)) {
      this.isOpen_ = true;
    }

    this.adapter_.registerInteractionHandler('click', this.clickHandler_);
    this.adapter_.registerInteractionHandler('keyup', this.keyupHandler_);
    this.adapter_.registerInteractionHandler('keydown', this.keydownHandler_);
  }

  destroy() {
    clearTimeout(this.selectedTriggerTimerId_);
    clearTimeout(this.openAnimationEndTimerId_);
    clearTimeout(this.closeAnimationEndTimerId_);
    // Cancel any currently running animations.
    cancelAnimationFrame(this.animationRequestId_);
    this.adapter_.deregisterInteractionHandler('click', this.clickHandler_);
    this.adapter_.deregisterInteractionHandler('keyup', this.keyupHandler_);
    this.adapter_.deregisterInteractionHandler('keydown', this.keydownHandler_);
    this.adapter_.deregisterBodyClickHandler(this.documentClickHandler_);
  }

  /**
   * @param {!Corner} corner Default anchor corner alignment of top-left menu corner.
   */
  setAnchorCorner(corner) {
    this.anchorCorner_ = corner;
  }

  /**
   * @param {!AnchorMargin} margin 4-plet of margins from anchor.
   */
  setAnchorMargin(margin) {
    this.anchorMargin_.top = typeof margin.top === 'number' ? margin.top : 0;
    this.anchorMargin_.right = typeof margin.right === 'number' ? margin.right : 0;
    this.anchorMargin_.bottom = typeof margin.bottom === 'number' ? margin.bottom : 0;
    this.anchorMargin_.left = typeof margin.left === 'number' ? margin.left : 0;
  }

  /**
   * @param {?number} focusIndex
   * @private
   */
  focusOnOpen_(focusIndex) {
    if (focusIndex === null) {
      // First, try focusing the menu.
      this.adapter_.focus();
      // If that doesn't work, focus first item instead.
      if (!this.adapter_.isFocused()) {
        this.adapter_.focusItemAtIndex(0);
      }
    } else {
      this.adapter_.focusItemAtIndex(focusIndex);
    }
  }

  /**
   * Handle clicks and cancel the menu if not a list item
   * @param {!Event} evt
   * @private
   */
  handleDocumentClick_(evt) {
    let el = evt.target;

    while (el && el !== document.documentElement) {
      if (this.adapter_.eventTargetHasClass(el, cssClasses.LIST_ITEM)) {
        return;
      }
      el = el.parentNode;
    }

    this.adapter_.notifyCancel();
    this.close(evt);
  };

  /**
   * Handle keys that we want to repeat on hold (tab and arrows).
   * @param {!Event} evt
   * @return {boolean}
   * @private
   */
  handleKeyboardDown_(evt) {
    // Do nothing if Alt, Ctrl or Meta are pressed.
    if (evt.altKey || evt.ctrlKey || evt.metaKey) {
      return true;
    }

    const {keyCode, key, shiftKey} = evt;
    const isTab = key === 'Tab' || keyCode === 9;
    const isArrowUp = key === 'ArrowUp' || keyCode === 38;
    const isArrowDown = key === 'ArrowDown' || keyCode === 40;
    const isSpace = key === 'Space' || keyCode === 32;

    const focusedItemIndex = this.adapter_.getFocusedItemIndex();
    const lastItemIndex = this.adapter_.getNumberOfItems() - 1;

    if (shiftKey && isTab && focusedItemIndex === 0) {
      this.adapter_.focusItemAtIndex(lastItemIndex);
      evt.preventDefault();
      return false;
    }

    if (!shiftKey && isTab && focusedItemIndex === lastItemIndex) {
      this.adapter_.focusItemAtIndex(0);
      evt.preventDefault();
      return false;
    }

    // Ensure Arrow{Up,Down} and space do not cause inadvertent scrolling
    if (isArrowUp || isArrowDown || isSpace) {
      evt.preventDefault();
    }

    if (isArrowUp) {
      if (focusedItemIndex === 0 || this.adapter_.isFocused()) {
        this.adapter_.focusItemAtIndex(lastItemIndex);
      } else {
        this.adapter_.focusItemAtIndex(focusedItemIndex - 1);
      }
    } else if (isArrowDown) {
      if (focusedItemIndex === lastItemIndex || this.adapter_.isFocused()) {
        this.adapter_.focusItemAtIndex(0);
      } else {
        this.adapter_.focusItemAtIndex(focusedItemIndex + 1);
      }
    }

    return true;
  }

  /**
   * Handle keys that we don't want to repeat on hold (Enter, Space, Escape).
   * @param {!Event} evt
   * @return {boolean}
   * @private
   */
  handleKeyboardUp_(evt) {
    // Do nothing if Alt, Ctrl or Meta are pressed.
    if (evt.altKey || evt.ctrlKey || evt.metaKey) {
      return true;
    }

    const {keyCode, key} = evt;
    const isEnter = key === 'Enter' || keyCode === 13;
    const isSpace = key === 'Space' || keyCode === 32;
    const isEscape = key === 'Escape' || keyCode === 27;

    if (isEnter || isSpace) {
      this.handlePossibleSelected_(evt);
    }

    if (isEscape) {
      this.adapter_.notifyCancel();
      this.close();
    }

    return true;
  }

  /**
   * @param {!Event} evt
   * @private
   */
  handlePossibleSelected_(evt) {
    if (this.adapter_.getAttributeForEventTarget(evt.target, strings.ARIA_DISABLED_ATTR) === 'true') {
      return;
    }
    const targetIndex = this.adapter_.getIndexForEventTarget(evt.target);
    if (targetIndex < 0) {
      return;
    }
    // Debounce multiple selections
    if (this.selectedTriggerTimerId_) {
      return;
    }
    this.selectedTriggerTimerId_ = setTimeout(() => {
      this.selectedTriggerTimerId_ = 0;
      this.close();
      this.adapter_.notifySelected({index: targetIndex});
    }, numbers.SELECTED_TRIGGER_DELAY);
  }

  /**
   * @return {AutoLayoutMeasurements} Measurements used to position menu popup.
   */
  getAutoLayoutMeasurements_() {
    const anchorRect = this.adapter_.getAnchorDimensions();
    const viewport = this.adapter_.getWindowDimensions();

    return {
      viewport: viewport,
      viewportDistance: {
        top: anchorRect.top,
        right: viewport.width - anchorRect.right,
        left: anchorRect.left,
        bottom: viewport.height - anchorRect.bottom,
      },
      anchorHeight: anchorRect.height,
      anchorWidth: anchorRect.width,
      menuHeight: this.dimensions_.height,
      menuWidth: this.dimensions_.width,
    };
  }

  /**
   * Computes the corner of the anchor from which to animate and position the menu.
   * @return {Corner}
   * @private
   */
  getOriginCorner_() {
    // Defaults: open from the top left.
    let corner = Corner.TOP_LEFT;

    const {viewportDistance, anchorHeight, anchorWidth, menuHeight, menuWidth} = this.measures_;
    const isBottomAligned = Boolean(this.anchorCorner_ & CornerBit.BOTTOM);
    const availableTop = isBottomAligned ? viewportDistance.top + anchorHeight + this.anchorMargin_.bottom
      : viewportDistance.top + this.anchorMargin_.top;
    const availableBottom = isBottomAligned ? viewportDistance.bottom - this.anchorMargin_.bottom
      : viewportDistance.bottom + anchorHeight - this.anchorMargin_.top;

    const topOverflow = menuHeight - availableTop;
    const bottomOverflow = menuHeight - availableBottom;
    if (bottomOverflow > 0 && topOverflow < bottomOverflow) {
      corner |= CornerBit.BOTTOM;
    }

    const isRtl = this.adapter_.isRtl();
    const isFlipRtl = Boolean(this.anchorCorner_ & CornerBit.FLIP_RTL);
    const avoidHorizontalOverlap = Boolean(this.anchorCorner_ & CornerBit.RIGHT);
    const isAlignedRight = (avoidHorizontalOverlap && !isRtl) ||
      (!avoidHorizontalOverlap && isFlipRtl && isRtl);
    const availableLeft = isAlignedRight ? viewportDistance.left + anchorWidth + this.anchorMargin_.right :
      viewportDistance.left + this.anchorMargin_.left;
    const availableRight = isAlignedRight ? viewportDistance.right - this.anchorMargin_.right :
      viewportDistance.right + anchorWidth - this.anchorMargin_.left;

    const leftOverflow = menuWidth - availableLeft;
    const rightOverflow = menuWidth - availableRight;

    if ((leftOverflow < 0 && isAlignedRight && isRtl) ||
        (avoidHorizontalOverlap && !isAlignedRight && leftOverflow < 0) ||
        (rightOverflow > 0 && leftOverflow < rightOverflow)) {
      corner |= CornerBit.RIGHT;
    }

    return corner;
  }

  /**
   * @param {Corner} corner Origin corner of the menu.
   * @return {number} Horizontal offset of menu origin corner from corresponding anchor corner.
   * @private
   */
  getHorizontalOriginOffset_(corner) {
    const {anchorWidth} = this.measures_;
    const isRightAligned = Boolean(corner & CornerBit.RIGHT);
    const avoidHorizontalOverlap = Boolean(this.anchorCorner_ & CornerBit.RIGHT);
    let x = 0;
    if (isRightAligned) {
      const rightOffset = avoidHorizontalOverlap ? anchorWidth - this.anchorMargin_.left : this.anchorMargin_.right;
      x = rightOffset;
    } else {
      const leftOffset = avoidHorizontalOverlap ? anchorWidth - this.anchorMargin_.right : this.anchorMargin_.left;
      x = leftOffset;
    }
    return x;
  }

  /**
   * @param {Corner} corner Origin corner of the menu.
   * @return {number} Vertical offset of menu origin corner from corresponding anchor corner.
   * @private
   */
  getVerticalOriginOffset_(corner) {
    const {viewport, viewportDistance, anchorHeight, menuHeight} = this.measures_;
    const isBottomAligned = Boolean(corner & CornerBit.BOTTOM);
    const {MARGIN_TO_EDGE} = MDCSimpleMenuFoundation.numbers;
    const avoidVerticalOverlap = Boolean(this.anchorCorner_ & CornerBit.BOTTOM);
    const canOverlapVertically = !avoidVerticalOverlap;
    let y = 0;

    if (isBottomAligned) {
      y = avoidVerticalOverlap ? anchorHeight - this.anchorMargin_.top : -this.anchorMargin_.bottom;
      // adjust for when menu can overlap anchor, but too tall to be aligned to bottom
      // anchor corner. Bottom margin is ignored in such cases.
      if (canOverlapVertically && menuHeight > viewportDistance.top + anchorHeight) {
        y = -(Math.min(menuHeight, viewport.height - MARGIN_TO_EDGE) - (viewportDistance.top + anchorHeight));
      }
    } else {
      y = avoidVerticalOverlap ? (anchorHeight + this.anchorMargin_.bottom) : this.anchorMargin_.top;
      // adjust for when menu can overlap anchor, but too tall to be aligned to top
      // anchor corners. Top margin is ignored in that case.
      if (canOverlapVertically && menuHeight > viewportDistance.bottom + anchorHeight) {
        y = -(Math.min(menuHeight, viewport.height - MARGIN_TO_EDGE) - (viewportDistance.bottom + anchorHeight));
      }
    }
    return y;
  }

  /**
   * @param {Corner} corner Origin corner of the menu.
   * @return {number} Maximum height of the menu, based on available space. 0 indicates should not be set.
   * @private
   */
  getMenuMaxHeight_(corner) {
    let maxHeight = 0;
    const {viewportDistance} = this.measures_;
    const isBottomAligned = Boolean(corner & CornerBit.BOTTOM);

    // When maximum height is not specified, it is handled from css.
    if (this.anchorCorner_ & CornerBit.BOTTOM) {
      if (isBottomAligned) {
        maxHeight = viewportDistance.top + this.anchorMargin_.top;
      } else {
        maxHeight = viewportDistance.bottom - this.anchorMargin_.bottom;
      }
    }

    return maxHeight;
  }

  /** @private */
  autoPosition_() {
    if (!this.adapter_.hasAnchor()) {
      return;
    }

    // Compute measurements for autoposition methods reuse.
    this.measures_ = this.getAutoLayoutMeasurements_();

    const corner = this.getOriginCorner_();
    const maxMenuHeight = this.getMenuMaxHeight_(corner);
    let verticalAlignment = (corner & CornerBit.BOTTOM) ? 'bottom' : 'top';
    let horizontalAlignment = (corner & CornerBit.RIGHT) ? 'right' : 'left';
    const horizontalOffset = this.getHorizontalOriginOffset_(corner);
    const verticalOffset = this.getVerticalOriginOffset_(corner);
    const position = {
      [horizontalAlignment]: horizontalOffset ? horizontalOffset + 'px' : '0',
      [verticalAlignment]: verticalOffset ? verticalOffset + 'px' : '0',
    };
    const {anchorWidth, menuHeight, menuWidth} = this.measures_;
    // Center align when anchor width is comparable or greater than menu, otherwise keep corner.
    if (anchorWidth / menuWidth > numbers.ANCHOR_TO_MENU_WIDTH_RATIO) {
      horizontalAlignment = 'center';
    }

    // Adjust vertical origin when menu is positioned with significant offset from anchor. This is done so that
    // scale animation is "anchored" on the anchor.
    if (!(this.anchorCorner_ & CornerBit.BOTTOM) &&
        Math.abs(verticalOffset / menuHeight) > numbers.OFFSET_TO_MENU_HEIGHT_RATIO) {
      const verticalOffsetPercent = Math.abs(verticalOffset / menuHeight) * 100;
      const originPercent = (corner & CornerBit.BOTTOM) ? 100 - verticalOffsetPercent : verticalOffsetPercent;
      verticalAlignment = Math.round(originPercent * 100) / 100 + '%';
    }

    this.adapter_.setTransformOrigin(`${horizontalAlignment} ${verticalAlignment}`);
    this.adapter_.setPosition(position);
    this.adapter_.setMaxHeight(maxMenuHeight ? maxMenuHeight + 'px' : '');

    // Clear measures after positioning is complete.
    this.measures_ = null;
  }

  /**
   * Open the menu.
   * @param {{focusIndex: ?number}=} options
   */
  open({focusIndex = null} = {}) {
    this.adapter_.saveFocus();
    this.adapter_.addClass(MDCSimpleMenuFoundation.cssClasses.ANIMATING_OPEN);

    this.animationRequestId_ = requestAnimationFrame(() => {
      this.dimensions_ = this.adapter_.getInnerDimensions();
      this.autoPosition_();
      this.adapter_.addClass(MDCSimpleMenuFoundation.cssClasses.OPEN);
      this.focusOnOpen_(focusIndex);
      this.adapter_.registerBodyClickHandler(this.documentClickHandler_);
      this.openAnimationEndTimerId_ = setTimeout(() => {
        this.openAnimationEndTimerId_ = 0;
        this.adapter_.removeClass(MDCSimpleMenuFoundation.cssClasses.ANIMATING_OPEN);
      }, numbers.TRANSITION_OPEN_DURATION);
    });
    this.isOpen_ = true;
  }

  /**
   * Closes the menu.
   * @param {Event=} evt
   */
  close(evt = null) {
    const targetIsDisabled = evt ?
      this.adapter_.getAttributeForEventTarget(evt.target, strings.ARIA_DISABLED_ATTR) === 'true' :
      false;

    if (targetIsDisabled) {
      return;
    }

    this.adapter_.deregisterBodyClickHandler(this.documentClickHandler_);
    this.adapter_.addClass(MDCSimpleMenuFoundation.cssClasses.ANIMATING_CLOSED);
    requestAnimationFrame(() => {
      this.adapter_.removeClass(MDCSimpleMenuFoundation.cssClasses.OPEN);
      this.closeAnimationEndTimerId_ = setTimeout(() => {
        this.closeAnimationEndTimerId_ = 0;
        this.adapter_.removeClass(MDCSimpleMenuFoundation.cssClasses.ANIMATING_CLOSED);
      }, numbers.TRANSITION_CLOSE_DURATION);
    });
    this.isOpen_ = false;
    this.adapter_.restoreFocus();
  }

  /** @return {boolean} */
  isOpen() {
    return this.isOpen_;
  }
}

export {MDCSimpleMenuFoundation, AnchorMargin};


text:
package facade_test

import (
	datastoremocks "github.com/control-center/serviced/datastore/mocks"
	dfsmocks "github.com/control-center/serviced/dfs/mocks"
	hostmocks "github.com/control-center/serviced/domain/host/mocks"
	poolmocks "github.com/control-center/serviced/domain/pool/mocks"
	registrymocks "github.com/control-center/serviced/domain/registry/mocks"
	servicemocks "github.com/control-center/serviced/domain/service/mocks"
	templatemocks "github.com/control-center/serviced/domain/servicetemplate/mocks"
	zzkmocks "github.com/control-center/serviced/facade/mocks"
	"github.com/control-center/serviced/facade"
	"github.com/stretchr/testify/mock"
	. "gopkg.in/check.v1"
)

var _ = Suite(&FacadeUnitTest{})

type FacadeUnitTest struct {
	Facade        *facade.Facade
	ctx           *datastoremocks.Context
	zzk           *zzkmocks.ZZK
	dfs           *dfsmocks.DFS
	hostStore     *hostmocks.Store
	poolStore     *poolmocks.Store
	registryStore *registrymocks.ImageRegistryStore
	serviceStore  *servicemocks.Store
	templateStore *templatemocks.Store
}

func (ft *FacadeUnitTest) SetUpSuite(c *C) {
	ft.Facade = facade.New()
}

func (ft *FacadeUnitTest) SetUpTest(c *C) {
	ft.ctx = &datastoremocks.Context{}

	ft.dfs = &dfsmocks.DFS{}
	ft.Facade.SetDFS(ft.dfs)

	ft.hostStore = &hostmocks.Store{}
	ft.Facade.SetHostStore(ft.hostStore)

	ft.poolStore = &poolmocks.Store{}
	ft.Facade.SetPoolStore(ft.poolStore)

	ft.registryStore = &registrymocks.ImageRegistryStore{}
	ft.Facade.SetRegistryStore(ft.registryStore)

	ft.serviceStore = &servicemocks.Store{}
	ft.Facade.SetServiceStore(ft.serviceStore)

	ft.templateStore = &templatemocks.Store{}
	ft.Facade.SetTemplateStore(ft.templateStore)

	ft.zzk = &zzkmocks.ZZK{}
	ft.Facade.SetZZK(ft.zzk)
}

// Mock all DFS locking operations into no-ops
func (ft *FacadeUnitTest) setupMockDFSLocking() {
	ft.dfs.On("Lock", mock.AnythingOfType("string")).Return()
	ft.dfs.On("LockWithTimeout", mock.AnythingOfType("string"), mock.AnythingOfType("time.Duration")).Return(nil)
	ft.dfs.On("Unlock").Return()
}


text:
/**
 * @since 2021-03-31 17:23
 * @author vivaxy
 */
document.addEventListener('selectionchange', function () {
  const selection = window.getSelection();
  const range = selection.getRangeAt(0);
  const {
    collapsed,
    commonAncestorContainer,
    startContainer,
    startOffset,
    endContainer,
    endOffset,
  } = range;
  console.log([
    collapsed,
    commonAncestorContainer,
    startContainer,
    startOffset,
    endContainer,
    endOffset,
  ]);
});


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

<title>Uses of Interface net.sf.jasperreports.engine.JRLineBox (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
net.sf.jasperreports.engine.JRLineBox

Packages that use JRLineBox

Package
Description

net.sf.jasperreports.components.iconlabel

Contains classes for the built-in Icon Label component.

net.sf.jasperreports.components.table

Contains classes for the built-in Table component.

net.sf.jasperreports.crosstabs.base

Contains base classes for the Crosstab report element.

net.sf.jasperreports.crosstabs.design

Contains design classes for the Crosstab report element.

net.sf.jasperreports.engine

Provides access to the library's main functionality through facade classes for compiling, filling
 and exporting reports and also publishes the library's main interfaces and classes.

net.sf.jasperreports.engine.base

Contains base implementations for the library's main interfaces.

net.sf.jasperreports.engine.design

Contains design time implementations for the library's main interfaces as well as report compiling tools.

net.sf.jasperreports.engine.export

Provides utility classes for exporting reports to various popular formats such as
 PDF, HTML, RTF, CSV, Excel, DOCX, PPTX, ODT, ODS, XML, Text, etc.

net.sf.jasperreports.engine.export.draw

Contains classes for drawing elements at export time.

net.sf.jasperreports.engine.export.oasis

Provides utility classes for exporting reports to Open Document Format, such as
 ODT and ODS.

net.sf.jasperreports.engine.export.ooxml

Provides utility classes for exporting reports to Office Open XML Format, such as
 DOCX, XLSX and PPTX.

net.sf.jasperreports.engine.export.tabulator

net.sf.jasperreports.engine.fill

Contains fill time implementations for the library's main interfaces and the entire
 engine used in the filling process (the actual core of JasperReports).

net.sf.jasperreports.engine.util

Contains utility classes for the core library.

net.sf.jasperreports.engine.xml

Contains classes for loading report templates from XML files.

Uses of JRLineBox in net.sf.jasperreports.components.iconlabel

Methods in net.sf.jasperreports.components.iconlabel that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
IconLabelComponent.getLineBox()

JRLineBox
IconLabelComponentFill.getLineBox()

Methods in net.sf.jasperreports.components.iconlabel with parameters of type JRLineBox

Modifier and Type
Method and Description

void
IconLabelComponent.setLineBox(JRLineBox lineBox)

Uses of JRLineBox in net.sf.jasperreports.components.table

Methods in net.sf.jasperreports.components.table that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
CompiledCell.getLineBox()

JRLineBox
DesignCell.getLineBox()

Uses of JRLineBox in net.sf.jasperreports.crosstabs.base

Fields in net.sf.jasperreports.crosstabs.base declared as JRLineBox

Modifier and Type
Field and Description

protected JRLineBox
JRBaseCellContents.lineBox

protected JRLineBox
JRBaseCrosstab.lineBox

Methods in net.sf.jasperreports.crosstabs.base that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
JRBaseCellContents.getLineBox()

JRLineBox
JRBaseCrosstab.getLineBox()

Uses of JRLineBox in net.sf.jasperreports.crosstabs.design

Fields in net.sf.jasperreports.crosstabs.design declared as JRLineBox

Modifier and Type
Field and Description

protected JRLineBox
JRDesignCrosstab.lineBox

Methods in net.sf.jasperreports.crosstabs.design that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
JRDesignCellContents.getLineBox()

JRLineBox
JRDesignCrosstab.getLineBox()

Uses of JRLineBox in net.sf.jasperreports.engine

Methods in net.sf.jasperreports.engine that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
JRLineBox.clone(JRBoxContainer boxContainer)

JRLineBox
JRBoxContainer.getLineBox()

JRLineBox
JRStyle.getLineBox()

Methods in net.sf.jasperreports.engine with parameters of type JRLineBox

Modifier and Type
Method and Description

JRPen
JRBoxPenProvider.getPen(JRLineBox box)

Gets the pen object.

Uses of JRLineBox in net.sf.jasperreports.engine.base

Classes in net.sf.jasperreports.engine.base that implement JRLineBox

Modifier and Type
Class and Description

class
JRBaseLineBox

This is useful for drawing borders around text elements and images.

Fields in net.sf.jasperreports.engine.base declared as JRLineBox

Modifier and Type
Field and Description

protected JRLineBox
JRBaseBoxPen.lineBox

protected JRLineBox
JRBaseTextElement.lineBox

protected JRLineBox
JRBaseChart.lineBox

protected JRLineBox
JRBaseFrame.lineBox

protected JRLineBox
JRBasePrintText.lineBox

protected JRLineBox
JRBaseImage.lineBox

protected JRLineBox
JRBaseStyle.lineBox

protected JRLineBox
JRBaseBox.lineBox

Deprecated.

protected JRLineBox
JRBasePrintImage.lineBox

Methods in net.sf.jasperreports.engine.base that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
JRBaseLineBox.clone(JRBoxContainer boxContainer)

JRLineBox
JRBaseBoxPen.getBox()

JRLineBox
JRBoxPen.getBox()

JRLineBox
JRBaseTextElement.getLineBox()

JRLineBox
JRBaseChart.getLineBox()

JRLineBox
JRBasePrintFrame.getLineBox()

JRLineBox
JRBaseFrame.getLineBox()

JRLineBox
JRBasePrintText.getLineBox()

JRLineBox
JRBaseImage.getLineBox()

JRLineBox
JRBaseStyle.getLineBox()

JRLineBox
JRBasePrintImage.getLineBox()

Methods in net.sf.jasperreports.engine.base with parameters of type JRLineBox

Modifier and Type
Method and Description

JRBoxPen
JRBaseBoxPen.clone(JRLineBox lineBox)

JRBoxPen
JRBoxPen.clone(JRLineBox lineBox)

void
JRBasePrintFrame.copyBox(JRLineBox lineBox)

void
JRBasePrintText.copyBox(JRLineBox lineBox)

void
JRBasePrintImage.copyBox(JRLineBox lineBox)

JRPen
JRBaseBoxPen.getPen(JRLineBox box)

JRPen
JRBaseBoxBottomPen.getPen(JRLineBox box)

JRPen
JRBaseBoxLeftPen.getPen(JRLineBox box)

JRPen
JRBaseBoxRightPen.getPen(JRLineBox box)

JRPen
JRBaseBoxTopPen.getPen(JRLineBox box)

JRPen
JRBoxPen.getPen(JRLineBox box)

Constructors in net.sf.jasperreports.engine.base with parameters of type JRLineBox

Constructor and Description

JRBaseBoxBottomPen(JRLineBox box)

JRBaseBoxLeftPen(JRLineBox box)

JRBaseBoxPen(JRLineBox box)

JRBaseBoxRightPen(JRLineBox box)

JRBaseBoxTopPen(JRLineBox box)

Uses of JRLineBox in net.sf.jasperreports.engine.design

Fields in net.sf.jasperreports.engine.design declared as JRLineBox

Modifier and Type
Field and Description

protected JRLineBox
JRDesignTextElement.lineBox

protected JRLineBox
JRDesignChart.lineBox

protected JRLineBox
JRDesignImage.lineBox

Methods in net.sf.jasperreports.engine.design that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
JRDesignTextElement.getLineBox()

JRLineBox
JRDesignChart.getLineBox()

JRLineBox
JRDesignImage.getLineBox()

JRLineBox
JRDesignFrame.getLineBox()

Methods in net.sf.jasperreports.engine.design with parameters of type JRLineBox

Modifier and Type
Method and Description

void
JRDesignFrame.copyBox(JRLineBox lineBox)

Uses of JRLineBox in net.sf.jasperreports.engine.export

Methods in net.sf.jasperreports.engine.export that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
GridCellStyle.getBox()

JRLineBox
JRExporterGridCell.getBox()

Methods in net.sf.jasperreports.engine.export with parameters of type JRLineBox

Modifier and Type
Method and Description

protected boolean
JRXhtmlExporter.appendBorderStyle(JRLineBox box,
                 java.lang.StringBuffer styleBuffer)

Deprecated.

protected boolean
JRHtmlExporter.appendBorderStyle(JRLineBox box,
                 java.lang.StringBuffer styleBuffer)

Deprecated.

protected boolean
HtmlExporter.appendBorderStyle(JRLineBox box,
                 java.lang.StringBuilder styleBuffer)

protected boolean
JRHtmlExporter.appendPaddingStyle(JRLineBox box,
                  java.lang.StringBuffer styleBuffer)

Deprecated.

protected boolean
HtmlExporter.appendPaddingStyle(JRLineBox box,
                  java.lang.StringBuilder styleBuffer)

protected GridCellStyle
JRGridLayout.cellStyle(java.awt.Color backcolor,
         java.awt.Color forecolor,
         JRLineBox box)

protected void
JRPdfExporter.exportBox(JRLineBox box,
         JRPrintElement element)

void
JRXlsMetadataExporter.BoxStyle.setBox(JRLineBox box)

void
ElementReplacementGridCell.setBox(JRLineBox box)

void
JExcelApiMetadataExporter.BoxStyle.setBox(JRLineBox box)

void
JExcelApiExporter.BoxStyle.setBox(JRLineBox box)

void
JRExporterGridCell.setBox(JRLineBox box)

void
ElementGridCell.setBox(JRLineBox box)

Constructors in net.sf.jasperreports.engine.export with parameters of type JRLineBox

Constructor and Description

GridCellStyle(java.awt.Color backcolor,
             java.awt.Color forecolor,
             JRLineBox box)

Uses of JRLineBox in net.sf.jasperreports.engine.export.draw

Methods in net.sf.jasperreports.engine.export.draw with parameters of type JRLineBox

Modifier and Type
Method and Description

protected void
ElementDrawer.drawBox(java.awt.Graphics2D grx,
       JRLineBox box,
       JRPrintElement element,
       int offsetX,
       int offsetY)

Uses of JRLineBox in net.sf.jasperreports.engine.export.oasis

Methods in net.sf.jasperreports.engine.export.oasis with parameters of type JRLineBox

Modifier and Type
Method and Description

void
BorderStyle.setBox(JRLineBox box)

Uses of JRLineBox in net.sf.jasperreports.engine.export.ooxml

Methods in net.sf.jasperreports.engine.export.ooxml with parameters of type JRLineBox

Modifier and Type
Method and Description

void
DocxBorderHelper.export(JRLineBox box)

void
XlsxBorderHelper.export(JRLineBox box)

Constructors in net.sf.jasperreports.engine.export.ooxml with parameters of type JRLineBox

Constructor and Description

DocxBorderInfo(JRLineBox box)

XlsxBorderInfo(JRLineBox box)

Uses of JRLineBox in net.sf.jasperreports.engine.export.tabulator

Methods in net.sf.jasperreports.engine.export.tabulator that return JRLineBox

Modifier and Type
Method and Description

protected JRLineBox
Tabulator.TableCellCreator.copyFrameBox(FrameCell frameCell,
            JRPrintFrame frame,
            JRLineBox baseBox,
            boolean keepLeft,
            boolean keepRight,
            boolean keepTop,
            boolean keepBottom)

protected JRLineBox
Tabulator.TableCellCreator.copyParentBox(Cell cell,
             JRPrintElement element,
             JRLineBox baseBox,
             boolean keepLeft,
             boolean keepRight,
             boolean keepTop,
             boolean keepBottom)

JRLineBox
TableCell.getBox()

Methods in net.sf.jasperreports.engine.export.tabulator with parameters of type JRLineBox

Modifier and Type
Method and Description

protected JRLineBox
Tabulator.TableCellCreator.copyFrameBox(FrameCell frameCell,
            JRPrintFrame frame,
            JRLineBox baseBox,
            boolean keepLeft,
            boolean keepRight,
            boolean keepTop,
            boolean keepBottom)

protected JRLineBox
Tabulator.TableCellCreator.copyParentBox(Cell cell,
             JRPrintElement element,
             JRLineBox baseBox,
             boolean keepLeft,
             boolean keepRight,
             boolean keepTop,
             boolean keepBottom)

void
TableCell.setBox(JRLineBox box)

Constructors in net.sf.jasperreports.engine.export.tabulator with parameters of type JRLineBox

Constructor and Description

TableCell(Tabulator tabulator,
         TablePosition position,
         Cell cell,
         JRPrintElement element,
         int colSpan,
         int rowSpan,
         java.awt.Color backcolor,
         JRLineBox box)

Uses of JRLineBox in net.sf.jasperreports.engine.fill

Classes in net.sf.jasperreports.engine.fill that implement JRLineBox

Modifier and Type
Class and Description

class
CachingLineBox

Fields in net.sf.jasperreports.engine.fill declared as JRLineBox

Modifier and Type
Field and Description

protected JRLineBox
JRFillTextElement.initLineBox

protected JRLineBox
JRFillChart.initLineBox

protected JRLineBox
JRFillImage.initLineBox

protected JRLineBox
JRFillTextElement.lineBox

protected JRLineBox
JRFillFrame.lineBox

protected JRLineBox
JRFillChart.lineBox

protected JRLineBox
JRFillImage.lineBox

protected JRLineBox
JRTemplateText.lineBox

protected JRLineBox
JRTemplateFrame.lineBox

protected JRLineBox
JRFillCrosstab.lineBox

Methods in net.sf.jasperreports.engine.fill that return JRLineBox

Modifier and Type
Method and Description

JRLineBox
CachingLineBox.clone(JRBoxContainer boxContainer)

JRLineBox
JRTemplatePrintFrame.getLineBox()

JRLineBox
JRFillTextElement.getLineBox()

JRLineBox
JRFillFrame.getLineBox()

JRLineBox
JRFillChart.getLineBox()

JRLineBox
JRTemplatePrintText.getLineBox()

JRLineBox
JRFillCellContents.getLineBox()

JRLineBox
JRTemplateImage.getLineBox()

JRLineBox
JRFillImage.getLineBox()

JRLineBox
JRTemplateText.getLineBox()

JRLineBox
JRTemplateFrame.getLineBox()

JRLineBox
JRFillCrosstab.getLineBox()

JRLineBox
JRTemplatePrintImage.getLineBox()

protected JRLineBox
JRFillTextElement.getPrintLineBox()

Methods in net.sf.jasperreports.engine.fill with parameters of type JRLineBox

Modifier and Type
Method and Description

void
JRTemplateFrame.copyBox(JRLineBox lineBox)

void
JRTemplateImage.copyLineBox(JRLineBox box)

Copies box attributes.

void
JRTemplateText.copyLineBox(JRLineBox box)

Copies box attributes.

protected void
JRFillCellContents.setBox(JRLineBox box)

Constructors in net.sf.jasperreports.engine.fill with parameters of type JRLineBox

Constructor and Description

CachingLineBox(JRLineBox base)

Uses of JRLineBox in net.sf.jasperreports.engine.util

Methods in net.sf.jasperreports.engine.util that return JRLineBox

Modifier and Type
Method and Description

static JRLineBox
JRBoxUtil.copyBordersNoPadding(JRLineBox box,
                    boolean keepLeft,
                    boolean keepRight,
                    boolean keepTop,
                    boolean keepBottom,
                    JRLineBox complementaryBox)

Methods in net.sf.jasperreports.engine.util with parameters of type JRLineBox

Modifier and Type
Method and Description

static void
JRStyleResolver.appendBox(JRLineBox destBox,
         JRLineBox srcBox)

Merges two boxes, by appending the properties of the source box to the ones of the destination box.

static void
JRBoxUtil.copy(JRLineBox source,
    JRLineBox dest)

static JRLineBox
JRBoxUtil.copyBordersNoPadding(JRLineBox box,
                    boolean keepLeft,
                    boolean keepRight,
                    boolean keepTop,
                    boolean keepBottom,
                    JRLineBox complementaryBox)

static void
JRBoxUtil.eraseBox(JRLineBox box)

static java.lang.Integer
JRStyleResolver.getBottomPadding(JRLineBox box)

static java.lang.Integer
JRStyleResolver.getLeftPadding(JRLineBox box)

static java.lang.Integer
JRStyleResolver.getPadding(JRLineBox box)

static java.lang.Integer
JRStyleResolver.getRightPadding(JRLineBox box)

static java.lang.Integer
JRStyleResolver.getTopPadding(JRLineBox box)

static void
JRBoxUtil.reset(JRLineBox box,
     boolean resetLeft,
     boolean resetRight,
     boolean resetTop,
     boolean resetBottom)

static void
JRBoxUtil.rotate(JRLineBox box,
      RotationEnum rotation)

static void
JRBoxUtil.setBoxToLineBox(JRBox box,
               JRLineBox lineBox)

static void
JRBoxUtil.setToBox(java.lang.Byte border,
        java.lang.Byte topBorder,
        java.lang.Byte leftBorder,
        java.lang.Byte bottomBorder,
        java.lang.Byte rightBorder,
        java.awt.Color borderColor,
        java.awt.Color topBorderColor,
        java.awt.Color leftBorderColor,
        java.awt.Color bottomBorderColor,
        java.awt.Color rightBorderColor,
        java.lang.Integer padding,
        java.lang.Integer topPadding,
        java.lang.Integer leftPadding,
        java.lang.Integer bottomPadding,
        java.lang.Integer rightPadding,
        JRLineBox box)

protected void
JRApiWriter.writeBox(JRLineBox box,
        java.lang.String boxHolder)

Uses of JRLineBox in net.sf.jasperreports.engine.xml

Methods in net.sf.jasperreports.engine.xml with parameters of type JRLineBox

Modifier and Type
Method and Description

static void
JRBoxFactory.setBoxAttributes(org.xml.sax.Attributes atts,
                JRLineBox box)

void
JRXmlBaseWriter.writeBox(JRLineBox box)

void
JRXmlBaseWriter.writeBox(JRLineBox box,
        XmlNamespace namespace)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
from __future__ import unicode_literals

import django.db.models.deletion
import modelcluster.fields
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtailembeds.blocks
import wagtail.wagtailimages.blocks
from django.db import migrations, models

import greyjay.articles.fields

class Migration(migrations.Migration):

    dependencies = [
        ('wagtailimages', '0006_add_verbose_names'),
        ('wagtailcore', '0001_squashed_0016_change_page_url_path_to_text_field'),
    ]

    operations = [
        migrations.CreateModel(
            name='ArticleAuthorLink',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('sort_order', models.IntegerField(null=True, editable=False, blank=True)),
            ],
            options={
                'ordering': ['sort_order'],
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='ArticleListPage',
            fields=[
                ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
            ],
            options={
                'abstract': False,
            },
            bases=('wagtailcore.page',),
        ),
        migrations.CreateModel(
            name='ArticlePage',
            fields=[
                ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
                ('subtitle', wagtail.wagtailcore.fields.RichTextField(default='', blank=True)),
                ('body', greyjay.articles.fields.BodyField([('Heading', wagtail.wagtailcore.blocks.CharBlock(classname='heading', icon='title')), ('Paragraph', wagtail.wagtailcore.blocks.RichTextBlock(icon='doc-full')), ('Image', wagtail.wagtailimages.blocks.ImageChooserBlock(icon='image')), ('Embed', wagtail.wagtailembeds.blocks.EmbedBlock(icon='site')), ('List', wagtail.wagtailcore.blocks.ListBlock(wagtail.wagtailcore.blocks.RichTextBlock(label='item'), icon='list-ul')), ('Sharable', greyjay.articles.fields.SharableBlock())])),
                ('excerpt', wagtail.wagtailcore.fields.RichTextField(default='', blank=True)),
                ('main_image', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True)),
            ],
            options={
                'abstract': False,
            },
            bases=('wagtailcore.page',),
        ),
        migrations.CreateModel(
            name='ArticleTopicLink',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('article', modelcluster.fields.ParentalKey(related_name='topic_links', to='articles.ArticlePage')),
            ],
        ),
        migrations.CreateModel(
            name='SeriesArticleLink',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('sort_order', models.IntegerField(null=True, editable=False, blank=True)),
                ('override_text', wagtail.wagtailcore.fields.RichTextField(default='', help_text='This field is optional. If not provided, the text will be pulled from the article page automatically. This field allows you to override the automatic text.', blank=True)),
                ('article', models.ForeignKey(related_name='series_links', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='articles.ArticlePage', null=True)),
            ],
            options={
                'ordering': ['sort_order'],
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SeriesListPage',
            fields=[
                ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
            ],
            options={
                'abstract': False,
            },
            bases=('wagtailcore.page',),
        ),
        migrations.CreateModel(
            name='SeriesPage',
            fields=[
                ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
                ('body', greyjay.articles.fields.BodyField([('Heading', wagtail.wagtailcore.blocks.CharBlock(classname='heading', icon='title')), ('Paragraph', wagtail.wagtailcore.blocks.RichTextBlock(icon='doc-full')), ('Image', wagtail.wagtailimages.blocks.ImageChooserBlock(icon='image')), ('Embed', wagtail.wagtailembeds.blocks.EmbedBlock(icon='site')), ('List', wagtail.wagtailcore.blocks.ListBlock(wagtail.wagtailcore.blocks.RichTextBlock(label='item'), icon='list-ul')), ('Sharable', greyjay.articles.fields.SharableBlock())], default='', blank=True)),
                ('image', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True)),
            ],
            options={
                'abstract': False,
            },
            bases=('wagtailcore.page',),
        ),
        migrations.CreateModel(
            name='Topic',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=1024)),
            ],
        ),
        migrations.AddField(
            model_name='seriespage',
            name='primary_topic',
            field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='articles.Topic', null=True),
        ),
        migrations.AddField(
            model_name='seriesarticlelink',
            name='series',
            field=modelcluster.fields.ParentalKey(related_name='related_article_links', to='articles.SeriesPage'),
        ),
        migrations.AddField(
            model_name='seriesarticlelink',
            name='override_image',
            field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', help_text='This field is optional. If not provided, the image will be pulled from the article page automatically. This field allows you to override the automatic image.', null=True),
        ),
        migrations.AddField(
            model_name='articletopiclink',
            name='topic',
            field=models.ForeignKey(related_name='article_links', to='articles.Topic'),
        ),
        migrations.AddField(
            model_name='articlepage',
            name='primary_topic',
            field=models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='articles.Topic', null=True),
        ),
        migrations.AddField(
            model_name='articleauthorlink',
            name='article',
            field=modelcluster.fields.ParentalKey(related_name='author_links', to='articles.ArticlePage'),
        ),
    ]


text:
package io.fabric8.forge.camel.java;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;

public class SimpleProcessorTest extends CamelTestSupport {

    public void testProcess() throws Exception {
        String out = template.requestBody("direct:start", "Hello World", String.class);
        assertEquals("Bye World", out);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        exchange.getOut().setBody("Bye World");
                    }
                });
            }
        };
    }

}


text:
(function () {
    'use strict';

    angular.module('eHA.authentication')
    .controller('LoginCtrl', ['$location', '$scope', 'Authentication', function($location, $scope, Authentication) {
        var mv = this;

        vm.login = login;

        function login() {
            Authentication.login(vm.email, vm.password);
        }

    }]);

})();


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

/*
Package cgo contains runtime support for code generated
by the cgo tool.  See the documentation for the cgo command
for details on using cgo.
*/
package cgo

/*

#cgo darwin LDFLAGS: -lpthread
#cgo dragonfly LDFLAGS: -lpthread
#cgo freebsd LDFLAGS: -lpthread
#cgo linux LDFLAGS: -lpthread
#cgo akaros LDFLAGS: -lpthread
#cgo netbsd LDFLAGS: -lpthread
#cgo openbsd LDFLAGS: -lpthread
#cgo windows LDFLAGS: -lm -mthreads

#cgo CFLAGS: -Wall -Werror

*/
import "C"

// Supports _cgo_panic by converting a string constant to an empty
// interface.

func cgoStringToEface(s string, ret *interface{}) {
	*ret = s
}


text:
require "redis"

post '/api/login/:uid/:name' do
    uid = params[:uid]
    name = params[:name]
    avatar=params[:avatar]
    type=params[:account_type]
    db_user=User.where(:Id=>uid).first
    unless db_user
        db_user=User.new
        db_user.Id=uid
        db_user.Name=name
        db_user.AvatarURL=avatar
        db_user.Type=type
        db_user.save
    end
    session[:current_user]=db_user
    return db_user.to_json
end

get '/api/:provider/callback' do
	if params[:provider]=='weibo'
		code=params[:code]
	        client = Weibo2::Client.from_code(code)
        	uid=client.token.params["uid"]
        	db_user=User.where(:Id=>uid).first
        	unless db_user
                	user=JSON.parse(client.users.show({:uid=>uid}).body)
                	db_user=User.new
                	db_user.Id=uid
                	db_user.Name=user["name"]
                	db_user.AvatarURL=user["profile_image_url"]
                	db_user.Type="weibo"
                        db_user.save
       		end
	else
        	data=request.env['omniauth.auth'].to_hash
        	uid=data["uid"]
        	db_user=User.where(:Id=>uid).first
        	unless db_user
        	        db_user=User.new
        	        db_user.Id=uid
               		db_user.Name=data["info"]["name"]
                	db_user.Email=data["info"]["email"]
                	db_user.AvatarURL=data["info"]["image"]
                        db_user.Type="google"
                	db_user.save
        	end
	end
        session[:current_user]=db_user
        return db_user.Id
end

get '/api/block/:id' do
	id=params[:id][1..-1]
	block=Block.where(:Id=>id).first
	block.to_json
end

get '/api/article/:id' do
	unless session[:current_user]
		nologin_user=User.new
		session[:current_user]=nologin_user
	end
	id=params[:id]
	main_block=Block.where(:Id=>id).first
	muid=main_block.AuthorId
	article={:main_block=>main_block,:tags=>[],:sub_blocks=>[],:left_blocks=>{},:right_blocks=>{},:users=>{muid=>user_avatar(muid)}}
	BlockTag.where(:BlockId=>main_block.Id).all.each do |bt|
		article[:tags]<<Tag.where(:Id=>bt.TagId).first
	end
	article[:left_blocks][id]=[]
	BlockLink.where(:RightId=>id).all.sort(Order: -1,Created_on: -1).each do |link|
		left_block=Block.where(:Id=>link.LeftId).first
		if (left_block.Type=="clone" and left_block.AuthorId==session[:current_user].Id) or left_block.Type!="clone"
			left_block.Type=link.Type
			article[:left_blocks][id]<<left_block
			article[:users][left_block.AuthorId]=user_avatar(left_block.AuthorId)
		end
	end
	article[:right_blocks][id]=[]
	BlockLink.where(:LeftId=>id).all.sort(Order: -1,Created_on: -1).each do |link|
		right_block=Block.where(:Id=>link.RightId).first
		if (right_block.Type=="clone" and right_block.AuthorId==session[:current_user].Id) or right_block.Type!="clone"
			right_block.Type=link.Type
			article[:right_blocks][id]<<right_block
			article[:users][right_block.AuthorId]=user_avatar(right_block.AuthorId)
		end
	end
	Block.where(:ParentId=>id).all.sort(Order: 1).each do |block|
		article[:sub_blocks]<<block
		article[:left_blocks][block.Id]=[]
		BlockLink.where(:RightId=>block.Id).all.sort(Order: -1,Created_on: -1).each do |link|
			left_block=Block.where(:Id=>link.LeftId).first
			if (left_block.Type=="clone" and left_block.AuthorId==session[:current_user].Id) or left_block.Type!="clone"
				left_block.Type=link.Type
				article[:left_blocks][block.Id]<<left_block
				article[:users][left_block.AuthorId]=user_avatar(left_block.AuthorId)
			end
		end
		article[:right_blocks][block.Id]=[]
		BlockLink.where(:LeftId=>block.Id).all.sort(Order: -1,Created_on: -1).each do |link|
			right_block=Block.where(:Id=>link.RightId).first
			if (right_block.Type=="clone" and right_block.AuthorId==session[:current_user].Id) or right_block.Type!="clone"
				right_block.Type=link.Type
				article[:right_blocks][block.Id]<<right_block
				article[:users][right_block.AuthorId]=user_avatar(right_block.AuthorId)
			end
		end
	end
	if session[:current_user].Id==nil
		session[:current_user]=nil
	end
	article.to_json
end

post '/api/append_block/:id' do
	unless session[:current_user]
		return "please login"
	end
	id=params[:id][1..-1]
	text=params[:text]
	block=Block.where(:Id=>id).to_a[0]
	user_id=session[:current_user].Id
	is_public=block.Public
	if block.ParentId
		pid=block.ParentId
		pblock=Block.where(:Id=>pid).to_a[0]
		a_uid=pblock.AuthorId
		subject=pblock.Subject
		next_block=Block.where(:ParentId=>pid,:Order.gt=>block.Order).sort(Order: 1).to_a[0]
		if next_block
			order=(block.Order+next_block.Order)/2.0
		else
			order=block.Order+1.0
		end
		pblock.Updated_on=DateTime.now
		pblock.save
		is_public=pblock.Public
	else
		pid=block.Id
		subject=block.Subject
		a_uid=block.AuthorId
		first_block=Block.where(:ParentId=>pid).sort(Order: 1).to_a[0]
		if first_block
			order=first_block.Order/2.0
		else
			order=1.0
		end
		block.Updated_on=DateTime.now
		block.save
	end
	if user_id.to_s!=a_uid.to_s
		return "another user"
	end
	new_block=Block.new
	new_block.Id=new_block.id.to_s
	new_block.ParentId=pid
	new_block.Subject=subject
	new_block.Body=text
	new_block.Order=order
	new_block.AuthorId=user_id
	new_block.Created_on=DateTime.now
	new_block.Type="sub"
	new_block.Public=is_public
	new_block.save
	cache_id="add_append_b"+id
	CachedContent.where(:Id=>cache_id,:AuthorId=>user_id).delete
	return "OK"
end

post '/api/comment_block/:id' do
	unless session[:current_user]
		return "please login"
	end
	id=params[:id][1..-1]
	text=params[:text]
	comment_type=params[:comment_type]
	comment_title=params[:comment_title]
	user_id=session[:current_user].Id
	block=Block.where(:Id=>id).first
	block.Updated_on=DateTime.now
	block.RightBlockCount=0 unless block.RightBlockCount
	block.RightBlockCount=block.RightBlockCount+1
	block.save
	new_block=Block.new
	new_block.Id=new_block.id.to_s
	new_block.Subject=comment_title
	new_block.Body=text
	new_block.Created_on=DateTime.now
	new_block.AuthorId=user_id
	new_block.Type="comment"
	new_block.Public=block.Public
	new_block.save
	link=BlockLink.new
	link.LeftId=id
	link.RightId=new_block.Id
	link.Type=comment_type
	link.Created_on=DateTime.now
	link.save
	cache_id="add_comment_b"+id
	CachedContent.where(:Id=>cache_id,:AuthorId=>user_id).delete
	return "OK"
end

post '/api/delete_block' do
	re_count_id_list=[]
	unless session[:current_user]
		return "please login"
	end
	id=params[:id][1..-1]
	block=Block.where(:Id=>id).first
	unless block.ParentId
		clean_tag(block.Id)
		block.delete
		BlockLink.where(:LeftId=>id).delete
		BlockLink.where(:RightId=>id).all.each do |bl|
			re_count_id_list << bl.LeftId
		end
		BlockLink.where(:RightId=>id).delete
		Block.where(:ParentId=>id).all.each do |b|
			BlockLink.where(:LeftId=>b.Id).delete
			BlockLink.where(:RightId=>b.Id).all.each do |bl|
				re_count_id_list << bl.LeftId
			end
			BlockLink.where(:RightId=>b.Id).delete
		end
		Block.where(:ParentId=>id).delete
		re_count_right_block(re_count_id_list)
		return "OK_ALL"
	else
		parent_block=Block.where(:Id=>block.ParentId).first
		parent_block.Updated_on=DateTime.now
		parent_block.save
		block.delete
		BlockLink.where(:LeftId=>id).delete
		BlockLink.where(:RightId=>id).all.each do |bl|
			re_count_id_list << bl.LeftId
		end
		BlockLink.where(:RightId=>id).delete
		re_count_right_block(re_count_id_list)
		return "OK"
	end
end

post '/api/edit_block/:id' do
	unless session[:current_user]
		return "please login"
	end
	id=params[:id][1..-1]
	block=Block.where(:Id=>id).first
	block.Body=params[:text]
	block.Updated_on=DateTime.now
	block.save
	if block.ParentId
		parent_block=Block.where(:Id=>block.ParentId).first
		parent_block.Updated_on=DateTime.now
		parent_block.save
	end
	cache_id="edit_b"+id
	CachedContent.where(:Id=>cache_id,:AuthorId=>block.AuthorId).delete
	return "OK"
end

post '/api/add_left_block/:id' do
	unless session[:current_user]
		return "please login"
	end
	id=params[:id][1..-1]
	block=Block.where(:Id=>id).first
	block.Updated_on=DateTime.now
	block.save
	if block.ParentId
		parent_block=Block.where(:Id=>block.ParentId).first
		parent_block.Updated_on=DateTime.now
		parent_block.save
	end
	left_id=params[:left_id]
	comment_type=params[:comment_type]
	link=BlockLink.new
	link.LeftId=left_id
	link.RightId=id
	link.Type=comment_type
	link.Created_on=DateTime.now
	link.save
	left_block=Block.where(:Id=>left_id).first
	left_block.RightBlockCount=0 unless left_block.RightBlockCount
	left_block.RightBlockCount=left_block.RightBlockCount+1
	left_block.save
	return "OK"
end

post '/api/add_exist_block/:id' do
	unless session[:current_user]
		return "please login"
	end
	id=params[:id][1..-1]
	exist_id=params[:exist_id]
	block=Block.where(:Id=>id).first
	exist_block=Block.where(:Id=>exist_id).first
	user_id=session[:current_user].Id
	if user_id.to_s!=exist_block.AuthorId.to_s
		return "another user"
	end
	if block.ParentId
		pid=block.ParentId
		pblock=Block.where(:Id=>pid).first
		a_uid=pblock.AuthorId
		next_block=Block.where(:ParentId=>pid,:Order.gt=>block.Order).first
		if next_block
			order=(block.Order+next_block.Order)/2
		else
			order=block.Order+1
		end
		pblock.Updated_on=DateTime.now
		pblock.save
	else
		pid=block.Id
		a_uid=block.AuthorId
		first_block=Block.where(:ParentId=>pid).sort(Order: 1).first
		if first_block
			order=first_block.Order/2
		else
			order=1
		end
		block.Updated_on=DateTime.now
		block.save
	end
	if user_id.to_s!=a_uid.to_s
		return "another user"
	end
	exist_block.ParentId=pid
	exist_block.Order=order
	exist_block.Updated_on=DateTime.now
	exist_block.Type="sub"
	exist_block.save
	return "OK"
end

post '/api/clone_block/:id' do
	unless session[:current_user]
		return "please login"
	end
	id=params[:id][1..-1]
	block=Block.where(:Id=>id).first
	block.RightBlockCount=0 unless block.RightBlockCount
	block.RightBlockCount=block.RightBlockCount+1
	block.save
	link_type="#000"
	new_block=Block.new
	new_block.Id=new_block.id.to_s
	new_block.Subject=block.Subject
	new_block.Body=block.Body
	new_block.Created_on=DateTime.now
	new_block.AuthorId=session[:current_user].Id
	new_block.Type="clone"
	new_block.Public=block.Public
	new_block.save
	link=BlockLink.new
	link.LeftId=id
	link.RightId=new_block.Id
	link.Type=link_type
	link.Created_on=DateTime.now
	link.save
	return "OK"
end

post '/api/delete_link' do
	unless session[:current_user]
		return "please login"
	end
	id=params[:id][1..-1]
	left_id=params[:left_id][2..-1]
	block=Block.where(:Id=>id).first
	unless block.ParentId
		block.Updated_on=DateTime.now
		block.save
	else
		pblock=Block.where(:Id=>block.ParentId).first
		pblock.Updated_on=DateTime.now
		pblock.save
	end
	BlockLink.where(:LeftId=>left_id,:RightId=>id).delete
	left_block=Block.where(:Id=>left_id).first
	left_block.RightBlockCount=left_block.RightBlockCount-1
	left_block.save
	return "OK"
end

get '/api/cache/:id' do
	@current_user=session[:current_user]
	if @current_user
		content=CachedContent.where(:Id=>params[:id],:AuthorId=>@current_user.Id).first
		if content
			return content.to_json
		end
	end
	return ""
end

post '/api/cache/:id' do
	@current_user=session[:current_user]
	if @current_user
		CachedContent.where(:Id=>params[:id],:AuthorId=>@current_user.Id).delete
		content=CachedContent.new
		content.Id=params[:id]
		content.AuthorId=@current_user.Id
		content.Subject=params[:subject]
		content.Body=params[:body]
		content.save
	end
end

delete '/api/cache/:id' do
	@current_user=session[:current_user]
	if @current_user
		CachedContent.where(:Id=>params[:id],:AuthorId=>@current_user.Id).delete
	end
end

post '/api/follow_user/:id' do
	to_user_id=params[:id]
	from_user_id=params[:from_user_id]
	w=Watch.new
	w.UserId=from_user_id
	w.WatchedId=to_user_id
	w.WatchType='user'
	w.save
	"OK"
end

post '/api/unfollow_user/:id' do
	to_user_id=params[:id]
	from_user_id=params[:from_user_id]
	Watch.where(:UserId=>from_user_id,:WatchedId=>to_user_id,:WatchType=>'user').delete
	"OK"
end

get '/api/articles' do
        Block.where(:ParentId=>nil,:Type=>"topic",:Public=>1).sort(Updated_on: -1).to_a.to_json
end

get '/api/articles/:page/:pagesize' do
	skip=(params[:page].to_i-1)*params[:pagesize].to_i
	count=params[:pagesize].to_i
	Block.where(:ParentId=>nil,:Type=>"topic",:Public=>1).sort(Updated_on: -1).skip(skip).limit(count).to_a.to_json
end

post '/api/article' do
	if session[:current_user]
		block=Block.new
		block.Id=block.id
		block.Subject=params[:subject]
		block.Format=params[:format]
		block.Body=params[:txtBody]
		block.Created_on=DateTime.now
		block.AuthorId=session[:current_user].Id
		block.Type="topic"
		block.Public=params[:public].to_s.to_i
		block.save
		update_tags(block.id,params[:tags])
		CachedContent.where(:Id=>'new',:AuthorId=>session[:current_user].Id).delete
		return block.Id
	else
		return "please login"
	end
end

get '/api/msgs/count' do
	return get_msg_count(session[:current_user]).to_s
end

get '/api/msgs' do
	r=Redis.new
	user=session[:current_user]
	if user
		return r.lrange(user.Id,0,-1).map{|v| Marshal.load(v)}.to_json
	else
		return "please login"
	end
end

get '/api/follow/:from_id/:to_id' do
	f1=is_followed(params[:from_id],params[:to_id])
	f2=is_followed(params[:to_id],params[:from_id]);
	return "both" if f1 && f2
	return "from" if f1
	return "to" if f2
	return "no"
end

get '/api/user/:id' do
	return User.where(:Id=>params[:id]).first.to_json
end

get '/api/tags' do
	return Tag.all.sort(BlockCount: -1).to_json
end

post '/api/edit_post/:id' do
        if session[:current_user]
                id=params[:id]
                block=Block.where(:Id=>id).first
                block.Subject=params[:subject]
                block.Updated_on=DateTime.now
                block.Public=params[:public]
                block.Format=params[:format]
                block.save
                update_tags(id,params[:tags])
		return "OK"
        else
		return "please login"
        end
end

get '/api/articles/tag/:tag' do
	block_ids=[]
	BlockTag.where(:TagId=>params[:tag]).each do |bt|
		block_ids<<bt.BlockId
	end
	article_list=Block.in(:Id=>block_ids).where(:Public=>1).all
	return article_list.to_json
end

get '/api/articles/tag/:tag/:page/:pagesize' do
	block_ids=[]
        BlockTag.where(:TagId=>params[:tag]).each do |bt|
                block_ids<<bt.BlockId
        end
	skip=(params[:page].to_i-1)*params[:pagesize].to_i
        count=params[:pagesize].to_i
	article_list=Block.in(:Id=>block_ids).where(:Public=>1).skip(skip).limit(count).to_a
	return article_list.to_json
end

get '/api/last_article/:userid' do
	return Block.where(:AuthorId=>params[:userid],:Public=>1,:Type=>'topic').sort(Updated_on: -1).limit(-1).to_a[0].to_json
end

get "/upload" do
	@tags=[]
	haml :upload
end

post '/api/upload_image' do
	if session[:current_user]
		img=Image.new
		img.Id=img.id.to_s
		img.AuthorId=session[:current_user].Id
		filename=params['file'][:filename]
		ext_name=filename.split(".")[1]
		img.FileName=img.Id.to_s+"."+ext_name.to_s
		img.URL="/uploads/"+img.AuthorId+"/"+img.FileName
		img.save
		Dir.mkdir("public/uploads/"+img.AuthorId) unless Dir.exist?("public/uploads/"+img.AuthorId)
		File.open('public/uploads/'+img.AuthorId+"/"+img.FileName, "w") do |f|
			f.write(params['file'][:tempfile].read)
		end
		return img.URL
	else
		return "please login"
	end
end

get '/api/delete_image/:id' do
	if session[:current_user]
		img=Image.where(:Id=>params[:id])
		if img
			img=img[0];
			File.delete("public/uploads/"+img.AuthorId+"/"+img.FileName)
			img.delete
			return "OK"
		else
			return "Not exist"
		end
	else
		return "please login"
	end
end

get '/api/get_images' do
        if session[:current_user]
                return Image.where(:AuthorId=>session[:current_user].Id).to_json
        else
                return "please login"
        end
end

get '/api/get_images/:page/:pagesize' do
	skip=(params[:page].to_i-1)*params[:pagesize].to_i
	count=params[:pagesize].to_i
	if session[:current_user]
                return Image.where(:AuthorId=>session[:current_user].Id).skip(skip).limit(count).to_json
        else
                return "please login"
        end
end

post '/api/send_msg/:receiver_user_id' do
	if session[:current_user]
		ru=User.where(:Id=>params[:receiver_user_id]).first
		if ru
			r=Redis.new
			last_id=r.incr("private:msg:id")
			pm=PrivateMessage.new
			pm.Id=last_id
			pm.FromUserId=session[:current_user].Id
			pm.FromUserName=session[:current_user].Name
			pm.ToUserId=ru.Id
			pm.ToUserName=ru.Name
			pm.Body=params[:body]
			pm.save
			ru.LastMsg=pm
			r.hset("inbox:"+session[:current_user].Id,ru.Id,ru.to_json)
			return "OK"
		else
			return "reciver user not exist"
		end
	else
		return "please login"
	end
end

get '/api/check_new_msg/:last_message_id/:page/:pagesize' do
	if session[:current_user]
		skip=(params[:page].to_i-1)*params[:pagesize].to_i
		count=params[:pagesize].to_i
		return PrivateMessage.where(:ToUserId=>session[:current_user].Id,:Id.gt=>params[:last_message_id])
			.sort(:Id=>-1).skip(skip).limit(count).to_json
	else
		return "please login"
	end
end

get '/api/get_private_msgs/:userid/:page/:pagesize' do
	if session[:current_user]
		skip=(params[:page].to_i-1)*params[:pagesize].to_i
                count=params[:pagesize].to_i
		return PrivateMessage.where(:Id.gt=>0)
			.or(:FromUserId=>params[:userid],:ToUserId=>session[:current_user].Id)
			.or(:FromUserId=>session[:current_user].Id,:ToUserId=>params[:userid])
			.sort(Id: -1).skip(skip).limit(count).to_json
	else
		return "please login"
	end
end

get '/api/inbox' do
	if session[:current_user]
		r=Redis.new
		return r.hgetall("inbox:"+session[:current_user].Id).to_json
	else
		return "please login"
	end
end


text:
namespace arangodb {

class LocalDocumentId;
class ManagedDocumentResult;
struct OperationCursor;
class StringRef;
class LogicalCollection;

namespace transaction {
class Methods;
}

namespace velocypack {
class Slice;
}

namespace graph {
struct BaseOptions;
struct SingleServerEdgeDocumentToken;

class SingleServerEdgeCursor : public EdgeCursor {
 private:
  BaseOptions* _opts;
  transaction::Methods* _trx;
  ManagedDocumentResult* _mmdr;
  std::vector<std::vector<OperationCursor*>> _cursors;
  size_t _currentCursor;
  size_t _currentSubCursor;
  std::vector<LocalDocumentId> _cache;
  size_t _cachePos;
  std::vector<size_t> const* _internalCursorMapping;
  using Callback = std::function<void(EdgeDocumentToken&&, arangodb::velocypack::Slice, size_t)>;
 public:
  SingleServerEdgeCursor(ManagedDocumentResult* mmdr, BaseOptions* options,
                         size_t, std::vector<size_t> const* mapping = nullptr);

  ~SingleServerEdgeCursor();

  bool next(std::function<void(EdgeDocumentToken&&,
                               arangodb::velocypack::Slice, size_t)>
                callback) override;

  void readAll(
      std::function<void(EdgeDocumentToken&&,
                         arangodb::velocypack::Slice, size_t)>) override;

  std::vector<std::vector<OperationCursor*>>& getCursors() { return _cursors; }

 private:
  //returns false if cursor can not be further advanced
  bool advanceCursor(OperationCursor*& cursor, std::vector<OperationCursor*>& cursorSet);

  void getDocAndRunCallback(OperationCursor*, Callback callback);
};
}  // namespace graph
}  // namespace arangodb

#endif


text:
const path = require('path');
const fs = require('fs');

const utils = require('./utils');

const {
    inlineSources,
    copySubdirectories,
    removeDir
} = utils;

const BUILD_DIR = path.join(__dirname, '..', 'build');
const PUBLIC_DIR = path.join(__dirname, '..');

const HTML_FILE_SOURCE = path.join(BUILD_DIR, 'index.html');
const CORE_CSS_SOURCE = path.join(BUILD_DIR, 'css', 'core.min.css');

// inline core css to speed up the paint time
const options = {
    '<core-styles/>': `<style>${fs.readFileSync(CORE_CSS_SOURCE).toString()}</style>`
};

console.log('post build process');
inlineSources(HTML_FILE_SOURCE, options);

// move build files from build folder to public polder
console.log('Moving build files into public folder.');
copySubdirectories(BUILD_DIR, PUBLIC_DIR)
    .then(() => {
        console.log('Removing build folder');
        return removeDir(BUILD_DIR);
    })
    .then(() => console.log('postbuild DONE'))
    .catch(error => console.log('Error while moving build files', error));


text:
import {listen} from '../../../src/ol/events.js';
import Collection from '../../../src/ol/Collection.js';
import CollectionEventType from '../../../src/ol/CollectionEventType.js';

describe('ol.collection', function() {
  let collection;

  beforeEach(function() {
    collection = new Collection();
  });

  describe('create an empty collection', function() {
    it('creates an empty collection', function() {
      expect(collection.getLength()).to.eql(0);
      expect(collection.getArray()).to.be.empty();
      expect(collection.item(0)).to.be(undefined);
    });
  });

  describe('create a collection from an array', function() {
    it('creates the expected collection', function() {
      const array = [0, 1, 2];
      const collection = new Collection(array);
      expect(collection.item(0)).to.eql(0);
      expect(collection.item(1)).to.eql(1);
      expect(collection.item(2)).to.eql(2);
    });
  });

  describe('push to a collection', function() {
    it('adds elements to the collection', function() {
      const length = collection.push(1);
      expect(collection.getLength()).to.eql(length);
      expect(collection.getArray()).to.eql([1]);
      expect(collection.item(0)).to.eql(1);
    });
    it('returns the correct new length of the collection', function() {
      let length;
      listen(collection, 'add', function(event) {
        if (event.element === 'remove_me') {
          collection.remove(event.element);
        }
      });
      length = collection.push('keep_me');
      expect(collection.getLength()).to.eql(length);
      length = collection.push('remove_me');
      expect(collection.getLength()).to.eql(length);
    });
  });

  describe('pop from a collection', function() {
    it('removes elements from the collection', function() {
      collection.push(1);
      collection.pop();
      expect(collection.getLength()).to.eql(0);
      expect(collection.getArray()).to.be.empty();
      expect(collection.item(0)).to.be(undefined);
    });
  });

  describe('insertAt', function() {
    it('inserts elements at the correct location', function() {
      collection = new Collection([0, 2]);
      collection.insertAt(1, 1);
      expect(collection.item(0)).to.eql(0);
      expect(collection.item(1)).to.eql(1);
      expect(collection.item(2)).to.eql(2);
    });
  });

  describe('setAt', function() {
    it('sets at the correct location', function() {
      collection.setAt(1, 1);
      expect(collection.getLength()).to.eql(2);
      expect(collection.item(0)).to.be(undefined);
      expect(collection.item(1)).to.eql(1);
    });
  });

  describe('removeAt', function() {
    it('removes elements at the correction', function() {
      const collection = new Collection([0, 1, 2]);
      collection.removeAt(1);
      expect(collection.item(0)).to.eql(0);
      expect(collection.item(1)).to.eql(2);
    });
  });

  describe('forEach', function() {
    let cb;
    beforeEach(function() {
      cb = sinon.spy();
    });
    describe('on an empty collection', function() {
      it('does not call the callback', function() {
        collection.forEach(cb);
        expect(cb).to.not.be.called();
      });
    });
    describe('on a non-empty collection', function() {
      it('does call the callback', function() {
        collection.push(1);
        collection.push(2);
        collection.forEach(cb);
        expect(cb.callCount).to.eql(2);
      });
    });
  });

  describe('remove', function() {
    it('removes the first matching element', function() {
      const collection = new Collection([0, 1, 2]);
      expect(collection.remove(1)).to.eql(1);
      expect(collection.getArray()).to.eql([0, 2]);
      expect(collection.getLength()).to.eql(2);
    });
    it('fires a remove event', function() {
      const collection = new Collection([0, 1, 2]);
      const cb = sinon.spy();
      listen(collection, CollectionEventType.REMOVE, cb);
      expect(collection.remove(1)).to.eql(1);
      expect(cb).to.be.called();
      expect(cb.lastCall.args[0].element).to.eql(1);
    });
    it('does not remove more than one matching element', function() {
      const collection = new Collection([0, 1, 1, 2]);
      expect(collection.remove(1)).to.eql(1);
      expect(collection.getArray()).to.eql([0, 1, 2]);
      expect(collection.getLength()).to.eql(3);
    });
    it('returns undefined if the element is not found', function() {
      const collection = new Collection([0, 1, 2]);
      expect(collection.remove(3)).to.be(undefined);
      expect(collection.getArray()).to.eql([0, 1, 2]);
      expect(collection.getLength()).to.eql(3);
    });
  });

  describe('setAt and event', function() {
    it('does dispatch events', function() {
      const collection = new Collection(['a', 'b']);
      let added, removed;
      listen(collection, CollectionEventType.ADD, function(e) {
        added = e.element;
      });
      listen(
        collection, CollectionEventType.REMOVE, function(e) {
          removed = e.element;
        });
      collection.setAt(1, 1);
      expect(added).to.eql(1);
      expect(removed).to.eql('b');
    });
  });

  describe('removeAt and event', function() {
    it('does dispatch events', function() {
      const collection = new Collection(['a']);
      let removed;
      listen(
        collection, CollectionEventType.REMOVE, function(e) {
          removed = e.element;
        });
      collection.pop();
      expect(removed).to.eql('a');
    });
  });

  describe('insertAt and event', function() {
    it('does dispatch events', function() {
      const collection = new Collection([0, 2]);
      let added;
      listen(
        collection, CollectionEventType.ADD, function(e) {
          added = e.element;
        });
      collection.insertAt(1, 1);
      expect(added).to.eql(1);
    });
  });

  describe('setAt beyond end', function() {
    it('triggers events properly', function() {
      const added = [];
      listen(
        collection, CollectionEventType.ADD, function(e) {
          added.push(e.element);
        });
      collection.setAt(2, 0);
      expect(collection.getLength()).to.eql(3);
      expect(collection.item(0)).to.be(undefined);
      expect(collection.item(1)).to.be(undefined);
      expect(collection.item(2)).to.eql(0);
      expect(added.length).to.eql(3);
      expect(added[0]).to.eql(undefined);
      expect(added[1]).to.eql(undefined);
      expect(added[2]).to.eql(0);
    });
  });

  describe('change:length event', function() {
    let collection, cb;
    beforeEach(function() {
      collection = new Collection([0, 1, 2]);
      cb = sinon.spy();
      listen(collection, 'change:length', cb);
    });

    describe('insertAt', function() {
      it('triggers change:length event', function() {
        collection.insertAt(2, 3);
        expect(cb).to.be.called();
      });
    });

    describe('removeAt', function() {
      it('triggers change:length event', function() {
        collection.removeAt(0);
        expect(cb).to.be.called();
      });
    });

    describe('setAt', function() {
      it('does not trigger change:length event', function() {
        collection.setAt(1, 1);
        expect(cb).to.not.be.called();
      });
    });
  });

  describe('add event', function() {
    it('triggers add when pushing', function() {
      const collection = new Collection();
      let elem;
      listen(collection, CollectionEventType.ADD, function(e) {
        elem = e.element;
      });
      const length = collection.push(1);
      expect(elem).to.eql(length);
    });
  });

  describe('remove event', function() {
    let collection, cb1, cb2;
    beforeEach(function() {
      collection = new Collection([1]);
      cb1 = sinon.spy();
      cb2 = sinon.spy();
    });
    describe('setAt', function() {
      it('triggers remove', function() {
        listen(collection, CollectionEventType.ADD, cb1);
        listen(collection, CollectionEventType.REMOVE, cb2);
        collection.setAt(0, 2);
        expect(cb2.lastCall.args[0].element).to.eql(1);
        expect(cb1.lastCall.args[0].element).to.eql(2);
      });
    });
    describe('pop', function() {
      it('triggers remove', function() {
        listen(collection, CollectionEventType.REMOVE, cb1);
        collection.pop();
        expect(cb1.lastCall.args[0].element).to.eql(1);
      });
    });
  });

  describe('extending a collection', function() {
    it('adds elements to end of the collection', function() {
      collection.extend([1, 2]);
      expect(collection.getLength()).to.eql(2);
      expect(collection.getArray()).to.eql([1, 2]);
      expect(collection.item(0)).to.eql(1);
      expect(collection.item(1)).to.eql(2);
    });
    it('fires events', function() {
      const collection = new Collection();
      const elems = [];
      listen(collection, CollectionEventType.ADD, function(e) {
        elems.push(e.element);
      });
      collection.extend([1, 2]);
      expect(elems).to.eql([1, 2]);
    });
  });

  describe('unique collection', function() {
    it('allows unique items in the constructor', function() {
      new Collection([{}, {}, {}], {unique: true});
    });

    it('throws if duplicate items are passed to the constructor', function() {
      const item = {};
      const call = function() {
        new Collection([item, item], {unique: true});
      };
      expect(call).to.throwException();
    });

    it('allows unique items to be added via push', function() {
      const unique = new Collection(undefined, {unique: true});
      unique.push({});
      unique.push({});
    });

    it('throws if duplicate items are added via push', function() {
      const unique = new Collection(undefined, {unique: true});
      const item = {};
      unique.push(item);
      const call = function() {
        unique.push(item);
      };
      expect(call).to.throwException();
    });

    it('allows unique items to be added via insertAt', function() {
      const unique = new Collection(undefined, {unique: true});
      unique.insertAt(0, {});
      unique.insertAt(0, {});
    });

    it('throws if duplicate items are added via insertAt', function() {
      const unique = new Collection(undefined, {unique: true});
      const item = {};
      unique.insertAt(0, item);
      const call = function() {
        unique.insertAt(0, item);
      };
      expect(call).to.throwException();
    });

    it('allows unique items to be added via setAt', function() {
      const unique = new Collection(undefined, {unique: true});
      unique.setAt(0, {});
      unique.setAt(1, {});
    });

    it('allows items to be reset via setAt', function() {
      const unique = new Collection(undefined, {unique: true});
      const item = {};
      unique.setAt(0, item);
      unique.setAt(0, item);
    });

    it('throws if duplicate items are added via setAt', function() {
      const unique = new Collection(undefined, {unique: true});
      const item = {};
      unique.setAt(0, item);
      const call = function() {
        unique.setAt(1, item);
      };
      expect(call).to.throwException();
    });

  });

});


text:
<?php
/**
 * file:retrieve command for Skeleton Console
 *
 * @author Lionel Laffineur <lionel@tigron.be>
 */

namespace Skeleton\Console\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;

class File_Retrieve extends \Skeleton\Console\Command {

	/**
	 * Configure the Create command
	 *
	 * @access protected
	 */
	protected function configure() {
		$this->setName('file:retrieve');
		$this->setDescription('Retrieve a file from file store');
		$this->addArgument('id', InputArgument::REQUIRED, '');
		$this->addArgument('dir', InputArgument::OPTIONAL, '');
	}

	/**
	 * Execute the Command
	 *
	 * @access protected
	 * @param InputInterface $input
	 * @param OutputInterface $output
	 */
	protected function execute(InputInterface $input, OutputInterface $output) {
		$id = $input->getArgument('id');
		$dir = $input->getArgument('dir');

		try {
			$file = \Skeleton\File\File::get_by_id($id);
			if ($dir != '') {
				if (file_exists($dir) == false) {
					$output->writeln('<error>Directory ' . $dir . ' not found</error>');
					return 1;
				}
				if (is_dir($dir) == false) {
					$output->writeln('<error>Directory ' . $dir . ' appears to be a file</error>');
					return 1;
				}
				file_put_contents($dir . '/' . $file->name, $file->get_contents());
			} else {
				file_put_contents($file->name, $file->get_contents());
			}
		} catch (Exception $e) {
			$output->writeln('<error>' . $e->getMessage() . ': file retrieve failed</error>');
			return 1;
		}

		return 0;
	}
}


text:
package model

import (
	"time"

	"gopkg.in/mgo.v2/bson"
)

type (
	Swit struct {
		Text   string        "json:text"
		Time   time.Time     "json:time"
		SwitId bson.ObjectId `json:"switId" bson:"switId,omitempty"`
		UserId bson.ObjectId `json:"userId" bson:"userId,omitempty"`
		Likes  []string      "json:likes"
	}
)