<commit_before>/**
 * concrete5 wrapper for jQuery UI
 */
$.widget("concrete.dialog", $.ui.dialog, {
    _allowInteraction: function(event) {
        return !!$(event.target).closest('.ccm-interaction-dialog').length
            || !!$(event.target).closest(".cke_dialog").length
            || this._super(event);
    }
});

$.widget.bridge( "jqdialog", $.concrete.dialog );
// wrap our old dialog function in the new dialog() function.
jQuery.fn.dialog = function() {
    // Pass this over to jQuery UI Dialog in a few circumstances
    if (arguments.length > 0) {
        $(this).jqdialog(arguments[0], arguments[1], arguments[2]);
        return;
    } else if ($(this).is('div')) {
        $(this).jqdialog();
        return;
    }
    // LEGACY SUPPORT
    return $(this).each(function() {
        $(this).unbind('click.make-dialog').bind('click.make-dialog', function(e) {
            var href = $(this).attr('href');
            var width = $(this).attr('dialog-width');
            var height =$(this).attr('dialog-height');
            var title = $(this).attr('dialog-title');
            var onOpen = $(this).attr('dialog-on-open');
            var dialogClass = $(this).attr('dialog-class');
            var onDestroy = $(this).attr('dialog-on-destroy');
            /*
             * no longer necessary. we auto detect
                var appendButtons = $(this).attr('dialog-append-buttons');
            */
            var onClose = $(this).attr('dialog-on-close');
            var onDirectClose = $(this).attr('dialog-on-direct-close');
            obj = {
                modal: true,
                href: href,
                width: width,
                height: height,
                title: title,
                onOpen: onOpen,
                onDestroy: onDestroy,
                dialogClass: dialogClass,
                onClose: onClose,
                onDirectClose: onDirectClose
            }
            jQuery.fn.dialog.open(obj);
            return false;
        });
    });
}

jQuery.fn.dialog.close = function(num) {
    num++;
    $("#ccm-dialog-content" + num).jqdialog('close');
}

jQuery.fn.dialog.open = function(options) {
    if (typeof(ConcreteMenu) != 'undefined') {
        var activeMenu = ConcreteMenuManager.getActiveMenu();
        if (activeMenu) {
            activeMenu.hide();
        }
    }

    if (typeof(options.width) == 'string') {
        if (options.width == 'auto') {
            w = 'auto';
        } else {
            if (options.width.indexOf('%', 0) > 0) {
                w = options.width.replace('%', '');
                w = $(window).width() * (w / 100);
                w = w + 50;
            } else {
                w = parseInt(options.width) + 50;
            }
        }
    } else if (options.width) {
        w = parseInt(options.width) + 50;
    } else {
        w = 550;
    }

    if (typeof(options.height) == 'string') {
        if (options.height == 'auto') {
            h = 'auto';
        } else {
            if (options.height.indexOf('%', 0) > 0) {
                h = options.height.replace('%', '');
                h = $(window).height() * (h / 100);
                h = h + 100;
            } else {
                h = parseInt(options.height) + 100;
            }
        }
    } else if (options.height) {
        h = parseInt(options.height) + 100;
    } else {
        h = 400;
    }
    if (h !== 'auto' && h > $(window).height()) {
        h = $(window).height();
    }

    options.width = w;
    options.height = h;

    var defaults = {
        'modal': true,
        'escapeClose': true,
        'width': w,
        'height': h,
        'dialogClass': 'ccm-ui ccm-ui-fieldless',
        'resizable': true,

        'create': function() {
            $(this).parent().addClass('animated fadeIn');
        },

        'open': function() {
            var $dialog = $(this);
            var nd = $(".ui-dialog").length;
            if (nd == 1) {
                $("body").attr('data-last-overflow', $('body').css('overflow'));
                $("body").css("overflow", "hidden");
            }
            var overlays = $('.ui-widget-overlay').length;
            $('.ui-widget-overlay').each(function(i, obj) {
                if ((i + 1) < overlays) {
                    $(this).removeClass('animated fadeIn').css('opacity', 0);
                }
            });
            if (overlays == 1) {
                $('.ui-widget-overlay').addClass('animated fadeIn');
            }

            jQuery.fn.dialog.activateDialogContents($dialog);

            // on some brother (eg: Chrome) the resizable get hidden because the button pane
            // in on top of it, here is a fix for this:
            if ( $dialog.jqdialog('option', 'resizable') )
            {
                var $wrapper = $($dialog.parent());
                var z = parseInt($wrapper.find('.ui-dialog-buttonpane').css('z-index'));
                $wrapper.find('.ui-resizable-handle').css('z-index', z + 1000);
            }

            if (typeof options.onOpen != "undefined") {
                if ((typeof options.onOpen) == 'function') {
                    options.onOpen($dialog);
                } else {
                    eval(options.onOpen);
                }
            }

        },
        'beforeClose': function() {
            var nd = $(".ui-dialog").length;
            if (nd == 1) {
                $("body").css("overflow", $('body').attr('data-last-overflow'));
            }
        },
        'close': function(ev, u) {
            if (!options.element) {
                $(this).jqdialog('destroy').remove();
            }
            if (typeof options.onClose != "undefined") {
                if ((typeof options.onClose) == 'function') {
                    options.onClose($(this));
                } else {
                    eval(options.onClose);
                }
            }
            if (typeof options.onDirectClose != "undefined" && ev.handleObj && (ev.handleObj.type == 'keydown' || ev.handleObj.type == 'click')) {
                if ((typeof options.onDirectClose) == 'function') {
                    options.onDirectClose();
                } else {
                    eval(options.onDirectClose);
                }
            }
            if (typeof options.onDestroy != "undefined") {
                if ((typeof options.onDestroy) == 'function') {
                    options.onDestroy();
                } else {
                    eval(options.onDestroy);
                }
            }
            var overlays = $('.ui-widget-overlay').length;
            $('.ui-widget-overlay').each(function(i, obj) {
                if ((i + 1) < overlays) {
                    $(this).css('opacity', 0);
                } else {
                    $(this).css('opacity', 1);
                }
            });
        }
    };

    var finalSettings = {'autoOpen': false, 'data': {} };
    $.extend(finalSettings, defaults, options);

    if (finalSettings.element) {
        $(finalSettings.element).jqdialog(finalSettings).jqdialog();
        $(finalSettings.element).jqdialog('open');
    } else {
        jQuery.fn.dialog.showLoader();
        $.ajax({
            type: 'GET',
            url: finalSettings.href,
            data: finalSettings.data,
            success: function(r) {
                jQuery.fn.dialog.hideLoader();
                // note the order here is very important in order to actually run javascript in
                // the pages we load while having access to the jqdialog object.
                // Ensure that the dialog is open prior to evaluating javascript.
                $('<div />').jqdialog(finalSettings).html(r).jqdialog('open');
            }
        });
    }

}

jQuery.fn.dialog.activateDialogContents = function($dialog) {
    // handle buttons

    $dialog.find('button[data-dialog-action=cancel]').on('click', function() {
        jQuery.fn.dialog.closeTop();
    });
    $dialog.find('[data-dialog-form]').concreteAjaxForm();

    $dialog.find('button[data-dialog-action=submit]').on('click', function() {
        $dialog.find('[data-dialog-form]').submit();
    });

    if ($dialog.find('.dialog-buttons').length > 0) {
        $dialog.jqdialog('option', 'buttons', [{}]);
        $dialog.parent().find(".ui-dialog-buttonset").remove();
        $dialog.parent().find(".ui-dialog-buttonpane").html('');
        $dialog.find('.dialog-buttons').eq(0).removeClass().appendTo($dialog.parent().find('.ui-dialog-buttonpane').addClass("ccm-ui"));
    }

    // make dialogs
    $dialog.find('.dialog-launch').dialog();

    // automated close handling
    $dialog.find('.ccm-dialog-close').on('click', function() {
        $dialog.dialog('close');
    });

    $dialog.find('.launch-tooltip').tooltip({'container': '#ccm-tooltip-holder'});

    // help handling
    if ($dialog.find('.dialog-help').length > 0) {
        $dialog.find('.dialog-help').hide();
        var helpContent = $dialog.find('.dialog-help').html();
        if (ccmi18n.helpPopup) {
            var helpText = ccmi18n.helpPopup;
        } else {
            var helpText = 'Help';
        }
        var button = $('<button class="ui-dialog-titlebar-help ccm-menu-help-trigger"><i class="fa fa-info-circle"></i></button>'),
            container = $('#ccm-tooltip-holder');
        $dialog.parent().find('.ui-dialog-titlebar').append(button);

        button.popover({
            content: function() {
                return helpContent;
            },
            placement: 'bottom',
            html: true,
            container: container,
            trigger: 'click'
        });
        button.on('shown.bs.popover', function() {
            var binding = function() {
                button.popover('hide', button);
                binding = $.noop;
            };

            button.on('hide.bs.popover', function(event) {
                button.unbind(event);
                binding = $.noop;
            });

            $('body').mousedown(function(e) {
                if ($(e.target).closest(container).length || $(e.target).closest(button).length) {
                    return;
                }
                $(this).unbind(e);
                binding();
            });
        });
    }
}

jQuery.fn.dialog.getTop = function() {
    var nd = $(".ui-dialog:visible").length;
    return $($('.ui-dialog:visible')[nd-1]).find('.ui-dialog-content');
}

jQuery.fn.dialog.replaceTop = function(html) {
    $dialog = jQuery.fn.dialog.getTop();
    $dialog.html(html);
    jQuery.fn.dialog.activateDialogContents($dialog);
}

jQuery.fn.dialog.showLoader = function(text) {
    $('body').addClass('ccm-loading');
}

jQuery.fn.dialog.hideLoader = function() {
    $('body').removeClass('ccm-loading');
}

jQuery.fn.dialog.closeTop = function() {
    $dialog = jQuery.fn.dialog.getTop();
    $dialog.jqdialog('close');
}

jQuery.fn.dialog.closeAll = function() {
    $($(".ui-dialog-content").get().reverse()).jqdialog('close');
}

<commit_msg>Fixing bug with some blocks disabling scrolling once dialogs are closed<commit_after>/**
 * concrete5 wrapper for jQuery UI
 */
$.widget("concrete.dialog", $.ui.dialog, {
    _allowInteraction: function(event) {
        return !!$(event.target).closest('.ccm-interaction-dialog').length
            || !!$(event.target).closest(".cke_dialog").length
            || this._super(event);
    }
});

$.widget.bridge( "jqdialog", $.concrete.dialog );
// wrap our old dialog function in the new dialog() function.
jQuery.fn.dialog = function() {
    // Pass this over to jQuery UI Dialog in a few circumstances
    if (arguments.length > 0) {
        $(this).jqdialog(arguments[0], arguments[1], arguments[2]);
        return;
    } else if ($(this).is('div')) {
        $(this).jqdialog();
        return;
    }
    // LEGACY SUPPORT
    return $(this).each(function() {
        $(this).unbind('click.make-dialog').bind('click.make-dialog', function(e) {
            var href = $(this).attr('href');
            var width = $(this).attr('dialog-width');
            var height =$(this).attr('dialog-height');
            var title = $(this).attr('dialog-title');
            var onOpen = $(this).attr('dialog-on-open');
            var dialogClass = $(this).attr('dialog-class');
            var onDestroy = $(this).attr('dialog-on-destroy');
            /*
             * no longer necessary. we auto detect
                var appendButtons = $(this).attr('dialog-append-buttons');
            */
            var onClose = $(this).attr('dialog-on-close');
            var onDirectClose = $(this).attr('dialog-on-direct-close');
            obj = {
                modal: true,
                href: href,
                width: width,
                height: height,
                title: title,
                onOpen: onOpen,
                onDestroy: onDestroy,
                dialogClass: dialogClass,
                onClose: onClose,
                onDirectClose: onDirectClose
            }
            jQuery.fn.dialog.open(obj);
            return false;
        });
    });
}

jQuery.fn.dialog.close = function(num) {
    num++;
    $("#ccm-dialog-content" + num).jqdialog('close');
}

jQuery.fn.dialog.open = function(options) {
    if (typeof(ConcreteMenu) != 'undefined') {
        var activeMenu = ConcreteMenuManager.getActiveMenu();
        if (activeMenu) {
            activeMenu.hide();
        }
    }

    if (typeof(options.width) == 'string') {
        if (options.width == 'auto') {
            w = 'auto';
        } else {
            if (options.width.indexOf('%', 0) > 0) {
                w = options.width.replace('%', '');
                w = $(window).width() * (w / 100);
                w = w + 50;
            } else {
                w = parseInt(options.width) + 50;
            }
        }
    } else if (options.width) {
        w = parseInt(options.width) + 50;
    } else {
        w = 550;
    }

    if (typeof(options.height) == 'string') {
        if (options.height == 'auto') {
            h = 'auto';
        } else {
            if (options.height.indexOf('%', 0) > 0) {
                h = options.height.replace('%', '');
                h = $(window).height() * (h / 100);
                h = h + 100;
            } else {
                h = parseInt(options.height) + 100;
            }
        }
    } else if (options.height) {
        h = parseInt(options.height) + 100;
    } else {
        h = 400;
    }
    if (h !== 'auto' && h > $(window).height()) {
        h = $(window).height();
    }

    options.width = w;
    options.height = h;

    var defaults = {
        'modal': true,
        'escapeClose': true,
        'width': w,
        'height': h,
        'dialogClass': 'ccm-ui ccm-ui-fieldless',
        'resizable': true,

        'create': function() {
            $(this).parent().addClass('animated fadeIn');
        },

        'open': function() {
            var $dialog = $(this);
            var nd = $(".ui-dialog").length;
            if (nd == 1) {
                $("body").attr('data-last-overflow', $('body').css('overflow'));
                $("body").css("overflow", "hidden");
            }
            var overlays = $('.ui-widget-overlay').length;
            $('.ui-widget-overlay').each(function(i, obj) {
                if ((i + 1) < overlays) {
                    $(this).removeClass('animated fadeIn').css('opacity', 0);
                }
            });
            if (overlays == 1) {
                $('.ui-widget-overlay').addClass('animated fadeIn');
            }

            jQuery.fn.dialog.activateDialogContents($dialog);

            // on some brother (eg: Chrome) the resizable get hidden because the button pane
            // in on top of it, here is a fix for this:
            if ( $dialog.jqdialog('option', 'resizable') )
            {
                var $wrapper = $($dialog.parent());
                var z = parseInt($wrapper.find('.ui-dialog-buttonpane').css('z-index'));
                $wrapper.find('.ui-resizable-handle').css('z-index', z + 1000);
            }

            if (typeof options.onOpen != "undefined") {
                if ((typeof options.onOpen) == 'function') {
                    options.onOpen($dialog);
                } else {
                    eval(options.onOpen);
                }
            }

        },
        'beforeClose': function() {
            var nd = $(".ui-dialog:visible").length;
            if (nd == 1) {
                $("body").css("overflow", $('body').attr('data-last-overflow'));
            }
        },
        'close': function(ev, u) {
            if (!options.element) {
                $(this).jqdialog('destroy').remove();
            }
            if (typeof options.onClose != "undefined") {
                if ((typeof options.onClose) == 'function') {
                    options.onClose($(this));
                } else {
                    eval(options.onClose);
                }
            }
            if (typeof options.onDirectClose != "undefined" && ev.handleObj && (ev.handleObj.type == 'keydown' || ev.handleObj.type == 'click')) {
                if ((typeof options.onDirectClose) == 'function') {
                    options.onDirectClose();
                } else {
                    eval(options.onDirectClose);
                }
            }
            if (typeof options.onDestroy != "undefined") {
                if ((typeof options.onDestroy) == 'function') {
                    options.onDestroy();
                } else {
                    eval(options.onDestroy);
                }
            }
            var overlays = $('.ui-widget-overlay').length;
            $('.ui-widget-overlay').each(function(i, obj) {
                if ((i + 1) < overlays) {
                    $(this).css('opacity', 0);
                } else {
                    $(this).css('opacity', 1);
                }
            });
        }
    };

    var finalSettings = {'autoOpen': false, 'data': {} };
    $.extend(finalSettings, defaults, options);

    if (finalSettings.element) {
        $(finalSettings.element).jqdialog(finalSettings).jqdialog();
        $(finalSettings.element).jqdialog('open');
    } else {
        jQuery.fn.dialog.showLoader();
        $.ajax({
            type: 'GET',
            url: finalSettings.href,
            data: finalSettings.data,
            success: function(r) {
                jQuery.fn.dialog.hideLoader();
                // note the order here is very important in order to actually run javascript in
                // the pages we load while having access to the jqdialog object.
                // Ensure that the dialog is open prior to evaluating javascript.
                $('<div />').jqdialog(finalSettings).html(r).jqdialog('open');
            }
        });
    }

}

jQuery.fn.dialog.activateDialogContents = function($dialog) {
    // handle buttons

    $dialog.find('button[data-dialog-action=cancel]').on('click', function() {
        jQuery.fn.dialog.closeTop();
    });
    $dialog.find('[data-dialog-form]').concreteAjaxForm();

    $dialog.find('button[data-dialog-action=submit]').on('click', function() {
        $dialog.find('[data-dialog-form]').submit();
    });

    if ($dialog.find('.dialog-buttons').length > 0) {
        $dialog.jqdialog('option', 'buttons', [{}]);
        $dialog.parent().find(".ui-dialog-buttonset").remove();
        $dialog.parent().find(".ui-dialog-buttonpane").html('');
        $dialog.find('.dialog-buttons').eq(0).removeClass().appendTo($dialog.parent().find('.ui-dialog-buttonpane').addClass("ccm-ui"));
    }

    // make dialogs
    $dialog.find('.dialog-launch').dialog();

    // automated close handling
    $dialog.find('.ccm-dialog-close').on('click', function() {
        $dialog.dialog('close');
    });

    $dialog.find('.launch-tooltip').tooltip({'container': '#ccm-tooltip-holder'});

    // help handling
    if ($dialog.find('.dialog-help').length > 0) {
        $dialog.find('.dialog-help').hide();
        var helpContent = $dialog.find('.dialog-help').html();
        if (ccmi18n.helpPopup) {
            var helpText = ccmi18n.helpPopup;
        } else {
            var helpText = 'Help';
        }
        var button = $('<button class="ui-dialog-titlebar-help ccm-menu-help-trigger"><i class="fa fa-info-circle"></i></button>'),
            container = $('#ccm-tooltip-holder');
        $dialog.parent().find('.ui-dialog-titlebar').append(button);

        button.popover({
            content: function() {
                return helpContent;
            },
            placement: 'bottom',
            html: true,
            container: container,
            trigger: 'click'
        });
        button.on('shown.bs.popover', function() {
            var binding = function() {
                button.popover('hide', button);
                binding = $.noop;
            };

            button.on('hide.bs.popover', function(event) {
                button.unbind(event);
                binding = $.noop;
            });

            $('body').mousedown(function(e) {
                if ($(e.target).closest(container).length || $(e.target).closest(button).length) {
                    return;
                }
                $(this).unbind(e);
                binding();
            });
        });
    }
}

jQuery.fn.dialog.getTop = function() {
    var nd = $(".ui-dialog:visible").length;
    return $($('.ui-dialog:visible')[nd-1]).find('.ui-dialog-content');
}

jQuery.fn.dialog.replaceTop = function(html) {
    $dialog = jQuery.fn.dialog.getTop();
    $dialog.html(html);
    jQuery.fn.dialog.activateDialogContents($dialog);
}

jQuery.fn.dialog.showLoader = function(text) {
    $('body').addClass('ccm-loading');
}

jQuery.fn.dialog.hideLoader = function() {
    $('body').removeClass('ccm-loading');
}

jQuery.fn.dialog.closeTop = function() {
    $dialog = jQuery.fn.dialog.getTop();
    $dialog.jqdialog('close');
}

jQuery.fn.dialog.closeAll = function() {
    $($(".ui-dialog-content").get().reverse()).jqdialog('close');
}

<|endoftext|>


<commit_before>var P = require('../prelude').install(GLOBAL);
var assert = require('assert');

describe('Lists', function () {

    it('isNull', function () {
        assert.strictEqual(true, isNull([]));
        assert.strictEqual(false, isNull([ 1 ]));
    });

    it('isNull /w string', function () {
        assert.strictEqual(true, isNull(""));
        assert.strictEqual(false, isNull("x"));
    });

    it('length', function () {
        assert.strictEqual(0, length([]));
        assert.strictEqual(1, length([ 1 ]));
    });

    it('length /w string', function () {
        assert.strictEqual(0, length(""));
        assert.strictEqual(1, length("x"));
    });

    it('head', function () {
        assert.strictEqual(10, head([ 10, 4, 21 ]));
    });

    it('head /w string', function () {
        assert.strictEqual('a', head("abc"));
    });

    it('tail', function () {
        assert.deepEqual([ 4, 21 ], tail([ 10, 4, 21 ]));
    });

    it('tail /w string', function () {
        assert.strictEqual("bc", tail("abc"));
    });

    it('init', function () {
        assert.deepEqual([ 10, 4 ], init([ 10, 4, 21 ]));
    });

    it('init /w string', function () {
        assert.strictEqual("ab", init("abc"));
    });

    it('last', function () {
        assert.strictEqual(21, last([ 10, 4, 21 ]));
    });

    it('last /w string', function () {
        assert.strictEqual('c', last("abc"));
    });

    it('take', function () {
        assert.deepEqual([], take(0, [ 10, 4, 18, 17 ]));
        assert.deepEqual([], take(10, []));
        assert.deepEqual([ 10, 4 ], take(2, [ 10, 4, 18, 17 ]));
        assert.deepEqual([ 10, 4 ], take(4, [ 10, 4 ]));
    });

    it('take /w string', function () {
        assert.deepEqual("abc", take(3, "abc"));
        assert.deepEqual("", take(0, ""));
    });

    it('drop', function () {
        assert.deepEqual([ 10, 4, 18, 17 ], drop(0, [ 10, 4, 18, 17 ]));
        assert.deepEqual([], drop(10, []));
        assert.deepEqual([ 18, 17 ], drop(2, [ 10, 4, 18, 17 ]));
        assert.deepEqual([], drop(4, [ 10, 4 ]));
    });

    it('drop /w string', function () {
        assert.deepEqual("", drop(3, "abc"));
        assert.deepEqual("", drop(5, "abc"));
        assert.deepEqual("abcde", drop(0, "abcde"));
        assert.deepEqual("de", drop(3, "abcde"));
        assert.deepEqual("", drop(0, ""));
    });

    it('takeWhile', function () {

    });

    it('takeWhile /w string', function () {

    });

    it('dropWhile', function () {

    });

    it('dropWhile /w string', function () {

    });
});

<commit_msg>more tests<commit_after>var P = require('../prelude').install(GLOBAL);
var assert = require('assert');

describe('Lists', function () {

    it('isNull', function () {
        assert.strictEqual(true, isNull([]));
        assert.strictEqual(false, isNull([ 1 ]));
    });

    it('isNull /w string', function () {
        assert.strictEqual(true, isNull(""));
        assert.strictEqual(false, isNull("x"));
    });

    it('length', function () {
        assert.strictEqual(0, length([]));
        assert.strictEqual(1, length([ 1 ]));
    });

    it('length /w string', function () {
        assert.strictEqual(0, length(""));
        assert.strictEqual(1, length("x"));
    });

    it('head', function () {
        assert.strictEqual(10, head([ 10, 4, 21 ]));
    });

    it('head /w string', function () {
        assert.strictEqual('a', head("abc"));
    });

    it('tail', function () {
        assert.deepEqual([ 4, 21 ], tail([ 10, 4, 21 ]));
    });

    it('tail /w string', function () {
        assert.strictEqual("bc", tail("abc"));
    });

    it('init', function () {
        assert.deepEqual([ 10, 4 ], init([ 10, 4, 21 ]));
    });

    it('init /w string', function () {
        assert.strictEqual("ab", init("abc"));
    });

    it('last', function () {
        assert.strictEqual(21, last([ 10, 4, 21 ]));
    });

    it('last /w string', function () {
        assert.strictEqual('c', last("abc"));
    });

    it('take', function () {
        assert.deepEqual([], take(0, [ 10, 4, 18, 17 ]));
        assert.deepEqual([], take(10, []));
        assert.deepEqual([ 10, 4 ], take(2, [ 10, 4, 18, 17 ]));
        assert.deepEqual([ 10, 4 ], take(4, [ 10, 4 ]));
    });

    it('take /w string', function () {
        assert.deepEqual("abc", take(3, "abc"));
        assert.deepEqual("", take(0, ""));
    });

    it('drop', function () {
        assert.deepEqual([ 10, 4, 18, 17 ], drop(0, [ 10, 4, 18, 17 ]));
        assert.deepEqual([], drop(10, []));
        assert.deepEqual([ 18, 17 ], drop(2, [ 10, 4, 18, 17 ]));
        assert.deepEqual([], drop(4, [ 10, 4 ]));
    });

    it('drop /w string', function () {
        assert.deepEqual("", drop(3, "abc"));
        assert.deepEqual("", drop(5, "abc"));
        assert.deepEqual("abcde", drop(0, "abcde"));
        assert.deepEqual("de", drop(3, "abcde"));
        assert.deepEqual("", drop(0, ""));
    });

    it('filter', function () {
        assert.deepEqual([], filter(flip(gte)(10), [ 1, 2, 3 ]));
        assert.deepEqual([ 3 ], filter(flip(gt)(2), [ 3 ]));
    });

    it('takeWhile', function () {

    });

    it('takeWhile /w string', function () {

    });

    it('dropWhile', function () {

    });

    it('dropWhile /w string', function () {

    });
});

<|endoftext|>


<commit_before>/**
 * @author Thomas Modeneis <thomas.modeneis@gmail.com>
 */
'use strict';
var curlrequest = require('curlrequest');
var request = require('request');
var fs = require('fs');
var _ = require('underscore');
var FormData = require('form-data');

exports.addTrack = function (options, callback) {
    var form = new FormData();

    form.append('format', 'json');
    if (options.title === undefined) {
        callback('Error while addTrack track options.title: ' + options.title);
        return;
    } else {
        form.append('track[title]', options.title);
    }
    if (options.description === undefined) {
        callback('Error  while addTrack track options.description is required and is: ' + options.description);
        return;
    } else {
        form.append('track[description]', options.description);
    }
    if (options.genre === undefined) {
        callback('Error  while addTrack track options.genre is required and is:  ' + options.genre);
        return;
    } else {
        form.append('track[genre]', options.genre);
    }

    var exist_artwork_data = fs.existsSync(options.artwork_data);
    if (exist_artwork_data) {
        form.append('track[artwork_data]', fs.createReadStream(options.artwork_data));
    }

    form.append('track[sharing]', options.sharing);

    if (options.oauth_token === undefined) {
        callback('Error  while addTrack track oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {
        form.append('oauth_token', options.oauth_token);
    }

    if (options.asset_data === undefined) {
        callback('Error  while addTrack track options.asset_data is required and is: ' + options.asset_data);
        return;
    } else {

        var exist_asset_data = fs.existsSync(options.asset_data);
        console.log(exist_asset_data);

        if (exist_asset_data) {
            form.append('track[asset_data]', fs.createReadStream(options.asset_data));
        } else {
            callback('Error addTrack could not find options.asset_data --> fs.createReadStream(options.asset_data): ' + exist_asset_data);
            return;
        }
    }

    form.submit('https://api.soundcloud.com/tracks', function (err, response) {
        if (!err) {

            response.on('error', function (err) {
                callback('Error addTrack while addTrack track: ' + err);
            });

            var data = "";
            response.on('data', function (chunk) {
                data = data + chunk;
            });

            response.on('end', function () {
                console.log('addTrack successful');
                callback(null, JSON.parse(data.toString('utf8')));
            });

        } else {
            console.log('Error while addTrack track : ' + err);
            callback('Error while addTrack track : ' + err);

        }
    });
};

exports.removeTrack = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error removeTrack oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {

        var uri = 'https://api.soundcloud.com/tracks/' + options.id + '?oauth_token=' + options.oauth_token + '&format=json';
        request(uri, {method: 'DELETE'}, function (err, response) {
            if (err || response.body !== undefined && response.body.indexOf(404) !== -1) {
                console.log('Error while removeTrack track: ' + response.body);
                callback('Error while removeTrack track: ' + response.body);
            } else {
                callback(null, {result: response.body});
            }
        });
    }
};

exports.getTracks = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error getTracks oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {
        var uri = 'https://api.soundcloud.com/me/tracks?format=json&oauth_token=' + options.oauth_token;
        request(uri, function (err, response, body) {
            if (!err) {
                console.log('getTracks successful');
                var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) {
                    return track;
                });
                callback(null, tracks);
            } else {
                console.log('Error while getTracks track: ' + err);
                callback('Error while getTracks track: ' + err);

            }
        });
    }
};

exports.searchTrack_q = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error searchTrack_q oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {

        if (options.q === undefined) {
            callback('Error searchTrack_q options.q is required and is: ' + options.q);
            return;
        } else {
            var uri = 'https://api.soundcloud.com/me/tracks?format=json&oauth_token=' + options.oauth_token + '&q=' + options.q;
            request(uri, function (err, response, body) {
                if (!err) {
                    console.log('getTracks successful');
                    callback(null, JSON.parse(body.toString('utf8')));
                } else {
                    console.log('Error while searchTrack_q track: ' + err);
                    callback('Error while searchTrack_q track: ' + err);

                }
            });
        }
    }
};

exports.resolveUri = function (options, callback) {
    if (options.client_id === undefined) {
        callback('Error resolveTrack options.client_id is required and is: ' + options.client_id);
        return;
    } else {

        if (options.uri === undefined) {
            callback('Error resolveTrack options.uri is required and is: ' + options.uri);
        } else {
//            http://api.soundcloud.com/resolve.json?url=https://soundcloud.com/user46387694/dog_example&client_id=6e110a037f1c9a14b1d3abd1d97f842a
            var uri = 'http://api.soundcloud.com/resolve.json?url=' + options.uri + '&client_id=' + options.client_id;
            request(uri, function (err, response, body) {
                if (err) {
                    console.log('Error while resolveTrack track: ' + err);
                    callback('Error while resolveTrack track: ' + err);

                } else {

                    response.on('error', function (err) {
                        callback('Error while resolveTrack track: ' + err);
                    });

                    console.log('resolveTrack successful');
                    callback(null, JSON.parse(response.body.toString('utf8')));

                }
            });
        }
    }
};

exports.addTrackToPlaylist = function (options, callback) {
    var form = new FormData();
    form.append('format', 'json');

    console.log(JSON.stringify(options.tracks));

    if (options.tracks === undefined) {
        callback('Error while addTrackToPlaylist options.tracks : ' + options.tracks);
        return;
    } else {
        _.each(trackIds(options.tracks), function (id) {
            console.log(id);
            form.append('playlist[tracks][][id]', id);
        });
    }

    if (options.track.id === undefined) {
        callback('Error while addTrackToPlaylist options.id : ' + options.track.id);
        return;
    } else {
        form.append('playlist[tracks][][id]', options.track.id);
    }

    if (options.title === undefined) {
        callback('Error while addTrackToPlaylist track : ' + options.title);
        return;
    } else {
        form.append('playlist[title]', options.title);
    }

    if (options.sharing === undefined) {
        callback('Error while addTrackToPlaylist track : ' + options.sharing);
        return;
    } else {
        form.append('playlist[sharing]', options.sharing);
    }

    if (options.oauth_token === undefined) {
        callback('Error while addTrackToPlaylist track : ' + options.oauth_token);
        return;
    } else {
        form.append('oauth_token', options.oauth_token);
    }

    console.log(parsedUrl(options));
    form.submit(parsedUrl(options), function (err, response) {
        if (!err) {

            response.on('error', function (err) {
                callback('Error while addTrackToPlaylist track: ' + err);
            });

            var data = "";
            response.on('data', function (chunk) {
                data = data + chunk;
            });

            response.on('end', function () {
                console.log('addPlaylist successful');
                callback(null, JSON.parse(data.toString('utf8')));
            });

        } else {
            console.log('Error while addTrackToPlaylist track: ' + err);
            callback('Error while addTrackToPlaylist track: ' + err);

        }
    });
};

var URL = require('url');
function parsedUrl(playlist) {
    var playListUri = URL.parse(playlist.uri);
    return {
        method: 'put',
        host: playListUri.host,
        path: playListUri.path,
        protocol: playListUri.protocol
    };
}

function trackIds(json) {
    return _.map(json, function (track) {
        return track.id;
    })
}

exports.addTrackToNewPlaylist = function (options, callback) {
    var form = new FormData();
    form.append('format', 'json');

    if (options.tracks === undefined) {
        callback('Error while addTrackToNewPlaylist options.tracks : ' + options.tracks);
        return;
    } else {
        _.each(options.tracks, function (id) {
            form.append('playlist[tracks][][id]', id);
        });
    }
    if (options.title === undefined) {
        callback('Error while addTrackToNewPlaylist options.title : ' + options.title);
        return;
    } else {
        form.append('playlist[title]', options.title);
    }
    if (options.sharing === undefined) {
        callback('Error while addTrackToNewPlaylist options.sharing : ' + options.sharing);
        return;
    } else {
        form.append('playlist[sharing]', options.sharing);
    }
    if (options.oauth_token === undefined) {
        callback('Error while addTrackToNewPlaylist options.oauth_token : ' + options.oauth_token);
        return;
    } else {
        form.append('oauth_token', options.oauth_token);
    }

    form.submit('https://api.soundcloud.com/playlists', function (err, response) {
        if (!err) {

            response.on('error', function (err) {
                callback('Error while addTrackToNewPlaylist track: ' + err);
            });

            var data = "";
            response.on('data', function (chunk) {
                data = data + chunk;
            });

            response.on('end', function () {
                console.log('addPlaylist successful');
                callback(null, JSON.parse(data.toString('utf8')));
            });

        } else {
            console.log('Error while addTrackToNewPlaylist track: ' + err);
            callback('Error while addTrackToNewPlaylist track: ' + err);

        }
    });
};

exports.getPlaylist = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {
        var uri = 'https://api.soundcloud.com/me/playlists?format=json&oauth_token=' + options.oauth_token;
        request(uri, function (err, response, body) {
            if (!err) {
                console.log('getPlaylist successful');
                var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) {
                    return track;
                });
                callback(null, tracks);
            } else {
                console.log('Error while getPlaylist track: ' + err);
                callback('Error while getPlaylist track: ' + err);

            }
        });
    }
};

exports.getPlaylistById = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error getPlaylistById options.oauth_token is required and is: ' + options.oauth_token);
        return;
    } else if (options.id === undefined) {
        callback('Error getPlaylistById options.id is required and is: ' + options.id);
        return;
    } else {
        var uri = 'https://api.soundcloud.com/me/playlists/' + options.id + '?format=json&oauth_token=' + options.oauth_token;
        request(uri, function (err, response, body) {
            if (!err) {
                console.log('getPlaylistById successful');
                var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) {
                    return track;
                });
                callback(null, tracks);
            } else {
                console.log('Error while getPlaylistById track: ' + err);
                callback('Error while getPlaylistById track: ' + err);

            }
        });
    }
};

exports.removePlaylist = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error removePlaylist options.oauth_token is required and is: ' + options.oauth_token);
        return;
    } else if (options.title === undefined) {
        callback('Error removePlaylist options.title is required and is: ' + options.title);
        return;
    } else {
        var uri = 'https://api.soundcloud.com/playlists/' + options.title + '?oauth_token=' + options.oauth_token + '&format=json';
        request(uri, {method: 'DELETE'}, function (err, response) {
            if (err || response.body !== undefined && response.body.indexOf(404) !== -1) {
                console.log('Error while removePlaylist track: ' + response.body);
                callback('Error while removePlaylist track: ' + response.body);
            } else {
                callback(null, {result: response.body});
            }
        });
    }
};

exports.getToken = function (options, callback) {

    var curl_options = {
        'url': 'https://api.soundcloud.com/oauth2/token',
        'method': 'POST',
        verbose: true,
        encoding: 'utf8',
        data: options
    };

    curlrequest.request(curl_options, function (err, data, meta) {
        callback(err, JSON.parse(data), meta);
    });
}
<commit_msg>adding timeout minor fixes<commit_after>/**
 * @author Thomas Modeneis <thomas.modeneis@gmail.com>
 */
'use strict';
var curlrequest = require('curlrequest');
var request = require('request');
var fs = require('fs');
var _ = require('underscore');
var FormData = require('form-data');

exports.addTrack = function (options, callback) {
    var form = new FormData();

    form.append('format', 'json');
    if (options.title === undefined) {
        callback('Error while addTrack track options.title: ' + options.title);
        return;
    } else {
        form.append('track[title]', options.title);
    }
    if (options.description === undefined) {
        callback('Error  while addTrack track options.description is required and is: ' + options.description);
        return;
    } else {
        form.append('track[description]', options.description);
    }
    if (options.genre === undefined) {
        callback('Error  while addTrack track options.genre is required and is:  ' + options.genre);
        return;
    } else {
        form.append('track[genre]', options.genre);
    }

    var exist_artwork_data = fs.existsSync(options.artwork_data);
    if (exist_artwork_data) {
        form.append('track[artwork_data]', fs.createReadStream(options.artwork_data));
    }

    form.append('track[sharing]', options.sharing);

    if (options.oauth_token === undefined) {
        callback('Error  while addTrack track oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {
        form.append('oauth_token', options.oauth_token);
    }

    if (options.asset_data === undefined) {
        callback('Error  while addTrack track options.asset_data is required and is: ' + options.asset_data);
        return;
    } else {

        var exist_asset_data = fs.existsSync(options.asset_data);
        console.log(exist_asset_data);

        if (exist_asset_data) {
            form.append('track[asset_data]', fs.createReadStream(options.asset_data));
        } else {
            callback('Error addTrack could not find options.asset_data --> fs.createReadStream(options.asset_data): ' + exist_asset_data);
            return;
        }
    }

    form.submit('https://api.soundcloud.com/tracks', function (err, response) {
        if (!err) {

            response.on('error', function (err) {
                callback('Error addTrack while addTrack track: ' + err);
            });

            var data = "";
            response.on('data', function (chunk) {
                data = data + chunk;
            });

            response.on('end', function () {
                console.log('addTrack successful');
                callback(null, JSON.parse(data.toString('utf8')));
            });

        } else {
            console.log('Error while addTrack track : ' + err);
            callback('Error while addTrack track : ' + err);

        }
    });
};

exports.removeTrack = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error removeTrack oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {

        var uri = 'https://api.soundcloud.com/tracks/' + options.id + '?oauth_token=' + options.oauth_token + '&format=json';
        request(uri, {method: 'DELETE',timeout:10000}, function (err, response) {
            if (err || response.body !== undefined && response.body.indexOf(404) !== -1) {
                console.log('Error while removeTrack track: ' + response.body);
                callback('Error while removeTrack track: ' + response.body);
            } else {
                callback(null, {result: response.body});
            }
        });
    }
};

exports.getTracks = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error getTracks oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {
        var uri = 'https://api.soundcloud.com/me/tracks?format=json&oauth_token=' + options.oauth_token;
        request(uri, {timeout:10000}, function (err, response, body) {
            if (!err) {
                console.log('getTracks successful');
                var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) {
                    return track;
                });
                callback(null, tracks);
            } else {
                console.log('Error while getTracks track: ' + err);
                callback('Error while getTracks track: ' + err);

            }
        });
    }
};

exports.searchTrack_q = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error searchTrack_q oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {

        if (options.q === undefined) {
            callback('Error searchTrack_q options.q is required and is: ' + options.q);
            return;
        } else {
            var uri = 'https://api.soundcloud.com/me/tracks?format=json&oauth_token=' + options.oauth_token + '&q=' + options.q;
            request(uri, {timeout:10000}, function (err, response, body) {
                if (!err) {
                    console.log('getTracks successful');
                    callback(null, JSON.parse(body.toString('utf8')));
                } else {
                    console.log('Error while searchTrack_q track: ' + err);
                    callback('Error while searchTrack_q track: ' + err);

                }
            });
        }
    }
};

exports.resolveUri = function (options, callback) {
    if (options.client_id === undefined) {
        callback('Error resolveUri options.client_id is required and is: ' + options.client_id);
        return;
    } else {

        if (options.uri === undefined) {
            callback('Error resolveUri options.uri is required and is: ' + options.uri);
        } else {
//            http://api.soundcloud.com/resolve.json?url=https://soundcloud.com/user46387694/dog_example&client_id=6e110a037f1c9a14b1d3abd1d97f842a
            var uri = 'http://api.soundcloud.com/resolve.json?url=' + options.uri + '&client_id=' + options.client_id;
            request(uri, {timeout:10000}, function (err, response, body) {

//                console.log(response.body);

                if (err !== null || (response.body !== undefined && response.body.indexOf('404') !== -1)) {

//                    console.log(response.body);
                    console.log('Error while resolveUri track: ' + err);
                    callback('Error while resolveUri track: ' + err);

                } else {

                    console.log('resolveUri successful');
                    callback(null, JSON.parse(response.body.toString('utf8')));

                }
            });
        }
    }
};

exports.addTrackToPlaylist = function (options, callback) {
    var form = new FormData();
    form.append('format', 'json');

    console.log(JSON.stringify(options.tracks));

    if (options.tracks === undefined) {
        callback('Error while addTrackToPlaylist options.tracks : ' + options.tracks);
        return;
    } else {
        _.each(trackIds(options.tracks), function (id) {
            console.log(id);
            form.append('playlist[tracks][][id]', id);
        });
    }

    if (options.track.id === undefined) {
        callback('Error while addTrackToPlaylist options.id : ' + options.track.id);
        return;
    } else {
        form.append('playlist[tracks][][id]', options.track.id);
    }

    if (options.title === undefined) {
        callback('Error while addTrackToPlaylist track : ' + options.title);
        return;
    } else {
        form.append('playlist[title]', options.title);
    }

    if (options.sharing === undefined) {
        callback('Error while addTrackToPlaylist track : ' + options.sharing);
        return;
    } else {
        form.append('playlist[sharing]', options.sharing);
    }

    if (options.oauth_token === undefined) {
        callback('Error while addTrackToPlaylist track : ' + options.oauth_token);
        return;
    } else {
        form.append('oauth_token', options.oauth_token);
    }

    var finish = false;
    setTimeout(function(){
        if(finish == false){
            console.log('timeout of 15s kick in');
            finish = true;
            callback('Error timeout addTrackToPlaylist: ');
        }
    },20000);

    console.log(parsedUrl(options));
    form.submit(parsedUrl(options), function (err, response) {
        if (!err) {
            finish = true;

            console.log('reset finish');

            response.on('error', function (err) {
                callback('Error while addTrackToPlaylist track: ' + err);
            });

            var data = "";
            response.on('data', function (chunk) {
                data = data + chunk;
            });

            response.on('end', function () {
                console.log('addPlaylist successful');
                if(data.toString('utf8').indexOf('xml')!==-1){
                    callback(null, data.toString('utf8'));
                }else {
                    callback(null, JSON.parse(data.toString('utf8')));
                }
            });

        } else {
            finish = true;
            console.log('Error while addTrackToPlaylist track: ' + err);
            callback('Error while addTrackToPlaylist track: ' + err);

        }
    });
};

var URL = require('url');
function parsedUrl(playlist) {
    var playListUri = URL.parse(playlist.uri);
    return {
        method: 'put',
        host: playListUri.host,
        path: playListUri.path,
        protocol: playListUri.protocol,
        timeout:10000
    };
}

function trackIds(json) {
    return _.map(json, function (track) {
        return track.id;
    })
}

exports.addTrackToNewPlaylist = function (options, callback) {
    var form = new FormData();
    form.append('format', 'json');

    if (options.tracks === undefined) {
        callback('Error while addTrackToNewPlaylist options.tracks : ' + options.tracks);
        return;
    } else {
        _.each(options.tracks, function (id) {
            form.append('playlist[tracks][][id]', id);
        });
    }
    if (options.title === undefined) {
        callback('Error while addTrackToNewPlaylist options.title : ' + options.title);
        return;
    } else {
        form.append('playlist[title]', options.title);
    }
    if (options.sharing === undefined) {
        callback('Error while addTrackToNewPlaylist options.sharing : ' + options.sharing);
        return;
    } else {
        form.append('playlist[sharing]', options.sharing);
    }
    if (options.oauth_token === undefined) {
        callback('Error while addTrackToNewPlaylist options.oauth_token : ' + options.oauth_token);
        return;
    } else {
        form.append('oauth_token', options.oauth_token);
    }

    form.submit('https://api.soundcloud.com/playlists', function (err, response) {
        if (!err) {

            response.on('error', function (err) {
                callback('Error while addTrackToNewPlaylist track: ' + err);
            });

            var data = "";
            response.on('data', function (chunk) {
                data = data + chunk;
            });

            response.on('end', function () {
                console.log('addPlaylist successful');
                callback(null, JSON.parse(data.toString('utf8')));
            });

        } else {
            console.log('Error while addTrackToNewPlaylist track: ' + err);
            callback('Error while addTrackToNewPlaylist track: ' + err);

        }
    });
};

exports.getPlaylist = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error oauth_token is required and is: ' + options.oauth_token);
        return;
    } else {
        var uri = 'https://api.soundcloud.com/me/playlists?format=json&oauth_token=' + options.oauth_token;
        request(uri, {timeout:10000}, function (err, response, body) {
            if (!err) {
                console.log('getPlaylist successful');
                var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) {
                    return track;
                });
                callback(null, tracks);
            } else {
                console.log('Error while getPlaylist track: ' + err);
                callback('Error while getPlaylist track: ' + err);

            }
        });
    }
};

exports.getPlaylistById = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error getPlaylistById options.oauth_token is required and is: ' + options.oauth_token);
        return;
    } else if (options.id === undefined) {
        callback('Error getPlaylistById options.id is required and is: ' + options.id);
        return;
    } else {
        var uri = 'https://api.soundcloud.com/me/playlists/' + options.id + '?format=json&oauth_token=' + options.oauth_token;
        request(uri, {timeout:10000}, function (err, response, body) {
            if (!err) {
                console.log('getPlaylistById successful');
                var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) {
                    return track;
                });
                callback(null, tracks);
            } else {
                console.log('Error while getPlaylistById track: ' + err);
                callback('Error while getPlaylistById track: ' + err);

            }
        });
    }
};

exports.removePlaylist = function (options, callback) {
    if (options.oauth_token === undefined) {
        callback('Error removePlaylist options.oauth_token is required and is: ' + options.oauth_token);
        return;
    } else if (options.title === undefined) {
        callback('Error removePlaylist options.title is required and is: ' + options.title);
        return;
    } else {
        var uri = 'https://api.soundcloud.com/playlists/' + options.title + '?oauth_token=' + options.oauth_token + '&format=json';
        request(uri, {method: 'DELETE', timeout:10000}, function (err, response) {
            if (err || response.body !== undefined && response.body.indexOf(404) !== -1) {
                console.log('Error while removePlaylist track: ' + response.body);
                callback('Error while removePlaylist track: ' + response.body);
            } else {
                callback(null, {result: response.body});
            }
        });
    }
};

exports.getToken = function (options, callback) {

    var curl_options = {
        'url': 'https://api.soundcloud.com/oauth2/token',
        'method': 'POST',
        verbose: true,
        encoding: 'utf8',
        data: options,
        timeout:10000
    };

    curlrequest.request(curl_options, function (err, data, meta) {
        if(err || !data){
            callback(err, null, meta);
        }else {
            callback(err, JSON.parse(data), meta);
        }
    });
}
<|endoftext|>


<commit_before>// $(document).on("ready", function(){

//   $('#answers-form').on('submit', function(event){
//     event.preventDefault();
//     $.ajax({
//       url: $('#answers-form form').attr("action"),
//       type: "POST",
//       data:  $('#answers-form form').serialize()

//     }).done(function(response) {
//       console.log("Success!")
//       $('.answers-list').append(response);
//     }).fail(function(response) {
//       console.log("FAILURE")
//     });
//   });

// });
<commit_msg>Finish writing js ajax request for posting answer to question<commit_after>$(document).on("ready", function(){

  $('#answers-form form').on('submit', function(event){
    event.preventDefault();
    var valuesToSubmit = $(this).serialize();
    $.ajax({
      url: $('#answers-form form').attr("action"),
      type: "POST",
      data: valuesToSubmit,
    }).done(function(response) {
      console.log("Success!")
      $('.answers-list').append(response);
    }).fail(function(response) {
      console.log("FAILURE")
    });
  });

});
<|endoftext|>


<commit_before>import Plugin from 'dispatcher/plugin';
import Chimee from 'index';

describe("plugin's error", () => {
  let dispatcher;
  let player;
  let error;

  beforeEach(() => {
    player = new Chimee({
      // 播放地址
      src: 'http://cdn.toxicjohann.com/lostStar.mp4',
      // 直播:live 点播：vod
      isLive: false,
      // 编解码容器
      box: 'native',
      // dom容器
      wrapper: 'body',
      plugin: [],
      events: {},
    });

    dispatcher = player.__dispatcher;

    error = new Error('i am an error');
  });

  afterEach(() => {
    player.destroy();
    dispatcher = null;
  });

  test('beforeCreate', () => {
    expect(() => new Plugin({
      id: 'err',
      beforeCreate() {
        throw error;
      },
    }, dispatcher)).toThrow(error.message);
  });

  test('create', () => {
    expect(() => new Plugin({
      id: 'err',
      create() {
        throw error;
      },
    }, dispatcher)).toThrow(error.message);
  });

  test('init', () => {
    const plugin = new Plugin({
      id: 'err',
      init() {
        throw error;
      },
    }, dispatcher);
    expect(() => plugin.__init({})).toThrow(error.message);
  });

  test('inited', () => {
    const plugin = new Plugin({
      id: 'err',
      inited() {
        throw error;
      },
    }, dispatcher);
    expect(() => plugin.__inited({})).toThrow(error.message);
  });

  test('inited with promise', async () => {
    const plugin = new Plugin({
      id: 'err',
      inited() {
        return new Promise(() => { throw error; });
      },
    }, dispatcher);
    let catcherr = false;
    try {
      await plugin.__inited({});
    } catch (err) {
      catcherr = true;
      expect(err).toBe(error);
    }
    expect(catcherr).toBe(true);
  });

  test('inited with reject', async () => {
    const plugin = new Plugin({
      id: 'err',
      inited() {
        return Promise.reject();
      },
    }, dispatcher);
    expect(plugin.__inited({})).rejects.toBe();
  });
});
<commit_msg>test: finish dispatcher/plugin/error unit test recovery<commit_after>import Plugin from 'dispatcher/plugin';
import Chimee from 'index';

describe("plugin's error", () => {
  let dispatcher;
  let player;
  let error;

  beforeEach(() => {
    player = new Chimee({
      // 播放地址
      src: 'http://cdn.toxicjohann.com/lostStar.mp4',
      // 直播:live 点播：vod
      isLive: false,
      // 编解码容器
      box: 'native',
      // dom容器
      wrapper: document.createElement('div'),
      plugin: [],
      events: {},
    });

    dispatcher = player.dispatcher;

    error = new Error('i am an error');
  });

  afterEach(() => {
    player.destroy();
    dispatcher = null;
  });

  test('beforeCreate', () => {
    expect(() => new Plugin({
      id: 'err',
      beforeCreate() {
        throw error;
      },
    }, dispatcher)).toThrow(error.message);
  });

  test('create', () => {
    expect(() => new Plugin({
      id: 'err',
      create() {
        throw error;
      },
    }, dispatcher)).toThrow(error.message);
  });

  test('init', () => {
    const plugin = new Plugin({
      id: 'err',
      init() {
        throw error;
      },
    }, dispatcher);
    expect(() => plugin.runInitHook({})).toThrow(error.message);
  });

  test('inited', () => {
    const plugin = new Plugin({
      id: 'err',
      inited() {
        throw error;
      },
    }, dispatcher);
    expect(() => plugin.runInitedHook({})).toThrow(error.message);
  });

  test('inited with promise', async () => {
    const plugin = new Plugin({
      id: 'err',
      inited() {
        return new Promise(() => { throw error; });
      },
    }, dispatcher);
    let catcherr = false;
    try {
      await plugin.runInitedHook({});
    } catch (err) {
      catcherr = true;
      expect(err).toBe(error);
    }
    expect(catcherr).toBe(true);
  });

  test('inited with reject', async () => {
    const plugin = new Plugin({
      id: 'err',
      inited() {
        return Promise.reject();
      },
    }, dispatcher);
    expect(plugin.runInitedHook({})).rejects.toBe();
  });
});
<|endoftext|>


<commit_before>import React from "react-native";

const {
	Animated,
	View,
	DeviceEventEmitter
} = React;

export default class KeyboardSpacer extends React.Component {
	constructor(props) {
		super(props);

		this.state = {
			keyboardHeightAnim: new Animated.Value(0)
		};
	}

	componentWillMount() {
		this._keyboardDidShowSubscription = DeviceEventEmitter.addListener("keyboardDidShow", e => this._keyboardDidShow(e));
		this._keyboardDidHideSubscription = DeviceEventEmitter.addListener("keyboardDidHide", e => this._keyboardDidHide(e));
	}

	componentWillUnmount() {
		this._keyboardDidShowSubscription.remove();
		this._keyboardDidHideSubscription.remove();
	}

	_keyboardDidShow(e) {
		Animated.spring(this.state.keyboardHeightAnim, {
			toValue: e.endCoordinates.height
		}).start();
	}

	_keyboardDidHide() {
		Animated.spring(this.state.keyboardHeightAnim, {
			toValue: 0
		}).start();
	}

	render() {
		return <Animated.View style={{ height: this.state.keyboardHeightAnim }} />;
	}
}
<commit_msg>Ignore Keyboard events below Kitkat<commit_after>import React from "react-native";
import DeviceVersion from "../../modules/device-version";

const {
	Platform,
	Animated,
	View,
	DeviceEventEmitter
} = React;

export default class KeyboardSpacer extends React.Component {
	constructor(props) {
		super(props);

		this.state = {
			ignoreKeboard: Platform.OS === "android" && DeviceVersion.VERSION_SDK_INT < DeviceVersion.VERSION_CODES_KITKAT,
			keyboardHeightAnim: new Animated.Value(0)
		};
	}

	componentWillMount() {
		if (this.state.ignoreKeboard) {
			return;
		}

		this._keyboardDidShowSubscription = DeviceEventEmitter.addListener("keyboardDidShow", e => this._keyboardDidShow(e));
		this._keyboardDidHideSubscription = DeviceEventEmitter.addListener("keyboardDidHide", e => this._keyboardDidHide(e));
	}

	componentWillUnmount() {
		if (this.state.ignoreKeboard) {
			return;
		}

		this._keyboardDidShowSubscription.remove();
		this._keyboardDidHideSubscription.remove();
	}

	_keyboardDidShow(e) {
		Animated.spring(this.state.keyboardHeightAnim, {
			toValue: e.endCoordinates.height
		}).start();
	}

	_keyboardDidHide() {
		Animated.spring(this.state.keyboardHeightAnim, {
			toValue: 0
		}).start();
	}

	render() {
		if (this.state.ignoreKeboard) {
			return null;
		}

		return <Animated.View style={{ height: this.state.keyboardHeightAnim }} />;
	}
}
<|endoftext|>


<commit_before>// Copyright 2017-2021, University of Colorado Boulder

/**
 * Utilities for creating and manipulating the unique identifiers assigned to instrumented PhET-iO instances, aka
 * phetioIDs.
 *
 * Many of these functions' jsdoc is rendered and visible publicly to PhET-iO client. Those sections should be
 * marked, see top level comment in Client.js about private vs public documentation
 *
 * @author Chris Malley (PixelZoom, Inc.)
 * @author Sam Reid (PhET Interactive Simulations)
 */
( function() {

  // define the phetio global
  window.phetio = window.phetio || {};

  // constants
  const SEPARATOR = '.';
  const GROUP_SEPARATOR = '_';
  const GENERAL_COMPONENT_NAME = 'general';
  const GLOBAL_COMPONENT_NAME = 'global';
  const HOME_SCREEN_COMPONENT_NAME = 'homeScreen';
  const MODEL_COMPONENT_NAME = 'model';
  const VIEW_COMPONENT_NAME = 'view';
  const COLORS_COMPONENT_NAME = 'colors';
  const CONTROLLER_COMPONENT_NAME = 'controller';

  /**
   * Helpful methods for manipulating phetioIDs. Used to minimize the amount of duplicated logic specific to the string
   * structure of the phetioID. Available in the main PhET-iO js import.
   * @namespace
   */
  window.phetio.PhetioIDUtils = {

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Appends a component to an existing phetioID to create a new unique phetioID for the component.
     * @example
     * append( 'myScreen.myControlPanel', 'myComboBox' )
     * -->  'myScreen.myControlPanel.myComboBox'
     * @public
     * @param {string} phetioID - the ID of the PhET-iO element
     * @param {string|string[]} componentNames - the name or list of names to append to the ID
     * @returns {string} - the appended phetioID
     */
    append: function( phetioID, ...componentNames ) {
      componentNames.forEach( componentName => {
        assert && assert( componentName.indexOf( SEPARATOR ) === -1, `separator appears in componentName: ${componentName}` );
        phetioID += SEPARATOR + componentName;
      } );
      return phetioID;
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Given a phetioID for a PhET-iO element, get the part of that ID that pertains to the component (basically the
     * tail piece).
     * @example
     * getComponentName( 'myScreen.myControlPanel.myComboBox' )
     * -->  'myComboBox'
     * @public
     * @param {string} phetioID - the ID of the PhET-iO element
     * @returns {string} - the component name
     */
    getComponentName: function( phetioID ) {
      assert && assert( phetioID.length > 0 );
      const indexOfLastSeparator = phetioID.lastIndexOf( SEPARATOR );
      if ( indexOfLastSeparator === -1 ) {
        return phetioID;
      }
      else {
        return phetioID.substring( indexOfLastSeparator + 1, phetioID.length );
      }
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Given a phetioID for a PhET-iO element, get the phetioID of the parent component.
     * @example
     * getParentID( 'myScreen.myControlPanel.myComboBox' )
     * -->  'myScreen.myControlPanel'
     * @public
     * @param {string} phetioID - the ID of the PhET-iO element
     * @returns {string|null} - the phetioID of the parent, or null if there is no parent
     */
    getParentID: function( phetioID ) {
      const indexOfLastSeparator = phetioID.lastIndexOf( SEPARATOR );
      return indexOfLastSeparator === -1 ? null : phetioID.substring( 0, indexOfLastSeparator );
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Given a phetioID for a instrumented object, get a string that can be used to assign an ID to a DOM element
     * @param {string} phetioID - the ID of the PhET-iO element
     * @returns {string}
     * @public
     */
    getDOMElementID: function( phetioID ) {
      return `phetioID:${phetioID}`;
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Get the screen id from the phetioID.
     * @example
     * getScreenID( 'sim.myScreen.model.property' )
     * --> sim.myScreen
     * getScreenID( 'sim.myScreen' )
     * --> sim.myScreen
     * getScreenID( 'sim.general.activeProperty' )
     * --> null
     * @param {string} phetioID
     * @returns {string|null} - null if there is no screen component name in the phetioID
     */
    getScreenID: function( phetioID ) {
      const screenIDParts = [];
      const phetioIDParts = phetioID.split( SEPARATOR );
      for ( let i = 0; i < phetioIDParts.length; i++ ) {
        const componentPart = phetioIDParts[ i ];
        screenIDParts.push( componentPart );
        const screenMarker = 'Screen';
        const indexOfScreenMarker = componentPart.indexOf( screenMarker );
        if ( indexOfScreenMarker > 0 && indexOfScreenMarker + screenMarker.length === componentPart.length ) { // endsWith proxy
          return screenIDParts.join( SEPARATOR );
        }
      }
      return null;
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Get the index number from the component name of the component name provided.
     * @param {string} componentName
     * @returns {number}
     * @example
     * getGroupElementIndex( 'particle_1' )
     * --> 1
     * @public
     */
    getGroupElementIndex: function( componentName ) {
      assert && assert( componentName.indexOf( window.phetio.PhetioIDUtils.GROUP_SEPARATOR ) >= 0,
        'component name for phetioID should have group element syntax' );
      return parseInt( componentName.split( window.phetio.PhetioIDUtils.GROUP_SEPARATOR )[ 1 ], 10 );
    },

    /**
     * Returns true if the potential ancestor is indeed an ancestor of the potential descendant, but not the same phetioID
     * @param {string} potentialAncestorPhetioID
     * @param {string} potentialDescendantPhetioID
     * @returns {boolean}
     * @public
     */
    isAncestor: function( potentialAncestorPhetioID, potentialDescendantPhetioID ) {
      const ancestorComponents = potentialAncestorPhetioID.split( SEPARATOR );
      const descendantComponents = potentialDescendantPhetioID.split( SEPARATOR );
      for ( let i = 0; i < ancestorComponents.length; i++ ) {
        if ( ancestorComponents[ i ] !== descendantComponents[ i ] ) {
          return false;
        }
      }

      // not the same child
      return potentialDescendantPhetioID !== potentialAncestorPhetioID;
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The separator used to piece together a phet-io ID.
     * @type {string}
     * @constant
     * @public
     */
    SEPARATOR: SEPARATOR,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The separator used to specify the count of a element in a group.
     * @type {string}
     * @constant
     * @public
     */
    GROUP_SEPARATOR: GROUP_SEPARATOR,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for the id section that holds phet-io elements general to all simulations.
     * @type {string}
     * @constant
     * @public
     */
    GENERAL_COMPONENT_NAME: GENERAL_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for the id section that holds simulation specific elements that don't belong in a screen.
     * @type {string}
     * @constant
     * @public
     */
    GLOBAL_COMPONENT_NAME: GLOBAL_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for the id section that holds the home screen.
     * @type {string}
     * @constant
     * @public
     */
    HOME_SCREEN_COMPONENT_NAME: HOME_SCREEN_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for an id section that holds model specific elements.
     * @type {string}
     * @constant
     * @public
     */
    MODEL_COMPONENT_NAME: MODEL_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for an id section that holds view specific elements.
     * @type {string}
     * @constant
     * @public
     */
    VIEW_COMPONENT_NAME: VIEW_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for an id section that holds controller specific elements.
     * @type {string}
     * @constant
     * @public
     */
    CONTROLLER_COMPONENT_NAME: CONTROLLER_COMPONENT_NAME,

    /**
     * The component name for a section that holds colors
     * @type {string}
     * @constant
     * @public
     */
    COLORS_COMPONENT_NAME: COLORS_COMPONENT_NAME
  };
} )();<commit_msg>Switch to Number(), see: https://github.com/phetsims/perennial/issues/275<commit_after>// Copyright 2017-2021, University of Colorado Boulder

/**
 * Utilities for creating and manipulating the unique identifiers assigned to instrumented PhET-iO instances, aka
 * phetioIDs.
 *
 * Many of these functions' jsdoc is rendered and visible publicly to PhET-iO client. Those sections should be
 * marked, see top level comment in Client.js about private vs public documentation
 *
 * @author Chris Malley (PixelZoom, Inc.)
 * @author Sam Reid (PhET Interactive Simulations)
 */
( function() {

  // define the phetio global
  window.phetio = window.phetio || {};

  // constants
  const SEPARATOR = '.';
  const GROUP_SEPARATOR = '_';
  const GENERAL_COMPONENT_NAME = 'general';
  const GLOBAL_COMPONENT_NAME = 'global';
  const HOME_SCREEN_COMPONENT_NAME = 'homeScreen';
  const MODEL_COMPONENT_NAME = 'model';
  const VIEW_COMPONENT_NAME = 'view';
  const COLORS_COMPONENT_NAME = 'colors';
  const CONTROLLER_COMPONENT_NAME = 'controller';

  /**
   * Helpful methods for manipulating phetioIDs. Used to minimize the amount of duplicated logic specific to the string
   * structure of the phetioID. Available in the main PhET-iO js import.
   * @namespace
   */
  window.phetio.PhetioIDUtils = {

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Appends a component to an existing phetioID to create a new unique phetioID for the component.
     * @example
     * append( 'myScreen.myControlPanel', 'myComboBox' )
     * -->  'myScreen.myControlPanel.myComboBox'
     * @public
     * @param {string} phetioID - the ID of the PhET-iO element
     * @param {string|string[]} componentNames - the name or list of names to append to the ID
     * @returns {string} - the appended phetioID
     */
    append: function( phetioID, ...componentNames ) {
      componentNames.forEach( componentName => {
        assert && assert( componentName.indexOf( SEPARATOR ) === -1, `separator appears in componentName: ${componentName}` );
        phetioID += SEPARATOR + componentName;
      } );
      return phetioID;
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Given a phetioID for a PhET-iO element, get the part of that ID that pertains to the component (basically the
     * tail piece).
     * @example
     * getComponentName( 'myScreen.myControlPanel.myComboBox' )
     * -->  'myComboBox'
     * @public
     * @param {string} phetioID - the ID of the PhET-iO element
     * @returns {string} - the component name
     */
    getComponentName: function( phetioID ) {
      assert && assert( phetioID.length > 0 );
      const indexOfLastSeparator = phetioID.lastIndexOf( SEPARATOR );
      if ( indexOfLastSeparator === -1 ) {
        return phetioID;
      }
      else {
        return phetioID.substring( indexOfLastSeparator + 1, phetioID.length );
      }
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Given a phetioID for a PhET-iO element, get the phetioID of the parent component.
     * @example
     * getParentID( 'myScreen.myControlPanel.myComboBox' )
     * -->  'myScreen.myControlPanel'
     * @public
     * @param {string} phetioID - the ID of the PhET-iO element
     * @returns {string|null} - the phetioID of the parent, or null if there is no parent
     */
    getParentID: function( phetioID ) {
      const indexOfLastSeparator = phetioID.lastIndexOf( SEPARATOR );
      return indexOfLastSeparator === -1 ? null : phetioID.substring( 0, indexOfLastSeparator );
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Given a phetioID for a instrumented object, get a string that can be used to assign an ID to a DOM element
     * @param {string} phetioID - the ID of the PhET-iO element
     * @returns {string}
     * @public
     */
    getDOMElementID: function( phetioID ) {
      return `phetioID:${phetioID}`;
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Get the screen id from the phetioID.
     * @example
     * getScreenID( 'sim.myScreen.model.property' )
     * --> sim.myScreen
     * getScreenID( 'sim.myScreen' )
     * --> sim.myScreen
     * getScreenID( 'sim.general.activeProperty' )
     * --> null
     * @param {string} phetioID
     * @returns {string|null} - null if there is no screen component name in the phetioID
     */
    getScreenID: function( phetioID ) {
      const screenIDParts = [];
      const phetioIDParts = phetioID.split( SEPARATOR );
      for ( let i = 0; i < phetioIDParts.length; i++ ) {
        const componentPart = phetioIDParts[ i ];
        screenIDParts.push( componentPart );
        const screenMarker = 'Screen';
        const indexOfScreenMarker = componentPart.indexOf( screenMarker );
        if ( indexOfScreenMarker > 0 && indexOfScreenMarker + screenMarker.length === componentPart.length ) { // endsWith proxy
          return screenIDParts.join( SEPARATOR );
        }
      }
      return null;
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * Get the index number from the component name of the component name provided.
     * @param {string} componentName
     * @returns {number}
     * @example
     * getGroupElementIndex( 'particle_1' )
     * --> 1
     * @public
     */
    getGroupElementIndex: function( componentName ) {
      assert && assert( componentName.indexOf( window.phetio.PhetioIDUtils.GROUP_SEPARATOR ) >= 0,
        'component name for phetioID should have group element syntax' );
      return Number( componentName.split( window.phetio.PhetioIDUtils.GROUP_SEPARATOR )[ 1 ] );
    },

    /**
     * Returns true if the potential ancestor is indeed an ancestor of the potential descendant, but not the same phetioID
     * @param {string} potentialAncestorPhetioID
     * @param {string} potentialDescendantPhetioID
     * @returns {boolean}
     * @public
     */
    isAncestor: function( potentialAncestorPhetioID, potentialDescendantPhetioID ) {
      const ancestorComponents = potentialAncestorPhetioID.split( SEPARATOR );
      const descendantComponents = potentialDescendantPhetioID.split( SEPARATOR );
      for ( let i = 0; i < ancestorComponents.length; i++ ) {
        if ( ancestorComponents[ i ] !== descendantComponents[ i ] ) {
          return false;
        }
      }

      // not the same child
      return potentialDescendantPhetioID !== potentialAncestorPhetioID;
    },

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The separator used to piece together a phet-io ID.
     * @type {string}
     * @constant
     * @public
     */
    SEPARATOR: SEPARATOR,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The separator used to specify the count of a element in a group.
     * @type {string}
     * @constant
     * @public
     */
    GROUP_SEPARATOR: GROUP_SEPARATOR,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for the id section that holds phet-io elements general to all simulations.
     * @type {string}
     * @constant
     * @public
     */
    GENERAL_COMPONENT_NAME: GENERAL_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for the id section that holds simulation specific elements that don't belong in a screen.
     * @type {string}
     * @constant
     * @public
     */
    GLOBAL_COMPONENT_NAME: GLOBAL_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for the id section that holds the home screen.
     * @type {string}
     * @constant
     * @public
     */
    HOME_SCREEN_COMPONENT_NAME: HOME_SCREEN_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for an id section that holds model specific elements.
     * @type {string}
     * @constant
     * @public
     */
    MODEL_COMPONENT_NAME: MODEL_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for an id section that holds view specific elements.
     * @type {string}
     * @constant
     * @public
     */
    VIEW_COMPONENT_NAME: VIEW_COMPONENT_NAME,

    // Private Doc: The below jsdoc is public to the PhET-iO API documentation. Change wisely.
    /**
     * The component name for an id section that holds controller specific elements.
     * @type {string}
     * @constant
     * @public
     */
    CONTROLLER_COMPONENT_NAME: CONTROLLER_COMPONENT_NAME,

    /**
     * The component name for a section that holds colors
     * @type {string}
     * @constant
     * @public
     */
    COLORS_COMPONENT_NAME: COLORS_COMPONENT_NAME
  };
} )();<|endoftext|>


<commit_before>// common dependencies
var fs = require('fs');
var url = require('url');
var colors = require('colors');
var debug = require('debug')('express-passport-app:setup');
var util = require('util')

// express dependencies
var morgan = require('morgan');
var compress = require('compression');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var flash = require('express-flash');

// configure express
module.exports.configureExpress = function(options, app, config) {
    // set view engine and parsers
    app.set('views', options.dir + '/views');
    app.set('view engine', 'html');
    app.engine('.html', options.handlebars.__express);
    app.set('json spaces', 2);

    // express common config
    app.use(compress());
    app.use(options.express.static(options.dir + '/client/public'));
    app.use(morgan('dev'));
    app.use(options.cookieParser());
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());
    app.use(methodOverride());
    app.use(options.session({
        secret: config.get('server.secret'),
        store: options.store,
        name: config.get('session.key'),
        resave: true,
        saveUninitialized: true
    }));
    app.use(options.passport.initialize());
    app.use(options.passport.session());
    app.use(flash());
    app.use(favicon(options.dir + '/client/public/favicon.ico'));

    // express dev config
    if ('development' == config.get('env')) {
        app.use(errorHandler());
    }
};

// handle express errors
module.exports.handleExpressError = function(app) {
    // handle 404 not found
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404', {
                url: req.url
            });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({
                error: 'Not found'
            });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // handling other errors
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        res.status(500).send('Something broke!');
    });
};

// register handlebars partials
module.exports.registerPartials = function(path, handlebars) {
    var partials = path;
    fs.readdirSync(partials).forEach(function(folder) {
        var extension = folder.split('.')[1];
        if (extension != undefined) return;
        fs.readdirSync(partials + folder).forEach(function(file) {
            var extension = file.split('.')[1];
            if (extension != 'html') return;
            var source = fs.readFileSync(partials + folder + '/' + file, "utf8");
            var partial = folder + '-' + file.split('.')[0];
            handlebars.registerPartial(partial, source);
        });
    });
};

// register handlebars block helpers
module.exports.registerHelpers = function(helpers, handlebars) {
    for (var helper in helpers) {
        if (helpers.hasOwnProperty(helper)) {
            handlebars.registerHelper(helper, helpers[helper]);
        }
    }
    return;
};

// create session store
module.exports.sessions = function (SessionStore, session, config) {
    var authObject;

    if (config.get('env') == 'production') {
        var parsedUrl = url.parse(config.get('database.redis.url'));
        authObject = {
            prefix: config.get('database.redis.prefix'),
            host: parsedUrl.hostname,
            port: parsedUrl.port,
            db: config.get('database.redis.db'),
            pass: parsedUrl.auth ? parsedUrl.auth.split(":")[1] : null,
            secret: config.get('server.secret')
        };

        return new SessionStore(authObject);
    } else {
        return (new session.MemoryStore());
    }
};

// connect to backend store (db)
module.exports.db = function(mongoose, config) {
    function connect() {
        mongoose.connect(config.get('database.mongo.url'));
    }

    // connection is open and ready
    mongoose.connection.on('open', function(ref) {
        debug('open connection to mongo server.');
    });

    // mongoose is connected to server
    mongoose.connection.on('connected', function(ref) {
        debug('connected to mongo server.');
    });

    // mongoose has disconnected
    mongoose.connection.on('disconnected', function(ref) {
        debug('disconnected from mongo server.');

        debug('retrying connection in 2 seconds..');
        setTimeout(function() {
            connect();
        }.bind(this), 2000);
    });

    // mongoose connection has closed
    mongoose.connection.on('close', function(ref) {
        debug('closed connection to mongo server');
    });

    // error has occured for mongoose connection
    mongoose.connection.on('error', function(err) {
        debug('error connection to mongo server!');
        debug(err);
    });

    // mongoose is reconnecting
    mongoose.connection.on('reconnect', function(ref) {
        debug('reconnect to mongo server.');
    });

    // initial connect
    connect();
};

// run application
module.exports.run = function(server, config) {
    server.listen(config.get('server.port'), function() {
        debug('listening on port %d'.green, server.address().port);
    });
};
<commit_msg>add session store error handling<commit_after>// common dependencies
var fs = require('fs');
var url = require('url');
var colors = require('colors');
var debug = require('debug')('express-passport-app:setup');
var util = require('util')

// express dependencies
var morgan = require('morgan');
var compress = require('compression');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var flash = require('express-flash');

// configure express
module.exports.configureExpress = function(options, app, config) {
    // set view engine and parsers
    app.set('views', options.dir + '/views');
    app.set('view engine', 'html');
    app.engine('.html', options.handlebars.__express);
    app.set('json spaces', 2);

    // express common config
    app.use(compress());
    app.use(options.express.static(options.dir + '/client/public'));
    app.use(morgan('dev'));
    app.use(options.cookieParser());
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());
    app.use(methodOverride());
    app.use(options.session({
        secret: config.get('server.secret'),
        store: options.store,
        name: config.get('session.key'),
        resave: true,
        saveUninitialized: true
    }));
    app.use(options.passport.initialize());
    app.use(options.passport.session());
    app.use(flash());
    app.use(favicon(options.dir + '/client/public/favicon.ico'));

    // handle when session store disconnects
    app.use(function(req, res, next) {
        if (!req.session) {
            return next(new Error('session store not available')) // handle error
        }
        next();
    });

    // express dev config
    if ('development' == config.get('env')) {
        app.use(errorHandler());
    }
};

// handle express errors
module.exports.handleExpressError = function(app) {
    // handle 404 not found
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404', {
                url: req.url
            });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({
                error: 'Not found'
            });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // handling other errors
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        res.status(500).send('Something broke!');
    });
};

// register handlebars partials
module.exports.registerPartials = function(path, handlebars) {
    var partials = path;
    fs.readdirSync(partials).forEach(function(folder) {
        var extension = folder.split('.')[1];
        if (extension != undefined) return;
        fs.readdirSync(partials + folder).forEach(function(file) {
            var extension = file.split('.')[1];
            if (extension != 'html') return;
            var source = fs.readFileSync(partials + folder + '/' + file, "utf8");
            var partial = folder + '-' + file.split('.')[0];
            handlebars.registerPartial(partial, source);
        });
    });
};

// register handlebars block helpers
module.exports.registerHelpers = function(helpers, handlebars) {
    for (var helper in helpers) {
        if (helpers.hasOwnProperty(helper)) {
            handlebars.registerHelper(helper, helpers[helper]);
        }
    }
    return;
};

// create session store
module.exports.sessions = function (SessionStore, session, config) {
    var authObject;

    if (config.get('env') == 'production') {
        var parsedUrl = url.parse(config.get('database.redis.url'));
        authObject = {
            prefix: config.get('database.redis.prefix'),
            host: parsedUrl.hostname,
            port: parsedUrl.port,
            db: config.get('database.redis.db'),
            pass: parsedUrl.auth ? parsedUrl.auth.split(":")[1] : null,
            secret: config.get('server.secret')
        };

        return new SessionStore(authObject);
    } else {
        return (new session.MemoryStore());
    }
};

// connect to backend store (db)
module.exports.db = function(mongoose, config) {
    function connect() {
        mongoose.connect(config.get('database.mongo.url'));
    }

    // connection is open and ready
    mongoose.connection.on('open', function(ref) {
        debug('open connection to mongo server.');
    });

    // mongoose is connected to server
    mongoose.connection.on('connected', function(ref) {
        debug('connected to mongo server.');
    });

    // mongoose has disconnected
    mongoose.connection.on('disconnected', function(ref) {
        debug('disconnected from mongo server.');

        debug('retrying connection in 2 seconds..');
        setTimeout(function() {
            connect();
        }.bind(this), 2000);
    });

    // mongoose connection has closed
    mongoose.connection.on('close', function(ref) {
        debug('closed connection to mongo server');
    });

    // error has occured for mongoose connection
    mongoose.connection.on('error', function(err) {
        debug('error connection to mongo server!');
        debug(err);
    });

    // mongoose is reconnecting
    mongoose.connection.on('reconnect', function(ref) {
        debug('reconnect to mongo server.');
    });

    // initial connect
    connect();
};

// run application
module.exports.run = function(server, config) {
    server.listen(config.get('server.port'), function() {
        debug('listening on port %d'.green, server.address().port);
    });
};
<|endoftext|>


<commit_before>var ActionButton = function (options) {
    this.backgroundSprite = game.add.sprite(options.x, options.y, options.background);
    this.dragSprite = game.add.sprite(options.x, options.y, options.background);
    this.isDragging = false;
    this.isSlowDown = options.isSlowDown;
    this.isSpeedUp = options.isSpeedUp;
    this.handleDropStop = options.handleDropStop;
};

ActionButton.prototype = {
    init: function () {
        this.dragSprite.inputEnabled = true;
        this.dragSprite.input.enableDrag({
            lockCenter: true
        });
        this.dragSprite.events.onDragStart.add(this.onDragStart, this);
        this.dragSprite.events.onDragStop.add(this.onDragStop, this);
        return this;
    },
    resetSpritePosition: function () {
        this.dragSprite.x = this.backgroundSprite.x;
        this.dragSprite.y = this.backgroundSprite.y;
    },
    onDragStart: function () {
        this.isDragging = true;
        this.dragSprite.scale.setTo(0.5, 0.5);
        this.dragSprite.anchor.setTo(-0.5);
        this.dragSprite.alpha = 0.2;
        console.log('dragStart');
    },
    onDragStop: function () {
        console.log('dragStop', this);
        this.dragSprite.scale.setTo(1, 1);
        this.dragSprite.anchor.setTo(0);
        this.handleDropStop();
        this.dragSprite.alpha = 1;
        this.isDragging = false;
        this.resetSpritePosition();
    },
    disable: function () {
        this.backgroundSprite.alpha = 0.25;
        this.dragSprite.destroy();
    }
};
<commit_msg>hide cursor while placing powerUps<commit_after>var ActionButton = function (options) {
    this.backgroundSprite = game.add.sprite(options.x, options.y, options.background);
    this.dragSprite = game.add.sprite(options.x, options.y, options.background);
    this.isDragging = false;
    this.isSlowDown = options.isSlowDown;
    this.isSpeedUp = options.isSpeedUp;
    this.handleDropStop = options.handleDropStop;
};

ActionButton.prototype = {
    init: function () {
        this.dragSprite.inputEnabled = true;
        this.dragSprite.input.enableDrag({
            lockCenter: true
        });
        this.dragSprite.events.onDragStart.add(this.onDragStart, this);
        this.dragSprite.events.onDragStop.add(this.onDragStop, this);
        return this;
    },
    resetSpritePosition: function () {
        this.dragSprite.x = this.backgroundSprite.x;
        this.dragSprite.y = this.backgroundSprite.y;
    },
    onDragStart: function () {
        this.isDragging = true;
        this.dragSprite.scale.setTo(0.5, 0.5);
        this.dragSprite.anchor.setTo(-0.5);
        this.dragSprite.alpha = 0.2;
        game.canvas.style.cursor = "none";
        console.log('dragStart');
    },
    onDragStop: function () {
        console.log('dragStop', this);
        this.dragSprite.scale.setTo(1, 1);
        this.dragSprite.anchor.setTo(0);
        this.handleDropStop();
        this.dragSprite.alpha = 1;
        this.isDragging = false;
        game.canvas.style.cursor = "default";
        this.resetSpritePosition();
    },
    disable: function () {
        this.backgroundSprite.alpha = 0.25;
        this.dragSprite.destroy();
    }
};
<|endoftext|>


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

/** JavaScript object module with data structure definitions **/

function LeftClass (att1, att2, name, duration) {
  this.att1 = att1;
  this.att2 = att2;
  this.name = name;
  this.duration = duration;
  this.drawIntoTable = function(startingRow) {
    return att1 + ' ' + att2 + ' ' + name + ' ' + duration;
  }
};

function RightClass (att1, att2, name, duration) {
  this.att1 = att1;
  this.att2 = att2;
  this.name = name;
  this.duration = duration;
  this.drawIntoTable = function(startingRow) {
    return att1 + att2 + name + duration;
  }
};

var leftObj1 = new LeftClass("Aqua", "left", "leftObj1", 5);
var leftObj2 = new LeftClass("Aqua", "left", "leftObj2", 10);
var leftObj3 = new LeftClass("Aqua", "left", "leftObj3", 15);

var rightObj1 = new RightClass("Aqua", "left", "rightObj1", 5);
var rightObj2 = new RightClass("Aqua", "left", "rightObj2", 10);
var rightObj3 = new RightClass("Aqua", "left", "rightObj3", 5);

var containerObj = {
  arrayLeft: [leftObj1, leftObj2, leftObj3,],
  arrayRigh: [rightObj1, rightObj2, rightObj3],
  populateTable: function(tableId) {
    console.log(this.arrayLeft[0].drawIntoTable())
  }
};

var leftCaption = "Objects of class LeftClass";
var rightCaption = "Objects of class RightClass";

var table_style = {
  width: "50%",
  border: 0,
  cellspacing: 0,
  cellpadding:0
};

var td_style_center = { textAlign: "center" };
var td_style_aqua = { backgroundColor: "aqua" };
var td_style_aqua_left = { backgroundColor: "aqua", textAlign: "left" };
var td_style_aqua_right = { backgroundColor: "aqua", textAlign: "right" };
var td_style_yellow = { backgroundColor: "yellow", textAlign: "center"};
var td_style_pink = { backgroundColor: "pink" };
var td_style_pink_center = {backgroundColor: "pink", textAlign: "center"};
var td_style_pink_right = {backgroundColor: "pink", textAlign: "right"};

var Table = React.createClass({
  getInitialState: function() {
    return {data: this.props.data};
  },

  render: function () {
    return (

          {leftCaption}

          {rightCaption}

           lefty1:

          lefty1.att2:
          08:20
          righty1.att1

          (button to insert a left/right pair)
          15 mins
           righty1

          lefty2.att1:
          08:35
          righty1.att2

    );
  }
});

React.renderComponent(
  Table(),
  document.getElementById('fancy_table')
);
<commit_msg>Remove unnecessary after restructure<commit_after><|endoftext|>