<commit_before>/*
 *  AAAP Version 1.0
 *  (c) 2010 Tomas Kirda
 *  (c) 2011 Andrew Newman
 *
 *  Web site: https://github.com/newmana/AAAP
 *
 * AAAP is freely distributable under the terms of an MIT-style license.
 * Original code Ajax AutoComplete for Prototype: http://www.devbridge.com/projects/autocomplete/
 */

var Autocomplete = function (el, options) {
    this.el = $(el);
    this.id = this.el.identify();
    this.el.setAttribute('autocomplete', 'off');
    this.badQueries = [];
    this.intervalId = 0;
    this.cachedResponse = [];
    this.instanceId = null;
    this.onChangeInterval = null;
    this.ignoreValueChange = false;
    this.serviceUrl = options.serviceUrl;
    this.parameters = options.parameters;
    this.currentValue = this.el.value;
    this.list = new AutocompleteList();
    this.options = {
        autoSubmit : false,
        minChars : 1,
        maxHeight : 300,
        deferRequestBy : 0,
        width : 0,
        container : null,
        autoHide : true
    };
    if (options) {
        Object.extend(this.options, options);
    }
    if (Autocomplete.isDomLoaded) {
        this.initialize();
    } else {
        Event.observe(document, 'dom:loaded', this.initialize.bind(this), false);
    }
};

Autocomplete.instances = [];
Autocomplete.isDomLoaded = false;

Autocomplete.getInstance = function (id) {
    var instances = Autocomplete.instances;
    var i = instances.length;
    while (i--) {
        if (instances[i].id === id) {
            return instances[i];
        }
    }
};

Autocomplete.highlight = function (value, re) {
    return value.replace(re, function (match) {
        return '' + match + '<\/strong>'
    });
};

Autocomplete.prototype = {

    killerFn : null,

    initialize : function () {
        var me = this;
        this.killerFn = function (e) {
            var element = $(Event.element(e));
            if (element && element.up !== undefined && !element.up('.autocomplete')) {
                me.killSuggestions();
                me.disableKillerFn();
            }
        }.bindAsEventListener(this);

        if (!this.options.width) {
            this.options.width = this.el.getWidth();
        }

        var div = new Element('div', { style : 'position:absolute;' });
        div.update('

');

        this.options.container = $(this.options.container);
        if (this.options.container) {
            this.options.container.appendChild(div);
            this.fixPosition = function () {
            };
        } else {
            document.body.appendChild(div);
        }

        this.mainContainerId = div.identify();
        this.container = $('Autocomplete_' + this.id);
        this.fixPosition();

        Event.observe(this.el, window.opera ? 'keypress' : 'keydown', this.onKeyPress.bind(this));
        Event.observe(this.el, 'keyup', this.onKeyUp.bind(this));
        Event.observe(this.el, 'blur', this.enableKillerFn.bind(this));
        Event.observe(this.el, 'focus', this.fixPosition.bind(this));
        Event.observe(this.el, 'select', this.textSelected.bind(this));
        if (this.options.maxHeight !== -1) {
            this.container.setStyle({ maxHeight : this.options.maxHeight + 'px' });
        }
        this.instanceId = Autocomplete.instances.push(this) - 1;
        if (!this.options.autoHide) {
            this.container.show();
        }
    },

    textSelected : function () {
        this.selectedNow = true;
        this.onValueChange();
    },

    fixPosition : function () {
        var offset = this.el.cumulativeOffset();
        $(this.mainContainerId).setStyle({ top : (offset.top + this.el.getHeight()) + 'px', left : offset.left + 'px' });
    },

    enableKillerFn : function () {
        Event.observe(document.body, 'click', this.killerFn);
    },

    disableKillerFn : function () {
        Event.stopObserving(document.body, 'click', this.killerFn);
    },

    killSuggestions : function () {
        this.stopKillSuggestions();
        this.intervalId = window.setInterval(function () {
            this.hide();
            this.stopKillSuggestions();
        }.bind(this), 300);
    },

    stopKillSuggestions : function () {
        window.clearInterval(this.intervalId);
    },

    onKeyPress : function (e) {
        switch (e.keyCode) {
            case Event.KEY_DELETE:
                if (this.selectedNow) {
                    this.hide();
                    this.selectedNow = false;
                }
                this.onKeypressed(e);
                return;
                break;
            case Event.KEY_ESC:
                this.updateValue(this.currentValue);
                this.hide();
                break;
            case Event.KEY_TAB:
            case Event.KEY_RETURN:
                if (this.list.atBeginning()) {
                    this.hide();
                    Event.stop(e);
                    return;
                }
                this.select(this.list.selectedIndex);
                if (e.keyCode === Event.KEY_TAB) {
                    return;
                }
                break;
            case Event.KEY_UP:
                this.moveUp();
                break;
            case Event.KEY_DOWN:
                this.moveDown();
                break;
            default:
                this.onKeypressed(e);
                return;
        }
        Event.stop(e);
    },

    onKeyUp : function (e) {
        switch (e.keyCode) {
            case Event.KEY_UP:
            case Event.KEY_DOWN:
                return;
        }
        clearInterval(this.onChangeInterval);
        if (this.currentValue !== this.el.value) {
            if (this.options.deferRequestBy > 0) {
                // Defer lookup in case when value changes very quickly:
                this.onChangeInterval = setInterval((function () {
                    this.onValueChange();
                }).bind(this), this.options.deferRequestBy);
            } else {
                this.onValueChange();
            }
        }
    },

    onValueChange : function () {
        clearInterval(this.onChangeInterval);
        this.currentValue = this.el.value;
        this.list.selectedIndex = -1;
        if (this.ignoreValueChange) {
            this.ignoreValueChange = false;
            return;
        }
        if (this.currentValue === '' || this.currentValue.length < this.options.minChars) {
            this.hide();
        } else {
            this.getSuggestions();
        }
    },

    getSuggestions : function () {
        var cr = this.cachedResponse[this.currentValue];
        if (cr && Object.isArray(cr.suggestions)) {
            this.list.setWithResponse(cr);
            this.suggest();
        } else if (!this.isBadQuery(this.currentValue)) {
            var options = new Object();
            options.parameters = new Object();
            for (var property in this.parameters) {
                if (this.parameters[property] instanceof Function) {
                    options.parameters[property] = this.parameters[property].call();
                } else {
                    options.parameters[property] = this.parameters[property];
                }
            }
            options.parameters.query = this.currentValue;
            options.onComplete = this.processResponse.bind(this);
            options.method = 'get';
            new Ajax.Request(this.serviceUrl, options);
        } else {
            this.onNoResults(this.currentValue);
        }
    },

    isBadQuery : function (q) {
        var i = this.badQueries.length;
        while (i--) {
            if (q.indexOf(this.badQueries[i]) === 0) {
                return true;
            }
        }
        return false;
    },

    hide : function () {
        if (this.options.autoHide) {
            this.enabled = false;
            this.list = new AutocompleteList();
            this.container.hide();
        }
    },

    suggest : function () {
        if (this.list.emptySuggestions()) {
            this.hide();
            this.container.hide();
        } else {
            var content = [];
            var re = new RegExp('\\b' + this.currentValue.match(/\w+/g).join('|\\b'), 'gi');
            this.list.activeSuggestions().each(function (value, i) {
                var divClass = value[1] ? value[1] : "";
                var startDiv = '
', '');
                content.push(Autocomplete.highlight(value[0], re), '
');
            }.bind(this));
            this.enabled = true;
            this.container.update(content.join('')).show();
        }
    },

    processResponse : function (xhr) {
        var response;
        try {
            response = xhr.responseText.evalJSON();
            if (!Object.isArray(response.data)) {
                response.data = [];
            }
        } catch (err) {
            return;
        }
        this.cachedResponse[response.query] = response;
        if (response.suggestions.length === 0) {
            this.badQueries.push(response.query);
            this.hide();
            this.onNoResults(response.query);
        }
        if (response.query === this.currentValue) {
            this.list = new AutocompleteList();
            this.list.setWithResponse(response);
            this.suggest();
            this.onSuggestion(response.suggestions);
        }
    },

    activate : function (index) {
        var divs = this.container.childNodes;
        var activeItem;
        // Clear previous selection:
        if (!this.list.atBeginning() && divs.length > this.list.selectedIndex) {
            divs[this.list.selectedIndex].removeClassName('selected');
        }
        this.list.selectedIndex = index;
        if (!this.list.atBeginning() && divs.length > this.list.selectedIndex) {
            activeItem = divs[this.list.selectedIndex];
            activeItem.addClassName('selected');
        }
        return activeItem;
    },

    deactivate : function (div, index) {
        div.className = '';
        if (this.list.selectedIndex === index) {
            this.list.selectedIndex = -1;
        }
    },

    select : function (index) {
        var selectedIndexAndValue = this.list.getEntryIndex(index);
        var selectedValue = selectedIndexAndValue[1][0];
        if (selectedValue) {
            if (this.autoHide) {
                this.updateValue(selectedValue);
            } else {
                this.updateValue(this.currentValue);
            }
            if (this.options.autoSubmit && this.el.form) {
                this.el.form.submit();
            }
            this.ignoreValueChange = true;
            this.hide();
            this.onSelect(index, selectedIndexAndValue);
        }
    },

    moveUp : function () {
        if (this.list.atBeginning()) {
            return;
        }
        if (this.list.selectedIndex === 0) {
            this.container.childNodes[0].removeClassName('selected');
            this.list.selectedIndex = -1;
            this.updateValue(this.currentValue);
            return;
        }
        this.adjustScroll(this.list.selectedIndex - 1);
    },

    moveDown : function () {
        if (this.list.atEnd()) {
            return;
        }
        this.adjustScroll(this.list.selectedIndex + 1);
    },

    adjustScroll : function (i) {
        var container = this.container;
        var activeItem = this.activate(i);
        var offsetTop = activeItem.offsetTop;
        var upperBound = container.scrollTop;
        var lowerBound = upperBound + this.options.maxHeight - 25;
        if (offsetTop < upperBound) {
            container.scrollTop = offsetTop;
        } else if (offsetTop > lowerBound) {
            container.scrollTop = offsetTop - this.options.maxHeight + 25;
        }
        this.updateValue(this.list.getSelectedValue()[0]);
    },

    updateValue : function (value) {
        this.el.value = value.replace(/ *\(.*\)/, "");
    },

    onSelect : function (origIndex, selectedIndexAndValue) {
        var selectedIndex = selectedIndexAndValue[0];
        var selectedValue = selectedIndexAndValue[1];
        var selectedData = this.list.data[selectedIndex];
        (this.options.onSelect || Prototype.emptyFunction)(origIndex, selectedValue, selectedData);
    },

    onNoResults : function (currentValue) {
        (this.options.onNoResults || Prototype.emptyFunction)(currentValue);
    },

    onKeypressed : function (e) {
        (this.options.onKeypressed || Prototype.emptyFunction)(e);
    },

    onSuggestion : function (suggestions) {
        (this.options.onSuggestion || Prototype.emptyFunction)(this.suggestions);
    }
};

var AutocompleteList = function () {
    this.selectedIndex = -1;
    this.suggestions = [];
    this.suggestionList = [];
    this.data = [];
};

AutocompleteList.prototype = {
    atBeginning : function() {
        return this.selectedIndex === -1;
    },

    atEnd : function() {
        return this.selectedIndex === this.suggestionList.entries().length - 1;
    },

    isSelected : function(index) {
        return this.selectedIndex === index;
    },

    createSuggestionList : function () {
        var thisSuggestionList = this.suggestionList;
        this.suggestions.each(function (value, index) {
            thisSuggestionList.push(index);
        });
    },

    emptySuggestions : function() {
        return this.suggestionList.entries().length === 0;
    },

    activeSuggestions : function() {
        var activeSuggestions = [];
        var auto = this;
        this.suggestionList.entries().each(function (index, i) {
            activeSuggestions.push(auto.suggestions[index]);
        });
        return activeSuggestions;
    },

    getEntryIndex : function (index) {
        var indexToSuggestion = this.suggestionList.entries()[index];
        return [indexToSuggestion, this.suggestions[indexToSuggestion]];
    },

    getSelectedValue : function () {
        return this.getEntryIndex(this.selectedIndex)[1];
    },

    removeSuggestion : function (index) {
        var entryIndex = this.getEntryIndex(index);
        delete this.suggestionList[entryIndex[0]];
        if (this.selectedIndex > 0) {
            this.selectedIndex--;
        }
        return entryIndex;
    },

    addSuggestion : function (entryIndex) {
        this.suggestionList[entryIndex] = entryIndex;
    },

    setWithResponse : function (response) {
        this.suggestions = response.suggestions;
        this.data = response.data;
        this.createSuggestionList();
    }
};

Event.observe(document, 'dom:loaded', function () {
    Autocomplete.isDomLoaded = true;
}, false);
<commit_msg>Don't clear list on hide.<commit_after>/*
 *  AAAP Version 1.0
 *  (c) 2010 Tomas Kirda
 *  (c) 2011 Andrew Newman
 *
 *  Web site: https://github.com/newmana/AAAP
 *
 * AAAP is freely distributable under the terms of an MIT-style license.
 * Original code Ajax AutoComplete for Prototype: http://www.devbridge.com/projects/autocomplete/
 */

var Autocomplete = function (el, options) {
    this.el = $(el);
    this.id = this.el.identify();
    this.el.setAttribute('autocomplete', 'off');
    this.badQueries = [];
    this.intervalId = 0;
    this.cachedResponse = [];
    this.instanceId = null;
    this.onChangeInterval = null;
    this.ignoreValueChange = false;
    this.serviceUrl = options.serviceUrl;
    this.parameters = options.parameters;
    this.currentValue = this.el.value;
    this.list = new AutocompleteList();
    this.options = {
        autoSubmit : false,
        minChars : 1,
        maxHeight : 300,
        deferRequestBy : 0,
        width : 0,
        container : null,
        autoHide : true
    };
    if (options) {
        Object.extend(this.options, options);
    }
    if (Autocomplete.isDomLoaded) {
        this.initialize();
    } else {
        Event.observe(document, 'dom:loaded', this.initialize.bind(this), false);
    }
};

Autocomplete.instances = [];
Autocomplete.isDomLoaded = false;

Autocomplete.getInstance = function (id) {
    var instances = Autocomplete.instances;
    var i = instances.length;
    while (i--) {
        if (instances[i].id === id) {
            return instances[i];
        }
    }
};

Autocomplete.highlight = function (value, re) {
    return value.replace(re, function (match) {
        return '' + match + '<\/strong>'
    });
};

Autocomplete.prototype = {

    killerFn : null,

    initialize : function () {
        var me = this;
        this.killerFn = function (e) {
            var element = $(Event.element(e));
            if (element && element.up !== undefined && !element.up('.autocomplete')) {
                me.killSuggestions();
                me.disableKillerFn();
            }
        }.bindAsEventListener(this);

        if (!this.options.width) {
            this.options.width = this.el.getWidth();
        }

        var div = new Element('div', { style : 'position:absolute;' });
        div.update('

');

        this.options.container = $(this.options.container);
        if (this.options.container) {
            this.options.container.appendChild(div);
            this.fixPosition = function () {
            };
        } else {
            document.body.appendChild(div);
        }

        this.mainContainerId = div.identify();
        this.container = $('Autocomplete_' + this.id);
        this.fixPosition();

        Event.observe(this.el, window.opera ? 'keypress' : 'keydown', this.onKeyPress.bind(this));
        Event.observe(this.el, 'keyup', this.onKeyUp.bind(this));
        Event.observe(this.el, 'blur', this.enableKillerFn.bind(this));
        Event.observe(this.el, 'focus', this.fixPosition.bind(this));
        Event.observe(this.el, 'select', this.textSelected.bind(this));
        if (this.options.maxHeight !== -1) {
            this.container.setStyle({ maxHeight : this.options.maxHeight + 'px' });
        }
        this.instanceId = Autocomplete.instances.push(this) - 1;
        if (!this.options.autoHide) {
            this.container.show();
        }
    },

    textSelected : function () {
        this.selectedNow = true;
        this.onValueChange();
    },

    fixPosition : function () {
        var offset = this.el.cumulativeOffset();
        $(this.mainContainerId).setStyle({ top : (offset.top + this.el.getHeight()) + 'px', left : offset.left + 'px' });
    },

    enableKillerFn : function () {
        Event.observe(document.body, 'click', this.killerFn);
    },

    disableKillerFn : function () {
        Event.stopObserving(document.body, 'click', this.killerFn);
    },

    killSuggestions : function () {
        this.stopKillSuggestions();
        this.intervalId = window.setInterval(function () {
            this.hide();
            this.stopKillSuggestions();
        }.bind(this), 300);
    },

    stopKillSuggestions : function () {
        window.clearInterval(this.intervalId);
    },

    onKeyPress : function (e) {
        switch (e.keyCode) {
            case Event.KEY_DELETE:
                if (this.selectedNow) {
                    this.hide();
                    this.selectedNow = false;
                }
                this.onKeypressed(e);
                return;
                break;
            case Event.KEY_ESC:
                this.updateValue(this.currentValue);
                this.hide();
                break;
            case Event.KEY_TAB:
            case Event.KEY_RETURN:
                if (this.list.atBeginning()) {
                    this.hide();
                    Event.stop(e);
                    return;
                }
                this.select(this.list.selectedIndex);
                if (e.keyCode === Event.KEY_TAB) {
                    return;
                }
                break;
            case Event.KEY_UP:
                this.moveUp();
                break;
            case Event.KEY_DOWN:
                this.moveDown();
                break;
            default:
                this.onKeypressed(e);
                return;
        }
        Event.stop(e);
    },

    onKeyUp : function (e) {
        switch (e.keyCode) {
            case Event.KEY_UP:
            case Event.KEY_DOWN:
                return;
        }
        clearInterval(this.onChangeInterval);
        if (this.currentValue !== this.el.value) {
            if (this.options.deferRequestBy > 0) {
                // Defer lookup in case when value changes very quickly:
                this.onChangeInterval = setInterval((function () {
                    this.onValueChange();
                }).bind(this), this.options.deferRequestBy);
            } else {
                this.onValueChange();
            }
        }
    },

    onValueChange : function () {
        clearInterval(this.onChangeInterval);
        this.currentValue = this.el.value;
        this.list.selectedIndex = -1;
        if (this.ignoreValueChange) {
            this.ignoreValueChange = false;
            return;
        }
        if (this.currentValue === '' || this.currentValue.length < this.options.minChars) {
            this.hide();
        } else {
            this.getSuggestions();
        }
    },

    getSuggestions : function () {
        var cr = this.cachedResponse[this.currentValue];
        if (cr && Object.isArray(cr.suggestions)) {
            this.list.setWithResponse(cr);
            this.suggest();
        } else if (!this.isBadQuery(this.currentValue)) {
            var options = new Object();
            options.parameters = new Object();
            for (var property in this.parameters) {
                if (this.parameters[property] instanceof Function) {
                    options.parameters[property] = this.parameters[property].call();
                } else {
                    options.parameters[property] = this.parameters[property];
                }
            }
            options.parameters.query = this.currentValue;
            options.onComplete = this.processResponse.bind(this);
            options.method = 'get';
            new Ajax.Request(this.serviceUrl, options);
        } else {
            this.onNoResults(this.currentValue);
        }
    },

    isBadQuery : function (q) {
        var i = this.badQueries.length;
        while (i--) {
            if (q.indexOf(this.badQueries[i]) === 0) {
                return true;
            }
        }
        return false;
    },

    hide : function () {
        if (this.options.autoHide) {
            this.enabled = false;
            this.container.hide();
        }
    },

    suggest : function () {
        if (this.list.emptySuggestions()) {
            this.hide();
            this.container.hide();
        } else {
            var content = [];
            var re = new RegExp('\\b' + this.currentValue.match(/\w+/g).join('|\\b'), 'gi');
            this.list.activeSuggestions().each(function (value, i) {
                var divClass = value[1] ? value[1] : "";
                var startDiv = '
', '');
                content.push(Autocomplete.highlight(value[0], re), '
');
            }.bind(this));
            this.enabled = true;
            this.container.update(content.join('')).show();
        }
    },

    processResponse : function (xhr) {
        var response;
        try {
            response = xhr.responseText.evalJSON();
            if (!Object.isArray(response.data)) {
                response.data = [];
            }
        } catch (err) {
            return;
        }
        this.cachedResponse[response.query] = response;
        if (response.suggestions.length === 0) {
            this.badQueries.push(response.query);
            this.hide();
            this.onNoResults(response.query);
        }
        if (response.query === this.currentValue) {
            this.list = new AutocompleteList();
            this.list.setWithResponse(response);
            this.suggest();
            this.onSuggestion(response.suggestions);
        }
    },

    activate : function (index) {
        var divs = this.container.childNodes;
        var activeItem;
        // Clear previous selection:
        if (!this.list.atBeginning() && divs.length > this.list.selectedIndex) {
            divs[this.list.selectedIndex].removeClassName('selected');
        }
        this.list.selectedIndex = index;
        if (!this.list.atBeginning() && divs.length > this.list.selectedIndex) {
            activeItem = divs[this.list.selectedIndex];
            activeItem.addClassName('selected');
        }
        return activeItem;
    },

    deactivate : function (div, index) {
        div.className = '';
        if (this.list.selectedIndex === index) {
            this.list.selectedIndex = -1;
        }
    },

    select : function (index) {
        var selectedIndexAndValue = this.list.getEntryIndex(index);
        var selectedValue = selectedIndexAndValue[1][0];
        if (selectedValue) {
            if (this.autoHide) {
                this.updateValue(selectedValue);
            } else {
                this.updateValue(this.currentValue);
            }
            if (this.options.autoSubmit && this.el.form) {
                this.el.form.submit();
            }
            this.ignoreValueChange = true;
            this.hide();
            this.onSelect(index, selectedIndexAndValue);
        }
    },

    moveUp : function () {
        if (this.list.atBeginning()) {
            return;
        }
        if (this.list.selectedIndex === 0) {
            this.container.childNodes[0].removeClassName('selected');
            this.list.selectedIndex = -1;
            this.updateValue(this.currentValue);
            return;
        }
        this.adjustScroll(this.list.selectedIndex - 1);
    },

    moveDown : function () {
        if (this.list.atEnd()) {
            return;
        }
        this.adjustScroll(this.list.selectedIndex + 1);
    },

    adjustScroll : function (i) {
        var container = this.container;
        var activeItem = this.activate(i);
        var offsetTop = activeItem.offsetTop;
        var upperBound = container.scrollTop;
        var lowerBound = upperBound + this.options.maxHeight - 25;
        if (offsetTop < upperBound) {
            container.scrollTop = offsetTop;
        } else if (offsetTop > lowerBound) {
            container.scrollTop = offsetTop - this.options.maxHeight + 25;
        }
        this.updateValue(this.list.getSelectedValue()[0]);
    },

    updateValue : function (value) {
        this.el.value = value.replace(/ *\(.*\)/, "");
    },

    onSelect : function (origIndex, selectedIndexAndValue) {
        var selectedIndex = selectedIndexAndValue[0];
        var selectedValue = selectedIndexAndValue[1];
        var selectedData = this.list.data[selectedIndex];
        (this.options.onSelect || Prototype.emptyFunction)(origIndex, selectedValue, selectedData);
    },

    onNoResults : function (currentValue) {
        (this.options.onNoResults || Prototype.emptyFunction)(currentValue);
    },

    onKeypressed : function (e) {
        (this.options.onKeypressed || Prototype.emptyFunction)(e);
    },

    onSuggestion : function (suggestions) {
        (this.options.onSuggestion || Prototype.emptyFunction)(this.suggestions);
    }
};

var AutocompleteList = function () {
    this.selectedIndex = -1;
    this.suggestions = [];
    this.suggestionList = [];
    this.data = [];
};

AutocompleteList.prototype = {
    atBeginning : function() {
        return this.selectedIndex === -1;
    },

    atEnd : function() {
        return this.selectedIndex === this.suggestionList.entries().length - 1;
    },

    isSelected : function(index) {
        return this.selectedIndex === index;
    },

    createSuggestionList : function () {
        var thisSuggestionList = this.suggestionList;
        this.suggestions.each(function (value, index) {
            thisSuggestionList.push(index);
        });
    },

    emptySuggestions : function() {
        return this.suggestionList.entries().length === 0;
    },

    activeSuggestions : function() {
        var activeSuggestions = [];
        var auto = this;
        this.suggestionList.entries().each(function (index, i) {
            activeSuggestions.push(auto.suggestions[index]);
        });
        return activeSuggestions;
    },

    getEntryIndex : function (index) {
        var indexToSuggestion = this.suggestionList.entries()[index];
        return [indexToSuggestion, this.suggestions[indexToSuggestion]];
    },

    getSelectedValue : function () {
        return this.getEntryIndex(this.selectedIndex)[1];
    },

    removeSuggestion : function (index) {
        var entryIndex = this.getEntryIndex(index);
        delete this.suggestionList[entryIndex[0]];
        if (this.selectedIndex > 0) {
            this.selectedIndex--;
        }
        return entryIndex;
    },

    addSuggestion : function (entryIndex) {
        this.suggestionList[entryIndex] = entryIndex;
    },

    setWithResponse : function (response) {
        this.suggestions = response.suggestions;
        this.data = response.data;
        this.createSuggestionList();
    }
};

Event.observe(document, 'dom:loaded', function () {
    Autocomplete.isDomLoaded = true;
}, false);
<|endoftext|>


<commit_before>var assert = require('assert');
var deepExtend = require('deep-extend');
var DotObject = require('dot-object');
var fs = require('fs');
var os = require('os');
var path = require('path');
var util = require('util');
var yamlJs = require('yaml-js');

var camlUtil = require('./camlUtil');

var DOT = '.';
var DOT_SUBSTITUTE = '_DOT_';
var dotObject = new DotObject(DOT);

// Replaces aliases by the block content of the anchors
function replaceAliases(yamlString) {
  yamlString = camlUtil.stripEmptyLinesAndComments(yamlString);

  var anchors = camlUtil.retrieveAnchors(yamlString);

  Object.keys(anchors).forEach(function (key) {
    anchors[key].block = camlUtil.replaceAliases(anchors[key].block.join('\n'), anchors).split('\n');
  });

  yamlString = sanitize(yamlString);
  yamlString = camlUtil.stripAnchors(yamlString);
  yamlString = camlUtil.replaceAliases(yamlString, anchors);

  return yamlString.split('\n');
}

/**
 * Sanitize yaml keys (remove "" or '' and replace dots by the surrogate)
 *
 * @param yamlString
 * @returns {*}
 */
function sanitize(yamlString) {
  var yaml = yamlString.split('\n');
  var yamlLinesSanitized = [];

  yaml.forEach(function (line) {
    var match = line.trim().match(/[",'].*\..*[",']:/);
    if (match) {
      var substituted = line.replace(match[0],
        match[0]
          .replace(/[",']/g, '')          // Strip " or ' from the keys
          .replace(/\./g, DOT_SUBSTITUTE) // Replace . by DOT_SUBSTITUTE in "" keys
      );

      yamlLinesSanitized.push(substituted);
    } else {
      yamlLinesSanitized.push(line)
    }
  });

  return yamlLinesSanitized.join('\n');
}

/** Write out the entire hierarchy in YAML
 * a:
 *  b:
 *   c:
 *
 * Becomes:
 *
 * a:
 * a.b:
 * a.b.c:
 *
 * @param yamlLines
 */
function blowUpHierarchy(yamlLines) {
  var fullKey = "";
  var indent = 0;
  var currentIndent = 0;
  var indentSteps = [];
  var postLines = [];

  for (var index = 0; index < yamlLines.length; null) {
    var line = yamlLines[index];
    // Skip empty lines and comments
    if (line.trim().length === 0 || line.trim().indexOf("#") > -1) {
      continue;
    }

    var match = line.trim().match(".*:");
    currentIndent = yamlLines[index].search(/\S|$/);

    // We're in a list, simply push the content
    if (line.trim().indexOf("- ") === 0) {
      while (index < yamlLines.length && (yamlLines[index].trim().indexOf("- ") === 0 || yamlLines[index].search(/\S|$/) > currentIndent)) {
        postLines.push(yamlLines[index]);
        index++;
      }
      continue;
    }

    // Down the tree
    if (match && (currentIndent > indent)) {
      if (currentIndent !== 0) {
        fullKey += DOT;
      } else {
        fullKey = "";
      }
      fullKey += match[0].replace(/:.*/, "");
      if ((currentIndent - indent) > 0) {
        indentSteps.push(currentIndent - indent);
      }
    }

    // Up the tree or peer property
    if (match && (currentIndent <= indent)) {
      if (currentIndent === 0) {
        fullKey = "";
      }

      var keyArr = fullKey.split(DOT);
      keyArr.pop();

      var steps = 0;
      // Get the number of steps to travel up the hierarchy tree
      while (indent > currentIndent) {
        indent -= indentSteps.pop();
        keyArr.pop();
        steps++;
      }

      fullKey = keyArr.join(DOT);
      if (currentIndent !== 0) {
        fullKey += DOT;
      }
      fullKey += match[0].replace(/:.*/, "");
    }

    if (line.trim().match(/.*:/)) {
      postLines.push(line.replace(line.split(":")[0], fullKey));
    } else {
      postLines.push(line);
    }

    indent = currentIndent;
    index++;
  }
  return postLines;
}

function parse(yamlLines) {
  var yaml = yamlJs.load(yamlLines.join('\n'));
  var result = [{}];

  Object.keys(yaml).forEach(function (key) {
    if (yaml[key] !== null) {
      var obj = {};
      obj[key] = yaml[key];
      result.push(dotObject.object(obj));
    }
  });

  deepExtend.apply(null, result);

  var jsonString = JSON.stringify(result[0]);
  jsonString = jsonString.replace(new RegExp(DOT_SUBSTITUTE, 'g'), '.');

  return JSON.parse(jsonString);
}

function camlize(options) {
  if (!options) {
    return;
  }

  if (options.separator) {
    dotObject = new DotObject(DOT);
  }

  // Default dir is the current working dir
  options.dir = options.dir || path.join(process.cwd());
  var yamlString = "";

  options.files.forEach(function (fileName) {
    var filePath;

    if (path.isAbsolute(fileName)) {
      filePath = fileName + ".yml";
    } else {
      filePath = path.join(options.dir, fileName + ".yml");
    }

    try {
      yamlString += fs.readFileSync(filePath, 'UTF8');
      yamlString += os.EOL;
    }
    catch (err) {
      console.warn("File " + path.relative(process.cwd(), filePath) + ' not found, ignoring it.');
    }
  });

  // Add overrides to the end of the yaml string
  if (options.overrides) {
    yamlString += options.overrides.join('\n');
  }

  return parse(
    blowUpHierarchy(
      replaceAliases(yamlString)
    )
  );
}

module.exports = {
  camlize: camlize,
  blowUpHierarchy: blowUpHierarchy,
  parse: parse,
  replaceAliases: replaceAliases,
  sanitize: sanitize
};
<commit_msg>Need to sanitize before fetching anchor blocks<commit_after>var assert = require('assert');
var deepExtend = require('deep-extend');
var DotObject = require('dot-object');
var fs = require('fs');
var os = require('os');
var path = require('path');
var util = require('util');
var yamlJs = require('yaml-js');

var camlUtil = require('./camlUtil');

var DOT = '.';
var DOT_SUBSTITUTE = '_DOT_';
var dotObject = new DotObject(DOT);

// Replaces aliases by the block content of the anchors
function replaceAliases(yamlString) {
  yamlString = camlUtil.stripEmptyLinesAndComments(yamlString);
  yamlString = sanitize(yamlString);

  var anchors = camlUtil.retrieveAnchors(yamlString);

  Object.keys(anchors).forEach(function (key) {
    anchors[key].block = camlUtil.replaceAliases(anchors[key].block.join('\n'), anchors).split('\n');
  });

  yamlString = camlUtil.stripAnchors(yamlString);
  yamlString = camlUtil.replaceAliases(yamlString, anchors);

  return yamlString.split('\n');
}

/**
 * Sanitize yaml keys (remove "" or '' and replace dots by the surrogate)
 *
 * @param yamlString
 * @returns {*}
 */
function sanitize(yamlString) {
  var yaml = yamlString.split('\n');
  var yamlLinesSanitized = [];

  yaml.forEach(function (line) {
    var match = line.trim().match(/[",'].*\..*[",']:/);
    if (match) {
      var substituted = line.replace(match[0],
        match[0]
          .replace(/[",']/g, '')          // Strip " or ' from the keys
          .replace(/\./g, DOT_SUBSTITUTE) // Replace . by DOT_SUBSTITUTE in "" keys
      );

      yamlLinesSanitized.push(substituted);
    } else {
      yamlLinesSanitized.push(line)
    }
  });

  return yamlLinesSanitized.join('\n');
}

/** Write out the entire hierarchy in YAML
 * a:
 *  b:
 *   c:
 *
 * Becomes:
 *
 * a:
 * a.b:
 * a.b.c:
 *
 * @param yamlLines
 */
function blowUpHierarchy(yamlLines) {
  var fullKey = "";
  var indent = 0;
  var currentIndent = 0;
  var indentSteps = [];
  var postLines = [];

  for (var index = 0; index < yamlLines.length; null) {
    var line = yamlLines[index];
    // Skip empty lines and comments
    if (line.trim().length === 0 || line.trim().indexOf("#") > -1) {
      continue;
    }

    var match = line.trim().match(".*:");
    currentIndent = yamlLines[index].search(/\S|$/);

    // We're in a list, simply push the content
    if (line.trim().indexOf("- ") === 0) {
      while (index < yamlLines.length && (yamlLines[index].trim().indexOf("- ") === 0 || yamlLines[index].search(/\S|$/) > currentIndent)) {
        postLines.push(yamlLines[index]);
        index++;
      }
      continue;
    }

    // Down the tree
    if (match && (currentIndent > indent)) {
      if (currentIndent !== 0) {
        fullKey += DOT;
      } else {
        fullKey = "";
      }
      fullKey += match[0].replace(/:.*/, "");
      if ((currentIndent - indent) > 0) {
        indentSteps.push(currentIndent - indent);
      }
    }

    // Up the tree or peer property
    if (match && (currentIndent <= indent)) {
      if (currentIndent === 0) {
        fullKey = "";
      }

      var keyArr = fullKey.split(DOT);
      keyArr.pop();

      var steps = 0;
      // Get the number of steps to travel up the hierarchy tree
      while (indent > currentIndent) {
        indent -= indentSteps.pop();
        keyArr.pop();
        steps++;
      }

      fullKey = keyArr.join(DOT);
      if (currentIndent !== 0) {
        fullKey += DOT;
      }
      fullKey += match[0].replace(/:.*/, "");
    }

    if (line.trim().match(/.*:/)) {
      postLines.push(line.replace(line.split(":")[0], fullKey));
    } else {
      postLines.push(line);
    }

    indent = currentIndent;
    index++;
  }
  return postLines;
}

function parse(yamlLines) {
  var yaml = yamlJs.load(yamlLines.join('\n'));
  var result = [{}];

  Object.keys(yaml).forEach(function (key) {
    if (yaml[key] !== null) {
      var obj = {};
      obj[key] = yaml[key];
      result.push(dotObject.object(obj));
    }
  });

  deepExtend.apply(null, result);

  var jsonString = JSON.stringify(result[0]);
  jsonString = jsonString.replace(new RegExp(DOT_SUBSTITUTE, 'g'), '.');

  return JSON.parse(jsonString);
}

function camlize(options) {
  if (!options) {
    return;
  }

  if (options.separator) {
    dotObject = new DotObject(DOT);
  }

  // Default dir is the current working dir
  options.dir = options.dir || path.join(process.cwd());
  var yamlString = "";

  options.files.forEach(function (fileName) {
    var filePath;

    if (path.isAbsolute(fileName)) {
      filePath = fileName + ".yml";
    } else {
      filePath = path.join(options.dir, fileName + ".yml");
    }

    try {
      yamlString += fs.readFileSync(filePath, 'UTF8');
      yamlString += os.EOL;
    }
    catch (err) {
      console.warn("File " + path.relative(process.cwd(), filePath) + ' not found, ignoring it.');
    }
  });

  // Add overrides to the end of the yaml string
  if (options.overrides) {
    yamlString += options.overrides.join('\n');
  }

  return parse(
    blowUpHierarchy(
      replaceAliases(yamlString)
    )
  );
}

module.exports = {
  camlize: camlize,
  blowUpHierarchy: blowUpHierarchy,
  parse: parse,
  replaceAliases: replaceAliases,
  sanitize: sanitize
};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const TIMER_DEFAULT_STYLE =
	"position: fixed; z-index: 2147483647; " +
	"top: 0px; left: 0px; margin: 2px; padding: 4px 4px 2px 4px; " +
	"background-color: #fff; color: #000; " +
	"border: solid 1px #000; border-radius: 4px; " +
	"font: normal 12px \"Lucida Console\", Monaco, monospace; " +
	"user-select: none; -moz-user-select: none;";

const TIMER_SIZES = ["10px", "12px", "14px", "16px"];

const TIMER_LOCATIONS = [
	["0px", "", "0px", ""],
	["0px", "", "", "0px"],
	["", "0px", "", "0px"],
	["", "0px", "0px", ""]
];

const ALERT_CONTAINER_STYLE =
	"position: fixed; z-index: 2147483647; display: none; " +
	"top: 0px; left: 0px; width: 100%; height: 100%; " +
	"margin: auto; padding: 0px; " +
	"background-color: transparent;";

const ALERT_BOX_STYLE =
	"margin: auto; padding: 12px; " +
	"line-height: normal; text-align: center; " +
	"background-color: #fff; color: #000; " +
	"border: solid 1px #000; border-radius: 4px; " +
	"font: normal 16px Helvetica, Arial, sans-serif; " +
	"box-shadow: 2px 2px 2px #888; " +
	"user-select: none; -moz-user-select: none;";

const ALERT_ICON_STYLE = "padding: 0px;"

const ALERT_TEXT_STYLE = "padding: 8px 0px 0px 0px;"

const ALERT_ICON = "data:image/png;base64,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";

var gTimer;
var gAlert;

// Update timer
//
function updateTimer(text, size, location) {
	if (!text) {
		if (gTimer) {
			// Hide timer
			gTimer.hidden = true;
		}
	} else {
		if (!gTimer) {
			// Create timer
			gTimer = document.createElement("div");
			gTimer.setAttribute("style", TIMER_DEFAULT_STYLE);
		}

		if (!document.body.contains(gTimer)) {
			// Insert timer at end of document body
			document.body.appendChild(gTimer);
		}

		// Set text
		gTimer.innerText = text;

		// Set size
		if (size >= 0 && size < TIMER_SIZES.length) {
			gTimer.style.fontSize = TIMER_SIZES[size];
		}

		// Set location
		if (location >= 0 && location < TIMER_LOCATIONS.length) {
			gTimer.style.top = TIMER_LOCATIONS[location][0];
			gTimer.style.bottom = TIMER_LOCATIONS[location][1];
			gTimer.style.left = TIMER_LOCATIONS[location][2];
			gTimer.style.right = TIMER_LOCATIONS[location][3];
		}

		// Show timer
		gTimer.hidden = false;
	}
}

// Show alert message
//
function showAlert(text) {
	let alertBox, alertIcon, alertText;

	if (!gAlert) {
		// Create container
		gAlert = document.createElement("div");
		gAlert.setAttribute("style", ALERT_CONTAINER_STYLE);
		document.body.appendChild(gAlert);

		// Create message box
		alertBox = document.createElement("div");
		alertBox.setAttribute("style", ALERT_BOX_STYLE);
		alertBox.addEventListener("click", hideAlert);
		alertIcon = document.createElement("img");
		alertIcon.setAttribute("style", ALERT_ICON_STYLE);
		alertIcon.setAttribute("src", ALERT_ICON);
		alertBox.appendChild(alertIcon);
		alertText = document.createElement("div");
		alertText.setAttribute("style", ALERT_TEXT_STYLE);
		alertBox.appendChild(alertText);
		gAlert.appendChild(alertBox);
	}

	// Set text
	alertText.innerText = text;

	// Show timer
	gAlert.style.display = "flex";
}

// Hide alert message
//
function hideAlert() {
	if (gAlert) {
		gAlert.style.display = "none";
	}
}

// Check page for keyword(s)
//
function checkKeyword(keywordRE) {
	// Get all text nodes in document
	let textNodes = document.evaluate(
		"//text()", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

	//console.log("Checking " + textNodes.snapshotLength + " text node(s) for keyword(s)...");

	for (let i = 0; i < textNodes.snapshotLength; i++) {
		if (keywordRE && keywordRE.test(textNodes.snapshotItem(i).data)) {
			return true; // keyword(s) found
		}
	}

	return false; // keyword(s) not found
}

/*** EVENT HANDLERS BEGIN HERE ***/

function handleMessage(message, sender, sendResponse) {
	if (message.type == "timer") {
		updateTimer(message.text, message.size, message.location);
	} else if (message.type == "alert") {
		showAlert(message.text);
	} else if (message.type == "keyword") {
		let keyword = checkKeyword(message.keywordRE);
		sendResponse(keyword);
	}
}

browser.runtime.onMessage.addListener(handleMessage);
<commit_msg>Hide timer on double-click<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const TIMER_DEFAULT_STYLE =
	"position: fixed; z-index: 2147483647; " +
	"top: 0px; left: 0px; margin: 2px; padding: 4px 4px 2px 4px; " +
	"background-color: #fff; color: #000; " +
	"border: solid 1px #000; border-radius: 4px; " +
	"font: normal 12px \"Lucida Console\", Monaco, monospace; " +
	"user-select: none; -moz-user-select: none;";

const TIMER_SIZES = ["10px", "12px", "14px", "16px"];

const TIMER_LOCATIONS = [
	["0px", "", "0px", ""],
	["0px", "", "", "0px"],
	["", "0px", "", "0px"],
	["", "0px", "0px", ""]
];

const ALERT_CONTAINER_STYLE =
	"position: fixed; z-index: 2147483647; display: none; " +
	"top: 0px; left: 0px; width: 100%; height: 100%; " +
	"margin: auto; padding: 0px; " +
	"background-color: transparent;";

const ALERT_BOX_STYLE =
	"margin: auto; padding: 12px; " +
	"line-height: normal; text-align: center; " +
	"background-color: #fff; color: #000; " +
	"border: solid 1px #000; border-radius: 4px; " +
	"font: normal 16px Helvetica, Arial, sans-serif; " +
	"box-shadow: 2px 2px 2px #888; " +
	"user-select: none; -moz-user-select: none;";

const ALERT_ICON_STYLE = "padding: 0px;"

const ALERT_TEXT_STYLE = "padding: 8px 0px 0px 0px;"

const ALERT_ICON = "data:image/png;base64,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";

var gTimer;
var gAlert;

// Update timer
//
function updateTimer(text, size, location) {
	if (!text) {
		if (gTimer) {
			// Hide timer
			gTimer.hidden = true;
		}
	} else {
		if (!gTimer) {
			// Create timer
			gTimer = document.createElement("div");
			gTimer.setAttribute("style", TIMER_DEFAULT_STYLE);
			gTimer.addEventListener("dblclick", function (e) { this.style.display = "none"; });
		}

		if (!document.body.contains(gTimer)) {
			// Insert timer at end of document body
			document.body.appendChild(gTimer);
		}

		// Set text
		gTimer.innerText = text;

		// Set size
		if (size >= 0 && size < TIMER_SIZES.length) {
			gTimer.style.fontSize = TIMER_SIZES[size];
		}

		// Set location
		if (location >= 0 && location < TIMER_LOCATIONS.length) {
			gTimer.style.top = TIMER_LOCATIONS[location][0];
			gTimer.style.bottom = TIMER_LOCATIONS[location][1];
			gTimer.style.left = TIMER_LOCATIONS[location][2];
			gTimer.style.right = TIMER_LOCATIONS[location][3];
		}

		// Show timer
		gTimer.hidden = false;
	}
}

// Show alert message
//
function showAlert(text) {
	let alertBox, alertIcon, alertText;

	if (!gAlert) {
		// Create container
		gAlert = document.createElement("div");
		gAlert.setAttribute("style", ALERT_CONTAINER_STYLE);
		document.body.appendChild(gAlert);

		// Create message box
		alertBox = document.createElement("div");
		alertBox.setAttribute("style", ALERT_BOX_STYLE);
		alertBox.addEventListener("click", hideAlert);
		alertIcon = document.createElement("img");
		alertIcon.setAttribute("style", ALERT_ICON_STYLE);
		alertIcon.setAttribute("src", ALERT_ICON);
		alertBox.appendChild(alertIcon);
		alertText = document.createElement("div");
		alertText.setAttribute("style", ALERT_TEXT_STYLE);
		alertBox.appendChild(alertText);
		gAlert.appendChild(alertBox);
	}

	// Set text
	alertText.innerText = text;

	// Show timer
	gAlert.style.display = "flex";
}

// Hide alert message
//
function hideAlert() {
	if (gAlert) {
		gAlert.style.display = "none";
	}
}

// Check page for keyword(s)
//
function checkKeyword(keywordRE) {
	// Get all text nodes in document
	let textNodes = document.evaluate(
		"//text()", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

	//console.log("Checking " + textNodes.snapshotLength + " text node(s) for keyword(s)...");

	for (let i = 0; i < textNodes.snapshotLength; i++) {
		if (keywordRE && keywordRE.test(textNodes.snapshotItem(i).data)) {
			return true; // keyword(s) found
		}
	}

	return false; // keyword(s) not found
}

/*** EVENT HANDLERS BEGIN HERE ***/

function handleMessage(message, sender, sendResponse) {
	if (message.type == "timer") {
		updateTimer(message.text, message.size, message.location);
	} else if (message.type == "alert") {
		showAlert(message.text);
	} else if (message.type == "keyword") {
		let keyword = checkKeyword(message.keywordRE);
		sendResponse(keyword);
	}
}

browser.runtime.onMessage.addListener(handleMessage);
<|endoftext|>


<commit_before>dop.protocol._onsubscribe = function(node, request_id, request, response) {
    if (response[0] !== undefined) {
        if (response[0] !== 0)
            request.promise.reject(dop.core.getRejectError(response[0]))
        else {
            var object_owner_id = response[1],
                object_owner = response[2],
                object_path = isArray(object_owner) ? object_owner : [],
                object,
                collector

            // New object
            if (node.owner[object_owner_id] === undefined) {
                // If is new object and third parameter is an array we must reject
                if (object_owner === object_path) {
                    request.promise.reject(
                        dop.core.error.reject_local.OBJECT_NOT_FOUND
                    )
                }

                collector = dop.collect()
                // New object
                if (request.into === undefined) {
                    object = dop.register(object_owner)
                }
                // Registered object
                else if (dop.isRegistered(request.into)) {
                    object = dop.core.mergeSubscription(
                        request.into,
                        object_owner
                    )
                }
                // No registered object
                else {
                    object = dop.register(
                        dop.core.mergeSubscription(request.into, object_owner)
                    )
                }
                dop.core.registerOwner(node, object, object_owner_id)
                collector.emit()
            }
            // Already registered
            else object = dop.data.object[node.owner[object_owner_id]].object

            object = dop.util.get(object, object_path)

            if (!isObject(object))
                request.promise.reject(
                    dop.core.error.reject_local.OBJECT_NOT_FOUND
                )
            else request.promise.resolve(dop.getObjectProxy(object))
        }
    }
}
<commit_msg>Fixed bug onunsubscribe<commit_after>dop.protocol._onsubscribe = function(node, request_id, request, response) {
    if (response[0] !== undefined) {
        if (response[0] !== 0)
            request.promise.reject(dop.core.getRejectError(response[0]))
        else {
            var object_owner_id = response[1],
                object_owner = response[2],
                object_path = isArray(object_owner) ? object_owner : [],
                object,
                collector

            // New object
            if (node.owner[object_owner_id] === undefined) {
                // If is new object and third parameter is an array we must reject
                if (object_owner === object_path) {
                    request.promise.reject(
                        dop.core.error.reject_local.OBJECT_NOT_FOUND
                    )
                }

                collector = dop.collect()
                // New object
                if (request.into === undefined) {
                    object = dop.register(object_owner)
                }
                // Registered object
                else if (dop.isRegistered(request.into)) {
                    object = dop.core.mergeSubscription(
                        request.into,
                        object_owner
                    )
                }
                // No registered object
                else {
                    object = dop.core.mergeSubscription(
                        dop.register(request.into),
                        object_owner
                    )
                }
                dop.core.registerOwner(node, object, object_owner_id)
                collector.emit()
            }
            // Already registered
            else object = dop.data.object[node.owner[object_owner_id]].object

            object = dop.util.get(object, object_path)

            if (!isObject(object))
                request.promise.reject(
                    dop.core.error.reject_local.OBJECT_NOT_FOUND
                )
            else request.promise.resolve(dop.getObjectProxy(object))
        }
    }
}
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var EdgeplateGenerator = module.exports = function EdgeplateGenerator(args, options, config) {
    yeoman.generators.Base.apply(this, arguments);

    this.argument('slug', { type: String, required: false });
    this.appSlug = this.slug || path.basename(process.cwd());

    this.on('end', function () {
        this.installDependencies({ skipInstall: options['skip-install'] });
    });

    this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(EdgeplateGenerator, yeoman.generators.Base);

EdgeplateGenerator.prototype.askFor = function askFor() {
    var cb = this.async();

    // welcome message
    var welcome =
    '\n     _-----_' +
    '\n    |       |' +
    '\n    |' + '--(o)--'.red + '|   .--------------------------.' +
    '\n   `---------´  |    ' + 'Welcome to Yeoman,'.yellow.bold + '    |' +
    '\n    ' + '( '.yellow + '_' + '´U`'.yellow + '_' + ' )'.yellow + '   |   ' + 'ladies and gentlemen!'.yellow.bold + '  |' +
    '\n    /___A___\\   \'__________________________\'' +
    '\n     |  ~  |'.yellow +
    '\n   __' + '\'.___.\''.yellow + '__' +
    '\n ´   ' + '`  |'.red + '° ' + '´ Y'.red + ' `\n';

    console.log(welcome);

    var prompts = [{
        name: 'appTitle',
        message: 'What is the display title of your app?',
        default: 'Edge Project'
    }];

    this.prompt(prompts, function (props) {
        this.appTitle = props.appTitle;

        cb();
    }.bind(this));
};

EdgeplateGenerator.prototype.app = function app() {

    this.copy('public/index.jade', 'app/public/index.jade');

    this.mkdir('app/services/models');

    this.copy('app.js', 'app/app.js');

    this.copy('_Gruntfile.js', 'Gruntfile.js');

    this.copy('README.md', 'README.md');

    this.copy('_package.json', 'package.json');
    this.copy('bowerrc', '.bowerrc');
    this.copy('_bower.json', 'bower.json');
};

EdgeplateGenerator.prototype.layout = function layoutFiles() {
    this.copy('public/layout/_global.jade', 'app/public/layout/_global.jade');
    this.copy('public/layout/_page.jade', 'app/public/layout/_page.jade');
};

EdgeplateGenerator.prototype.components = function componentFiles() {
    this.copy('public/components/navbar/_navbar.scss', 'app/public/components/navbar/_navbar.jade');
    this.copy('public/components/navbar/navbar.jade', 'app/public/components/navbar/navbar.jade');
};

EdgeplateGenerator.prototype.directives = function directiveFiles() {
    this.mkdir('app/public/directives');
};

EdgeplateGenerator.prototype.images = function imageFiles() {
    this.mkdir('app/public/images');
};

EdgeplateGenerator.prototype.filters = function filterFiles() {
    this.mkdir('app/public/scripts/filters');
};

EdgeplateGenerator.prototype.services = function serviceFiles() {
    this.copy('public/scripts/services/edgePage.js', 'app/public/scripts/services/edgePage.js');
};

EdgeplateGenerator.prototype.scripts = function scriptFiles() {
    this.copy('public/scripts/app.js', 'app/public/scripts/app.js');
    this.copy('public/scripts/helper.js', 'app/public/scripts/helper.js');
};

EdgeplateGenerator.prototype.styles = function styleFiles() {
    this.mkdir('app/public/styles');
    this.copy('public/styles/_mixins.scss', 'app/public/styles/_mixins.scss');
    this.copy('public/styles/_styles.scss', 'app/public/styles/_styles.scss');
    this.copy('public/styles/_variables.scss', 'app/public/styles/_variables.scss');
    this.copy('public/styles/app.scss', 'app/public/styles/app.scss');
};

EdgeplateGenerator.prototype.controllers = function controllerFiles() {
    this.copy('public/controllers/App/AppController.js', 'app/public/controllers/App/AppController.js');
    this.copy('public/controllers/Body/BodyController.js', 'app/public/controllers/Body/BodyController.js');

    this.copy('public/controllers/pages/Dashboard/_Dashboard.scss', 'app/public/controllers/pages/Dashboard/_Dashboard.scss');
    this.copy('public/controllers/pages/Dashboard/DashboardController.js', 'app/public/controllers/pages/Dashboard/DashboardController.js');
    this.copy('public/controllers/pages/Dashboard/DashboardView.jade', 'app/public/controllers/pages/Dashboard/DashboardView.jade');
};

EdgeplateGenerator.prototype.projectfiles = function projectfiles() {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
    this.copy('gitignore', '.gitignore');
};
<commit_msg>Path fixed, no really, I've done this before...<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var EdgeplateGenerator = module.exports = function EdgeplateGenerator(args, options, config) {
    yeoman.generators.Base.apply(this, arguments);

    this.argument('slug', { type: String, required: false });
    this.appSlug = this.slug || path.basename(process.cwd());

    this.on('end', function () {
        this.installDependencies({ skipInstall: options['skip-install'] });
    });

    this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(EdgeplateGenerator, yeoman.generators.Base);

EdgeplateGenerator.prototype.askFor = function askFor() {
    var cb = this.async();

    // welcome message
    var welcome =
    '\n     _-----_' +
    '\n    |       |' +
    '\n    |' + '--(o)--'.red + '|   .--------------------------.' +
    '\n   `---------´  |    ' + 'Welcome to Yeoman,'.yellow.bold + '    |' +
    '\n    ' + '( '.yellow + '_' + '´U`'.yellow + '_' + ' )'.yellow + '   |   ' + 'ladies and gentlemen!'.yellow.bold + '  |' +
    '\n    /___A___\\   \'__________________________\'' +
    '\n     |  ~  |'.yellow +
    '\n   __' + '\'.___.\''.yellow + '__' +
    '\n ´   ' + '`  |'.red + '° ' + '´ Y'.red + ' `\n';

    console.log(welcome);

    var prompts = [{
        name: 'appTitle',
        message: 'What is the display title of your app?',
        default: 'Edge Project'
    }];

    this.prompt(prompts, function (props) {
        this.appTitle = props.appTitle;

        cb();
    }.bind(this));
};

EdgeplateGenerator.prototype.app = function app() {

    this.copy('public/index.jade', 'app/public/index.jade');

    this.mkdir('app/services/models');

    this.copy('app.js', 'app/app.js');

    this.copy('_Gruntfile.js', 'Gruntfile.js');

    this.copy('README.md', 'README.md');

    this.copy('_package.json', 'package.json');
    this.copy('bowerrc', '.bowerrc');
    this.copy('_bower.json', 'bower.json');
};

EdgeplateGenerator.prototype.layout = function layoutFiles() {
    this.copy('public/layout/_global.jade', 'app/public/layout/_global.jade');
    this.copy('public/layout/_page.jade', 'app/public/layout/_page.jade');
};

EdgeplateGenerator.prototype.components = function componentFiles() {
    this.copy('public/components/navbar/_navbar.scss', 'app/public/components/navbar/_navbar.scss');
    this.copy('public/components/navbar/navbar.jade', 'app/public/components/navbar/navbar.jade');
};

EdgeplateGenerator.prototype.directives = function directiveFiles() {
    this.mkdir('app/public/directives');
};

EdgeplateGenerator.prototype.images = function imageFiles() {
    this.mkdir('app/public/images');
};

EdgeplateGenerator.prototype.filters = function filterFiles() {
    this.mkdir('app/public/scripts/filters');
};

EdgeplateGenerator.prototype.services = function serviceFiles() {
    this.copy('public/scripts/services/edgePage.js', 'app/public/scripts/services/edgePage.js');
};

EdgeplateGenerator.prototype.scripts = function scriptFiles() {
    this.copy('public/scripts/app.js', 'app/public/scripts/app.js');
    this.copy('public/scripts/helper.js', 'app/public/scripts/helper.js');
};

EdgeplateGenerator.prototype.styles = function styleFiles() {
    this.mkdir('app/public/styles');
    this.copy('public/styles/_mixins.scss', 'app/public/styles/_mixins.scss');
    this.copy('public/styles/_styles.scss', 'app/public/styles/_styles.scss');
    this.copy('public/styles/_variables.scss', 'app/public/styles/_variables.scss');
    this.copy('public/styles/app.scss', 'app/public/styles/app.scss');
};

EdgeplateGenerator.prototype.controllers = function controllerFiles() {
    this.copy('public/controllers/App/AppController.js', 'app/public/controllers/App/AppController.js');
    this.copy('public/controllers/Body/BodyController.js', 'app/public/controllers/Body/BodyController.js');

    this.copy('public/controllers/pages/Dashboard/_Dashboard.scss', 'app/public/controllers/pages/Dashboard/_Dashboard.scss');
    this.copy('public/controllers/pages/Dashboard/DashboardController.js', 'app/public/controllers/pages/Dashboard/DashboardController.js');
    this.copy('public/controllers/pages/Dashboard/DashboardView.jade', 'app/public/controllers/pages/Dashboard/DashboardView.jade');
};

EdgeplateGenerator.prototype.projectfiles = function projectfiles() {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
    this.copy('gitignore', '.gitignore');
};
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const http = require('http')
const config = require('../config')

module.exports = {
  /**
   * Initialize the module to access REPL trailpack
   * Need to access to the log and config later
   */
    init (app){
    this.app = app
  },
  /**
   * Exectute a GET http request
   * @param url to fetch
   */
  get (url){
    this.request('get', url, null, null)
  },
  /**
   * Exectute a POST http request
   * @param url to fetch
   * @param params to send
   * @param contentType of the params (default to 'application/json')
   */
    post (url, params, contentType){
    contentType = contentType || 'application/json'
    this.request('post', url, params, contentType)
  },
  /**
   * Exectute a PUT http request
   * @param url to fetch
   * @param params to send
   * @param contentType of the params (default to 'application/json')
   */
    put (url, params, contentType){
    contentType = contentType || 'application/json'
    this.request('put', url, params, contentType)
  },
  /**
   * Exectute a DELETE http request
   * @param url to fetch
   */
    delete (url){
    this.request('delete', url, null, null)
  },
  /**
   * Exectute an http request
   * @param method to exectute (GET, POST, PUT, DELETE)
   * @param url to fetch
   * @param params to send
   * @param contentType of the params (default to 'application/json')
   */
    request (method, url, params, contentType) {
    const log = this.app.log

    if (!url.startsWith('/')) {
      url = '/' + url
    }

    const configExtends = _.extend(config, this.app.config.repl || {})

    const options = {
      host: 'localhost',
      port: this.app.config.web.port,
      method: method,
      path: url
    }

    if (params != null && typeof params != 'string') params = JSON.stringify(params)

    if (contentType != null) {
      options.headers = {
        'Content-Type': contentType,
        'Content-Length': Buffer.byteLength(params)
      }
    }

    const request = http.request(options, function (resp) {
      let body = ''
      resp.setEncoding(configExtends.httpEncoding)

      resp.on('data', function (chunk) {
        body += chunk
      })

      resp.on('end', function () {
        const response = JSON.parse(body)
        log.info(response)
      }.bind(this))

    }.bind(this)).on('error', function (e) {
      log.error('Got error: ' + e.message)
    }.bind(this))

    if (params) {
      request.write(params)
    }
    request.end()
  }
}
<commit_msg>Catch and print error when url doesn't return json<commit_after>'use strict'

const _ = require('lodash')
const http = require('http')
const config = require('../config')

module.exports = {
  /**
   * Initialize the module to access REPL trailpack
   * Need to access to the log and config later
   */
  init (app){
    this.app = app
  },
  /**
   * Exectute a GET http request
   * @param url to fetch
   */
  get (url){
    this.request('get', url, null, null)
  },
  /**
   * Exectute a POST http request
   * @param url to fetch
   * @param params to send
   * @param contentType of the params (default to 'application/json')
   */
  post (url, params, contentType){
    contentType = contentType || 'application/json'
    this.request('post', url, params, contentType)
  },
  /**
   * Exectute a PUT http request
   * @param url to fetch
   * @param params to send
   * @param contentType of the params (default to 'application/json')
   */
  put (url, params, contentType){
    contentType = contentType || 'application/json'
    this.request('put', url, params, contentType)
  },
  /**
   * Exectute a DELETE http request
   * @param url to fetch
   */
  delete (url){
    this.request('delete', url, null, null)
  },
  /**
   * Exectute an http request
   * @param method to exectute (GET, POST, PUT, DELETE)
   * @param url to fetch
   * @param params to send
   * @param contentType of the params (default to 'application/json')
   */
  request (method, url, params, contentType) {
    const log = this.app.log

    if (!url.startsWith('/')) {
      url = '/' + url
    }

    const configExtends = _.extend(config, this.app.config.repl || {})

    const options = {
      host: 'localhost',
      port: this.app.config.web.port,
      method: method,
      path: url
    }

    if (params != null && typeof params != 'string') params = JSON.stringify(params)

    if (contentType != null) {
      options.headers = {
        'Content-Type': contentType,
        'Content-Length': Buffer.byteLength(params)
      }
    }

    const request = http.request(options, function (resp) {
      let body = ''
      resp.setEncoding(configExtends.httpEncoding)

      resp.on('data', function (chunk) {
        body += chunk
      })

      resp.on('end', function () {
        try {
          const response = JSON.parse(body)
          log.info(response)
        }
        catch (e) {
          log.info(resp.statusCode, body)
        }
      }.bind(this))

    }.bind(this)).on('error', function (e) {
      log.error('Got error: ' + e.message)
    }.bind(this))

    if (params) {
      request.write(params)
    }
    request.end()
  }
}
<|endoftext|>


<commit_before>"use strict";

var http, url, get, toJSON, CGDS;

http = require("http");
url = require("url");

get = function (uri, callback) {
    var options;
    options = url.parse(uri);
    http.get(options, function (res) {
        var body;
        body = new Buffer(0);
        res.on("data", function (chunk) {
            var buffer;
            buffer = new Buffer(body.length + chunk.length);
            body.copy(buffer);
            chunk.copy(buffer, body.length);
            body = buffer;
        });
        res.on("end", function () {
            callback(null, body.toString("utf8"));
        });
    });
};

toJSON = function (data) {
    var lines, columns;
 // Split lines.
    lines = data.split(/\r?\n/);
 // Drop comments.
    lines = lines.filter(function (line) {
        if (line.charAt(0) === "#") {
            return false;
        } else {
            return true;
        }
    });
 // Convert to JSON.
    columns = lines.shift().split(/\t/);
    lines = lines.map(function (line) {
        var obj;
        obj = {};
        line.split(/\t/).forEach(function (column, idx) {
            obj[columns[idx]] = column;
        });
        return obj;
    });
    return lines;
};

CGDS = function (url) {
    if (typeof url === "string") {
        this.url = url;
    } else if (url !== null && typeof url === "object" && url.hasOwnProperty("url") === true) {
        this.url = url.url;
    } else {
        throw new Error("Please provide a URL parameter.");
    }
};

CGDS.prototype.getTypesOfCancer = function (callback) {
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getTypesOfCancer", function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getCancerStudies = function (callback) {
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getCancerStudies", function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getGeneticProfiles = function (cancerStudyId, callback) {
    if (cancerStudyId === undefined) {
        throw new Error("Please provide a cancer_study_id parameter.");
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getGeneticProfiles&cancer_study_id=" + cancerStudyId, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getCaseLists = function (cancerStudyId, callback) {
    if (cancerStudyId === undefined) {
        throw new Error("Please provide a cancer_study_id parameter.");
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getCaseLists&cancer_study_id=" + cancerStudyId, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getProfileData = function (caseSetId, geneticProfileId, geneList, callback) {
    if (caseSetId === undefined) {
        throw new Error("Please provide a case_set_id parameter.");
    }
    if (geneticProfileId === undefined) {
        throw new Error("Please provide a genetic_profile_id parameter.");
    }
    if (geneList === undefined) {
        throw new Error("Please provide a gene_list parameter.");
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    if (Array.isArray(geneticProfileId) && Array.isArray(geneList)) {
        throw new Error("You can specify multiple genes or multiple genetic profiles, but not both at once!");
    }
 // Convert geneticProfileId to string.
    if (Array.isArray(geneticProfileId) === true) {
        geneticProfileId = geneticProfileId.join("+");
    }
 // Convert geneList to string.
    if (Array.isArray(geneList) === true) {
        geneList = geneList.join("+");
    }
    get(this.url + "?cmd=getProfileData&case_set_id=" + caseSetId + "&genetic_profile_id=" + geneticProfileId + "&gene_list=" + geneList, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getMutationData = function (geneticProfileId, geneList, caseSetId, callback) {
    var url;
    if (geneticProfileId === undefined) {
        throw new Error("Please provide a genetic_profile_id parameter.");
    }
    if (geneList === undefined) {
        throw new Error("Please provide a gene_list parameter.");
    }
    if (typeof caseSetId === "function") {
        callback = caseSetId;
        caseSetId = undefined;
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
 // Convert geneticProfileId to string.
    if (Array.isArray(geneticProfileId) === true) {
        geneticProfileId = geneticProfileId.join("+");
    }
 // Convert geneList to string.
    if (Array.isArray(geneList) === true) {
        geneList = geneList.join("+");
    }
    url = this.url + "?cmd=getMutationData&genetic_profile_id=" + geneticProfileId + "&gene_list=" + geneList;
    if (caseSetId !== undefined) {
        url = url + "&case_set_id=" + caseSetId;
    }
    get(url, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getClinicalData = function (caseSetId, callback) {
    if (caseSetId === undefined) {
        throw new Error("Please provide a case_set_id parameter.");
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getClinicalData&case_set_id=" + caseSetId, function (err, res) {
        callback(null, toJSON(res));
    });
};

module.exports = CGDS;
<commit_msg>Add possibility to add proxy.<commit_after>"use strict";

var http, url, get, toJSON, CGDS;

http = require("http");
url = require("url");

get = function (uri, proxy, callback) {
    var options;
    if (typeof proxy === "function") {
        callback = proxy;
        proxy = undefined;
    }
    if (proxy !== undefined) {
        options = url.parse(proxy + encodeURIComponent(uri));
    } else {
        options = url.parse(uri);
    }
    http.get(options, function (res) {
        var body;
        body = new Buffer(0);
        res.on("data", function (chunk) {
            var buffer;
            buffer = new Buffer(body.length + chunk.length);
            body.copy(buffer);
            chunk.copy(buffer, body.length);
            body = buffer;
        });
        res.on("end", function () {
            callback(null, body.toString("utf8"));
        });
    });
};

toJSON = function (data) {
    var lines, columns;
 // Split lines.
    lines = data.split(/\r?\n/);
 // Drop comments.
    lines = lines.filter(function (line) {
        if (line.charAt(0) === "#") {
            return false;
        } else {
            return true;
        }
    });
 // Convert to JSON.
    columns = lines.shift().split(/\t/);
    lines = lines.map(function (line) {
        var obj;
        obj = {};
        line.split(/\t/).forEach(function (column, idx) {
            obj[columns[idx]] = column;
        });
        return obj;
    });
    return lines;
};

CGDS = function (url) {
    if (typeof url === "string") {
        this.url = url;
    } else if (url !== null && typeof url === "object" && url.hasOwnProperty("url") === true) {
        this.url = url.url;
        if (url.hasOwnProperty("proxy") === true) {
            this.proxy = url.proxy;
        }
    } else {
        throw new Error("Please provide a URL parameter.");
    }
};

CGDS.prototype.getTypesOfCancer = function (callback) {
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getTypesOfCancer", this.proxy, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getCancerStudies = function (callback) {
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getCancerStudies", this.proxy, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getGeneticProfiles = function (cancerStudyId, callback) {
    if (cancerStudyId === undefined) {
        throw new Error("Please provide a cancer_study_id parameter.");
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getGeneticProfiles&cancer_study_id=" + cancerStudyId, this.proxy, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getCaseLists = function (cancerStudyId, callback) {
    if (cancerStudyId === undefined) {
        throw new Error("Please provide a cancer_study_id parameter.");
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getCaseLists&cancer_study_id=" + cancerStudyId, this.proxy, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getProfileData = function (caseSetId, geneticProfileId, geneList, callback) {
    if (caseSetId === undefined) {
        throw new Error("Please provide a case_set_id parameter.");
    }
    if (geneticProfileId === undefined) {
        throw new Error("Please provide a genetic_profile_id parameter.");
    }
    if (geneList === undefined) {
        throw new Error("Please provide a gene_list parameter.");
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    if (Array.isArray(geneticProfileId) && Array.isArray(geneList)) {
        throw new Error("You can specify multiple genes or multiple genetic profiles, but not both at once!");
    }
 // Convert geneticProfileId to string.
    if (Array.isArray(geneticProfileId) === true) {
        geneticProfileId = geneticProfileId.join("+");
    }
 // Convert geneList to string.
    if (Array.isArray(geneList) === true) {
        geneList = geneList.join("+");
    }
    get(this.url + "?cmd=getProfileData&case_set_id=" + caseSetId + "&genetic_profile_id=" + geneticProfileId + "&gene_list=" + geneList, this.proxy, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getMutationData = function (geneticProfileId, geneList, caseSetId, callback) {
    var url;
    if (geneticProfileId === undefined) {
        throw new Error("Please provide a genetic_profile_id parameter.");
    }
    if (geneList === undefined) {
        throw new Error("Please provide a gene_list parameter.");
    }
    if (typeof caseSetId === "function") {
        callback = caseSetId;
        caseSetId = undefined;
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
 // Convert geneticProfileId to string.
    if (Array.isArray(geneticProfileId) === true) {
        geneticProfileId = geneticProfileId.join("+");
    }
 // Convert geneList to string.
    if (Array.isArray(geneList) === true) {
        geneList = geneList.join("+");
    }
    url = this.url + "?cmd=getMutationData&genetic_profile_id=" + geneticProfileId + "&gene_list=" + geneList;
    if (caseSetId !== undefined) {
        url = url + "&case_set_id=" + caseSetId;
    }
    get(url, this.proxy, function (err, res) {
        callback(null, toJSON(res));
    });
};

CGDS.prototype.getClinicalData = function (caseSetId, callback) {
    if (caseSetId === undefined) {
        throw new Error("Please provide a case_set_id parameter.");
    }
    if (callback === undefined) {
        throw new Error("Please provide a callback parameter.");
    }
    get(this.url + "?cmd=getClinicalData&case_set_id=" + caseSetId, this.proxy, function (err, res) {
        callback(null, toJSON(res));
    });
};

module.exports = CGDS;
<|endoftext|>


<commit_before>function determineIfTrump(url, callback, errorCallback){

	var x = new XMLHttpRequest();
	x.open('GET', "https://ec2-52-50-209-51.eu-west-1.compute.amazonaws.com/" + url);
	x.responseType = 'json';

	x.onload = function(){
		var response = x.response;

		if(!response){
			errorCallback();
		}

		callback(response);
	}

	x.onerror = function(){
		errorCallback();
	}

	x.send();
1
}

$(document).ready(function() {
    $('img').each(function(index, image){
    	$(image).load(function(){
    		console.log("loaded");
	        var url = $(image).attr('src');

	        var original_style = $(image).html();
	        var width = $(image).width();
	        var height= $(image).height();
	        var hourglass = chrome.extension.getURL("hourglass.gif");

	        var replacement = "

";
	        console.log(replacement);

	        $(image).replaceWith(replacement);

	        // $(image).attr("style", "background:url(" + url + ")");
	        // $(image).attr("src", chrome.extension.getURL("hourglass.gif"));

	        determineIfTrump(url, function(response){
	        	if (response.isTrump == true){
	        		$(image).attr('src', response.cat);
	        	}
	        	$(image).replaceWith(original_style);
	        }, function(){
	           	$(image).replaceWith(original_style);
        	})
    	});
	});
});<commit_msg>best till now<commit_after>function determineIfTrump(url, callback, errorCallback){

	var x = new XMLHttpRequest();
	x.open('GET', "https://ec2-52-50-209-51.eu-west-1.compute.amazonaws.com/" + url);
	x.responseType = 'json';

	x.onload = function(){
		var response = x.response;

		if(!response){
			errorCallback();
		}

		callback(response);
	}

	x.onerror = function(){
		errorCallback();
	}

	x.send();
1
}

$(document).ready(function() {
    $('img').each(function(index, image){
        var url = $(image).attr('src');

        var original_style = $(image).attr("style");
        $(image).attr("style", "background:url(" + url + ")");
        $(image).attr("src", chrome.extension.getURL("hourglass.gif"));

        determineIfTrump(url, function(response){
        	if (response.isTrump == true){
        		$(image).attr('src', response.cat);
        	}
        	else{
        		$(image).attr("src",  url);
        	}
        	$(image).attr("style", original_style);
        }, function(){

        	$(image).attr("style", original_style);
        	$(image).attr("src", url);
        })
    });
});<|endoftext|>