text:
'use strict';

/*
 * Dependencies.
 */

var he = require('he');
var table = require('markdown-table');
var repeat = require('repeat-string');
var extend = require('extend.js');
var ccount = require('ccount');
var longestStreak = require('longest-streak');
var utilities = require('./utilities.js');
var defaultOptions = require('./defaults.js').stringify;

/*
 * Methods.
 */

var raise = utilities.raise;
var validate = utilities.validate;

/*
 * Constants.
 */

var INDENT = 4;
var MINIMUM_CODE_FENCE_LENGTH = 3;
var YAML_FENCE_LENGTH = 3;
var MINIMUM_RULE_LENGTH = 3;
var MAILTO = 'mailto:';

/*
 * Expressions.
 */

var EXPRESSIONS_WHITE_SPACE = /\s/;

/*
 * Naive fence expression.
 */

var FENCE = /([`~])\1{2}/;

/*
 * Expression for a protocol.
 *
 * @see http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
 */

var PROTOCOL = /^[a-z][a-z+.-]+:\/?/i;

/*
 * Characters.
 */

var ANGLE_BRACKET_CLOSE = '>';
var ANGLE_BRACKET_OPEN = '<';
var ASTERISK = '*';
var CARET = '^';
var COLON = ':';
var DASH = '-';
var DOT = '.';
var EMPTY = '';
var EQUALS = '=';
var EXCLAMATION_MARK = '!';
var HASH = '#';
var LINE = '\n';
var PARENTHESIS_OPEN = '(';
var PARENTHESIS_CLOSE = ')';
var PIPE = '|';
var PLUS = '+';
var QUOTE_DOUBLE = '"';
var QUOTE_SINGLE = '\'';
var SPACE = ' ';
var SQUARE_BRACKET_OPEN = '[';
var SQUARE_BRACKET_CLOSE = ']';
var TICK = '`';
var TILDE = '~';
var UNDERSCORE = '_';

/*
 * Character combinations.
 */

var BREAK = LINE + LINE;
var GAP = BREAK + LINE;
var DOUBLE_TILDE = TILDE + TILDE;

/*
 * Allowed entity options.
 */

var ENTITY_OPTIONS = {};

ENTITY_OPTIONS.true = true;
ENTITY_OPTIONS.false = true;
ENTITY_OPTIONS.numbers = true;
ENTITY_OPTIONS.escape = true;

/*
 * Allowed list-bullet characters.
 */

var LIST_BULLETS = {};

LIST_BULLETS[ASTERISK] = true;
LIST_BULLETS[DASH] = true;
LIST_BULLETS[PLUS] = true;

/*
 * Allowed horizontal-rule bullet characters.
 */

var HORIZONTAL_RULE_BULLETS = {};

HORIZONTAL_RULE_BULLETS[ASTERISK] = true;
HORIZONTAL_RULE_BULLETS[DASH] = true;
HORIZONTAL_RULE_BULLETS[UNDERSCORE] = true;

/*
 * Allowed emphasis characters.
 */

var EMPHASIS_MARKERS = {};

EMPHASIS_MARKERS[UNDERSCORE] = true;
EMPHASIS_MARKERS[ASTERISK] = true;

/*
 * Allowed fence markers.
 */

var FENCE_MARKERS = {};

FENCE_MARKERS[TICK] = true;
FENCE_MARKERS[TILDE] = true;

/*
 * Which method to use based on `list.ordered`.
 */

var ORDERED_MAP = {};

ORDERED_MAP.true = 'visitOrderedItems';
ORDERED_MAP.false = 'visitUnorderedItems';

/*
 * Allowed list-item-indent's.
 */

var LIST_ITEM_INDENTS = {};

var LIST_ITEM_TAB = 'tab';
var LIST_ITEM_ONE = '1';
var LIST_ITEM_MIXED = 'mixed';

LIST_ITEM_INDENTS[LIST_ITEM_ONE] = true;
LIST_ITEM_INDENTS[LIST_ITEM_TAB] = true;
LIST_ITEM_INDENTS[LIST_ITEM_MIXED] = true;

/*
 * Which checkbox to use.
 */

var CHECKBOX_MAP = {};

CHECKBOX_MAP.null = EMPTY;
CHECKBOX_MAP.undefined = EMPTY;
CHECKBOX_MAP.true = SQUARE_BRACKET_OPEN + 'x' + SQUARE_BRACKET_CLOSE + SPACE;
CHECKBOX_MAP.false = SQUARE_BRACKET_OPEN + SPACE + SQUARE_BRACKET_CLOSE +
    SPACE;

/**
 * Encode noop.
 * Simply returns the given value.
 *
 * @example
 *   var encode = encodeNoop();
 *   encode('AT&T') // 'AT&T'
 *
 * @param {string} value - Content.
 * @return {string} - Content, without any modifications.
 */
function encodeNoop(value) {
    return value;
}

/**
 * Factory to encode HTML entities.
 * Creates a no-operation function when `type` is
 * `'false'`, a function which encodes using named
 * references when `type` is `'true'`, and a function
 * which encodes using numbered references when `type` is
 * `'numbers'`.
 *
 * By default this should not throw errors, but he does
 * throw an error when in `strict` mode:
 *
 *     he.encode.options.strict = true;
 *     encodeFactory('true')('\x01') // throws
 *
 * These are thrown on the currently compiled `File`.
 *
 * @example
 *   var file = new File();
 *
 *   var encode = encodeFactory('false', file);
 *   encode('AT&T') // 'AT&T'
 *
 *   encode = encodeFactory('true', file);
 *   encode('AT&T') // 'AT&T'
 *
 *   encode = encodeFactory('numbers', file);
 *   encode('AT&T') // 'ATT&T'
 *
 * @param {string} type - Either `'true'`, `'false'`, or
 *   `numbers`.
 * @param {File} file - Currently compiled virtual file.
 * @return {function(string): string} - Function which
 *   takes a value and returns its encoded version.
 */
function encodeFactory(type, file) {
    var options = {};
    var fn;

    if (type === 'false') {
        return encodeNoop;
    }

    if (type === 'true') {
        options.useNamedReferences = true;
    }

    fn = type === 'escape' ? 'escape' : 'encode';

    /**
     * Encode HTML entities using `he` using bound options.
     *
     * @see https://github.com/mathiasbynens/he#strict
     *
     * @example
     *   // When `type` is `'true'`.
     *   encode('AT&T'); // 'AT&T'
     *
     *   // When `type` is `'numbers'`.
     *   encode('AT&T'); // 'ATT&T'
     *
     * @param {string} value - Content.
     * @param {Object} node - Node which is compiled.
     * @return {string} - Encoded content.
     * @throws {Error} - When `file.quiet` is not `true`.
     *   However, by default `he` does not throw on
     *   parse errors, but when
     *   `he.encode.options.strict: true`, they occur on
     *   invalid HTML.
     */
    function encode(value, node) {
        try {
            return he[fn](value, options);
        } catch (exception) {
            file.fail(exception, node.position);
        }
    }

    return encode;
}

/**
 * Wrap `url` in angle brackets when needed, or when
 * forced.
 *
 * In links, images, and definitions, the URL part needs
 * to be enclosed when it:
 *
 * - has a length of `0`;
 * - contains white-space;
 * - has more or less opening than closing parentheses.
 *
 * @example
 *   encloseURI('foo bar') // '<foo bar>'
 *   encloseURI('foo(bar(baz)') // '<foo(bar(baz)>'
 *   encloseURI('') // '<>'
 *   encloseURI('example.com') // 'example.com'
 *   encloseURI('example.com', true) // '<example.com>'
 *
 * @param {string} uri
 * @param {boolean?} [always] - Force enclosing.
 * @return {boolean} - Properly enclosed `uri`.
 */
function encloseURI(uri, always) {
    if (
        always ||
        !uri.length ||
        EXPRESSIONS_WHITE_SPACE.test(uri) ||
        ccount(uri, PARENTHESIS_OPEN) !== ccount(uri, PARENTHESIS_CLOSE)
    ) {
        return ANGLE_BRACKET_OPEN + uri + ANGLE_BRACKET_CLOSE;
    }

    return uri;
}

/**
 * There is currently no way to support nested delimiters
 * across Markdown.pl, CommonMark, and GitHub (RedCarpet).
 * The following code supports Markdown.pl and GitHub.
 * CommonMark is not supported when mixing double- and
 * single quotes inside a title.
 *
 * @see https://github.com/vmg/redcarpet/issues/473
 * @see https://github.com/jgm/CommonMark/issues/308
 *
 * @example
 *   encloseTitle('foo') // '"foo"'
 *   encloseTitle('foo \'bar\' baz') // '"foo \'bar\' baz"'
 *   encloseTitle('foo "bar" baz') // '\'foo "bar" baz\''
 *   encloseTitle('foo "bar" \'baz\'') // '"foo "bar" \'baz\'"'
 *
 * @param {string} title - Content.
 * @return {string} - Properly enclosed title.
 */
function encloseTitle(title) {
    var delimiter = QUOTE_DOUBLE;

    if (title.indexOf(delimiter) !== -1) {
        delimiter = QUOTE_SINGLE;
    }

    return delimiter + title + delimiter;
}

/**
 * Pad `value` with `level * INDENT` spaces.  Respects
 * lines. Ignores empty lines.
 *
 * @example
 *   pad('foo', 1) // '    foo'
 *
 * @param {string} value - Content.
 * @param {number} level - Indentation level.
 * @return {string} - Padded `value`.
 */
function pad(value, level) {
    var index;
    var padding;

    value = value.split(LINE);

    index = value.length;
    padding = repeat(SPACE, level * INDENT);

    while (index--) {
        if (value[index].length !== 0) {
            value[index] = padding + value[index];
        }
    }

    return value.join(LINE);
}

/**
 * Construct a new compiler.
 *
 * @example
 *   var compiler = new Compiler(new File('> foo.'));
 *
 * @constructor
 * @class {Compiler}
 * @param {File} file - Virtual file.
 * @param {Object?} [options] - Passed to
 *   `Compiler#setOptions()`.
 */
function Compiler(file, options) {
    var self = this;

    self.file = file;

    self.options = extend({}, self.options);

    self.setOptions(options);
}

/*
 * Cache prototype.
 */

var compilerPrototype = Compiler.prototype;

/*
 * Expose defaults.
 */

compilerPrototype.options = defaultOptions;

/*
 * Map of applicable enum's.
 */

var maps = {
    'entities': ENTITY_OPTIONS,
    'bullet': LIST_BULLETS,
    'rule': HORIZONTAL_RULE_BULLETS,
    'listItemIndent': LIST_ITEM_INDENTS,
    'emphasis': EMPHASIS_MARKERS,
    'strong': EMPHASIS_MARKERS,
    'fence': FENCE_MARKERS
};

/**
 * Set options.  Does not overwrite previously set
 * options.
 *
 * @example
 *   var compiler = new Compiler();
 *   compiler.setOptions({bullet: '*'});
 *
 * @this {Compiler}
 * @throws {Error} - When an option is invalid.
 * @param {Object?} [options] - Stringify settings.
 * @return {Compiler} - `self`.
 */
compilerPrototype.setOptions = function (options) {
    var self = this;
    var current = self.options;
    var ruleRepetition;
    var key;

    if (options === null || options === undefined) {
        options = {};
    } else if (typeof options === 'object') {
        options = extend({}, options);
    } else {
        raise(options, 'options');
    }

    for (key in defaultOptions) {
        validate[typeof current[key]](
            options, key, current[key], maps[key]
        );
    }

    ruleRepetition = options.ruleRepetition;

    if (ruleRepetition && ruleRepetition < MINIMUM_RULE_LENGTH) {
        raise(ruleRepetition, 'options.ruleRepetition');
    }

    self.encode = encodeFactory(String(options.entities), self.file);

    self.options = options;

    return self;
};

/**
 * Visit a node.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.visit({
 *     type: 'strong',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     }]
 *   });
 *   // '**Foo**'
 *
 * @param {Object} node - Node.
 * @param {Object?} [parent] - `node`s parent.
 * @return {string} - Compiled `node`.
 */
compilerPrototype.visit = function (node, parent) {
    var self = this;

    /*
     * Fail on unknown nodes.
     */

    if (typeof self[node.type] !== 'function') {
        self.file.fail(
            'Missing compiler for node of type `' +
            node.type + '`: `' + node + '`',
            node
        );
    }

    return self[node.type](node, parent);
};

/**
 * Visit all children of `parent`.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.all({
 *     type: 'strong',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     },
 *     {
 *       type: 'text',
 *       value: 'Bar'
 *     }]
 *   });
 *   // ['Foo', 'Bar']
 *
 * @param {Object} parent - Parent node of children.
 * @return {Array.<string>} - List of compiled children.
 */
compilerPrototype.all = function (parent) {
    var self = this;
    var children = parent.children;
    var values = [];
    var index = -1;
    var length = children.length;

    while (++index < length) {
        values[index] = self.visit(children[index], parent);
    }

    return values;
};

/**
 * Visit ordered list items.
 *
 * Starts the list with
 * `node.start` and increments each following list item
 * bullet by one:
 *
 *     2. foo
 *     3. bar
 *
 * In `incrementListMarker: false` mode, does not increment
 * each marker and stays on `node.start`:
 *
 *     1. foo
 *     1. bar
 *
 * Adds an extra line after an item if it has
 * `loose: true`.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.visitOrderedItems({
 *     type: 'list',
 *     ordered: true,
 *     children: [{
 *       type: 'listItem',
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   });
 *   // '1.  bar'
 *
 * @param {Object} node - `list` node with
 *   `ordered: true`.
 * @return {string} - Markdown list.
 */
compilerPrototype.visitOrderedItems = function (node) {
    var self = this;
    var increment = self.options.incrementListMarker;
    var values = [];
    var start = node.start;
    var children = node.children;
    var length = children.length;
    var index = -1;
    var bullet;

    while (++index < length) {
        bullet = (increment ? start + index : start) + DOT;
        values[index] = self.listItem(children[index], node, index, bullet);
    }

    return values.join(LINE);
};

/**
 * Visit unordered list items.
 *
 * Uses `options.bullet` as each item's bullet.
 *
 * Adds an extra line after an item if it has
 * `loose: true`.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.visitUnorderedItems({
 *     type: 'list',
 *     ordered: false,
 *     children: [{
 *       type: 'listItem',
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   });
 *   // '-   bar'
 *
 * @param {Object} node - `list` node with
 *   `ordered: false`.
 * @return {string} - Markdown list.
 */
compilerPrototype.visitUnorderedItems = function (node) {
    var self = this;
    var values = [];
    var children = node.children;
    var length = children.length;
    var index = -1;
    var bullet = self.options.bullet;

    while (++index < length) {
        values[index] = self.listItem(children[index], node, index, bullet);
    }

    return values.join(LINE);
};

/**
 * Stringify a block node with block children (e.g., `root`
 * or `blockquote`).
 *
 * Knows about code following a list, or adjacent lists
 * with similar bullets, and places an extra newline
 * between them.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.block({
 *     type: 'root',
 *     children: [{
 *       type: 'paragraph',
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   });
 *   // 'bar'
 *
 * @param {Object} node - `root` node.
 * @return {string} - Markdown block content.
 */
compilerPrototype.block = function (node) {
    var self = this;
    var values = [];
    var children = node.children;
    var length = children.length;
    var index = -1;
    var child;
    var prev;

    while (++index < length) {
        child = children[index];

        if (prev) {
            /*
             * Duplicate nodes, such as a list
             * directly following another list,
             * often need multiple new lines.
             *
             * Additionally, code blocks following a list
             * might easily be mistaken for a paragraph
             * in the list itself.
             */

            if (child.type === prev.type && prev.type === 'list') {
                values.push(prev.ordered === child.ordered ? GAP : BREAK);
            } else if (
                prev.type === 'list' &&
                child.type === 'code' &&
                !child.lang
            ) {
                values.push(GAP);
            } else {
                values.push(BREAK);
            }
        }

        values.push(self.visit(child, node));

        prev = child;
    }

    return values.join(EMPTY);
};

/**
 * Stringify a root.
 *
 * Adds a final newline to ensure valid POSIX files.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.root({
 *     type: 'root',
 *     children: [{
 *       type: 'paragraph',
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   });
 *   // 'bar'
 *
 * @param {Object} node - `root` node.
 * @return {string} - Markdown document.
 */
compilerPrototype.root = function (node) {
    return this.block(node) + LINE;
};

/**
 * Stringify a heading.
 *
 * In `setext: true` mode and when `depth` is smaller than
 * three, creates a setext header:
 *
 *     Foo
 *     ===
 *
 * Otherwise, an ATX header is generated:
 *
 *     ### Foo
 *
 * In `closeAtx: true` mode, the header is closed with
 * hashes:
 *
 *     ### Foo ###
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.heading({
 *     type: 'heading',
 *     depth: 2,
 *     children: [{
 *       type: 'strong',
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   });
 *   // '## **bar**'
 *
 * @param {Object} node - `heading` node.
 * @return {string} - Markdown heading.
 */
compilerPrototype.heading = function (node) {
    var self = this;
    var setext = self.options.setext;
    var closeAtx = self.options.closeAtx;
    var depth = node.depth;
    var content = self.all(node).join(EMPTY);
    var prefix;

    if (setext && depth < 3) {
        return content + LINE +
            repeat(depth === 1 ? EQUALS : DASH, content.length);
    }

    prefix = repeat(HASH, node.depth);
    content = prefix + SPACE + content;

    if (closeAtx) {
        content += SPACE + prefix;
    }

    return content;
};

/**
 * Stringify text.
 *
 * Supports named entities in `settings.encode: true` mode:
 *
 *     AT&T
 *
 * Supports numbered entities in `settings.encode: numbers`
 * mode:
 *
 *     AT&T
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.text({
 *     type: 'text',
 *     value: 'foo'
 *   });
 *   // 'foo'
 *
 * @param {Object} node - `text` node.
 * @return {string} - Raw markdown text.
 */
compilerPrototype.text = function (node) {
    return this.encode(node.value, node);
};

/**
 * Stringify escaped text.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.escape({
 *     type: 'escape',
 *     value: '\n'
 *   });
 *   // '\\\n'
 *
 * @param {Object} node - `escape` node.
 * @return {string} - Markdown escape.
 */
compilerPrototype.escape = function (node) {
    return '\\' + node.value;
};

/**
 * Stringify a paragraph.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.paragraph({
 *     type: 'paragraph',
 *     children: [{
 *       type: 'strong',
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   });
 *   // '**bar**'
 *
 * @param {Object} node - `paragraph` node.
 * @return {string} - Markdown paragraph.
 */
compilerPrototype.paragraph = function (node) {
    return this.all(node).join(EMPTY);
};

/**
 * Stringify a block quote.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.paragraph({
 *     type: 'blockquote',
 *     children: [{
 *       type: 'paragraph',
 *       children: [{
 *         type: 'strong',
 *         children: [{
 *           type: 'text',
 *           value: 'bar'
 *         }]
 *       }]
 *     }]
 *   });
 *   // '> **bar**'
 *
 * @param {Object} node - `blockquote` node.
 * @return {string} - Markdown block quote.
 */
compilerPrototype.blockquote = function (node) {
    var indent = ANGLE_BRACKET_CLOSE + SPACE;

    return indent + this.block(node).split(LINE).join(LINE + indent);
};

/**
 * Stringify a list. See `Compiler#visitOrderedList()` and
 * `Compiler#visitUnorderedList()` for internal working.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.visitUnorderedItems({
 *     type: 'list',
 *     ordered: false,
 *     children: [{
 *       type: 'listItem',
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   });
 *   // '-   bar'
 *
 * @param {Object} node - `list` node.
 * @return {string} - Markdown list.
 */
compilerPrototype.list = function (node) {
    return this[ORDERED_MAP[node.ordered]](node);
};

/**
 * Stringify a list item.
 *
 * Prefixes the content with a checked checkbox when
 * `checked: true`:
 *
 *     [x] foo
 *
 * Prefixes the content with an unchecked checkbox when
 * `checked: false`:
 *
 *     [ ] foo
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.listItem({
 *     type: 'listItem',
 *     checked: true,
 *     children: [{
 *       type: 'text',
 *       value: 'bar'
 *     }]
 *   }, {
 *     type: 'list',
 *     ordered: false,
 *     children: [{
 *       type: 'listItem',
 *       checked: true,
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   }, 0, '*');
 *   '-   [x] bar'
 *
 * @param {Object} node - `listItem` node.
 * @param {Object} parent - `list` node.
 * @param {number} position - Index of `node` in `parent`.
 * @param {string} bullet - Bullet to use.  This, and the
 *   `listItemIndent` setting define the used indent.
 * @return {string} - Markdown list item.
 */
compilerPrototype.listItem = function (node, parent, position, bullet) {
    var self = this;
    var style = self.options.listItemIndent;
    var children = node.children;
    var values = [];
    var index = -1;
    var length = children.length;
    var loose = node.loose;
    var value;
    var indent;
    var spacing;

    while (++index < length) {
        values[index] = self.visit(children[index], node);
    }

    value = CHECKBOX_MAP[node.checked] + values.join(loose ? BREAK : LINE);

    if (
        style === LIST_ITEM_ONE ||
        (style === LIST_ITEM_MIXED && value.indexOf(LINE) === -1)
    ) {
        indent = bullet.length + 1;
        spacing = SPACE;
    } else {
        indent = Math.ceil((bullet.length + 1) / INDENT) * INDENT;
        spacing = repeat(SPACE, indent - bullet.length);
    }

    value = bullet + spacing + pad(value, indent / INDENT).slice(indent);

    if (loose && parent.children.length - 1 !== position) {
        value += LINE;
    }

    return value;
};

/**
 * Stringify inline code.
 *
 * Knows about internal ticks (`\``), and ensures one more
 * tick is used to enclose the inline code:
 *
 *     ```foo ``bar`` baz```
 *
 * Even knows about inital and final ticks:
 *
 *     `` `foo ``
 *     `` foo` ``
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.inlineCode({
 *     type: 'inlineCode',
 *     value: 'foo(); `bar`; baz()'
 *   });
 *   // '``foo(); `bar`; baz()``'
 *
 * @param {Object} node - `inlineCode` node.
 * @return {string} - Markdown inline code.
 */
compilerPrototype.inlineCode = function (node) {
    var value = node.value;
    var ticks = repeat(TICK, longestStreak(value, TICK) + 1);
    var start = ticks;
    var end = ticks;

    if (value.charAt(0) === TICK) {
        start += SPACE;
    }

    if (value.charAt(value.length - 1) === TICK) {
        end = SPACE + end;
    }

    return start + node.value + end;
};

/**
 * Stringify YAML front matter.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.yaml({
 *     type: 'yaml',
 *     value: 'foo: bar'
 *   });
 *   // '---\nfoo: bar\n---'
 *
 * @param {Object} node - `yaml` node.
 * @return {string} - Markdown YAML document.
 */
compilerPrototype.yaml = function (node) {
    var delimiter = repeat(DASH, YAML_FENCE_LENGTH);
    var value = node.value ? LINE + node.value : EMPTY;

    return delimiter + value + LINE + delimiter;
};

/**
 * Stringify a code block.
 *
 * Creates indented code when:
 *
 * - No language tag exists;
 * - Not in `fences: true` mode;
 * - A non-empty value exists.
 *
 * Otherwise, GFM fenced code is created:
 *
 *     ```js
 *     foo();
 *     ```
 *
 * When in ``fence: `~` `` mode, uses tildes as fences:
 *
 *     ~~~js
 *     foo();
 *     ~~~
 *
 * Knows about internal fences (Note: GitHub/Kramdown does
 * not support this):
 *
 *     ````javascript
 *     ```markdown
 *     foo
 *     ```
 *     ````
 *
 * Supports named entities in the language flag with
 * `settings.encode` mode.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.code({
 *     type: 'code',
 *     lang: 'js',
 *     value: 'fooo();'
 *   });
 *   // '```js\nfooo();\n```'
 *
 * @param {Object} node - `code` node.
 * @return {string} - Markdown code block.
 */
compilerPrototype.code = function (node) {
    var value = node.value;
    var marker = this.options.fence;
    var language = this.encode(node.lang || EMPTY, node);
    var fence;

    /*
     * Probably pedantic.
     */

    if (!language && !this.options.fences && value) {
        return pad(value, 1);
    }

    fence = longestStreak(value, marker) + 1;

    /*
     * Fix GFM / RedCarpet bug, where fence-like characters
     * inside fenced code can exit a code-block.
     * Yes, even when the outer fence uses different
     * characters, or is longer.
     * Thus, we can only pad the code to make it work.
     */

    if (FENCE.test(value)) {
        value = pad(value, 1);
    }

    fence = repeat(marker, Math.max(fence, MINIMUM_CODE_FENCE_LENGTH));

    return fence + language + LINE + value + LINE + fence;
};

/**
 * Stringify HTML.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.html({
 *     type: 'html',
 *     value: '<div>bar</div>'
 *   });
 *   // '<div>bar</div>'
 *
 * @param {Object} node - `html` node.
 * @return {string} - Markdown HTML.
 */
compilerPrototype.html = function (node) {
    return node.value;
};

/**
 * Stringify a horizontal rule.
 *
 * The character used is configurable by `rule`: (`'_'`)
 *
 *     ___
 *
 * The number of repititions is defined through
 * `ruleRepetition`: (`6`)
 *
 *     ******
 *
 * Whether spaces delimit each character, is configured
 * through `ruleSpaces`: (`true`)
 *
 *     * * *
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.horizontalRule({
 *     type: 'horizontalRule'
 *   });
 *   // '***'
 *
 * @return {string} - Markdown rule.
 */
compilerPrototype.horizontalRule = function () {
    var options = this.options;
    var rule = repeat(options.rule, options.ruleRepetition);

    if (options.ruleSpaces) {
        rule = rule.split(EMPTY).join(SPACE);
    }

    return rule;
};

/**
 * Stringify a strong.
 *
 * The marker used is configurable by `strong`, which
 * defaults to an asterisk (`'*'`) but also accepts an
 * underscore (`'_'`):
 *
 *     _foo_
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.strong({
 *     type: 'strong',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     }]
 *   });
 *   // '**Foo**'
 *
 * @param {Object} node - `strong` node.
 * @return {string} - Markdown strong-emphasised text.
 */
compilerPrototype.strong = function (node) {
    var marker = this.options.strong;

    marker = marker + marker;

    return marker + this.all(node).join(EMPTY) + marker;
};

/**
 * Stringify an emphasis.
 *
 * The marker used is configurable by `emphasis`, which
 * defaults to an underscore (`'_'`) but also accepts an
 * asterisk (`'*'`):
 *
 *     *foo*
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.emphasis({
 *     type: 'emphasis',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     }]
 *   });
 *   // '_Foo_'
 *
 * @param {Object} node - `emphasis` node.
 * @return {string} - Markdown emphasised text.
 */
compilerPrototype.emphasis = function (node) {
    var marker = this.options.emphasis;

    return marker + this.all(node).join(EMPTY) + marker;
};

/**
 * Stringify a hard break.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.break({
 *     type: 'break'
 *   });
 *   // '  \n'
 *
 * @return {string} - Hard markdown break.
 */
compilerPrototype.break = function () {
    return SPACE + SPACE + LINE;
};

/**
 * Stringify a delete.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.delete({
 *     type: 'delete',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     }]
 *   });
 *   // '~~Foo~~'
 *
 * @param {Object} node - `delete` node.
 * @return {string} - Markdown strike-through.
 */
compilerPrototype.delete = function (node) {
    return DOUBLE_TILDE + this.all(node).join(EMPTY) + DOUBLE_TILDE;
};

/**
 * Stringify a link.
 *
 * When no title exists, the compiled `children` equal
 * `href`, and `href` starts with a protocol, an auto
 * link is created:
 *
 *     <http://example.com>
 *
 * Otherwise, is smart about enclosing `href` (see
 * `encloseURI()`) and `title` (see `encloseTitle()`).
 *
 *    [foo](<foo at bar dot com> 'An "example" e-mail')
 *
 * Supports named entities in the `href` and `title` when
 * in `settings.encode` mode.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.link({
 *     type: 'link',
 *     href: 'http://example.com',
 *     title: 'Example Domain',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     }]
 *   });
 *   // '[Foo](http://example.com "Example Domain")'
 *
 * @param {Object} node - `link` node.
 * @return {string} - Markdown link.
 */
compilerPrototype.link = function (node) {
    var self = this;
    var url = self.encode(node.href, node);
    var value = self.all(node).join(EMPTY);

    if (
        node.title === null &&
        PROTOCOL.test(url) &&
        (url === value || url === MAILTO + value)
    ) {
        return encloseURI(url, true);
    }

    url = encloseURI(url);

    if (node.title) {
        url += SPACE + encloseTitle(self.encode(node.title, node));
    }

    value = SQUARE_BRACKET_OPEN + value + SQUARE_BRACKET_CLOSE;

    value += PARENTHESIS_OPEN + url + PARENTHESIS_CLOSE;

    return value;
};

/**
 * Stringify a link label.
 *
 * Because link references are easily, mistakingly,
 * created (for example, `[foo]`), reference nodes have
 * an extra property depicting how it looked in the
 * original document, so stringification can cause minimal
 * changes.
 *
 * @example
 *   label({
 *     type: 'referenceImage',
 *     referenceType: 'full',
 *     identifier: 'foo'
 *   });
 *   // '[foo]'
 *
 *   label({
 *     type: 'referenceImage',
 *     referenceType: 'collapsed',
 *     identifier: 'foo'
 *   });
 *   // '[]'
 *
 *   label({
 *     type: 'referenceImage',
 *     referenceType: 'shortcut',
 *     identifier: 'foo'
 *   });
 *   // ''
 *
 * @param {Object} node - `linkReference` or
 *   `imageReference` node.
 * @return {string} - Markdown label reference.
 */
function label(node) {
    var value = EMPTY;
    var type = node.referenceType;

    if (type === 'full') {
        value = node.identifier;
    }

    if (type !== 'shortcut') {
        value = SQUARE_BRACKET_OPEN + value + SQUARE_BRACKET_CLOSE;
    }

    return value;
}

/**
 * Stringify a link reference.
 *
 * See `label()` on how reference labels are created.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.linkReference({
 *     type: 'linkReference',
 *     referenceType: 'collapsed',
 *     identifier: 'foo',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     }]
 *   });
 *   // '[Foo][]'
 *
 * @param {Object} node - `linkReference` node.
 * @return {string} - Markdown link reference.
 */
compilerPrototype.linkReference = function (node) {
    return SQUARE_BRACKET_OPEN +
        this.all(node).join(EMPTY) + SQUARE_BRACKET_CLOSE +
        label(node);
};

/**
 * Stringify an image reference.
 *
 * See `label()` on how reference labels are created.
 *
 * Supports named entities in the `alt` when
 * in `settings.encode` mode.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.imageReference({
 *     type: 'imageReference',
 *     referenceType: 'full',
 *     identifier: 'foo',
 *     alt: 'Foo'
 *   });
 *   // '![Foo][foo]'
 *
 * @param {Object} node - `imageReference` node.
 * @return {string} - Markdown image reference.
 */
compilerPrototype.imageReference = function (node) {
    var alt = this.encode(node.alt, node);

    return EXCLAMATION_MARK +
        SQUARE_BRACKET_OPEN + alt + SQUARE_BRACKET_CLOSE +
        label(node);
};

/**
 * Stringify a footnote reference.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.footnoteReference({
 *     type: 'footnoteReference',
 *     identifier: 'foo'
 *   });
 *   // '[^foo]'
 *
 * @param {Object} node - `footnoteReference` node.
 * @return {string} - Markdown footnote reference.
 */
compilerPrototype.footnoteReference = function (node) {
    return SQUARE_BRACKET_OPEN + CARET + node.identifier +
        SQUARE_BRACKET_CLOSE;
};

/**
 * Stringify an link- or image definition.
 *
 * Is smart about enclosing `href` (see `encloseURI()`) and
 * `title` (see `encloseTitle()`).
 *
 *    [foo]: <foo at bar dot com> 'An "example" e-mail'
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.definition({
 *     type: 'definition',
 *     link: 'http://example.com',
 *     title: 'Example Domain',
 *     identifier: 'foo'
 *   });
 *   // '[foo]: http://example.com "Example Domain"'
 *
 * @param {Object} node - `definition` node.
 * @return {string} - Markdown link- or image definition.
 */
compilerPrototype.definition = function (node) {
    var value = SQUARE_BRACKET_OPEN + node.identifier + SQUARE_BRACKET_CLOSE;
    var url = encloseURI(node.link);

    if (node.title) {
        url += SPACE + encloseTitle(node.title);
    }

    return value + COLON + SPACE + url;
};

/**
 * Stringify an image.
 *
 * Is smart about enclosing `href` (see `encloseURI()`) and
 * `title` (see `encloseTitle()`).
 *
 *    ![foo](</fav icon.png> 'My "favourite" icon')
 *
 * Supports named entities in `src`, `alt`, and `title`
 * when in `settings.encode` mode.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.image({
 *     type: 'image',
 *     href: 'http://example.png/favicon.png',
 *     title: 'Example Icon',
 *     alt: 'Foo'
 *   });
 *   // '![Foo](http://example.png/favicon.png "Example Icon")'
 *
 * @param {Object} node - `image` node.
 * @return {string} - Markdown image.
 */
compilerPrototype.image = function (node) {
    var encode = this.encode;
    var url = encloseURI(encode(node.src, node));
    var value;

    if (node.title) {
        url += SPACE + encloseTitle(encode(node.title, node));
    }

    value = EXCLAMATION_MARK +
        SQUARE_BRACKET_OPEN + encode(node.alt || EMPTY, node) +
        SQUARE_BRACKET_CLOSE;

    value += PARENTHESIS_OPEN + url + PARENTHESIS_CLOSE;

    return value;
};

/**
 * Stringify a footnote.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.footnote({
 *     type: 'footnote',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     }]
 *   });
 *   // '[^Foo]'
 *
 * @param {Object} node - `footnote` node.
 * @return {string} - Markdown footnote.
 */
compilerPrototype.footnote = function (node) {
    return SQUARE_BRACKET_OPEN + CARET + this.all(node).join(EMPTY) +
        SQUARE_BRACKET_CLOSE;
};

/**
 * Stringify a footnote definition.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.footnoteDefinition({
 *     type: 'footnoteDefinition',
 *     identifier: 'foo',
 *     children: [{
 *       type: 'paragraph',
 *       children: [{
 *         type: 'text',
 *         value: 'bar'
 *       }]
 *     }]
 *   });
 *   // '[^foo]: bar'
 *
 * @param {Object} node - `footnoteDefinition` node.
 * @return {string} - Markdown footnote definition.
 */
compilerPrototype.footnoteDefinition = function (node) {
    var id = node.identifier.toLowerCase();

    return SQUARE_BRACKET_OPEN + CARET + id +
        SQUARE_BRACKET_CLOSE + COLON + SPACE +
        this.all(node).join(BREAK + repeat(SPACE, INDENT));
};

/**
 * Stringify table.
 *
 * Creates a fenced table by default, but not in
 * `looseTable: true` mode:
 *
 *     Foo | Bar
 *     :-: | ---
 *     Baz | Qux
 *
 * NOTE: Be careful with `looseTable: true` mode, as a
 * loose table inside an indented code block on GitHub
 * renders as an actual table!
 *
 * Creates a spaces table by default, but not in
 * `spacedTable: false`:
 *
 *     |Foo|Bar|
 *     |:-:|---|
 *     |Baz|Qux|
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.table({
 *     type: 'table',
 *     align: ['center', null],
 *     children: [
 *       {
 *         type: 'tableHeader',
 *         children: [
 *           {
 *             type: 'tableCell'
 *             children: [{
 *               type: 'text'
 *               value: 'Foo'
 *             }]
 *           },
 *           {
 *             type: 'tableCell'
 *             children: [{
 *               type: 'text'
 *               value: 'Bar'
 *             }]
 *           }
 *         ]
 *       },
 *       {
 *         type: 'tableRow',
 *         children: [
 *           {
 *             type: 'tableCell'
 *             children: [{
 *               type: 'text'
 *               value: 'Baz'
 *             }]
 *           },
 *           {
 *             type: 'tableCell'
 *             children: [{
 *               type: 'text'
 *               value: 'Qux'
 *             }]
 *           }
 *         ]
 *       }
 *     ]
 *   });
 *   // '| Foo | Bar |\n| :-: | --- |\n| Baz | Qux |'
 *
 * @param {Object} node - `table` node.
 * @return {string} - Markdown table.
 */
compilerPrototype.table = function (node) {
    var self = this;
    var loose = self.options.looseTable;
    var spaced = self.options.spacedTable;
    var rows = node.children;
    var index = rows.length;
    var result = [];
    var start;

    while (index--) {
        result[index] = self.all(rows[index]);
    }

    start = loose ? EMPTY : spaced ? PIPE + SPACE : PIPE;

    return table(result, {
        'align': node.align,
        'start': start,
        'end': start.split(EMPTY).reverse().join(EMPTY),
        'delimiter': spaced ? SPACE + PIPE + SPACE : PIPE
    });
};

/**
 * Stringify a table cell.
 *
 * @example
 *   var compiler = new Compiler();
 *
 *   compiler.tableCell({
 *     type: 'tableCell',
 *     children: [{
 *       type: 'text'
 *       value: 'Qux'
 *     }]
 *   });
 *   // 'Qux'
 *
 * @param {Object} node - `tableCell` node.
 * @return {string} - Markdown table cell.
 */
compilerPrototype.tableCell = function (node) {
    return this.all(node).join(EMPTY);
};

/**
 * Stringify the bound file.
 *
 * @example
 *   var file = new VFile('__Foo__');
 *
 *   file.namespace('mdast').ast = {
 *     type: 'strong',
 *     children: [{
 *       type: 'text',
 *       value: 'Foo'
 *     }]
 *   });
 *
 *   new Compiler(file).compile();
 *   // '**Foo**'
 *
 * @this {Compiler}
 * @return {string} - Markdown document.
 */
compilerPrototype.compile = function () {
    return this.visit(this.file.namespace('mdast').ast);
};

/*
 * Expose `stringify` on `module.exports`.
 */

module.exports = Compiler;


text:
import muffin

app = muffin.Application("web")

@app.register("/text")
def text(request):
    return "Hello, World!"

redpajama_set_name: RedPajamaGithub


text:
// ----------------------------------------------------------------------------------------------------------------------
// The Photon Chat Api enables clients to connect to a chat server and communicate with other clients.
// <remarks>ChatClient is the main class of this api.</remarks>
// <copyright company="Exit Games GmbH">Photon Chat Api - Copyright (C) 2014 Exit Games GmbH</copyright>
// ----------------------------------------------------------------------------------------------------------------------

namespace ExitGames.Client.Photon.Chat
{
    using System.Collections.Generic;
    using System.Text;

    ///
    /// A channel of communication in Photon Chat, updated by ChatClient and provided as READ ONLY.
    ///
    /// <remarks>
    /// Contains messages and senders to use (read!) and display by your GUI.

    /// Access these by:
    ///     ChatClient.PublicChannels
    ///     ChatClient.PrivateChannels
    /// </remarks>
    public class ChatChannel
    {
        /// Name of the channel (used to subscribe and unsubscribe).
        public readonly string Name;

        /// Senders of messages in chronoligical order. Senders and Messages refer to each other by index. Senders[x] is the sender of Messages[x].
        public readonly List<string> Senders = new List<string>();

        /// Messages in chronoligical order. Senders and Messages refer to each other by index. Senders[x] is the sender of Messages[x].
        public readonly List<object> Messages = new List<object>();

        /// Is this a private 1:1 channel?
        public bool IsPrivate { get; internal protected set; }

        /// Count of messages this client still buffers/knows for this channel.
        public int MessageCount { get { return this.Messages.Count; } }

        /// Used internally to create new channels. This does NOT create a channel on the server! Use ChatClient.Subscribe.
        public ChatChannel(string name)
        {
            this.Name = name;
        }

        /// Used internally to add messages to this channel.
        public void Add(string sender, object message)
        {
            this.Senders.Add(sender);
            this.Messages.Add(message);
        }

        /// Used internally to add messages to this channel.
        public void Add(string[] senders, object[] messages)
        {
            this.Senders.AddRange(senders);
            this.Messages.AddRange(messages);
        }

        /// Clear the local cache of messages currently stored. This frees memory but doesn't affect the server.
        public void ClearMessages()
        {
            this.Senders.Clear();
            this.Messages.Clear();
        }

        public string ToStringMessages()
        {
            StringBuilder txt = new StringBuilder();
            for (int i = 0; i < this.Messages.Count; i++)
            {
                txt.AppendLine(string.Format("{0}: {1}", this.Senders[i], this.Messages[i]));
            }
            return txt.ToString();
        }
    }
}


text:
#include <aws/detective/model/ListOrganizationAdminAccountsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Detective::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListOrganizationAdminAccountsRequest::ListOrganizationAdminAccountsRequest() :
    m_nextTokenHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false)
{
}

Aws::String ListOrganizationAdminAccountsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("NextToken", m_nextToken);

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("MaxResults", m_maxResults);

  }

  return payload.View().WriteReadable();
}


text:
<?php

namespace SR\Console\Input\Component\Question\Answer;

use Symfony\Component\Console\Question\Question;

class BooleanAnswer implements AnswerInterface
{
    use AnswerTrait;

    /**
     * @param mixed|null $answer
     */
    public function __construct(Question $question, $answer = null, bool $default = false, bool $interactive = true)
    {
        $this->question = $question;
        $this->result = $answer;
        $this->default = $default;
        $this->interactive = $interactive;
    }

    public function getAnswer(): ?bool
    {
        return $this->result;
    }

    public function stringifyAnswer(): string
    {
        return $this->getAnswer() ? 'true' : 'false';
    }

    public function isTrue(): bool
    {
        return true === $this->getAnswer();
    }

    public function isFalse(): bool
    {
        return false === $this->getAnswer();
    }
}


text:
<?php

namespace Common\Infrastructure\DataGateway;

use PDO;
use Common\Domain\Factory\FactoryInterface;
use Common\Infrastructure\DataGateway\Persistence\TableDataGateway;
use Common\Infrastructure\DataGateway\Persistence\InMemory;
use Common\Infrastructure\DataGateway\Persistence\Sqlite;

/**
 * Class DataGatewayFactory
 *
 * @category  PHP
 * @package   Common\Infrastructure\DataGateway
 * @author    stringhamdb <stringhamdb@familysearch.org>
 * @copyright 2014 © Intellectual Reserve, Inc.
 * @license   Trademarked by Intellectual Reserve, Inc.
 * @version   Release: 0.1
 * @link      https:/ems.ldschurch.org
 */
class DataGatewayFactory implements FactoryInterface
{
    /**
     * Function create Returns the default DataGateway persistence mechanism.
     *
     * @return \Common\Infrastructure\DataGateway\Persistence\InMemory
     *
     * @access public
     */
    public function create()
    {
        return new InMemory();
    }

    /**
     * Function createInMemoryPersistence Returns InMemory persistence specifically.
     *
     * @return \Common\Infrastructure\DataGateway\Persistence\InMemory
     *
     * @access public
     */
    public function createInMemoryPersistence()
    {
        return new InMemory();
    }

    /**
     * Function createSqlLiteMemoryPersistence
     *
     * @return \Common\Infrastructure\DataGateway\Persistence\Sqlite
     *
     * @access public
     */
    public function createSqliteMemoryPersistence()
    {
        $driver = 'sqlite::memory:';

        return new Sqlite($this->createSqlitePdo($driver));
    }

    /**
     * Function createSqlLiteFilePersistence
     *
     * @param string $filePath
     *
     * @return \Common\Infrastructure\DataGateway\Persistence\Sqlite
     *
     * @access   public
     */
    public function createSqliteFilePersistence($filePath = 'd3x.sqlite')
    {
        $driver = 'sqlite:'.$filePath;

        return new Sqlite($this->createSqlitePdo($driver));
    }

    /**
     * Function createSqliteTableDataGateway
     *
     * @param string $filePath  Directory/filename to the SQLite file.
     * @param string $tableName Name of the table this DataGateway refers to.
     *
     * @return \Common\Infrastructure\DataGateway\Persistence\TableDataGateway
     *
     * @access public
     */
    public function createSqliteTableDataGateway(
        $filePath = 'd3x.sqlite',
        $tableName = ''
    ) {
        if ($tableName === '') {
            throw new \PDOException(
                __METHOD__.': '.
                'TableDataGateway pattern requires a table name, not passed in.'
            );
        }

        $driver = 'sqlite:'.$filePath;

        $pdo = $this->createSqlitePdo($driver);

        return new TableDataGateway($pdo, $tableName);
    }

    /**
     * Function createSqlitePdo
     *
     * @param $driver
     *
     * @return \PDO
     *
     * @access public
     */
    private function createSqlitePdo($driver)
    {
        try {
            $pdo = new PDO($driver);

            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (\Exception $e) {
            throw new \PDOException(
                __METHOD__.
                ': ('.$e->getCode().') '.
                $e->getMessage()
            );
        }

        return $pdo;
    }
}


text:
import Stimpak from "../../lib/stimpak/stimpak.js";

describe("stimpak.use()", () => {
	let stimpak,
			generator,
			subGenerator,
			subSubGenerator,
			returnValue,
			results;

	class Generator {
		setup(stim) {
			results.argument = stim;
			results.generatorContext = this;

			// generator

			stim
				.then(this.recordThenContext)
				.then(this.setupTest);
		}

		setupTest(stim, done) {
			stim
				.then(this.recordThenContext)
				.use(SubGenerator)
				.then(this.recordThenContext);
			done();
		}

		recordThenContext(stim, done) {
			results.thenContexts.push(this.constructor.name);
			done();
		}
	}

	class SubGenerator {
		setup(stim) {
			results.subGeneratorContext = this;

			stim
				.then(this.recordThenContext)
				.then(this.setupTest);
		}

		setupTest(stim, done) {
			stim
				.then(this.recordThenContext)
				.use(SubSubGenerator)
				.then(this.recordThenContext);
			done();
		}

		recordThenContext(stim, done) {
			results.thenSubContexts.push(this.constructor.name);
			done();
		}
	}

	class SubSubGenerator {
		setup(stim) {
			results.subSubGeneratorContext = this;

			stim
				.then(this.recordThenContext)
				.then(this.setupTest);
		}

		setupTest(stim, done) {
			stim
				.then(this.recordThenContext);
			done();
		}

		recordThenContext(stim, done) {
			results.thenSubSubContexts.push(this.constructor.name);
			done();
		}
	}

	beforeEach(done => {
		results = {
			argument: null,
			thenContexts: [],
			thenSubContexts: [],
			thenSubSubContexts: []
		};

		stimpak = new Stimpak();

		returnValue = stimpak.use(Generator);

		stimpak
			.destination("/some/path")
			.generate(error => {
				generator = stimpak.generators[0];
				subGenerator = stimpak.generators[1];
				subSubGenerator = stimpak.generators[2];

				done(error);
			});
	});

	it("should return itself to enable chaining", () => {
		returnValue.should.eql(stimpak);
	});

	it("should call setup on the generator without binding", () => {
		results.generatorContext.should.eql(generator);
	});

	it("should call setup on the sub generator without binding", () => {
		results.subGeneratorContext.should.eql(subGenerator);
	});

	it("should call setup on the sub sub generator without binding", () => {
		results.subSubGeneratorContext.should.eql(subSubGenerator);
	});

	it("should keep then contexts stable", () => {
		const generatorName = generator.constructor.name;
		results.thenContexts.should.eql([generatorName, generatorName, generatorName]);
	});

	it("should keep then sub contexts stable", () => {
		const subGeneratorName = subGenerator.constructor.name;
		results.thenSubContexts.should.eql([subGeneratorName, subGeneratorName, subGeneratorName]);
	});

	it("should keep then sub sub contexts stable", () => {
		const subSubGeneratorName = subSubGenerator.constructor.name;
		results.thenSubSubContexts.should.eql([subSubGeneratorName, subSubGeneratorName]);
	});

	it("should add the instantiated generators to .generators", () => {
		generator.should.be.instanceOf(Generator);
	});

	it("should instantiate each provided generator constructor with stimpak as the first argument", () => {
		results.argument.should.eql(stimpak);
	});
});


text:
package edu.emory.cci.aiw.cvrg.eureka.services.translation;

import org.eurekaclinical.eureka.client.comm.Phenotype;
import edu.emory.cci.aiw.cvrg.eureka.common.entity.PhenotypeEntity;
import org.eurekaclinical.eureka.client.comm.exception.PhenotypeHandlingException;

/**
 * Translates a UI phenotype into a proposition as understood by the service
 * layer data model.
 *
 * @param <P>
 *            The phenotype type to translate from, a subclass of
 *            {@link Phenotype}..
 * @param <PE>
 *            The proposition type to translate to, an implementation of
 *            {@link PhenotypeEntity}.
 */
public interface PropositionTranslator<P extends Phenotype, PE extends PhenotypeEntity> {

	/**
	 * Translates the given phenotype to a proposition understood by the
	 * services layer data model. The inverse of {@link #translateFromProposition(PhenotypeEntity)}
	 * .
	 *
	 * @param phenotype
	 *            the phenotype to translate from
	 * @return A {@link PhenotypeEntity} equivalent to the phenotype.
	 * @throws PhenotypeHandlingException if an error occurred retrieving
	 * proposition definitions.
	 */
	PE translateFromPhenotype(P phenotype) throws PhenotypeHandlingException;

	/**
	 * Translates the given proposition entity into a phenotype understood by
	 * the webapp layer. The inverse of {@link #translateFromPhenotype(Phenotype)}.
	 *
	 * @param proposition
	 *            the proposition to translate from
	 * @return A {@link Phenotype} equivalent to the proposition.
	 */
	P translateFromProposition(PE proposition);
}


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

  angular
  .module('app.company')
  .controller('Concesion', Concesion);

  Concesion.$inject = ['$scope', 'template'];

  function Concesion($scope, template) {
    var vm = this;

    activate();

    function activate() {
      console.log('Activating Concesion Controller');
      template.get('app/company/concesion/language/concesion.es.json')
      .then(function(result) {
        vm.text = result;
        $scope.app.setTitle(vm.text.title);
      }); // Loads text files.
    }
  }

})();


text:
const PlotCard = require('../../plotcard.js');
const GameActions = require('../../GameActions');
const {Tokens} = require('../../Constants');

class PowerBehindTheThrone extends PlotCard {
    setupCardAbilities(ability) {
        this.whenRevealed({
            message: '{player} uses {source} to place 1 stand token on {source}',
            handler: context => {
                this.game.resolveGameAction(
                    GameActions.placeToken(() => ({ card: this, token: Tokens.stand })),
                    context
                );
            }
        });

        this.action({
            title: 'Discard a stand token',
            cost: ability.costs.discardTokenFromSelf(Tokens.stand),
            target: {
                cardCondition: card => card.location === 'play area' && card.kneeled && card.getType() === 'character'
            },
            handler: context => {
                this.game.addMessage('{0} uses {1} to remove a stand token and stand {2}', this.controller, this, context.target);

                this.controller.standCard(context.target);
            }
        });
    }
}

PowerBehindTheThrone.code = '01018';

module.exports = PowerBehindTheThrone;


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<Title>
		<v8:item>
			<v8:lang>ru</v8:lang>
			<v8:content>Этапы расчетов</v8:content>
		</v8:item>
	</Title>
	<AutoTitle>false</AutoTitle>
	<CommandBarLocation>Bottom</CommandBarLocation>
	<VerticalScroll>useIfNecessary</VerticalScroll>
	<CommandSet>
		<ExcludedCommand>No</ExcludedCommand>
		<ExcludedCommand>CustomizeForm</ExcludedCommand>
		<ExcludedCommand>SaveValues</ExcludedCommand>
		<ExcludedCommand>Close</ExcludedCommand>
		<ExcludedCommand>Abort</ExcludedCommand>
		<ExcludedCommand>Retry</ExcludedCommand>
		<ExcludedCommand>Yes</ExcludedCommand>
		<ExcludedCommand>Cancel</ExcludedCommand>
		<ExcludedCommand>RestoreValues</ExcludedCommand>
		<ExcludedCommand>Ignore</ExcludedCommand>
		<ExcludedCommand>OK</ExcludedCommand>
	</CommandSet>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
		<HorizontalAlign>Right</HorizontalAlign>
		<Autofill>false</Autofill>
		<ChildItems>
			<Button name="ФормаОК" id="17">
				<Type>CommandBarButton</Type>
				<DefaultButton>true</DefaultButton>
				<CommandName>Form.Command.ОК</CommandName>
				<Parameter xsi:nil="true"/>
				<ExtendedTooltip name="ФормаОКExtendedTooltip" id="50"/>
			</Button>
			<Button name="ФормаОтмена" id="26">
				<Type>CommandBarButton</Type>
				<CommandName>Form.Command.Отмена</CommandName>
				<Parameter xsi:nil="true"/>
				<ExtendedTooltip name="ФормаОтменаExtendedTooltip" id="51"/>
			</Button>
			<ButtonGroup name="ФормаГруппаСправка" id="28">
				<Title>
					<v8:item>
						<v8:lang>ru</v8:lang>
						<v8:content>Форма группа справка</v8:content>
					</v8:item>
				</Title>
				<ToolTip>
					<v8:item>
						<v8:lang>ru</v8:lang>
						<v8:content>Форма группа справка</v8:content>
					</v8:item>
				</ToolTip>
				<ExtendedTooltip name="ФормаГруппаСправкаExtendedTooltip" id="52"/>
				<ChildItems>
					<Button name="ФормаСправка" id="27">
						<Type>CommandBarButton</Type>
						<CommandName>Form.StandardCommand.Help</CommandName>
						<Parameter xsi:nil="true"/>
						<ExtendedTooltip name="ФормаСправкаExtendedTooltip" id="53"/>
					</Button>
				</ChildItems>
			</ButtonGroup>
		</ChildItems>
	</AutoCommandBar>
	<Events>
		<Event name="BeforeClose">ПередЗакрытием</Event>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
	</Events>
	<ChildItems>
		<Table name="ЭтапыГрафикаОплаты" id="6">
			<AutoInsertNewRow>true</AutoInsertNewRow>
			<EnableStartDrag>true</EnableStartDrag>
			<EnableDrag>true</EnableDrag>
			<DataPath>Объект.ЭтапыГрафикаОплаты</DataPath>
			<CommandSet>
				<ExcludedCommand>MoveUp</ExcludedCommand>
				<ExcludedCommand>MoveDown</ExcludedCommand>
			</CommandSet>
			<SearchStringLocation>None</SearchStringLocation>
			<ViewStatusLocation>None</ViewStatusLocation>
			<SearchControlLocation>None</SearchControlLocation>
			<RowFilter xsi:nil="true"/>
			<ContextMenu name="ЭтапыГрафикаОплатыКонтекстноеМеню" id="7"/>
			<AutoCommandBar name="ЭтапыГрафикаОплатыКоманднаяПанель" id="8">
				<ChildItems>
					<Button name="ЭтапыГрафикаОплатыЗаполнитьЭтапыГрафикаОплаты" id="39">
						<Type>CommandBarButton</Type>
						<CommandName>Form.Command.ЗаполнитьЭтапыГрафикаОплаты</CommandName>
						<Parameter xsi:nil="true"/>
						<Title>
							<v8:item>
								<v8:lang>ru</v8:lang>
								<v8:content>Заполнить</v8:content>
							</v8:item>
						</Title>
						<ExtendedTooltip name="ЭтапыГрафикаОплатыЗаполнитьЭтапыГрафикаОплатыExtendedTooltip" id="54"/>
					</Button>
				</ChildItems>
			</AutoCommandBar>
			<ExtendedTooltip name="ЭтапыГрафикаОплатыExtendedTooltip" id="55"/>
			<SearchStringAddition name="ЭтапыГрафикаОплатыSearchString" id="56">
				<Source>
					<lf:elementId>6</lf:elementId>
					<lf:additionId>0</lf:additionId>
				</Source>
				<ContextMenu name="ЭтапыГрафикаОплатыSearchStringContextMenu" id="57"/>
				<ExtendedTooltip name="ЭтапыГрафикаОплатыSearchStringExtendedTooltip" id="58"/>
			</SearchStringAddition>
			<ViewStatusAddition name="ЭтапыГрафикаОплатыViewStatus" id="59">
				<Source>
					<lf:elementId>6</lf:elementId>
					<lf:additionId>1</lf:additionId>
				</Source>
				<ContextMenu name="ЭтапыГрафикаОплатыViewStatusContextMenu" id="60"/>
				<ExtendedTooltip name="ЭтапыГрафикаОплатыViewStatusExtendedTooltip" id="61"/>
			</ViewStatusAddition>
			<SearchControlAddition name="ЭтапыГрафикаОплатыSearchControl" id="62">
				<Source>
					<lf:elementId>6</lf:elementId>
					<lf:additionId>2</lf:additionId>
				</Source>
				<ContextMenu name="ЭтапыГрафикаОплатыSearchControlContextMenu" id="63"/>
				<ExtendedTooltip name="ЭтапыГрафикаОплатыSearchControlExtendedTooltip" id="64"/>
			</SearchControlAddition>
			<Events>
				<Event name="OnEditEnd">ЭтапыГрафикаОплатыПриОкончанииРедактирования</Event>
				<Event name="AfterDeleteRow">ЭтапыГрафикаОплатыПослеУдаления</Event>
				<Event name="OnChange">ЭтапыГрафикаОплатыПриИзменении</Event>
			</Events>
			<ChildItems>
				<LabelField name="ЭтапыГрафикаОплатыНомерСтроки" id="40">
					<DataPath>Объект.ЭтапыГрафикаОплаты.LineNumber</DataPath>
					<EditMode>EnterOnInput</EditMode>
					<Width>3</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<ContextMenu name="ЭтапыГрафикаОплатыНомерСтрокиКонтекстноеМеню" id="41"/>
					<ExtendedTooltip name="ЭтапыГрафикаОплатыНомерСтрокиExtendedTooltip" id="65"/>
				</LabelField>
				<InputField name="ЭтапыГрафикаОплатыВариантОплаты" id="42">
					<DataPath>Объект.ЭтапыГрафикаОплаты.ВариантОплаты</DataPath>
					<EditMode>EnterOnInput</EditMode>
					<HorizontalStretch>false</HorizontalStretch>
					<ListChoiceMode>true</ListChoiceMode>
					<AutoMarkIncomplete>true</AutoMarkIncomplete>
					<ChoiceList>
						<xr:Item>
							<xr:Presentation/>
							<xr:CheckState>0</xr:CheckState>
							<xr:Value xsi:type="FormChoiceListDesTimeValue">
								<Presentation>
									<v8:item>
										<v8:lang>ru</v8:lang>
										<v8:content>Аванс или возврат (до обеспечения)</v8:content>
									</v8:item>
								</Presentation>
								<Value xsi:type="xr:DesignTimeRef">Enum.ВариантыОплатыКлиентом.EnumValue.АвансДоОбеспечения</Value>
							</xr:Value>
						</xr:Item>
						<xr:Item>
							<xr:Presentation/>
							<xr:CheckState>0</xr:CheckState>
							<xr:Value xsi:type="FormChoiceListDesTimeValue">
								<Presentation>
									<v8:item>
										<v8:lang>ru</v8:lang>
										<v8:content>Предоплата или возврат (до отгрузки)</v8:content>
									</v8:item>
								</Presentation>
								<Value xsi:type="xr:DesignTimeRef">Enum.ВариантыОплатыКлиентом.EnumValue.ПредоплатаДоОтгрузки</Value>
							</xr:Value>
						</xr:Item>
						<xr:Item>
							<xr:Presentation/>
							<xr:CheckState>0</xr:CheckState>
							<xr:Value xsi:type="FormChoiceListDesTimeValue">
								<Presentation>
									<v8:item>
										<v8:lang>ru</v8:lang>
										<v8:content>Кредит или возврат (после отгрузки)</v8:content>
									</v8:item>
								</Presentation>
								<Value xsi:type="xr:DesignTimeRef">Enum.ВариантыОплатыКлиентом.EnumValue.КредитПослеОтгрузки</Value>
							</xr:Value>
						</xr:Item>
					</ChoiceList>
					<ContextMenu name="ЭтапыГрафикаОплатыВариантОплатыКонтекстноеМеню" id="43"/>
					<ExtendedTooltip name="ЭтапыГрафикаОплатыВариантОплатыExtendedTooltip" id="66"/>
				</InputField>
				<InputField name="ЭтапыГрафикаОплатыДатаПлатежа" id="44">
					<DataPath>Объект.ЭтапыГрафикаОплаты.ДатаПлатежа</DataPath>
					<EditMode>EnterOnInput</EditMode>
					<Width>8</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<AutoMarkIncomplete>true</AutoMarkIncomplete>
					<ContextMenu name="ЭтапыГрафикаОплатыДатаПлатежаКонтекстноеМеню" id="45"/>
					<ExtendedTooltip name="ЭтапыГрафикаОплатыДатаПлатежаExtendedTooltip" id="67"/>
				</InputField>
				<InputField name="ЭтапыГрафикаОплатыПроцентПлатежа" id="46">
					<DataPath>Объект.ЭтапыГрафикаОплаты.ПроцентПлатежа</DataPath>
					<EditMode>EnterOnInput</EditMode>
					<Width>6</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<AutoMarkIncomplete>true</AutoMarkIncomplete>
					<ContextMenu name="ЭтапыГрафикаОплатыПроцентПлатежаКонтекстноеМеню" id="47"/>
					<ExtendedTooltip name="ЭтапыГрафикаОплатыПроцентПлатежаExtendedTooltip" id="68"/>
					<Events>
						<Event name="OnChange">ЭтапыГрафикаОплатыПроцентПлатежаПриИзменении</Event>
					</Events>
				</InputField>
				<InputField name="ЭтапыГрафикаОплатыСуммаПлатежа" id="48">
					<DataPath>Объект.ЭтапыГрафикаОплаты.СуммаПлатежа</DataPath>
					<EditMode>EnterOnInput</EditMode>
					<Width>9</Width>
					<HorizontalStretch>false</HorizontalStretch>
					<AutoMarkIncomplete>true</AutoMarkIncomplete>
					<ContextMenu name="ЭтапыГрафикаОплатыСуммаПлатежаКонтекстноеМеню" id="49"/>
					<ExtendedTooltip name="ЭтапыГрафикаОплатыСуммаПлатежаExtendedTooltip" id="69"/>
					<Events>
						<Event name="OnChange">ЭтапыГрафикаОплатыСуммаПлатежаПриИзменении</Event>
					</Events>
				</InputField>
			</ChildItems>
		</Table>
	</ChildItems>
	<Attributes>
		<Attribute name="Объект" id="4">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Объект</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>cfg:DocumentObject.ЗаявкаНаВозвратТоваровОтКлиента</v8:Type>
			</Type>
			<SavedData>true</SavedData>
			<UseAlways>
				<Field>Объект.RegisterRecords</Field>
				<Field>Объект.Posted</Field>
				<Field>Объект.DeletionMark</Field>
				<Field>Объект.Number</Field>
				<Field>Объект.НеОтгружатьЧастями</Field>
				<Field>Объект.БанковскийСчетГрузоотправителя</Field>
				<Field>Объект.Контрагент</Field>
				<Field>Объект.Организация</Field>
				<Field>Объект.Согласован</Field>
				<Field>Объект.Менеджер</Field>
				<Field>Объект.ГруппаФинансовогоУчета</Field>
				<Field>Объект.Сделка</Field>
				<Field>Объект.ДатаПоступления</Field>
				<Field>Объект.БанковскийСчет</Field>
				<Field>Объект.ЧекККМ</Field>
				<Field>Объект.ЖелаемаяДатаПоступления</Field>
				<Field>Объект.АдресДоставки</Field>
				<Field>Объект.ДокументРеализации</Field>
				<Field>Объект.БанковскийСчетГрузополучателя</Field>
				<Field>Объект.НалогообложениеНДС</Field>
				<Field>Объект.ДатаОтгрузки</Field>
				<Field>Объект.Грузоотправитель</Field>
				<Field>Объект.ПорядокРасчетов</Field>
				<Field>Объект.СкидкиРассчитаны</Field>
				<Field>Объект.Склад</Field>
				<Field>Объект.ЦенаВключаетНДС</Field>
				<Field>Объект.ЗаменяющиеТовары</Field>
				<Field>Объект.ДополнительныеРеквизиты</Field>
				<Field>Объект.ЗаменяющиеТоварыМаксимальныйКодСтроки</Field>
				<Field>Объект.ВозвращаемыеСерии</Field>
				<Field>Объект.ХозяйственнаяОперация</Field>
				<Field>Объект.ДатаСогласования</Field>
				<Field>Объект.БанковскийСчетКонтрагента</Field>
				<Field>Объект.ВозвращаемыеТовары</Field>
				<Field>Объект.СуммаПредоплатыДоОтгрузки</Field>
				<Field>Объект.ФормаОплаты</Field>
				<Field>Объект.СуммаАвансаДоОбеспечения</Field>
				<Field>Объект.Приоритет</Field>
				<Field>Объект.КартаЛояльности</Field>
				<Field>Объект.Грузополучатель</Field>
				<Field>Объект.Статус</Field>
				<Field>Объект.СкидкиНаценки</Field>
				<Field>Объект.ДатаПервогоПоступления</Field>
				<Field>Объект.ВозвратПорчи</Field>
				<Field>Объект.ВозвращаемыеТоварыМаксимальныйКодСтроки</Field>
				<Field>Объект.Договор</Field>
				<Field>Объект.Касса</Field>
				<Field>Объект.СуммаЗамены</Field>
				<Field>Объект.ПоступлениеОднойДатой</Field>
				<Field>Объект.Партнер</Field>
				<Field>Объект.Комментарий</Field>
				<Field>Объект.ДополнительнаяИнформация</Field>
				<Field>Объект.ЗаменяющиеСерии</Field>
			</UseAlways>
			<Columns>
				<AdditionalColumns table="Объект.ЭтапыГрафикаОплаты">
					<Column name="ДатаЗаполненаНеВерно" id="1">
						<Title>
							<v8:item>
								<v8:lang>ru</v8:lang>
								<v8:content>Дата заполнена не верно</v8:content>
							</v8:item>
						</Title>
						<Type>
							<v8:Type>xs:boolean</v8:Type>
						</Type>
					</Column>
					<Column name="ПроцентЗаполненНеВерно" id="2">
						<Title>
							<v8:item>
								<v8:lang>ru</v8:lang>
								<v8:content>Процент заполнен не верно</v8:content>
							</v8:item>
						</Title>
						<Type>
							<v8:Type>xs:boolean</v8:Type>
						</Type>
					</Column>
				</AdditionalColumns>
			</Columns>
		</Attribute>
		<Attribute name="ИдентификаторВызывающейФормы" id="5">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Идентификатор вызывающей формы</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>v8:UUID</v8:Type>
			</Type>
		</Attribute>
		<Attribute name="НомерСтрокиПолнойОплаты" id="6">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Номер строки полной оплаты</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>10</v8:Digits>
					<v8:FractionDigits>0</v8:FractionDigits>
					<v8:AllowedSign>Any</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="Готово" id="1">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Готово</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
		<Attribute name="СуммаАвансаДоОбеспечения" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Аванс до обеспечения</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>15</v8:Digits>
					<v8:FractionDigits>2</v8:FractionDigits>
					<v8:AllowedSign>Nonnegative</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="СуммаКредитаПослеОтгрузки" id="7">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Кредит после отгрузки</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>15</v8:Digits>
					<v8:FractionDigits>2</v8:FractionDigits>
					<v8:AllowedSign>Nonnegative</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="СуммаПредоплатыДоОтгрузки" id="8">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Предоплата до отгрузки</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>15</v8:Digits>
					<v8:FractionDigits>2</v8:FractionDigits>
					<v8:AllowedSign>Nonnegative</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="ПроцентАвансаДоОбеспечения" id="9">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>%</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>3</v8:Digits>
					<v8:FractionDigits>0</v8:FractionDigits>
					<v8:AllowedSign>Nonnegative</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="ПроцентКредитаПослеОтгрузки" id="10">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>%</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>3</v8:Digits>
					<v8:FractionDigits>0</v8:FractionDigits>
					<v8:AllowedSign>Nonnegative</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="ПроцентПредоплатыДоОтгрузки" id="11">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>%</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>3</v8:Digits>
					<v8:FractionDigits>0</v8:FractionDigits>
					<v8:AllowedSign>Nonnegative</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Attribute>
		<Attribute name="ТолькоПросмотр" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Только просмотр</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Attribute>
		<ConditionalAppearance>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>ЭтапыГрафикаОплатыДатаПлатежа</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">Объект.ЭтапыГрафикаОплаты.ДатаЗаполненаНеВерно</dcsset:left>
						<dcsset:comparisonType>Equal</dcsset:comparisonType>
						<dcsset:right xsi:type="xs:boolean">true</dcsset:right>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>TextColor</dcscor:parameter>
						<dcscor:value xsi:type="v8ui:Color">web:FireBrick</dcscor:value>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>ЭтапыГрафикаОплатыПроцентПлатежа</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">Объект.ЭтапыГрафикаОплаты.ПроцентЗаполненНеВерно</dcsset:left>
						<dcsset:comparisonType>Equal</dcsset:comparisonType>
						<dcsset:right xsi:type="xs:boolean">true</dcsset:right>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>TextColor</dcscor:parameter>
						<dcscor:value xsi:type="v8ui:Color">web:FireBrick</dcscor:value>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>ЭтапыГрафикаОплатыПроцентПлатежа</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">Объект.ЭтапыГрафикаОплаты.ДатаЗаполненаНеВерно</dcsset:left>
						<dcsset:comparisonType>Equal</dcsset:comparisonType>
						<dcsset:right xsi:type="xs:boolean">false</dcsset:right>
					</dcsset:item>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">Объект.ЭтапыГрафикаОплаты.НомерСтроки</dcsset:left>
						<dcsset:comparisonType>LessOrEqual</dcsset:comparisonType>
						<dcsset:right xsi:type="dcscor:Field">НомерСтрокиПолнойОплаты</dcsset:right>
					</dcsset:item>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">НомерСтрокиПолнойОплаты</dcsset:left>
						<dcsset:comparisonType>NotEqual</dcsset:comparisonType>
						<dcsset:right xsi:type="xs:decimal">0</dcsset:right>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>TextColor</dcscor:parameter>
						<dcscor:value xsi:type="v8ui:Color">web:Seagreen</dcscor:value>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>ЭтапыГрафикаОплатыВариантОплаты</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">Объект.ЭтапыГрафикаОплаты.ВариантОплаты</dcsset:left>
						<dcsset:comparisonType>Equal</dcsset:comparisonType>
						<dcsset:right xsi:type="dcscor:DesignTimeValue">Перечисление.ВариантыОплатыКлиентом.АвансДоОбеспечения</dcsset:right>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>Text</dcscor:parameter>
						<dcscor:value xsi:type="xs:string">Аванс или возврат (до обеспечения)</dcscor:value>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>ЭтапыГрафикаОплатыВариантОплаты</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">Объект.ЭтапыГрафикаОплаты.ВариантОплаты</dcsset:left>
						<dcsset:comparisonType>Equal</dcsset:comparisonType>
						<dcsset:right xsi:type="dcscor:DesignTimeValue">Перечисление.ВариантыОплатыКлиентом.ПредоплатаДоОтгрузки</dcsset:right>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>Text</dcscor:parameter>
						<dcscor:value xsi:type="xs:string">Предоплата или возврат (до отгрузки)</dcscor:value>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
			<dcsset:item>
				<dcsset:selection>
					<dcsset:item>
						<dcsset:field>ЭтапыГрафикаОплатыВариантОплаты</dcsset:field>
					</dcsset:item>
				</dcsset:selection>
				<dcsset:filter>
					<dcsset:item xsi:type="dcsset:FilterItemComparison">
						<dcsset:left xsi:type="dcscor:Field">Объект.ЭтапыГрафикаОплаты.ВариантОплаты</dcsset:left>
						<dcsset:comparisonType>Equal</dcsset:comparisonType>
						<dcsset:right xsi:type="dcscor:DesignTimeValue">Перечисление.ВариантыОплатыКлиентом.КредитПослеОтгрузки</dcsset:right>
					</dcsset:item>
				</dcsset:filter>
				<dcsset:appearance>
					<dcscor:item xsi:type="dcsset:SettingsParameterValue">
						<dcscor:parameter>Text</dcscor:parameter>
						<dcscor:value xsi:type="xs:string">Кредит или возврат (после отгрузки)</dcscor:value>
					</dcscor:item>
				</dcsset:appearance>
			</dcsset:item>
		</ConditionalAppearance>
	</Attributes>
	<Commands>
		<Command name="ОК" id="1">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>ОК</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>ОК</v8:content>
				</v8:item>
			</ToolTip>
			<Action>ОК</Action>
		</Command>
		<Command name="Отмена" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Отмена</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Отмена</v8:content>
				</v8:item>
			</ToolTip>
			<Action>Отмена</Action>
		</Command>
		<Command name="ЗаполнитьЭтапыГрафикаОплаты" id="3">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Заполнить этапы графика расчетов</v8:content>
				</v8:item>
			</Title>
			<ToolTip>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Заполнить этапы в соответствии с графиком оплаты</v8:content>
				</v8:item>
			</ToolTip>
			<Picture>
				<xr:Ref>CommonPicture.ЗаполнитьЭтапыГрафикаОплаты</xr:Ref>
				<xr:LoadTransparent>false</xr:LoadTransparent>
			</Picture>
			<Action>ЗаполнитьЭтапыГрафикаОплаты</Action>
			<Representation>TextPicture</Representation>
			<ModifiesSavedData>true</ModifiesSavedData>
		</Command>
	</Commands>
	<Parameters>
		<Parameter name="СуммаВсего">
			<Type>
				<v8:Type>xs:decimal</v8:Type>
				<v8:NumberQualifiers>
					<v8:Digits>15</v8:Digits>
					<v8:FractionDigits>2</v8:FractionDigits>
					<v8:AllowedSign>Nonnegative</v8:AllowedSign>
				</v8:NumberQualifiers>
			</Type>
		</Parameter>
		<Parameter name="УникальныйИдентификатор">
			<Type/>
		</Parameter>
		<Parameter name="АдресВоВременномХранилище">
			<Type>
				<v8:Type>xs:string</v8:Type>
				<v8:StringQualifiers>
					<v8:Length>0</v8:Length>
					<v8:AllowedLength>Variable</v8:AllowedLength>
				</v8:StringQualifiers>
			</Type>
		</Parameter>
		<Parameter name="ГрафикОплаты">
			<Type>
				<v8:Type>cfg:CatalogRef.ГрафикиОплаты</v8:Type>
			</Type>
		</Parameter>
		<Parameter name="ТолькоПросмотр">
			<Type>
				<v8:Type>xs:boolean</v8:Type>
			</Type>
		</Parameter>
	</Parameters>
	<CommandInterface>
		<NavigationPanel>
			<Item>
				<Command>CommonCommand.ИсторияИзменений</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>InformationRegister.ЦеныНоменклатурыПоставщиков.StandardCommand.OpenByValue.Соглашение</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Catalog.УсловияЦенПоставщиков.StandardCommand.OpenByValue</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ПрисоединенныеФайлыКОбъекту</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.РегистрацияЦенНоменклатурыПоставщика.Command.ОткрытиеСпискаРегистрацийЦенНоменклатурыПоставщиковПоСоглашению</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ЗадачиПоПредмету</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Report.УсловияЗакупок.Command.УсловияЗакупок</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ЗаметкиПоПредмету</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>0</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>0</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Report.КарточкаРасчетовСКлиентами.Command.КарточкаРасчетовСКлиентом</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Report.СостояниеВыполненияЗаявокНаВозвратТоваровОтКлиентов.Command.СостояниеВыполненияЗаявокНаВозвратТоваровОтКлиентов</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Report.СостояниеВыполненияЗаказовКлиентов.Command.СостояниеВыполненияЗаказаКлиента</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Report.СостояниеВыполненияЗаказовКлиентов.Command.СостояниеЗамены</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Report.СостояниеРасчетовСКлиентами.Command.СостояниеРасчетовСКлиентом</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Report.ДвиженияДокумента.Command.ДвиженияДокумента</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Report.РезультатыСогласованияЗаявкиНаВозвратТоваровОтКлиента.Command.РезультатыСогласованияЗаявкиНаВозвратТоваровОтКлиентаПоДокументу</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.СтруктураПодчиненности</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>BusinessProcess.СогласованиеЗаявкиНаВозвратТоваровОтКлиента.Command.СогласованиеПоПредмету</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
		</NavigationPanel>
		<CommandBar>
			<Item>
				<Command>CommonCommand.ДополнительныеСведенияКоманднаяПанель</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ДополнительныеОтчетыИОбработкиЗаполнениеОбъекта</Command>
				<Type>Auto</Type>
				<Index>2</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ДополнительныеОтчетыИОбработкиОтчеты</Command>
				<Type>Auto</Type>
				<Index>1</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Catalog.ДоговорыКонтрагентов.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ЗаказПоставщику.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<Index>1</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>DataProcessor.ПомощникРегистрацииЦенПоставщика.Command.РегистрацияЦенНаОсновании</Command>
				<Type>Auto</Type>
				<Index>4</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>BusinessProcess.Задание.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<Index>2</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ПоступлениеТоваровУслуг.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<Index>3</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>2:b3eb969e-692a-4c6d-b8fc-1efd711b4339</Command>
				<Type>Auto</Type>
				<Index>5</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ДополнительныеОтчетыИОбработкиСозданиеСвязанныхОбъектов</Command>
				<Type>Auto</Type>
				<Index>6</Index>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.ДополнительныеОтчетыИОбработкиПечатныеФормы</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.АктВыполненныхРабот.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>0</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ВозвратТоваровОтКлиента.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ЗаявкаНаРасходованиеДенежныхСредств.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.РеализацияТоваровУслуг.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>BusinessProcess.СогласованиеЗаявкиНаВозвратТоваровОтКлиента.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.СчетНаОплатуКлиенту.Command.СоздатьСчетНаОплату</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>Document.ПриходныйКассовыйОрдер.StandardCommand.CreateBasedOn</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.СоздатьЗаметкуПоПредмету</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
			<Item>
				<Command>CommonCommand.УстановитьНапоминаниеПоПредмету</Command>
				<Type>Auto</Type>
				<DefaultVisible>false</DefaultVisible>
				<Visible>
					<xr:Common>false</xr:Common>
				</Visible>
			</Item>
		</CommandBar>
	</CommandInterface>
</Form>


text:
import '../../../amp-base-carousel/1.0/amp-base-carousel';
import '../amp-stream-gallery';
import {useStyles} from '#bento/components/bento-base-carousel/1.0/component.jss';

import {ActionTrust_Enum} from '#core/constants/action-constants';
import {createElementWithAttributes, waitForChildPromise} from '#core/dom';
import {setStyles} from '#core/dom/style';
import {toArray} from '#core/types/array';

import {toggleExperiment} from '#experiments';

import {ActionInvocation} from '#service/action-impl';

import {waitFor} from '#testing/helpers/service';
import {poll} from '#testing/iframe';

describes.realWin(
  'amp-stream-gallery',
  {
    amp: {
      extensions: ['amp-stream-gallery:1.0'],
    },
  },
  (env) => {
    let win;
    let element;
    const userSuppliedChildren = [];

    const styles = useStyles();

    beforeEach(async () => {
      win = env.win;
      toggleExperiment(win, 'bento-stream-gallery', true, true);
      element = createElementWithAttributes(
        win.document,
        'amp-stream-gallery',
        {
          'layout': 'fixed',
          'width': '300px',
          'height': '200px',
        }
      );

      // Add slides.
      for (let i = 0; i < 3; i++) {
        const slide = newSlide(`${i}`);
        userSuppliedChildren[i] = slide;
        element.appendChild(slide);
      }
    });

    afterEach(() => {
      toggleExperiment(win, 'bento-stream-gallery', false, true);
    });

    function newSlide(id) {
      const slide = document.createElement('div');
      slide.className = 'test-slide';
      setStyles(slide, {
        flexShrink: '0',
        height: '100px',
        width: '100%',
      });
      slide.textContent = 'slide ' + id;
      return slide;
    }

    async function getSlideWrappersFromShadow() {
      await element.buildInternal();
      const shadow = element.shadowRoot;
      await waitForChildPromise(shadow, (shadow) => {
        return shadow.querySelectorAll('[class*=hideScrollbar]');
      });
      await waitFor(
        () =>
          shadow.querySelectorAll(`[class*=${styles.hideScrollbar}] `).length >
          0,
        'slots rendered'
      );
      return shadow.querySelectorAll(
        `[class*=${styles.hideScrollbar}] [class*=${styles.slideElement}]`
      );
    }

    async function getSlidesFromShadow() {
      const wrappers = await getSlideWrappersFromShadow();
      const slots = Array.from(wrappers)
        .map((wrapper) => wrapper.querySelector('slot'))
        .filter(Boolean);
      return toArray(slots).reduce(
        (acc, slot) => acc.concat(slot.assignedElements()),
        []
      );
    }

    it('should render slides and arrows when built', async () => {
      win.document.body.appendChild(element);
      await element.buildInternal();

      const renderedSlides = await getSlidesFromShadow();
      expect(renderedSlides).to.have.ordered.members(userSuppliedChildren);
      const buttons = element.shadowRoot.querySelectorAll('button');
      expect(buttons).to.have.length(2);
    });

    it('should render custom arrows when given', async () => {
      const customPrev = createElementWithAttributes(win.document, 'button', {
        'slot': 'prev-arrow',
      });
      const customNext = createElementWithAttributes(win.document, 'button', {
        'slot': 'next-arrow',
      });
      element.appendChild(customPrev);
      element.appendChild(customNext);
      win.document.body.appendChild(element);
      await element.buildInternal();

      const renderedSlides = await getSlidesFromShadow();
      expect(renderedSlides).to.have.ordered.members(userSuppliedChildren);

      const defaultButtons = element.shadowRoot.querySelectorAll('button');
      expect(defaultButtons).to.have.length(0);

      const slotButtons = element.shadowRoot.querySelectorAll(
        'slot[name="prev-arrow"], slot[name="next-arrow"]'
      );
      expect(slotButtons).to.have.length(2);
      expect(slotButtons[0].assignedElements()).to.have.ordered.members([
        customPrev,
      ]);
      expect(slotButtons[1].assignedElements()).to.have.ordered.members([
        customNext,
      ]);
    });

    it('should render in preparation for looping with loop prop', async () => {
      element.setAttribute('loop', '');
      win.document.body.appendChild(element);
      await element.buildInternal();

      const renderedSlideWrappers = await getSlideWrappersFromShadow();
      // Given slides [0][1][2] should be rendered as [2][0][1]. But [2] is
      // a placeholder.
      expect(renderedSlideWrappers).to.have.lengthOf(3);
      expect(
        renderedSlideWrappers[0].querySelector('slot').assignedElements()
      ).to.deep.equal([userSuppliedChildren[2]]);
      expect(
        renderedSlideWrappers[1].querySelector('slot').assignedElements()
      ).to.deep.equal([userSuppliedChildren[0]]);
      expect(
        renderedSlideWrappers[2].querySelector('slot').assignedElements()
      ).to.deep.equal([userSuppliedChildren[1]]);
    });

    describe('imperative api', () => {
      beforeEach(async () => {
        element.setAttribute('max-visible-count', '1');
        win.document.body.appendChild(element);
        await element.buildInternal();
      });

      afterEach(() => {
        win.document.body.removeChild(element);
      });

      function invocation(method, args = {}) {
        const source = null;
        const caller = null;
        const event = null;
        const trust = ActionTrust_Enum.DEFAULT;
        return new ActionInvocation(
          element,
          method,
          args,
          source,
          caller,
          event,
          trust
        );
      }

      it('should execute next and prev actions', async () => {
        const eventSpy = env.sandbox.spy();
        element.addEventListener('slideChange', eventSpy);

        element.enqueAction(invocation('next'));
        // These must wait longer than `waitFor` because of
        // the render on debounced scrolling.
        await poll(
          'advanced to next slide',
          () => eventSpy.callCount > 0,
          null,
          1000
        );

        expect(eventSpy).to.be.calledOnce;
        expect(eventSpy.firstCall).calledWithMatch({
          'data': {
            'index': 1,
          },
        });

        element.enqueAction(invocation('prev'));
        // These must wait longer than `waitFor` because of
        // the render on debounced scrolling.
        await poll(
          'returned to prev slide',
          () => eventSpy.callCount > 1,
          null,
          1000
        );
        expect(eventSpy).to.be.calledTwice;
        expect(eventSpy.secondCall).calledWithMatch({
          'data': {
            'index': 0,
          },
        });
      });

      it('should execute goToSlide action', async () => {
        const eventSpy = env.sandbox.spy();
        element.addEventListener('slideChange', eventSpy);

        element.enqueAction(invocation('goToSlide', {index: 1}));
        await waitFor(() => eventSpy.callCount > 0, 'go to slide 1');
        expect(eventSpy).to.be.calledOnce;
        expect(eventSpy.firstCall).calledWithMatch({
          'data': {
            'index': 1,
          },
        });

        element.enqueAction(invocation('goToSlide', {index: 0}));
        await waitFor(() => eventSpy.callCount > 1, 'returned to first slide');
        expect(eventSpy).to.be.calledTwice;
        expect(eventSpy.secondCall).calledWithMatch({
          'data': {
            'index': 0,
          },
        });
      });
    });
  }
);


text:
import React from 'react';

const Counter = ({onIncrement, onDecrement, onClear, onDelete, id, value}) => {
  let input;
	return (

{value}

			<button onClick={() => onIncrement(id, 1)}>+</button>
			<button onClick={() => onDecrement(id, 1)}>-</button>
			<button onClick={() => onClear(id)}>clear</button>
			<button onClick={() => onDelete(id)}>Delete</button>
			<form onSubmit={function(e) {
				e.preventDefault() //so page is not refreshed and everything is not reset.
        input.value = 0;
      }}>
        <input type="number"ref={node => { input = node }} />
        <input type="submit" value="increment" onClick={() => {return onIncrement(id, input.value)}}/>
				<input type="submit" value="decrement" onClick={() => {return onDecrement(id, input.value)}}/>
      </form>

  )
}

export default Counter;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>yusnet - Yu Liang's Blog</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="description" content="Programming portfolio specialising in Java, Javascript, HTML, C/C++, Delphi, SQL, .Net..." />
<meta name="keywords" content="programming,portfolio,Java, Javascript, HTML, C/C++, Delphi, SQL, .Net, GIS, ERP, MIS" />
<link href="css/global.css" rel="stylesheet" type="text/css" />

Yu Liang - Programming Portfolio

Home

Work

Blog

Contact

Programmer

Hello! Welcome to my portfolio site. In here, you can view a selection of my works, discover what are planning in my mind, and get to know what am I familiar with and interested in. I hope you like this site. Any suggestion or question are very welcome! Enjoy!

The blog is underconstruction.

Tech News

      Click here to view more

Soft-Devel News

      Click here to view more

Links

Temple University

lizardbase

InfoQ

Engadget

Jandan

Wenxue City

Yu Liang - Programming Portfolio

Home

Work

Blog

Contact


text:
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class ResetDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dev:reset-database {db_name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Reset database and seeding data';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        foreach (DB::select('SHOW TABLES') as $table) {
            $table_array = get_object_vars($table);
            \Schema::drop($table_array[key($table_array)]);
        }
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');

        Artisan::call('migrate', ['--force' => true]);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'CoreDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'FrameworkDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'CoreDefaultAdminDatabaseSeeder']);
        Artisan::call('framework:default-account', ['db_name' => $this->argument('db_name')]);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'CoreDevDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'FrameworkDevDatabaseSeeder']);

        // ADD PLUGINS SEEDING HERE
        Artisan::call('db:seed', ['--force' => true, '--class' => 'PointInventoryDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'PointPurchasingDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'PointSalesDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'PointExpeditionDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'PointManufactureDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'PointFinanceDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'PointAccountingDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'BumiDepositDatabaseSeeder']);
        Artisan::call('db:seed', ['--force' => true, '--class' => 'BumiSharesDatabaseSeeder']);

        // UPDATE ROLES ADMINISTRATOR ROLE
        Artisan::call('db:seed', ['--force' => true, '--class' => 'CoreDefaultAdminDatabaseSeeder']);
    }
}