<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2008-2012  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// TextCell
//============================================================================

/**
    A module that allow to create different type of Text Cell
    @module IPython
    @namespace IPython
 */
var IPython = (function (IPython) {

    // TextCell base class
    var key = IPython.utils.keycodes;

    /**
     * Construct a new TextCell, codemirror mode is by default 'htmlmixed', and cell type is 'text'
     * cell start as not redered.
     *
     * @class TextCell
     * @constructor TextCell
     * @extend Ipython.Cell
     * @param {object|undefined} [options]
     *      @param [options.cm_config] {object} config to pass to CodeMirror, will extend/overwrite default config
     */
    var TextCell = function (options) {
        this.code_mirror_mode = this.code_mirror_mode || 'htmlmixed';
        var options = options || {};

        var cm_overwrite_options  = {
            extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess"},
            onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
        };

        var arg_cm_options = options.cm_options || {};
        var cm_config = $.extend({},TextCell.cm_default, arg_cm_options, cm_overwrite_options);

        var options = {};
        options.cm_config = cm_config;

        IPython.Cell.apply(this, [options]);
        this.rendered = false;
        this.cell_type = this.cell_type || 'text';
    };

    TextCell.cm_default = {
            mode: this.code_mirror_mode,
            theme: 'default',
            value: this.placeholder,
            lineWrapping : true,
        }

    TextCell.prototype = new IPython.Cell();

    /**
     * Create the DOM element of the TextCell
     * @method create_element
     * @private
     */
    TextCell.prototype.create_element = function () {
        IPython.Cell.prototype.create_element.apply(this, arguments);
        var cell = $("
").addClass('cell text_cell border-box-sizing vbox');
        cell.attr('tabindex','2');

        this.celltoolbar = new IPython.CellToolbar(this);
        cell.append(this.celltoolbar.element);

        var input_area = $('
').addClass('text_cell_input border-box-sizing');
        this.code_mirror = CodeMirror(input_area.get(0), this.cm_config);
        // The tabindex=-1 makes this div focusable.
        var render_area = $('
').addClass('text_cell_render border-box-sizing').
            addClass('rendered_html').attr('tabindex','-1');
        cell.append(input_area).append(render_area);
        this.element = cell;
    };

    /**
     * Bind the DOM evet to cell actions
     * Need to be called after TextCell.create_element
     * @private
     * @method bind_event
     */
    TextCell.prototype.bind_events = function () {
        IPython.Cell.prototype.bind_events.apply(this);
        var that = this;
        this.element.keydown(function (event) {
            if (event.which === 13 && !event.shiftKey) {
                if (that.rendered) {
                    that.edit();
                    return false;
                };
            };
        });
        this.element.dblclick(function () {
            that.edit();
        });
    };

    /**
     * This method gets called in CodeMirror's onKeyDown/onKeyPress
     * handlers and is used to provide custom key handling.
     *
     * Subclass should override this method to have custom handeling
     *
     * @method handle_codemirror_keyevent
     * @param {CodeMirror} editor - The codemirror instance bound to the cell
     * @param {event} event -
     * @return {Boolean} `true` if CodeMirror should ignore the event, `false` Otherwise
     */
    TextCell.prototype.handle_codemirror_keyevent = function (editor, event) {

        if (event.keyCode === 13 && (event.shiftKey || event.ctrlKey)) {
            // Always ignore shift-enter in CodeMirror as we handle it.
            return true;
        }
        return false;
    };

    /**
     * Select the current cell and trigger 'focus'
     * @method select
     */
    TextCell.prototype.select = function () {
        IPython.Cell.prototype.select.apply(this);
        var output = this.element.find("div.text_cell_render");
        output.trigger('focus');
    };

    /**
     * unselect the current cell and `render` it
     * @method unselect
     */
    TextCell.prototype.unselect = function() {
        // render on selection of another cell
        this.render();
        IPython.Cell.prototype.unselect.apply(this);
    };

    /**
     *
     * put the current cell in edition mode
     * @method edit
     */
    TextCell.prototype.edit = function () {
        if ( this.read_only ) return;
        if (this.rendered === true) {
            var text_cell = this.element;
            var output = text_cell.find("div.text_cell_render");
            output.hide();
            text_cell.find('div.text_cell_input').show();
            this.code_mirror.refresh();
            this.code_mirror.focus();
            // We used to need an additional refresh() after the focus, but
            // it appears that this has been fixed in CM. This bug would show
            // up on FF when a newly loaded markdown cell was edited.
            this.rendered = false;
            if (this.get_text() === this.placeholder) {
                this.set_text('');
                this.refresh();
            }
        }
    };

    /**
     * Empty, Subclasses must define render.
     * @method render
     */
    TextCell.prototype.render = function () {};

    /**
     * setter: {{#crossLink "TextCell/set_text"}}{{/crossLink}}
     * @method get_text
     * @retrun {string} CodeMirror current text value
     */
    TextCell.prototype.get_text = function() {
        return this.code_mirror.getValue();
    };

    /**
     * @param {string} text - Codemiror text value
     * @see TextCell#get_text
     * @method set_text
     * */
    TextCell.prototype.set_text = function(text) {
        this.code_mirror.setValue(text);
        this.code_mirror.refresh();
    };

    /**
     * setter :{{#crossLink "TextCell/set_rendered"}}{{/crossLink}}
     * @method get_rendered
     * @return {html} html of rendered element
     * */
    TextCell.prototype.get_rendered = function() {
        return this.element.find('div.text_cell_render').html();
    };

    /**
     * @method set_rendered
     */
    TextCell.prototype.set_rendered = function(text) {
        this.element.find('div.text_cell_render').html(text);
    };

    /**
     * not deprecated, but implementation wrong
     * @method at_top
     * @deprecated
     * @return {Boolean} true is cell rendered, false otherwise
     * I doubt this is what it is supposed to do
     * this implementation is completly false
     */
    TextCell.prototype.at_top = function () {
        if (this.rendered) {
            return true;
        } else {
            return false;
        }
    };

    /**
     * not deprecated, but implementation wrong
     * @method at_bottom
     * @deprecated
     * @return {Boolean} true is cell rendered, false otherwise
     * I doubt this is what it is supposed to do
     * this implementation is completly false
     * */
    TextCell.prototype.at_bottom = function () {
        if (this.rendered) {
            return true;
        } else {
            return false;
        }
    };

    /**
     * Create Text cell from JSON
     * @param {json} data - JSON serialized text-cell
     * @method fromJSON
     */
    TextCell.prototype.fromJSON = function (data) {
        IPython.Cell.prototype.fromJSON.apply(this, arguments);
        if (data.cell_type === this.cell_type) {
            if (data.source !== undefined) {
                this.set_text(data.source);
                // make this value the starting point, so that we can only undo
                // to this state, instead of a blank cell
                this.code_mirror.clearHistory();
                this.set_rendered(data.rendered || '');
                this.rendered = false;
                this.render();
            }
        }
    };

    /** Generate JSON from cell
     * @return {object} cell data serialised to json
     */
    TextCell.prototype.toJSON = function () {
        var data = IPython.Cell.prototype.toJSON.apply(this);
        data.cell_type = this.cell_type;
        data.source = this.get_text();
        return data;
    };

    /**
     * @constructor HtmlCell
     * @class HtmlCell
     * @extends Ipython.TextCell
     */
    var HTMLCell = function () {
        this.placeholder = "Type HTML and LaTeX: $\\alpha^2$";
        IPython.TextCell.apply(this, arguments);
        this.cell_type = 'html';
    };

    HTMLCell.prototype = new TextCell();

    /**
     * @method render
     */
    HTMLCell.prototype.render = function () {
        if (this.rendered === false) {
            var text = this.get_text();
            if (text === "") { text = this.placeholder; }
            this.set_rendered(text);
            this.typeset();
            this.element.find('div.text_cell_input').hide();
            this.element.find("div.text_cell_render").show();
            this.rendered = true;
        }
    };

    /**
     * @class MarkdownCell
     * @constructor MarkdownCell
     * @extends Ipython.HtmlCell
     */
    var MarkdownCell = function () {
        this.placeholder = "Type *Markdown* and LaTeX: $\\alpha^2$";
        IPython.TextCell.apply(this, arguments);
        this.cell_type = 'markdown';
    };

    MarkdownCell.prototype = new TextCell();

    /**
     * @method render
     */
    MarkdownCell.prototype.render = function () {
        if (this.rendered === false) {
            var text = this.get_text();
            if (text === "") { text = this.placeholder; }
            text = IPython.mathjaxutils.remove_math(text)
            var html = IPython.markdown_converter.makeHtml(text);
            html = IPython.mathjaxutils.replace_math(html)
            try {
                this.set_rendered(html);
            } catch (e) {
                console.log("Error running Javascript in Markdown:");
                console.log(e);
                this.set_rendered($("
").addClass("js-error").html(
                    "Error rendering Markdown!
" + e.toString())
                );
            }
            this.element.find('div.text_cell_input').hide();
            this.element.find("div.text_cell_render").show();
            var code_snippets = this.element.find("pre > code");
            code_snippets.replaceWith(function () {
                var code = $(this).html();
                /* Substitute br for newlines and   for spaces
                   before highlighting, since prettify doesn't
                   preserve those on all browsers */
                code = code.replace(/(\r\n|\n|\r)/gm, "
");
                code = code.replace(/ /gm, ' ');
                code = prettyPrintOne(code);

                return '' + code + '';
            });
            this.typeset()
            this.rendered = true;
        }
    };

    // RawCell

    /**
     * @class RawCell
     * @constructor RawCell
     * @extends Ipython.TextCell
     */
    var RawCell = function () {
        this.placeholder = "Type plain text and LaTeX: $\\alpha^2$";
        this.code_mirror_mode = 'rst';
        IPython.TextCell.apply(this, arguments);
        this.cell_type = 'raw';
        var that = this

        this.element.focusout(
                function() { that.auto_highlight(); }
            );
    };

    RawCell.prototype = new TextCell();

    /**
     * Trigger autodetection of highlight scheme for current cell
     * @method auto_highlight
     */
    RawCell.prototype.auto_highlight = function () {
        this._auto_highlight(IPython.config.raw_cell_highlight);
    };

    /** @method render **/
    RawCell.prototype.render = function () {
        this.rendered = true;
        this.edit();
    };

    /** @method handle_codemirror_keyevent **/
    RawCell.prototype.handle_codemirror_keyevent = function (editor, event) {

        var that = this;
        if (event.which === key.UPARROW && event.type === 'keydown') {
            // If we are not at the top, let CM handle the up arrow and
            // prevent the global keydown handler from handling it.
            if (!that.at_top()) {
                event.stop();
                return false;
            } else {
                return true;
            };
        } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
            // If we are not at the bottom, let CM handle the down arrow and
            // prevent the global keydown handler from handling it.
            if (!that.at_bottom()) {
                event.stop();
                return false;
            } else {
                return true;
            };
        };
        return false;
    };

    /** @method select **/
    RawCell.prototype.select = function () {
        IPython.Cell.prototype.select.apply(this);
        this.code_mirror.refresh();
        this.code_mirror.focus();
    };

    /** @method at_top **/
    RawCell.prototype.at_top = function () {
        var cursor = this.code_mirror.getCursor();
        if (cursor.line === 0 && cursor.ch === 0) {
            return true;
        } else {
            return false;
        }
    };

    /** @method at_bottom **/
    RawCell.prototype.at_bottom = function () {
        var cursor = this.code_mirror.getCursor();
        if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
            return true;
        } else {
            return false;
        }
    };

    /**
     * @class HeadingCell
     * @extends Ipython.TextCell
     */

    /**
     * @constructor HeadingCell
     * @extends Ipython.TextCell
     */
    var HeadingCell = function () {
        this.placeholder = "Type Heading Here";
        IPython.TextCell.apply(this, arguments);
        /**
         * heading level of the cell, use getter and setter to access
         * @property level
         */
        this.level = 1;
        this.cell_type = 'heading';
    };

    HeadingCell.prototype = new TextCell();

    /** @method fromJSON */
    HeadingCell.prototype.fromJSON = function (data) {
        if (data.level != undefined){
            this.level = data.level;
        }
        IPython.TextCell.prototype.fromJSON.apply(this, arguments);
    };

    /** @method toJSON */
    HeadingCell.prototype.toJSON = function () {
        var data = IPython.TextCell.prototype.toJSON.apply(this);
        data.level = this.get_level();
        return data;
    };

    /**
     * Change heading level of cell, and re-render
     * @method set_level
     */
    HeadingCell.prototype.set_level = function (level) {
        this.level = level;
        if (this.rendered) {
            this.rendered = false;
            this.render();
        };
    };

    /** The depth of header cell, based on html (h1 to h6)
     * @method get_level
     * @return {integer} level - for 1 to 6
     */
    HeadingCell.prototype.get_level = function () {
        return this.level;
    };

    HeadingCell.prototype.set_rendered = function (text) {
        var r = this.element.find("div.text_cell_render");
        r.empty();
        r.append(
            $('<h'+this.level+'/>')
            .append(
            $('')
                .addClass('heading-anchor')
                .attr('href', '#' + text)
                .attr('name', text)
                .html(text)
            )
        );
    };

    HeadingCell.prototype.get_rendered = function () {
        var r = this.element.find("div.text_cell_render");
        return r.children().first().html();
    };

    HeadingCell.prototype.render = function () {
        if (this.rendered === false) {
            var text = this.get_text();
            if (text === "") { text = this.placeholder; }
            this.set_rendered(text);
            this.typeset();
            this.element.find('div.text_cell_input').hide();
            this.element.find("div.text_cell_render").show();
            this.rendered = true;
        };
    };

    IPython.TextCell = TextCell;
    IPython.HTMLCell = HTMLCell;
    IPython.MarkdownCell = MarkdownCell;
    IPython.RawCell = RawCell;
    IPython.HeadingCell = HeadingCell;

    return IPython;

}(IPython));

<commit_msg>minor heading-link tweaks<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2008-2012  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// TextCell
//============================================================================

/**
    A module that allow to create different type of Text Cell
    @module IPython
    @namespace IPython
 */
var IPython = (function (IPython) {

    // TextCell base class
    var key = IPython.utils.keycodes;

    /**
     * Construct a new TextCell, codemirror mode is by default 'htmlmixed', and cell type is 'text'
     * cell start as not redered.
     *
     * @class TextCell
     * @constructor TextCell
     * @extend Ipython.Cell
     * @param {object|undefined} [options]
     *      @param [options.cm_config] {object} config to pass to CodeMirror, will extend/overwrite default config
     */
    var TextCell = function (options) {
        this.code_mirror_mode = this.code_mirror_mode || 'htmlmixed';
        var options = options || {};

        var cm_overwrite_options  = {
            extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess"},
            onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
        };

        var arg_cm_options = options.cm_options || {};
        var cm_config = $.extend({},TextCell.cm_default, arg_cm_options, cm_overwrite_options);

        var options = {};
        options.cm_config = cm_config;

        IPython.Cell.apply(this, [options]);
        this.rendered = false;
        this.cell_type = this.cell_type || 'text';
    };

    TextCell.cm_default = {
            mode: this.code_mirror_mode,
            theme: 'default',
            value: this.placeholder,
            lineWrapping : true,
        }

    TextCell.prototype = new IPython.Cell();

    /**
     * Create the DOM element of the TextCell
     * @method create_element
     * @private
     */
    TextCell.prototype.create_element = function () {
        IPython.Cell.prototype.create_element.apply(this, arguments);
        var cell = $("
").addClass('cell text_cell border-box-sizing vbox');
        cell.attr('tabindex','2');

        this.celltoolbar = new IPython.CellToolbar(this);
        cell.append(this.celltoolbar.element);

        var input_area = $('
').addClass('text_cell_input border-box-sizing');
        this.code_mirror = CodeMirror(input_area.get(0), this.cm_config);
        // The tabindex=-1 makes this div focusable.
        var render_area = $('
').addClass('text_cell_render border-box-sizing').
            addClass('rendered_html').attr('tabindex','-1');
        cell.append(input_area).append(render_area);
        this.element = cell;
    };

    /**
     * Bind the DOM evet to cell actions
     * Need to be called after TextCell.create_element
     * @private
     * @method bind_event
     */
    TextCell.prototype.bind_events = function () {
        IPython.Cell.prototype.bind_events.apply(this);
        var that = this;
        this.element.keydown(function (event) {
            if (event.which === 13 && !event.shiftKey) {
                if (that.rendered) {
                    that.edit();
                    return false;
                };
            };
        });
        this.element.dblclick(function () {
            that.edit();
        });
    };

    /**
     * This method gets called in CodeMirror's onKeyDown/onKeyPress
     * handlers and is used to provide custom key handling.
     *
     * Subclass should override this method to have custom handeling
     *
     * @method handle_codemirror_keyevent
     * @param {CodeMirror} editor - The codemirror instance bound to the cell
     * @param {event} event -
     * @return {Boolean} `true` if CodeMirror should ignore the event, `false` Otherwise
     */
    TextCell.prototype.handle_codemirror_keyevent = function (editor, event) {

        if (event.keyCode === 13 && (event.shiftKey || event.ctrlKey)) {
            // Always ignore shift-enter in CodeMirror as we handle it.
            return true;
        }
        return false;
    };

    /**
     * Select the current cell and trigger 'focus'
     * @method select
     */
    TextCell.prototype.select = function () {
        IPython.Cell.prototype.select.apply(this);
        var output = this.element.find("div.text_cell_render");
        output.trigger('focus');
    };

    /**
     * unselect the current cell and `render` it
     * @method unselect
     */
    TextCell.prototype.unselect = function() {
        // render on selection of another cell
        this.render();
        IPython.Cell.prototype.unselect.apply(this);
    };

    /**
     *
     * put the current cell in edition mode
     * @method edit
     */
    TextCell.prototype.edit = function () {
        if ( this.read_only ) return;
        if (this.rendered === true) {
            var text_cell = this.element;
            var output = text_cell.find("div.text_cell_render");
            output.hide();
            text_cell.find('div.text_cell_input').show();
            this.code_mirror.refresh();
            this.code_mirror.focus();
            // We used to need an additional refresh() after the focus, but
            // it appears that this has been fixed in CM. This bug would show
            // up on FF when a newly loaded markdown cell was edited.
            this.rendered = false;
            if (this.get_text() === this.placeholder) {
                this.set_text('');
                this.refresh();
            }
        }
    };

    /**
     * Empty, Subclasses must define render.
     * @method render
     */
    TextCell.prototype.render = function () {};

    /**
     * setter: {{#crossLink "TextCell/set_text"}}{{/crossLink}}
     * @method get_text
     * @retrun {string} CodeMirror current text value
     */
    TextCell.prototype.get_text = function() {
        return this.code_mirror.getValue();
    };

    /**
     * @param {string} text - Codemiror text value
     * @see TextCell#get_text
     * @method set_text
     * */
    TextCell.prototype.set_text = function(text) {
        this.code_mirror.setValue(text);
        this.code_mirror.refresh();
    };

    /**
     * setter :{{#crossLink "TextCell/set_rendered"}}{{/crossLink}}
     * @method get_rendered
     * @return {html} html of rendered element
     * */
    TextCell.prototype.get_rendered = function() {
        return this.element.find('div.text_cell_render').html();
    };

    /**
     * @method set_rendered
     */
    TextCell.prototype.set_rendered = function(text) {
        this.element.find('div.text_cell_render').html(text);
    };

    /**
     * not deprecated, but implementation wrong
     * @method at_top
     * @deprecated
     * @return {Boolean} true is cell rendered, false otherwise
     * I doubt this is what it is supposed to do
     * this implementation is completly false
     */
    TextCell.prototype.at_top = function () {
        if (this.rendered) {
            return true;
        } else {
            return false;
        }
    };

    /**
     * not deprecated, but implementation wrong
     * @method at_bottom
     * @deprecated
     * @return {Boolean} true is cell rendered, false otherwise
     * I doubt this is what it is supposed to do
     * this implementation is completly false
     * */
    TextCell.prototype.at_bottom = function () {
        if (this.rendered) {
            return true;
        } else {
            return false;
        }
    };

    /**
     * Create Text cell from JSON
     * @param {json} data - JSON serialized text-cell
     * @method fromJSON
     */
    TextCell.prototype.fromJSON = function (data) {
        IPython.Cell.prototype.fromJSON.apply(this, arguments);
        if (data.cell_type === this.cell_type) {
            if (data.source !== undefined) {
                this.set_text(data.source);
                // make this value the starting point, so that we can only undo
                // to this state, instead of a blank cell
                this.code_mirror.clearHistory();
                this.set_rendered(data.rendered || '');
                this.rendered = false;
                this.render();
            }
        }
    };

    /** Generate JSON from cell
     * @return {object} cell data serialised to json
     */
    TextCell.prototype.toJSON = function () {
        var data = IPython.Cell.prototype.toJSON.apply(this);
        data.cell_type = this.cell_type;
        data.source = this.get_text();
        return data;
    };

    /**
     * @constructor HtmlCell
     * @class HtmlCell
     * @extends Ipython.TextCell
     */
    var HTMLCell = function () {
        this.placeholder = "Type HTML and LaTeX: $\\alpha^2$";
        IPython.TextCell.apply(this, arguments);
        this.cell_type = 'html';
    };

    HTMLCell.prototype = new TextCell();

    /**
     * @method render
     */
    HTMLCell.prototype.render = function () {
        if (this.rendered === false) {
            var text = this.get_text();
            if (text === "") { text = this.placeholder; }
            this.set_rendered(text);
            this.typeset();
            this.element.find('div.text_cell_input').hide();
            this.element.find("div.text_cell_render").show();
            this.rendered = true;
        }
    };

    /**
     * @class MarkdownCell
     * @constructor MarkdownCell
     * @extends Ipython.HtmlCell
     */
    var MarkdownCell = function () {
        this.placeholder = "Type *Markdown* and LaTeX: $\\alpha^2$";
        IPython.TextCell.apply(this, arguments);
        this.cell_type = 'markdown';
    };

    MarkdownCell.prototype = new TextCell();

    /**
     * @method render
     */
    MarkdownCell.prototype.render = function () {
        if (this.rendered === false) {
            var text = this.get_text();
            if (text === "") { text = this.placeholder; }
            text = IPython.mathjaxutils.remove_math(text)
            var html = IPython.markdown_converter.makeHtml(text);
            html = IPython.mathjaxutils.replace_math(html)
            try {
                this.set_rendered(html);
            } catch (e) {
                console.log("Error running Javascript in Markdown:");
                console.log(e);
                this.set_rendered($("
").addClass("js-error").html(
                    "Error rendering Markdown!
" + e.toString())
                );
            }
            this.element.find('div.text_cell_input').hide();
            this.element.find("div.text_cell_render").show();
            var code_snippets = this.element.find("pre > code");
            code_snippets.replaceWith(function () {
                var code = $(this).html();
                /* Substitute br for newlines and   for spaces
                   before highlighting, since prettify doesn't
                   preserve those on all browsers */
                code = code.replace(/(\r\n|\n|\r)/gm, "
");
                code = code.replace(/ /gm, ' ');
                code = prettyPrintOne(code);

                return '' + code + '';
            });
            this.typeset()
            this.rendered = true;
        }
    };

    // RawCell

    /**
     * @class RawCell
     * @constructor RawCell
     * @extends Ipython.TextCell
     */
    var RawCell = function () {
        this.placeholder = "Type plain text and LaTeX: $\\alpha^2$";
        this.code_mirror_mode = 'rst';
        IPython.TextCell.apply(this, arguments);
        this.cell_type = 'raw';
        var that = this

        this.element.focusout(
                function() { that.auto_highlight(); }
            );
    };

    RawCell.prototype = new TextCell();

    /**
     * Trigger autodetection of highlight scheme for current cell
     * @method auto_highlight
     */
    RawCell.prototype.auto_highlight = function () {
        this._auto_highlight(IPython.config.raw_cell_highlight);
    };

    /** @method render **/
    RawCell.prototype.render = function () {
        this.rendered = true;
        this.edit();
    };

    /** @method handle_codemirror_keyevent **/
    RawCell.prototype.handle_codemirror_keyevent = function (editor, event) {

        var that = this;
        if (event.which === key.UPARROW && event.type === 'keydown') {
            // If we are not at the top, let CM handle the up arrow and
            // prevent the global keydown handler from handling it.
            if (!that.at_top()) {
                event.stop();
                return false;
            } else {
                return true;
            };
        } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
            // If we are not at the bottom, let CM handle the down arrow and
            // prevent the global keydown handler from handling it.
            if (!that.at_bottom()) {
                event.stop();
                return false;
            } else {
                return true;
            };
        };
        return false;
    };

    /** @method select **/
    RawCell.prototype.select = function () {
        IPython.Cell.prototype.select.apply(this);
        this.code_mirror.refresh();
        this.code_mirror.focus();
    };

    /** @method at_top **/
    RawCell.prototype.at_top = function () {
        var cursor = this.code_mirror.getCursor();
        if (cursor.line === 0 && cursor.ch === 0) {
            return true;
        } else {
            return false;
        }
    };

    /** @method at_bottom **/
    RawCell.prototype.at_bottom = function () {
        var cursor = this.code_mirror.getCursor();
        if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
            return true;
        } else {
            return false;
        }
    };

    /**
     * @class HeadingCell
     * @extends Ipython.TextCell
     */

    /**
     * @constructor HeadingCell
     * @extends Ipython.TextCell
     */
    var HeadingCell = function () {
        this.placeholder = "Type Heading Here";
        IPython.TextCell.apply(this, arguments);
        /**
         * heading level of the cell, use getter and setter to access
         * @property level
         */
        this.level = 1;
        this.cell_type = 'heading';
    };

    HeadingCell.prototype = new TextCell();

    /** @method fromJSON */
    HeadingCell.prototype.fromJSON = function (data) {
        if (data.level != undefined){
            this.level = data.level;
        }
        IPython.TextCell.prototype.fromJSON.apply(this, arguments);
    };

    /** @method toJSON */
    HeadingCell.prototype.toJSON = function () {
        var data = IPython.TextCell.prototype.toJSON.apply(this);
        data.level = this.get_level();
        return data;
    };

    /**
     * Change heading level of cell, and re-render
     * @method set_level
     */
    HeadingCell.prototype.set_level = function (level) {
        this.level = level;
        if (this.rendered) {
            this.rendered = false;
            this.render();
        };
    };

    /** The depth of header cell, based on html (h1 to h6)
     * @method get_level
     * @return {integer} level - for 1 to 6
     */
    HeadingCell.prototype.get_level = function () {
        return this.level;
    };

    HeadingCell.prototype.set_rendered = function (text) {
        var r = this.element.find("div.text_cell_render");
        r.empty();
        var link = text.replace(/ /g, '_');
        r.append(
            $('<h'+this.level+'/>')
            .append(
            $('')
                .addClass('heading-anchor')
                .attr('href', '#' + link)
                .attr('id', link)
                .html(text)
            )
        );
    };

    HeadingCell.prototype.get_rendered = function () {
        var r = this.element.find("div.text_cell_render");
        return r.children().first().html();
    };

    HeadingCell.prototype.render = function () {
        if (this.rendered === false) {
            var text = this.get_text();
            if (text === "") { text = this.placeholder; }
            this.set_rendered(text);
            this.typeset();
            this.element.find('div.text_cell_input').hide();
            this.element.find("div.text_cell_render").show();
            this.rendered = true;
        };
    };

    IPython.TextCell = TextCell;
    IPython.HTMLCell = HTMLCell;
    IPython.MarkdownCell = MarkdownCell;
    IPython.RawCell = RawCell;
    IPython.HeadingCell = HeadingCell;

    return IPython;

}(IPython));

<|endoftext|>


<commit_before>/**
 * @ngdoc module
 * @name dgeniDemo
 * @module dgeniDemo
 * @kind module
 *
 * @description Simplest demo module
 */
angular.module('dgeniDemo', []);
<commit_msg>chore(app): Added dependencies of main module, added test comment<commit_after>/**
 * @ngdoc module
 * @name dgeniDemo
 * @module dgeniDemo
 * @kind module
 *
 * @description Simplest demo module
 */

/**
 * Simple test comment
 */
angular.module('dgeniDemo', ['dgeniDemo.directive1', 'dgeniDemo.directive2']);
<|endoftext|>


<commit_before><commit_msg>#1: Create Gruntfile<commit_after>/*jslint node: true */
'use strict';

/**
 * This is the basic Gruntfile for Yaga.
 *
 * @module ./Gruntfile.js
 * @author Arne Schubert <atd.schubert@gmail.com>
 */

/**
 * Common.JS object
 * @name module
 * @type {object}
 * @property {*} exports - Reference to export module data
 */

/**
 * Function to require Common.JS modules
 * @name require
 * @type {function}
 */

/**
 * Grunt module
 * @name grunt
 * @link http://gruntjs.com/api/grunt - Grunt API Documentation
 * @requires grunt
 * @property {function} initConfig
 * @property {function} loadNpmTasks
 * @property {function} registerMultiTask
 * @property {function} registerTask
 * @property {object} config
 * @property {object} task
 * @property {function} task.run
 * @property {object} log
 * @property {object} file
 * @property {object} fail
 * @property {function} fail.fatal
 * @type {object}
 */

/**
 * Project settings
 *
 * @name project
 * @type object
 */
var project = {
    css: [
        'scripts/vendor/jquery-mobile-bower/*.css',
        'scripts/vendor/leaflet/*.css',
        'scripts/yaga.css'
    ],
    livereload: 12345,
    port: 3000,
    localHostname: 'localhost'
};

/**
 * Task-runner for yaga-client
 * @param {grunt} grunt
 */

module.exports = function yagaClientTaskRunner(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        connect: {
            debug: {
                options: {
                    keepalive: false,
                    port: project.port,
                    open: true,
                    hostname: '*',
                    base: {
                        path: './',
                        options: {
                            index: 'debug.html',
                            maxAge: 300000
                        }
                    }
                }
            },
            dist: {
                options: {
                    keepalive: true,
                    port: project.port,
                    open: true,
                    hostname: '*',
                    base: {
                        path: './',
                        options: {
                            index: 'dist/dist.html',
                            maxAge: 300000
                        }
                    }
                }
            }
        },
        requirejs: {
            dist: {
                options: {
                    name: 'app',
                    baseUrl: 'scripts',
                    mainConfigFile: 'scripts/main.js',
                    out: 'dist/dist.min.js'
                }
            }
        },
        watch: {
            changeJsFiles: {
                files: ['scripts/*.js'],
                //tasks: ['requirejs'],
                options: {
                    livereload: project.livereload
                }
            },
            changeCssFiles: {
                files: [''],
                tasks: ['concat:css', 'cssmin'],
                options: {
                    livereload: project.livereload
                }
            },
            changeVendorFiles: {
                files: ['scripts/vendor/**'],
                //tasks: ['requirejs', 'concat:css', 'cssmin'],
                options: {
                    livereload: project.livereload
                }
            },
            views: {
                files: ['views/**'],
                tasks: ['jade'],
                options: {
                    livereload: project.livereload
                }
            }
        },
        concat: {
            options: {
                separator: ' '
            },
            css: {
                src: project.cssFileOrder,
                dest: 'scripts/dist.css'
            }
        },
        cssmin: {
            options: {
                shorthandCompacting: false,
                roundingPrecision: -1
            },
            dist: {
                files: {
                    'scripts/dist.min.css': project.cssFileOrder
                }
            }
        },
        bower: {
            install: {
                options: {
                    targetDir: 'scripts/vendor',
                    layout: 'byType',
                    install: true,
                    verbose: false,
                    cleanTargetDir: true,
                    cleanBowerDir: true,
                    bowerOptions: {}
                }
                //just run 'grunt bower:install' and you'll see files from your Bower packages in lib directory
            }
        },
        clean: {
            dist: ['dist'],
            bower: ['scripts/vendor'],
            debug: ['debug.html']
        },
        jade: {
            debug: {
                options: {
                    data: {
                        css: project.css,
                        livereload: {
                            port: project.livereload,
                            host: project.localHostname
                        },
                        jsSrc: 'scripts/vendor/requirejs/require.js',
                        amdMain: 'scripts/main.js'
                    }
                },
                files: {
                    'debug.html': 'views/index.jade'
                }
            },
            dist: {
                options: {
                    data: {
                        livereload: false,
                        manifest: 'dist.appcache',
                        jsSrc: 'scripts/dist.min.js'
                    }
                },
                files: {
                    'dist.html': 'views/index.jade'
                }
            }
        },
        manifest: {
            dist: {
                options: {
                    //basePath: '../',
                    cache: ['scripts/dist.min.js', 'scripts/dist.min.css'],
                    network: [],
                    fallback: [],
                    exclude: [],
                    preferOnline: true,
                    verbose: true,
                    timestamp: false,
                    hash: true,
                    master: ['dist.html'],
                    process: function(path) {
                        return path.substring('build/'.length);
                    }
                },
                src: [
                    'dist.html',
                    'scripts/dist.min.js',
                    'scripts/dist.min.css'
                ],
                dest: 'dist.appcache'
            },
            debug: {
                options: {
                    //basePath: '../',
                    cache: [],
                    network: [],
                    fallback: [],
                    exclude: [],
                    preferOnline: true,
                    verbose: true,
                    timestamp: false,
                    hash: true,
                    master: ['dist/index.html'],
                    process: function(path) {
                        return path.substring('dist/'.length);
                    }
                },
                src: [
                    'dist.html',
                    'scripts/dist.min.js',
                    'scripts/dist.min.css'
                ],
                dest: 'debug.appcache'
            }
        }
    });

// Loaded-tasks:
// General
    /**
     * Task for opening static files in a virtual server
     * @link https://github.com/gruntjs/grunt-contrib-connect - Github
     * @requires grunt-contrib-connect/tasks/connect.js
     */
    grunt.loadNpmTasks('grunt-contrib-connect');

    /**
     * Task for opening static files in a virtual server
     * @link https://github.com/gruntjs/grunt-contrib-requirejs - Github
     * @requires grunt-contrib-requirejs/tasks/requirejs.js
     */
    grunt.loadNpmTasks('grunt-contrib-requirejs');

    /**
     * Task for watching file changes
     * @link https://github.com/gruntjs/grunt-contrib-watch - Github
     * @requires grunt-contrib-watch/tasks/watch.js
     */
    grunt.loadNpmTasks('grunt-contrib-watch');

    /**
     * Task for concat files
     * @link https://github.com/gruntjs/grunt-contrib-concat - Github
     * @requires grunt-contrib-concat/tasks/concat.js
     */
    grunt.loadNpmTasks('grunt-contrib-concat');

    /**
     * Task for minifying css files
     * @link https://github.com/gruntjs/grunt-contrib-cssmin - Github
     * @requires grunt-contrib-cssmin/tasks/cssmin.js
     */
    grunt.loadNpmTasks('grunt-contrib-cssmin');

    /**
     * Task for handle bower
     * @link https://github.com/yatskevich/grunt-bower-task - Github
     * @requires grunt-bower-task/tasks/bower_task.js
     */
    grunt.loadNpmTasks('grunt-bower-task');

    /**
     * Task to clean files
     * @link https://github.com/gruntjs/grunt-contrib-clean - Github
     * @requires grunt-contrib-clean/tasks/clean.js
     */
    grunt.loadNpmTasks('grunt-contrib-clean');

    /**
     * Task create html files from jade
     * @link https://github.com/gruntjs/grunt-contrib-jade - Github
     * @requires grunt-contrib-jade/tasks/jade.js
     */
    grunt.loadNpmTasks('grunt-contrib-jade');

    /**
     * Task to generate manifest files
     * @link https://github.com/gunta/grunt-manifest - Github
     * @requires grunt-manifest/tasks/manifest.js
     */
    grunt.loadNpmTasks('grunt-manifest');

    grunt.registerTask('dist', ['jade:dist', 'requirejs', 'cssmin', 'connect:dist']);
    grunt.registerTask('init', ['bower']);
    grunt.registerTask('default', ['jade:debug', 'concat:css', 'connect:debug', 'watch']);
};<|endoftext|>


<commit_before>/**
 * @fileOverview Implementation of query language function features.
 * @author David Huynh
 * @author Ryan Lee
 */

/**
 * @namespace
 */
Exhibit.Functions = {};

/**
 * @namespace
 */
Exhibit.FunctionUtilities = {};

/**
 * @static
 * @param {String} name
 * @param {Function} f
 * @param {String} valueType
 */
Exhibit.FunctionUtilities.registerSimpleMappingFunction = function(name, f, valueType) {
    Exhibit.Functions[name] = {
        f: function(args) {
            var set = new Exhibit.Set(), i, fn;
            fn = function() {
                return function(v) {
                    var v2 = f(v);
                    if (typeof v2 !== "undefined") {
                        set.add(v2);
                    }
                };
            };
            for (i = 0; i < args.length; i++) {
                args[i].forEachValue(fn());
            }
            return new Exhibit.Expression._Collection(set, valueType);
        }
    };
};

Exhibit.Functions["union"] = {
    f: function(args) {
        var set, valueType, i, arg;
        set = new Exhibit.Set();
        valueType = null;

        if (args.length > 0) {
            valueType = args[0].valueType;
            for (i = 0; i < args.length; i++) {
                arg = args[i];
                if (arg.size > 0) {
                    if (typeof valueType === "undefined" || valueType === null) {
                        valueType = arg.valueType;
                    }
                    set.addSet(arg.getSet());
                }
            }
        }
        return new Exhibit.Expression._Collection(set, (typeof valueType !== "undefined" && valueType !== null) ? valueType : "text");
    }
};

Exhibit.Functions["contains"] = {
    f: function(args) {
        var result, set;
        result = args[0].size > 0;
        set = args[0].getSet();

        args[1].forEachValue(function(v) {
            if (!set.contains(v)) {
                result = false;
                return true;
            }
        });

        return new Exhibit.Expression._Collection([ result ], "boolean");
    }
};

Exhibit.Functions["exists"] = {
    f: function(args) {
        return new Exhibit.Expression._Collection([ args[0].size > 0 ], "boolean");
    }
};

Exhibit.Functions["count"] = {
    f: function(args) {
        return new Exhibit.Expression._Collection([ args[0].size ], "number");
    }
};

Exhibit.Functions["not"] = {
    f: function(args) {
        return new Exhibit.Expression._Collection([ !args[0].contains(true) ], "boolean");
    }
};

Exhibit.Functions["and"] = {
    f: function(args) {
        var r = true, i;
        for (i = 0; r && i < args.length; i++) {
            r = r && args[i].contains(true);
        }
        return new Exhibit.Expression._Collection([ r ], "boolean");
    }
};

Exhibit.Functions["or"] = {
    f: function(args) {
        var r = false, i;
        for (i = 0; !r && i < args.length; i++) {
            r = r || args[i].contains(true);
        }
        return new Exhibit.Expression._Collection([ r ], "boolean");
    }
};

Exhibit.Functions["add"] = {
    f: function(args) {
        var total, i, fn;
        total = 0;
        fn = function() {
            return function(v) {
                if (typeof v !== "undefined" && v !== null) {
                    if (typeof v === "number") {
                        total += v;
                    } else {
                        var n = parseFloat(v);
                        if (!isNaN(n)) {
                            total += n;
                        }
                    }
                }
            };
        };
        for (i = 0; i < args.length; i++) {
            args[i].forEachValue(fn());
        }

        return new Exhibit.Expression._Collection([ total ], "number");
    }
};

// Note: arguments expanding to multiple items get concatenated in random order
Exhibit.Functions["concat"] = {
    f: function(args) {
        var result = [], i, fn;
        fn = function() {
            return function(v) {
                if (typeof v !== "undefined" && v !== null) {
                    result.push(v);
                }
            };
        };
        for (i = 0; i < args.length; i++) {
            args[i].forEachValue(fn());
        }

        return new Exhibit.Expression._Collection([ result.join('') ], "text");
    }
};

Exhibit.Functions["multiply"] = {
    f: function(args) {
        var product = 1, i, fn;
        fn = function() {
            return function(v) {
                var n;
                if (typeof v !== "undefined" && v !== null) {
                    if (typeof v === "number") {
                        product *= v;
                    } else {
                        n = parseFloat(v);
                        if (!isNaN(n)) {
                            product *= n;
                        }
                    }
                }
            };
        };
        for (i = 0; i < args.length; i++) {
            args[i].forEachValue(fn());
        }

        return new Exhibit.Expression._Collection([ product ], "number");
    }
};

Exhibit.Functions["date-range"] = {
    _parseDate: function (v) {
        if (typeof v === "undefined" || v === null) {
            return Number.NEGATIVE_INFINITY;
        } else if (v instanceof Date) {
            return v.getTime();
        } else {
            try {
                return Exhibit.DateTime.parseIso8601DateTime(v).getTime();
            } catch (e) {
                return Number.NEGATIVE_INFINITY;
            }
        }
    },
    _computeRange: function(from, to, interval) {
        var range = to - from;
        if (isFinite(range)) {
            if (typeof Exhibit.DateTime[interval.toUpperCase()] !== "undefined") {
                range = Math.round(range / Exhibit.DateTime.gregorianUnitLengths[Exhibit.DateTime[interval.toUpperCase()]]);
            }
            return range;
        }
        return null;
    },
    f: function(args) {
        var self = this, from, to, interval, range;

        from = Number.POSITIVE_INFINITY;
        args[0].forEachValue(function(v) {
            from = Math.min(from, self._parseDate(v));
        });

        to = Number.NEGATIVE_INFINITY;
        args[1].forEachValue(function(v) {
            to = Math.max(to, self._parseDate(v));
        });

        interval = "day";
        args[2].forEachValue(function(v) {
            interval = v;
        });

        range = this._computeRange(from, to, interval);
        return new Exhibit.Expression._Collection((typeof range !== "undefined" && range !== null) ? [ range ] : [], "number");
    }
};

Exhibit.Functions["distance"] = {
    _units: {
        km:         1e3,
        mile:       1609.344
    },
    _computeDistance: function(from, to, unit, roundTo) {
        var range = from.distanceFrom(to);
        if (!roundTo) {
            roundTo = 1;
        }
        if (isFinite(range)) {
            if (typeof this._units[unit] !== "undefined") {
                range = range / this._units[unit];
            }
            return Exhibit.Util.round(range, roundTo);
        }
        return null;
    },
    f: function(args) {
        var self = this, data, name, i, latlng, from, to, range, fn;
        data = {};
        name = ["origo", "lat", "lng", "unit", "round"];
        fn = function(nm) {
            return function(v) {
                data[nm] = v;
            };
        };
        for (i = 0, n = name[i]; i < name.length; i++) {
            args[i].forEachValue(fn(n));
        }

        latlng = data.origo.split(",");
        from = new GLatLng( latlng[0], latlng[1] );
        to = new GLatLng( data.lat, data.lng );

        range = this._computeDistance(from, to, data.unit, data.round);
        return new Exhibit.Expression._Collection((typeof range !== "undefined" && range !== null) ? [ range ] : [], "number");
    }
};

Exhibit.Functions["min"] = {
    f: function(args) {
        /** @ignore */
        var returnMe = function (val) { return val; }, min, valueType, i, arg, currentValueType, parser, fn;
        min = Number.POSITIVE_INFINITY;
        valueType = null;
        fn = function(p, c) {
            return function(v) {
                var parsedV = p(v, returnMe);
                if (parsedV < min || min === Number.POSITIVE_INFINITY) {
                    min = parsedV;
                    valueType = (valueType === null) ? c :
                        (valueType === c ? valueType : "text") ;
                }
            };
        };
        for (i = 0; i < args.length; i++) {
            arg = args[i];
            currentValueType = arg.valueType ? arg.valueType : 'text';
            parser = Exhibit.SettingsUtilities._typeToParser(currentValueType);

            arg.forEachValue(fn(parser, currentValueType));
        }

        return new Exhibit.Expression._Collection([ min ], (typeof valueType !== "undefined" && valueType !== null) ? valueType : "text");
    }
};

Exhibit.Functions["max"] = {
    f: function(args) {
        var returnMe = function (val) { return val; }, max, valueType, i, arg, currentValueType, parser, fn;
        max = Number.NEGATIVE_INFINITY;
        valueType = null;
        fn = function(p, c) {
            return function(v) {
                var parsedV = p(v, returnMe);
                if (parsedV > max || max === Number.NEGATIVE_INFINITY) {
                    max = parsedV;
                    valueType = (valueType === null) ? c :
                        (valueType === c ? valueType : "text") ;
                }
            };
        };

        for (i = 0; i < args.length; i++) {
            arg = args[i];
            currentValueType = arg.valueType ? arg.valueType : 'text';
            parser = Exhibit.SettingsUtilities._typeToParser(currentValueType);

            arg.forEachValue(fn(parser, c));
        }
        return new Exhibit.Expression._Collection([ max ], (typeof valueType !== "undefined" && valueType !== null) ? valueType : "text");
    }
};

Exhibit.Functions["remove"] = {
    f: function(args) {
        var set, valueType, i, arg;
        set = args[0].getSet();
        valueType = args[0].valueType;
        for (i = 1; i < args.length; i++) {
            arg = args[i];
            if (arg.size > 0) {
                set.removeSet(arg.getSet());
            }
        }
        return new Exhibit.Expression._Collection(set, valueType);
    }
};

Exhibit.Functions["now"] = {
    f: function(args) {
        return new Exhibit.Expression._Collection([ new Date() ], "date");
    }
};
<commit_msg>Fix max function<commit_after>/**
 * @fileOverview Implementation of query language function features.
 * @author David Huynh
 * @author Ryan Lee
 */

/**
 * @namespace
 */
Exhibit.Functions = {};

/**
 * @namespace
 */
Exhibit.FunctionUtilities = {};

/**
 * @static
 * @param {String} name
 * @param {Function} f
 * @param {String} valueType
 */
Exhibit.FunctionUtilities.registerSimpleMappingFunction = function(name, f, valueType) {
    Exhibit.Functions[name] = {
        f: function(args) {
            var set = new Exhibit.Set(), i, fn;
            fn = function() {
                return function(v) {
                    var v2 = f(v);
                    if (typeof v2 !== "undefined") {
                        set.add(v2);
                    }
                };
            };
            for (i = 0; i < args.length; i++) {
                args[i].forEachValue(fn());
            }
            return new Exhibit.Expression._Collection(set, valueType);
        }
    };
};

Exhibit.Functions["union"] = {
    f: function(args) {
        var set, valueType, i, arg;
        set = new Exhibit.Set();
        valueType = null;

        if (args.length > 0) {
            valueType = args[0].valueType;
            for (i = 0; i < args.length; i++) {
                arg = args[i];
                if (arg.size > 0) {
                    if (typeof valueType === "undefined" || valueType === null) {
                        valueType = arg.valueType;
                    }
                    set.addSet(arg.getSet());
                }
            }
        }
        return new Exhibit.Expression._Collection(set, (typeof valueType !== "undefined" && valueType !== null) ? valueType : "text");
    }
};

Exhibit.Functions["contains"] = {
    f: function(args) {
        var result, set;
        result = args[0].size > 0;
        set = args[0].getSet();

        args[1].forEachValue(function(v) {
            if (!set.contains(v)) {
                result = false;
                return true;
            }
        });

        return new Exhibit.Expression._Collection([ result ], "boolean");
    }
};

Exhibit.Functions["exists"] = {
    f: function(args) {
        return new Exhibit.Expression._Collection([ args[0].size > 0 ], "boolean");
    }
};

Exhibit.Functions["count"] = {
    f: function(args) {
        return new Exhibit.Expression._Collection([ args[0].size ], "number");
    }
};

Exhibit.Functions["not"] = {
    f: function(args) {
        return new Exhibit.Expression._Collection([ !args[0].contains(true) ], "boolean");
    }
};

Exhibit.Functions["and"] = {
    f: function(args) {
        var r = true, i;
        for (i = 0; r && i < args.length; i++) {
            r = r && args[i].contains(true);
        }
        return new Exhibit.Expression._Collection([ r ], "boolean");
    }
};

Exhibit.Functions["or"] = {
    f: function(args) {
        var r = false, i;
        for (i = 0; !r && i < args.length; i++) {
            r = r || args[i].contains(true);
        }
        return new Exhibit.Expression._Collection([ r ], "boolean");
    }
};

Exhibit.Functions["add"] = {
    f: function(args) {
        var total, i, fn;
        total = 0;
        fn = function() {
            return function(v) {
                if (typeof v !== "undefined" && v !== null) {
                    if (typeof v === "number") {
                        total += v;
                    } else {
                        var n = parseFloat(v);
                        if (!isNaN(n)) {
                            total += n;
                        }
                    }
                }
            };
        };
        for (i = 0; i < args.length; i++) {
            args[i].forEachValue(fn());
        }

        return new Exhibit.Expression._Collection([ total ], "number");
    }
};

// Note: arguments expanding to multiple items get concatenated in random order
Exhibit.Functions["concat"] = {
    f: function(args) {
        var result = [], i, fn;
        fn = function() {
            return function(v) {
                if (typeof v !== "undefined" && v !== null) {
                    result.push(v);
                }
            };
        };
        for (i = 0; i < args.length; i++) {
            args[i].forEachValue(fn());
        }

        return new Exhibit.Expression._Collection([ result.join('') ], "text");
    }
};

Exhibit.Functions["multiply"] = {
    f: function(args) {
        var product = 1, i, fn;
        fn = function() {
            return function(v) {
                var n;
                if (typeof v !== "undefined" && v !== null) {
                    if (typeof v === "number") {
                        product *= v;
                    } else {
                        n = parseFloat(v);
                        if (!isNaN(n)) {
                            product *= n;
                        }
                    }
                }
            };
        };
        for (i = 0; i < args.length; i++) {
            args[i].forEachValue(fn());
        }

        return new Exhibit.Expression._Collection([ product ], "number");
    }
};

Exhibit.Functions["date-range"] = {
    _parseDate: function (v) {
        if (typeof v === "undefined" || v === null) {
            return Number.NEGATIVE_INFINITY;
        } else if (v instanceof Date) {
            return v.getTime();
        } else {
            try {
                return Exhibit.DateTime.parseIso8601DateTime(v).getTime();
            } catch (e) {
                return Number.NEGATIVE_INFINITY;
            }
        }
    },
    _computeRange: function(from, to, interval) {
        var range = to - from;
        if (isFinite(range)) {
            if (typeof Exhibit.DateTime[interval.toUpperCase()] !== "undefined") {
                range = Math.round(range / Exhibit.DateTime.gregorianUnitLengths[Exhibit.DateTime[interval.toUpperCase()]]);
            }
            return range;
        }
        return null;
    },
    f: function(args) {
        var self = this, from, to, interval, range;

        from = Number.POSITIVE_INFINITY;
        args[0].forEachValue(function(v) {
            from = Math.min(from, self._parseDate(v));
        });

        to = Number.NEGATIVE_INFINITY;
        args[1].forEachValue(function(v) {
            to = Math.max(to, self._parseDate(v));
        });

        interval = "day";
        args[2].forEachValue(function(v) {
            interval = v;
        });

        range = this._computeRange(from, to, interval);
        return new Exhibit.Expression._Collection((typeof range !== "undefined" && range !== null) ? [ range ] : [], "number");
    }
};

Exhibit.Functions["distance"] = {
    _units: {
        km:         1e3,
        mile:       1609.344
    },
    _computeDistance: function(from, to, unit, roundTo) {
        var range = from.distanceFrom(to);
        if (!roundTo) {
            roundTo = 1;
        }
        if (isFinite(range)) {
            if (typeof this._units[unit] !== "undefined") {
                range = range / this._units[unit];
            }
            return Exhibit.Util.round(range, roundTo);
        }
        return null;
    },
    f: function(args) {
        var self = this, data, name, i, latlng, from, to, range, fn;
        data = {};
        name = ["origo", "lat", "lng", "unit", "round"];
        fn = function(nm) {
            return function(v) {
                data[nm] = v;
            };
        };
        for (i = 0, n = name[i]; i < name.length; i++) {
            args[i].forEachValue(fn(n));
        }

        latlng = data.origo.split(",");
        from = new GLatLng( latlng[0], latlng[1] );
        to = new GLatLng( data.lat, data.lng );

        range = this._computeDistance(from, to, data.unit, data.round);
        return new Exhibit.Expression._Collection((typeof range !== "undefined" && range !== null) ? [ range ] : [], "number");
    }
};

Exhibit.Functions["min"] = {
    f: function(args) {
        /** @ignore */
        var returnMe = function (val) { return val; }, min, valueType, i, arg, currentValueType, parser, fn;
        min = Number.POSITIVE_INFINITY;
        valueType = null;
        fn = function(p, c) {
            return function(v) {
                var parsedV = p(v, returnMe);
                if (parsedV < min || min === Number.POSITIVE_INFINITY) {
                    min = parsedV;
                    valueType = (valueType === null) ? c :
                        (valueType === c ? valueType : "text") ;
                }
            };
        };
        for (i = 0; i < args.length; i++) {
            arg = args[i];
            currentValueType = arg.valueType ? arg.valueType : 'text';
            parser = Exhibit.SettingsUtilities._typeToParser(currentValueType);

            arg.forEachValue(fn(parser, currentValueType));
        }

        return new Exhibit.Expression._Collection([ min ], (typeof valueType !== "undefined" && valueType !== null) ? valueType : "text");
    }
};

Exhibit.Functions["max"] = {
    f: function(args) {
        var returnMe = function (val) { return val; }, max, valueType, i, arg, currentValueType, parser, fn;
        max = Number.NEGATIVE_INFINITY;
        valueType = null;
        fn = function(p, c) {
            return function(v) {
                var parsedV = p(v, returnMe);
                if (parsedV > max || max === Number.NEGATIVE_INFINITY) {
                    max = parsedV;
                    valueType = (valueType === null) ? c :
                        (valueType === c ? valueType : "text") ;
                }
            };
        };

        for (i = 0; i < args.length; i++) {
            arg = args[i];
            currentValueType = arg.valueType ? arg.valueType : 'text';
            parser = Exhibit.SettingsUtilities._typeToParser(currentValueType);

            arg.forEachValue(fn(parser, currentValueType));
        }
        return new Exhibit.Expression._Collection([ max ], (typeof valueType !== "undefined" && valueType !== null) ? valueType : "text");
    }
};

Exhibit.Functions["remove"] = {
    f: function(args) {
        var set, valueType, i, arg;
        set = args[0].getSet();
        valueType = args[0].valueType;
        for (i = 1; i < args.length; i++) {
            arg = args[i];
            if (arg.size > 0) {
                set.removeSet(arg.getSet());
            }
        }
        return new Exhibit.Expression._Collection(set, valueType);
    }
};

Exhibit.Functions["now"] = {
    f: function(args) {
        return new Exhibit.Expression._Collection([ new Date() ], "date");
    }
};
<|endoftext|>


<commit_before>module.exports.Primal = Primal; // interface for creating magnet objects from javascript values

module.exports.Library = Library; // interface for registering stdlib methods written in javascript

// utility
module.exports.repeatString = repeatString;

module.exports.interpret = function interpret(code, libs) {
  code += "\r\n";
  var b2mb = function(b) {
    return ((b / Math.pow(2, 10))/ Math.pow(2, 10)).toFixed(2) + ' MB';
  };
  var startmemory = process.memoryUsage().heapUsed;
  console.time('# Execution time');

  var globalScope = new Scope;
  globalScope.meta = {identifier: '<Global>'};

  libs = libs ? libs : [];
  libs.forEach(function(lib) {
    lib.attach(globalScope);
  });

  var opcode = [];
  var err_offsets = [];
  var err_lookaheads = [];
  var err_count = 0;
  var errors = [];

  if( ( err_count = __parse( code, err_offsets, err_lookaheads, opcode ) ) > 0 ) {
    for( var i = 0; i < err_count; i++ ) {
      var line = calcLineNo(code, err_offsets[i]);
      errors.push({
        line : line,
        col :  getLineCol(code, err_offsets[i]),
        msg : 'Parse Error: unexpected token '+JSON.stringify(code[err_offsets[i]])+' expecting ' + err_lookaheads[i].map(JSON.stringify).join(' or '),
        excerpt : getLineExcerpt(code, err_offsets[i])
      });
    }
    return {errors: errors};
  }

  try {
    var ret = globalScope.executeTokenList(opcode); // the returned value
  }catch(e){
    if(!e.scope) process.exit(console.log(e));
    var trace = e.scope.backtrace().map(function(call) {
      return {caller: call.caller, at: calcLineNo(code, call.at)};
    });
    trace.unshift({caller: e.scope.meta.identifier, at: calcLineNo(code, e.offset)});
    return {errors: [{ msg: 'Runtime Error: '+e.message, line: calcLineNo(code, e.offset), col: getLineCol(code, e.offset), excerpt: getLineExcerpt(code, e.offset), backtrace: trace }]};
  };

  // post execution notes
  console.timeEnd('# Execution time');
  console.log('# Heap size: ', globalScope.env.heap.length);
  console.log('# Memory usage: ', b2mb(process.memoryUsage().heapUsed - startmemory));

  return {errors: errors};
};<commit_msg>throw unexpected errors normally<commit_after>module.exports.Primal = Primal; // interface for creating magnet objects from javascript values

module.exports.Library = Library; // interface for registering stdlib methods written in javascript

// utility
module.exports.repeatString = repeatString;

module.exports.interpret = function interpret(code, libs) {
  code += "\r\n";
  var b2mb = function(b) {
    return ((b / Math.pow(2, 10))/ Math.pow(2, 10)).toFixed(2) + ' MB';
  };
  var startmemory = process.memoryUsage().heapUsed;
  console.time('# Execution time');

  var globalScope = new Scope;
  globalScope.meta = {identifier: '<Global>'};

  libs = libs ? libs : [];
  libs.forEach(function(lib) {
    lib.attach(globalScope);
  });

  var opcode = [];
  var err_offsets = [];
  var err_lookaheads = [];
  var err_count = 0;
  var errors = [];

  if( ( err_count = __parse( code, err_offsets, err_lookaheads, opcode ) ) > 0 ) {
    for( var i = 0; i < err_count; i++ ) {
      var line = calcLineNo(code, err_offsets[i]);
      errors.push({
        line : line,
        col :  getLineCol(code, err_offsets[i]),
        msg : 'Parse Error: unexpected token '+JSON.stringify(code[err_offsets[i]])+' expecting ' + err_lookaheads[i].map(JSON.stringify).join(' or '),
        excerpt : getLineExcerpt(code, err_offsets[i])
      });
    }
    return {errors: errors};
  }

  try {
    var ret = globalScope.executeTokenList(opcode); // the returned value
  }catch(e){
    if(!e.scope) thorw e;
    var trace = e.scope.backtrace().map(function(call) {
      return {caller: call.caller, at: calcLineNo(code, call.at)};
    });
    trace.unshift({caller: e.scope.meta.identifier, at: calcLineNo(code, e.offset)});
    return {errors: [{ msg: 'Runtime Error: '+e.message, line: calcLineNo(code, e.offset), col: getLineCol(code, e.offset), excerpt: getLineExcerpt(code, e.offset), backtrace: trace }]};
  };

  // post execution notes
  console.timeEnd('# Execution time');
  console.log('# Heap size: ', globalScope.env.heap.length);
  console.log('# Memory usage: ', b2mb(process.memoryUsage().heapUsed - startmemory));

  return {errors: errors};
};<|endoftext|>


<commit_before>module.exports = function (body, callback) {
  var stripe = require('stripe')(body.secrets.elistripe)
  stripe.customers.create({
    email: body.data.stripeCustomer,
    source: body.data.stripeToken,
    description: body.data.stripeCustomer
  })
  .then(function(customer) {
    return stripe.charges.create({
      amount: body.data.stripeAmount,
      currency: 'usd',
      customer: customer.id,
      description: body.data.stripeCharge
    }, function(err, charge) {
      console.log(err);
    });
  }, callback)
};
<commit_msg>Stripe fix.<commit_after>module.exports = function (body, callback) {
  var stripe = require('stripe')(body.secrets.elistripe)
  stripe.customers.create({
    email: body.data.stripeCustomer,
    source: body.data.stripeToken,
    description: body.data.stripeCustomer
  }, callback)
  .then(function(customer) {
    return stripe.charges.create({
      amount: body.data.stripeAmount,
      currency: 'usd',
      customer: customer.id,
      description: body.data.stripeCharge
    }, callback);
  })
};
<|endoftext|>


<commit_before>/* Return an object with the following members:
 * - n: the number of vertices
 * - hasEdge(i, j): function which returns true iff. ij is an edge
 * - canvas: an HTML 5 canvas element
 * - position(i): determine the position of vertex i on the canvas
 * - timeInterval: the amount of time it takes to draw a vertex or edge
 * - showVertices: if true, display the vertices as dots
 * - draw(): start drawing the graph
 * - stop(): stop drawing the graph
 */
var graphDrawer = function(n, hasEdge, canvas, position, timeInterval, showVertices) {
	var drawer = {
		n: n,
		hasEdge: hasEdge,
		canvas: canvas,
		position: position,
		timeInterval: timeInterval,
		showVertices: showVertices,
	};

	var verticesDrawn = false;
	var i = 0;
	var j = 1;

	var drawNext = function() {
		var ctx = drawer.canvas.getContext("2d");

		// First draw the vertices
		if(!verticesDrawn && drawer.showVertices) {
			ctx.beginPath();
			var point = drawer.position(i);
			ctx.arc(point.x, point.y, 4, 0, 2 * Math.PI);
			ctx.fill();
			if(++i >= drawer.n) {
				i = 0;
				verticesDrawn = true;
			}
		}
		else {
			var edgeDrawn = false;
			while(!edgeDrawn) {
				if(drawer.hasEdge(i, j)) {
					ctx.beginPath();
					iCoords = drawer.position(i);
					jCoords = drawer.position(j);
					ctx.moveTo(iCoords.x, iCoords.y);
					ctx.lineTo(jCoords.x, jCoords.y);
					ctx.stroke();
					edgeDrawn = true;
				}
				// Increment i and j
				if(++j >= drawer.n) {
					j = ++i + 1;
					if(i >= drawer.n - 1) {
						// No more vertices to draw
						drawer.stop()
					}
				}
			}
		}
	};

	var timer = null;
	drawer.draw = function() {
		timer = setInterval(drawNext, drawer.timeInterval);
	};

    drawer.stop = function() {
		clearInterval(timer);
	}

	return drawer;
};
<commit_msg>Fix indentation in graphDrawer.js<commit_after>/* Return an object with the following members:
 * - n: the number of vertices
 * - hasEdge(i, j): function which returns true iff. ij is an edge
 * - canvas: an HTML 5 canvas element
 * - position(i): determine the position of vertex i on the canvas
 * - timeInterval: the amount of time it takes to draw a vertex or edge
 * - showVertices: if true, display the vertices as dots
 * - draw(): start drawing the graph
 * - stop(): stop drawing the graph
 */
var graphDrawer = function(n, hasEdge, canvas, position, timeInterval, showVertices) {
	var drawer = {
		n: n,
		hasEdge: hasEdge,
		canvas: canvas,
		position: position,
		timeInterval: timeInterval,
		showVertices: showVertices,
	};

	var verticesDrawn = false;
	var i = 0;
	var j = 1;

	var drawNext = function() {
		var ctx = drawer.canvas.getContext("2d");

		// First draw the vertices
		if(!verticesDrawn && drawer.showVertices) {
			ctx.beginPath();
			var point = drawer.position(i);
			ctx.arc(point.x, point.y, 4, 0, 2 * Math.PI);
			ctx.fill();
			if(++i >= drawer.n) {
				i = 0;
				verticesDrawn = true;
			}
		}
		else {
			var edgeDrawn = false;
			while(!edgeDrawn) {
				if(drawer.hasEdge(i, j)) {
					ctx.beginPath();
					iCoords = drawer.position(i);
					jCoords = drawer.position(j);
					ctx.moveTo(iCoords.x, iCoords.y);
					ctx.lineTo(jCoords.x, jCoords.y);
					ctx.stroke();
					edgeDrawn = true;
				}
				// Increment i and j
				if(++j >= drawer.n) {
					j = ++i + 1;
					if(i >= drawer.n - 1) {
						// No more vertices to draw
						drawer.stop()
					}
				}
			}
		}
	};

	var timer = null;
	drawer.draw = function() {
		timer = setInterval(drawNext, drawer.timeInterval);
	};

	drawer.stop = function() {
		clearInterval(timer);
	}

	return drawer;
};
<|endoftext|>


<commit_before>openerp.portal_anonymous = function(instance) {

    instance.web.Session.include({
        load_translations: function() {
            var self = this;
            // browser_lang can contain 'xx' or 'xx_XX'
            // we use the 'xx' to find matching languages installed in the DB
            var browser_lang = (navigator.language || navigator.userLanguage).replace('-', '_');
            // By default for anonymous session.user_context.lang === 'en_US',
            // so do nothing if browser_lang is contained in 'en_US' (like 'en' or 'en_US')
            if (this.username === 'anonymous' && this.user_context.lang.indexOf(browser_lang) === -1) {
                return (new instance.web.Model('res.lang')).query(['code', 'iso_code'])
                    .filter([['code', 'like', browser_lang.substring(0, 2).toLowerCase()]]).all()
                .then(function(langs) {
                    // If langs is empty (OpenERP doesn't support the language),
                    // then don't change session.user_context.lang
                    if (langs.length > 0) {
                        // Try to get the right user preference in the browser, else
                        // get the shortest language returned ('xx' country code) or
                        // just the first one
                        var l = _.filter(langs, function(lang) { return lang.code === browser_lang || lang.iso_code === browser_lang; });
                        if (!_.isEmpty(l)) {
                            self.user_context.lang = l[0].code;
                        } else {
                            l = _.filter(langs, function(lang) {
                                return lang.iso_code === _.pluck(langs, 'iso_code')
                                    .sort(function(a, b) {
                                        return a.length - b.length;
                                    })[0];
                            });
                            self.user_context.lang = l[0].code;
                        }
                    }
                    return self.rpc('/web/webclient/translations', { mods: self.module_list, lang: self.user_context.lang }).done(function(trans) {
                        instance.web._t.database.set_bundle(trans);
                    });
                });
            }
            return this._super();
        },
    });

    instance.web.Login.include({
        start: function() {
            var self = this;
            return $.when(this._super()).then(function() {
                var dblist = self.db_list || [];
                if (!self.session.session_is_valid() && !(self.params.token || self.params.login)) {
                    self.remember_credentials = false;
                    // XXX get login/pass from server (via a rpc call) ?
                    return self.do_login(self.selected_db, 'anonymous', 'anonymous');
                }
            });
        },
    });

    instance.web.UserMenu.include({
        init: function(parent) {
            this._super(parent);
            if (this.session.username == 'anonymous') {
                this.template = 'UserMenu.portal_anonymous';
                this.do_update = function() {};     // avoid change of avatar
            }
        },
        start: function() {
            var self = this;
            this._super.apply(this, arguments);
            this.$el.find('a.login').click(function() {
                var p = self.getParent();
                var am = p.action_manager;
                p.$el.find('.oe_leftbar, .oe_topbar').hide();
                self.session.session_logout().done(function () {
                    am.do_action({
                        type:'ir.actions.client',
                        tag:'login',
                        target: 'current',
                        params: {
                            login_successful: function() {
                                am.do_action("reload");
                            }
                        }
                    });
                });
            });
        }
    });

    instance.web.WebClient.include({
        check_timezone: function() {
            if (this.session.username !== 'anonymous') {
                return this._super.apply(this, arguments);
            }
            return false;
        },
    });

};
<commit_msg>[REM] Remove unused code<commit_after>openerp.portal_anonymous = function(instance) {

    instance.web.Session.include({
        load_translations: function() {
            var self = this;
            // browser_lang can contain 'xx' or 'xx_XX'
            // we use the 'xx' to find matching languages installed in the DB
            var browser_lang = (navigator.language || navigator.userLanguage).replace('-', '_');
            // By default for anonymous session.user_context.lang === 'en_US',
            // so do nothing if browser_lang is contained in 'en_US' (like 'en' or 'en_US')
            if (this.username === 'anonymous' && this.user_context.lang.indexOf(browser_lang) === -1) {
                return (new instance.web.Model('res.lang')).query(['code', 'iso_code'])
                    .filter([['code', 'like', browser_lang.substring(0, 2).toLowerCase()]]).all()
                .then(function(langs) {
                    // If langs is empty (OpenERP doesn't support the language),
                    // then don't change session.user_context.lang
                    if (langs.length > 0) {
                        // Try to get the right user preference in the browser, else
                        // get the shortest language returned ('xx' country code) or
                        // just the first one
                        var l = _.filter(langs, function(lang) { return lang.code === browser_lang || lang.iso_code === browser_lang; });
                        if (!_.isEmpty(l)) {
                            self.user_context.lang = l[0].code;
                        } else {
                            l = _.filter(langs, function(lang) {
                                return lang.iso_code === _.pluck(langs, 'iso_code')
                                    .sort(function(a, b) {
                                        return a.length - b.length;
                                    })[0];
                            });
                            self.user_context.lang = l[0].code;
                        }
                    }
                    return self.rpc('/web/webclient/translations', { mods: self.module_list, lang: self.user_context.lang }).done(function(trans) {
                        instance.web._t.database.set_bundle(trans);
                    });
                });
            }
            return this._super();
        },
    });

    instance.web.Login.include({
        start: function() {
            var self = this;
            return $.when(this._super()).then(function() {
                if (!self.session.session_is_valid() && !(self.params.token || self.params.login)) {
                    self.remember_credentials = false;
                    // XXX get login/pass from server (via a rpc call) ?
                    return self.do_login(self.selected_db, 'anonymous', 'anonymous');
                }
            });
        },
    });

    instance.web.UserMenu.include({
        init: function(parent) {
            this._super(parent);
            if (this.session.username == 'anonymous') {
                this.template = 'UserMenu.portal_anonymous';
                this.do_update = function() {};     // avoid change of avatar
            }
        },
        start: function() {
            var self = this;
            this._super.apply(this, arguments);
            this.$el.find('a.login').click(function() {
                var p = self.getParent();
                var am = p.action_manager;
                p.$el.find('.oe_leftbar, .oe_topbar').hide();
                self.session.session_logout().done(function () {
                    am.do_action({
                        type:'ir.actions.client',
                        tag:'login',
                        target: 'current',
                        params: {
                            login_successful: function() {
                                am.do_action("reload");
                            }
                        }
                    });
                });
            });
        }
    });

    instance.web.WebClient.include({
        check_timezone: function() {
            if (this.session.username !== 'anonymous') {
                return this._super.apply(this, arguments);
            }
            return false;
        },
    });

};
<|endoftext|>


<commit_before>/** @jsx React.DOM */

define(
  [
    'react',
    'components/common/PageHeader.react',
    './FeedbackForm.react'
  ],
  function (React, PageHeader, FeedbackForm) {

    var resources = [
      {
        title: "User Manual",
        href: "https://pods.iplantcollaborative.org/wiki/x/Iaxm",
        description: "Complete documentation for using Atmosphere"
      },
      {
        title: "User Forums",
        href: "http://ask.iplantcollaborative.org",
        description: "Get answers from iPlant users and staff"
      },
      {
        title: "FAQs",
        href: "https://pods.iplantcollaborative.org/wiki/x/Iaxm",
        description: "Atmosphere's most frequently asked questions"
      },
      {
        title: "VNC Viewer Tutorial",
        href: "https://pods.iplantcollaborative.org/wiki/x/Iaxm",
        description: "Instructions for downloading and using VNC Viewer"
      }
    ];

    return React.createClass({
      render: function () {

        var resourceElements = _.map(resources, function (resource) {
          return (

              {resource.title}
              {" " + resource.description}

          );
        });

        return (

            <PageHeader title="Help"/>

External resources

              {resourceElements}

Atmosphere staff support

              {
                "Are you experiencing a problem with Atmosphere to which you " +
                "can't find a solution? Do you have a feature request or bug " +
                "report? Let us know!"
              }

            <FeedbackForm/>

        );
      }
    });

  });
<commit_msg>Hide feedback form from public site<commit_after>/** @jsx React.DOM */

define(
  [
    'react',
    'backbone',
    'components/common/PageHeader.react',
    './FeedbackForm.react'
  ],
  function (React, Backbone, PageHeader, FeedbackForm) {

    var resources = [
      {
        title: "User Manual",
        href: "https://pods.iplantcollaborative.org/wiki/x/Iaxm",
        description: "Complete documentation for using Atmosphere"
      },
      {
        title: "User Forums",
        href: "http://ask.iplantcollaborative.org",
        description: "Get answers from iPlant users and staff"
      },
      {
        title: "FAQs",
        href: "https://pods.iplantcollaborative.org/wiki/x/Iaxm",
        description: "Atmosphere's most frequently asked questions"
      },
      {
        title: "VNC Viewer Tutorial",
        href: "https://pods.iplantcollaborative.org/wiki/x/Iaxm",
        description: "Instructions for downloading and using VNC Viewer"
      }
    ];

    return React.createClass({

      propTypes: {
        profile: React.PropTypes.instanceOf(Backbone.Model)
      },

      render: function () {

        var resourceElements = _.map(resources, function (resource) {
          return (

              {resource.title}
              {" " + resource.description}

          );
        });

        var feedbackSection = (

Atmosphere staff support

              {
                "Are you experiencing a problem with Atmosphere to which you " +
                "can't find a solution? Do you have a feature request or bug " +
                "report? Let us know!"
              }

            <FeedbackForm/>

        );

        return (

            <PageHeader title="Help"/>

External resources

              {resourceElements}

            {this.props.profile ? feedbackSection : null}

        );
      }
    });

  });
<|endoftext|>


<commit_before>hqDefine("registry/js/registry_list", [
    'jquery',
    'underscore',
    'knockout',
    'hqwebapp/js/initial_page_data',
    'hqwebapp/js/alert_user',
    'registry/js/registry_text',
    'registry/js/registry_actions',
], function (
    $,
    _,
    ko,
    initialPageData,
    alertUser,
    text,
    actions,
) {

    let OwnedDataRegistry = function (registry) {
        let self = ko.mapping.fromJS(registry);
        self.acceptedText = ko.computed(function() {
            return text.getAcceptedBadgeText(self);
        });
        self.pendingText = ko.computed(function() {
            return text.getPendingBadgeText(self);
        });
        self.rejectedText = ko.computed(function() {
            return text.getRejectedBadgeText(self);
        });
        self.manageUrl = initialPageData.reverse('manage_registry', self.slug())

        return self;
    };

    let InvitedDataRegistry = function (registry) {
        let self = ko.mapping.fromJS(registry);
        self.participatorCountText = ko.computed(function() {
            return text.getParticipatorCountBadgeText(self);
        });
        self.statusText = ko.computed(function() {
            return text.getStatusText(self.invitation.status());
        });

        self.manageUrl = initialPageData.reverse('manage_registry', self.slug())

        self.acceptInvitation = function() {
            actions.acceptInvitation(self.slug, (data) => {
                ko.mapping.fromJS(data, self);
            });
        }

        self.rejectInvitation = function() {
            actions.rejectInvitation(self.slug, (data) => {
                ko.mapping.fromJS(data, self);
            });
        }
        return self;
    };

    let dataRegistryList = function ({ownedRegistries, invitedRegistries}) {
        return {
            ownedRegistries: _.map(ownedRegistries, (registry) => OwnedDataRegistry(registry)),
            invitedRegistries: _.map(invitedRegistries, (registry) => InvitedDataRegistry(registry)),
            newRegistry: function() {
                console.log("TODO: New Registry");
            }
        }
    }
    $(function () {
        $("#data-registry-list").koApplyBindings(dataRegistryList({
            ownedRegistries: initialPageData.get("owned_registries"),
            invitedRegistries: initialPageData.get("invited_registries"),
        }));
    });
});
<commit_msg>fix modal in list<commit_after>hqDefine("registry/js/registry_list", [
    'jquery',
    'underscore',
    'knockout',
    'hqwebapp/js/initial_page_data',
    'hqwebapp/js/alert_user',
    'registry/js/registry_text',
    'registry/js/registry_actions',
    'hqwebapp/js/knockout_bindings.ko', // openModal
], function (
    $,
    _,
    ko,
    initialPageData,
    alertUser,
    text,
    actions,
) {

    let OwnedDataRegistry = function (registry) {
        let self = ko.mapping.fromJS(registry);
        self.acceptedText = ko.computed(function() {
            return text.getAcceptedBadgeText(self);
        });
        self.pendingText = ko.computed(function() {
            return text.getPendingBadgeText(self);
        });
        self.rejectedText = ko.computed(function() {
            return text.getRejectedBadgeText(self);
        });
        self.manageUrl = initialPageData.reverse('manage_registry', self.slug())

        return self;
    };

    let InvitedDataRegistry = function (registry) {
        let self = ko.mapping.fromJS(registry);
        self.participatorCountText = ko.computed(function() {
            return text.getParticipatorCountBadgeText(self);
        });
        self.statusText = ko.computed(function() {
            return text.getStatusText(self.invitation.status());
        });

        self.manageUrl = initialPageData.reverse('manage_registry', self.slug())

        self.acceptInvitation = function() {
            actions.acceptInvitation(self.slug, (data) => {
                ko.mapping.fromJS(data, self);
            });
        }

        self.rejectInvitation = function() {
            actions.rejectInvitation(self.slug, (data) => {
                ko.mapping.fromJS(data, self);
            });
        }
        return self;
    };

    let dataRegistryList = function ({ownedRegistries, invitedRegistries}) {
        return {
            ownedRegistries: _.map(ownedRegistries, (registry) => OwnedDataRegistry(registry)),
            invitedRegistries: _.map(invitedRegistries, (registry) => InvitedDataRegistry(registry)),
            newRegistry: function() {
                console.log("TODO: New Registry");
            }
        }
    }
    $(function () {
        $("#data-registry-list").koApplyBindings(dataRegistryList({
            ownedRegistries: initialPageData.get("owned_registries"),
            invitedRegistries: initialPageData.get("invited_registries"),
        }));
    });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         YouKu Fullscreen
// @namespace    gucheen
// @version      0.12
// @description  Webpage Fullscreen for YouKu.com
// @author       gucheen
// @match        http*://v.youku.com/v_show/*
// @grant        none
// @license      MIT
// @homepageURL  https://github.com/BlinkTunnel/youku-fullscreen
// @updateURL https://openuserjs.org/meta/gucheen/YouKu_Fullscreen.meta.js
// ==/UserScript==

(function() {
    'use strict';

    var style = document.createElement('style');
    style.id = 'ykfull-chrome';
    style.textContent = '#player,#ykPlayer{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000}.yk-header,.yk-sidebar-w970,#id_google_tr,#player_sidebar,#sideTool,.mainCol,#qheader,#vpactionv5_wrap,.sideCol{display:none!important}.toggle{opacity:0}';

    var toggleButtonStyle = document.createElement('style');
    toggleButtonStyle.textContent = '.toggle{z-index:99999;display:block;position:absolute;top:60px;left:60px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;transition:all .25s ease-in}.toggle:hover{opacity:1}.toggle--checkbox{display:none}.toggle--btn{display:block;margin:0 auto;font-size:1.4em;transition:all .35s ease-in}.toggle--btn:hover{cursor:pointer}.toggle--btn,.toggle--btn:before,.toggle--btn:after,.toggle--checkbox,.toggle--checkbox:before,.toggle--checkbox:after,.toggle--feature,.toggle--feature:before,.toggle--feature:after{transition:all .25s ease-in}.toggle--btn:before,.toggle--btn:after,.toggle--checkbox:before,.toggle--checkbox:after,.toggle--feature:before,.toggle--feature:after{content:"";display:block}@keyframes neon{0%{text-shadow:0 0 10px #fff,0 0 15px #fff,0 0 25px #fff,0 0 40px #f90,0 0 70px #f90,0 0 90px #f90,0 0 90px #f90}to{text-shadow:0 0 5px #fff,0 0 10px #fff,0 0 15px #fff,0 0 20px #f90,0 0 35px #f90,0 0 40px #f90,0 0 50px #f90}}.toggle--neon .toggle--btn{font-family:Audiowide;text-transform:uppercase;font-size:2em;color:#a0a0a0;text-shadow:0 0 10px transparent,0 0 15px transparent,0 0 25px transparent,0 0 40px transparent,0 0 70px transparent,0 0 90px transparent,0 0 90px transparent}.toggle--neon .toggle--btn:before,.toggle--neon .toggle--btn:after{display:inline-block;margin:0 20px;transition:all .22s ease-in-out}.toggle--neon .toggle--btn:before{content:attr(data-label-off);animation:neon 1.5s ease-in-out infinite alternate;animation-delay:90ms;color:#f1f1f1}.toggle--neon .toggle--btn:after{content:attr(data-label-on)}.toggle--neon .toggle--checkbox:checked+.toggle--btn:before{animation:none;color:#a0a0a0}.toggle--neon .toggle--checkbox:checked+.toggle--btn:after{animation:neon 1.5s ease-in-out infinite alternate;animation-delay:90ms;color:#f1f1f1}';

    var toggleInput = document.createElement('input');
    toggleInput.type = 'checkbox';
    toggleInput.id = 'toggle--neon';
    toggleInput.className = 'toggle--checkbox';

    var toggleLabel = document.createElement('label');
    toggleLabel.className = 'toggle--btn';
    toggleLabel.setAttribute('for', 'toggle--neon');
    toggleLabel.dataset.labelOn = 'on';
    toggleLabel.dataset.labelOff = 'off';

    var toggleButton = document.createElement('div');
    toggleButton.className = 'youku-fullscreen-toggle toggle toggle--neon';
    toggleButton.appendChild(toggleInput);
    toggleButton.appendChild(toggleLabel);

    document.head.appendChild(toggleButtonStyle);
    document.body.appendChild(toggleButton);

    toggleInput.addEventListener('change', function (event) {
        if (event.target.checked) {
            document.head.appendChild(style);
        } else {
            document.head.removeChild(style);
        }
    });

})();
<commit_msg>Update version<commit_after>// ==UserScript==
// @name         YouKu Fullscreen
// @namespace    gucheen
// @version      0.13
// @description  Webpage Fullscreen for YouKu.com
// @author       gucheen
// @match        http*://v.youku.com/v_show/*
// @grant        none
// @license      MIT
// @homepageURL  https://github.com/BlinkTunnel/youku-fullscreen
// @updateURL https://openuserjs.org/meta/gucheen/YouKu_Fullscreen.meta.js
// ==/UserScript==

(function() {
    'use strict';

    var style = document.createElement('style');
    style.id = 'ykfull-chrome';
    style.textContent = '#player,#ykPlayer{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000}.yk-header,.yk-sidebar-w970,#id_google_tr,#player_sidebar,#sideTool,.mainCol,#qheader,#vpactionv5_wrap,.sideCol{display:none!important}.toggle{opacity:0}';

    var toggleButtonStyle = document.createElement('style');
    toggleButtonStyle.textContent = '.toggle{z-index:99999;display:block;position:absolute;top:60px;left:60px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;transition:all .25s ease-in}.toggle:hover{opacity:1}.toggle--checkbox{display:none}.toggle--btn{display:block;margin:0 auto;font-size:1.4em;transition:all .35s ease-in}.toggle--btn:hover{cursor:pointer}.toggle--btn,.toggle--btn:before,.toggle--btn:after,.toggle--checkbox,.toggle--checkbox:before,.toggle--checkbox:after,.toggle--feature,.toggle--feature:before,.toggle--feature:after{transition:all .25s ease-in}.toggle--btn:before,.toggle--btn:after,.toggle--checkbox:before,.toggle--checkbox:after,.toggle--feature:before,.toggle--feature:after{content:"";display:block}@keyframes neon{0%{text-shadow:0 0 10px #fff,0 0 15px #fff,0 0 25px #fff,0 0 40px #f90,0 0 70px #f90,0 0 90px #f90,0 0 90px #f90}to{text-shadow:0 0 5px #fff,0 0 10px #fff,0 0 15px #fff,0 0 20px #f90,0 0 35px #f90,0 0 40px #f90,0 0 50px #f90}}.toggle--neon .toggle--btn{font-family:Audiowide;text-transform:uppercase;font-size:2em;color:#a0a0a0;text-shadow:0 0 10px transparent,0 0 15px transparent,0 0 25px transparent,0 0 40px transparent,0 0 70px transparent,0 0 90px transparent,0 0 90px transparent}.toggle--neon .toggle--btn:before,.toggle--neon .toggle--btn:after{display:inline-block;margin:0 20px;transition:all .22s ease-in-out}.toggle--neon .toggle--btn:before{content:attr(data-label-off);animation:neon 1.5s ease-in-out infinite alternate;animation-delay:90ms;color:#f1f1f1}.toggle--neon .toggle--btn:after{content:attr(data-label-on)}.toggle--neon .toggle--checkbox:checked+.toggle--btn:before{animation:none;color:#a0a0a0}.toggle--neon .toggle--checkbox:checked+.toggle--btn:after{animation:neon 1.5s ease-in-out infinite alternate;animation-delay:90ms;color:#f1f1f1}';

    var toggleInput = document.createElement('input');
    toggleInput.type = 'checkbox';
    toggleInput.id = 'toggle--neon';
    toggleInput.className = 'toggle--checkbox';

    var toggleLabel = document.createElement('label');
    toggleLabel.className = 'toggle--btn';
    toggleLabel.setAttribute('for', 'toggle--neon');
    toggleLabel.dataset.labelOn = 'on';
    toggleLabel.dataset.labelOff = 'off';

    var toggleButton = document.createElement('div');
    toggleButton.className = 'youku-fullscreen-toggle toggle toggle--neon';
    toggleButton.appendChild(toggleInput);
    toggleButton.appendChild(toggleLabel);

    document.head.appendChild(toggleButtonStyle);
    document.body.appendChild(toggleButton);

    toggleInput.addEventListener('change', function (event) {
        if (event.target.checked) {
            document.head.appendChild(style);
        } else {
            document.head.removeChild(style);
        }
    });

})();
<|endoftext|>