<commit_before>/**
 * BMotion Studio for ProB Observer Module
 *
 */
define(['prob.api', 'angular', 'jquery', 'xeditable', 'qtip'], function (prob) {

    function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }

    var guid = (function () {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        return function () {
            return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
                s4() + '-' + s4() + s4() + s4();
        };
    })();

    return angular.module('prob.observers', ['bms.main'])
        .service('bmsObserverService', ['$q', '$injector', function ($q, $injector) {
            var observers = {};
            var events = {};
            var bmsidCache = {};
            var observerService = {
                addObserver: function (name, o) {
                    if (observers[name] === undefined) {
                        observers[name] = [];
                    }
                    var no = $.extend({cause: "AnimationChanged"}, o);
                    observers[name].push(no);
                },
                addEvent: function (name, e) {
                    if (events[name] === undefined) {
                        events[name] = [];
                    }
                    events[name].push(e);
                },
                addObservers: function (name, obs) {
                    if (observers[name] === undefined) {
                        observers[name] = [];
                    }
                    if (obs) {
                        $.each(obs, function (i, v) {
                            observerService.addObserver(name, v)
                        });
                    }
                },
                addEvents: function (name, evts) {
                    if (events[name] === undefined) {
                        events[name] = [];
                    }
                    if (evts) {
                        $.each(evts, function (i, v) {
                            observerService.addEvent(name, v)
                        });
                    }
                },
                getObservers: function (name) {
                    return observers[name];
                },
                getBmsIds: function (selector, element) {
                    var bmsid = element.attr("data-bms-id");
                    if (bmsidCache[bmsid] === undefined) {
                        bmsidCache[bmsid] = {};
                    }
                    if (bmsidCache[bmsid][selector] === undefined) {
                        var bmsids = $(element).find(selector).map(function () {
                            return $(this).attr("data-bms-id");
                        });
                        bmsidCache[bmsid][selector] = bmsids;
                    }
                    return bmsidCache[bmsid][selector];
                },
                checkObserver: function (observer, container, stateid) {
                    var defer = $q.defer();
                    var observerInstance = $injector.get(observer.type, "");
                    if (observerInstance) {
                        observerInstance.check(observer, container, stateid).then(function (data) {
                            defer.resolve(data);
                        });
                    }
                    return defer.promise;
                },
                checkObservers: function (observers, container, stateid) {

                    var defer = $q.defer();

                    var formulaObservers = [];
                    var predicateObservers = [];
                    var promises = [];

                    angular.forEach(observers, function (o) {
                        if (o.type === 'formula') {
                            formulaObservers.push(o);
                        } else if (o.type === 'predicate') {
                            predicateObservers.push(o);
                        } else {
                            var observerInstance = $injector.get(o.type, "");
                            if (observerInstance) {
                                promises.push(observerInstance.check(o, container, stateid));
                            }
                        }
                    });

                    // Special case for formula observers
                    if (!$.isEmptyObject(formulaObservers)) {
                        // Execute formula observer at once (performance boost)
                        var observerInstance = $injector.get("formula", "");
                        promises.push(observerInstance.check(formulaObservers, container, stateid));
                    }

                    // Special case for predicate observers
                    if (!$.isEmptyObject(predicateObservers)) {
                        // Execute predicate observer at once (performance boost)
                        var observerInstance = $injector.get("predicate", "");
                        promises.push(observerInstance.check(predicateObservers, container, stateid));
                    }

                    $q.all(promises).then(function (data) {
                        defer.resolve(data);
                    });

                    return defer.promise;

                }
            };
            return observerService;
        }])
        .service('csp-event', ['ws', '$q', 'bmsObserverService', function (ws, $q, bmsObserverService) {

            var replaceParameter = function (str, para) {
                var fstr = str;
                angular.forEach(para, function (p, i) {
                    var find = '{{a' + (i + 1) + '}}';
                    var re = new RegExp(find, 'g');
                    fstr = fstr.replace(re, p);
                });
                return fstr;
            };

            return {
                check: function (observer, element, stateid) {

                    var defer = $q.defer();
                    ws.emit("observeCSPTrace", {
                        data: {
                            observers: observer.data.observers,
                            stateid: stateid
                        }
                    }, function (result) {

                        var fmap = {};

                        angular.forEach(result.ops, function (t) {

                            angular.forEach(observer.data.observers, function (o) {

                                var exprArray = result.exp[o.exp].replace("{", "").replace("}", "").split(",");

                                if ($.inArray(t.name, exprArray) > -1) {

                                    angular.forEach(o.actions, function (a) {

                                        var selector = replaceParameter(a.selector, t.parameter);
                                        var attr = replaceParameter(a.attr, t.parameter);
                                        var value = replaceParameter(a.value, t.parameter);
                                        var bmsids = bmsObserverService.getBmsIds(selector, element);
                                        angular.forEach(bmsids, function (id) {
                                            if (fmap[id] === undefined) {
                                                fmap[id] = {};
                                            }
                                            fmap[id][attr] = value;
                                        });

                                    });

                                }

                            });

                        });
                        defer.resolve(fmap);
                    });

                    return defer.promise;
                }
            }
        }])
        .service('formula', ['ws', '$q', 'bmsObserverService', function (ws, $q, bmsObserverService) {

            var formulaObserver = {
                getFormulas: function (observer) {
                    return observer.data.formulas;
                },
                apply: function (observer, container, result) {
                    var defer = $q.defer();
                    if (observer.data.trigger !== undefined) {
                        var element = container.find("[data-bms-id=" + observer.bmsid + "]");
                        observer.data.trigger.call(this, $(element), result);
                        defer.resolve();
                    } else if (observer.data.getChanges !== undefined) {
                        var obj = {};
                        var rr = observer.data.getChanges.call(this, result);
                        if (rr) {
                            var bmsids = bmsObserverService.getBmsIds(observer.data.selector, container);
                            angular.forEach(bmsids, function (id) {
                                obj[id] = rr;
                            });
                        }
                        defer.resolve(obj);
                    } else {
                        defer.resolve();
                    }
                    return defer.promise;
                },
                check: function (observer, element, stateid) {

                    var defer = $q.defer();

                    if (Object.prototype.toString.call(observer) === '[object Array]') {

                        var oo = {};
                        angular.forEach(observer, function (o) {
                            angular.forEach(o.data.formulas, function (f) {
                                oo[f] = {};
                                // TODO: handle translate property ...
                            });
                        });
                        ws.emit("observe", {data: {observers: oo, stateId: stateid}}, function (data) {
                            var promises = [];
                            $.each(observer, function (i, o) {
                                var ff = [];
                                angular.forEach(o.data.formulas, function (f) {
                                    ff.push(data[f] ? data[f].result : null);
                                });
                                promises.push(formulaObserver.apply(o, element, ff));
                            });
                            var fvalues = {};
                            $q.all(promises).then(function (data) {
                                angular.forEach(data, function (value) {
                                    if (value !== undefined) {
                                        $.extend(true, fvalues, value);
                                    }
                                });
                                defer.resolve(fvalues);
                            });
                        });

                    } else {

                        var oo = {};
                        angular.forEach(observer.data.formulas, function (f) {
                            oo[f] = {};
                            // TODO: handle translate property ...
                        });

                        ws.emit("observe", {data: {observers: oo, stateId: stateid}}, function (res) {

                            var ff = [];
                            angular.forEach(observer.data.formulas, function (f) {
                                ff.push(res[f] ? res[f].result : null);
                            });
                            formulaObserver.apply(observer, element, ff).then(function (data) {
                                var fvalues = {};
                                angular.forEach(data, function (value) {
                                    if (value !== undefined) {
                                        $.extend(true, fvalues, value);
                                    }
                                });
                                defer.resolve(fvalues);
                            });

                        });

                    }

                    return defer.promise;

                }
            };

            return formulaObserver;

        }])
        .service('refinement', ['ws', '$q', 'bmsObserverService', function (ws, $q, bmsObserverService) {

            return {
                check: function (observer, element, stateid) {

                    var defer = $q.defer();

                    ws.emit("observeRefinement", {data: observer.data}, function (data) {

                        var obj = {};
                        var rr;

                        $.each(observer.data.refinements, function (i, v) {
                            if ($.inArray(v, data.refinements) > -1) {
                                rr = observer.data.enable;
                            } else {
                                rr = observer.data.disable;
                            }
                        });

                        if (rr) {
                            obj[observer.bmsid] = rr
                        }

                        defer.resolve(obj);

                    });

                    return defer.promise;
                }
            }

        }])
        .service('predicate', ['ws', '$q', 'bmsObserverService', function (ws, $q, bmsObserverService) {

            var observePredicateHelper = function (tf, element, observer) {
                if (Object.prototype.toString.call(tf) === '[object Object]') {
                    return tf;
                } else if (isFunction(tf)) {
                    var el = observer.element ? $(observer.element) : element.find(observer.data.selector);
                    el.each(function (i, v) {
                        tf.call(this, $(v))
                    });
                    return null;
                }
            };

            var predicateObserver = {

                getFormulas: function (observer) {
                    return [observer.data.predicate];
                },
                apply: function (observer, element, result) {
                    var defer = $q.defer();
                    var rr = {};
                    if (result[0] === "TRUE") {
                        rr = observePredicateHelper(observer.data.true, element, observer);
                    } else if (result[0] === "FALSE") {
                        rr = observePredicateHelper(observer.data.false, element, observer);
                    }
                    var obj = {};
                    if (rr) {
                        obj[observer.bmsid] = rr;
                    }
                    defer.resolve(obj);
                    return defer.promise;
                },
                check: function (observers, element, stateid) {
                    var defer = $q.defer();
                    var oo = {};
                    $.each(observers, function (i, o) {
                        oo[o.data.predicate] = {};
                    });
                    var promises = [];
                    //var startWebsocket = new Date().getTime();
                    ws.emit("observe", {data: {observers: oo, stateId: stateid}}, function (data) {
                        //var end = new Date().getTime();
                        //var time = end - startWebsocket;
                        //console.log('WEBSOCKET: ' + time);
                        //var startPredicate = new Date().getTime();
                        angular.forEach(observers, function (o) {
                            var r = data[o.data.predicate];
                            if (r) {
                                promises.push(predicateObserver.apply(o, element, [r.result]));
                            }
                        });
                        //var endPredicate = new Date().getTime();
                        //var time = endPredicate - startPredicate;
                        //console.log('PREDICATE OBSERVER: ' + time);
                        var fvalues = {};
                        $q.all(promises).then(function (data) {
                            angular.forEach(data, function (value) {
                                if (value !== undefined) {
                                    $.extend(true, fvalues, value);
                                }
                            });
                            defer.resolve(fvalues);
                        });
                    });
                    return defer.promise;
                }
            };

            return predicateObserver;

        }])
        .service('executeEvent', ['ws', '$q', function (ws, $q) {

            var ev = {

                executeEvent: function (data, origin) {
                    var settings = prob.normalize($.extend({
                        events: [],
                        callback: function () {
                        }
                    }, data), ["callback"], origin);
                    ws.emit("executeEvent", {data: settings}, function (result) {
                        settings.callback.call(this, result)
                    });
                    return settings
                },
                getTooltipContent: function (data, origin, api) {
                    var defer = $q.defer();
                    ws.emit('initTooltip', {
                        data: prob.normalize(data, ["callback"], origin)
                    }, function (data) {
                        var container = $('

');
                        $.each(data.events, function (i, v) {
                            var spanClass = v.canExecute ? 'glyphicon glyphicon-ok-circle' : 'glyphicon glyphicon-remove-circle'
                            var span = $('').addClass(spanClass);
                            var link = $(' ' + v.name + '(' + v.predicate + ')');
                            if (v.canExecute) {
                                link = $(' ' + v.name + '(' + v.predicate + ')').click(function () {
                                    ev.executeEvent({
                                        events: [{name: v.name, predicate: v.predicate}],
                                        callback: function () {
                                            api.hide();
                                        }
                                    })
                                });
                            }
                            container.append($('

').addClass(v.canExecute ? 'enabled' : 'disabled').append(span, link))
                        });
                        defer.resolve(container);
                    });
                    return defer.promise;
                },
                setup: function (event, element) {

                    var defer = $q.defer();

                    var settings = $.extend({
                        events: [],
                        tooltip: true,
                        callback: function () {
                        }
                    }, event.data);

                    var el = event.element ? $(event.element) : $(element).find(settings.selector);
                    el.each(function (i2, v) {
                        var e = $(v);
                        e.click(function (event) {
                            $(e).qtip('hide');
                            ev.executeEvent(settings, $(event.target));
                        }).css('cursor', 'pointer');
                        if (settings.tooltip) {
                            e.qtip({ // Grab some elements to apply the tooltip to
                                content: {
                                    text: function (event, api) {
                                        return ev.getTooltipContent(settings, event.target, api).then(function (container) {
                                            return container;
                                        });
                                    }
                                },
                                position: {
                                    my: 'bottom left',
                                    at: 'top right',
                                    effect: false
                                },
                                show: {
                                    delay: 600
                                },
                                hide: {
                                    fixed: true,
                                    delay: 300

                                },
                                style: {
                                    classes: 'qtip-light qtip-bootstrap'
                                }
                            });
                        }
                        defer.resolve();
                    });
                    return defer.promise;
                }
            };

            return ev;

        }]);

});<commit_msg>set viewport for tooltip<commit_after>/**
 * BMotion Studio for ProB Observer Module
 *
 */
define(['prob.api', 'angular', 'jquery', 'xeditable', 'qtip'], function (prob) {

    function isFunction(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }

    var guid = (function () {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        return function () {
            return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
                s4() + '-' + s4() + s4() + s4();
        };
    })();

    return angular.module('prob.observers', ['bms.main'])
        .service('bmsObserverService', ['$q', '$injector', function ($q, $injector) {
            var observers = {};
            var events = {};
            var bmsidCache = {};
            var observerService = {
                addObserver: function (name, o) {
                    if (observers[name] === undefined) {
                        observers[name] = [];
                    }
                    var no = $.extend({cause: "AnimationChanged"}, o);
                    observers[name].push(no);
                },
                addEvent: function (name, e) {
                    if (events[name] === undefined) {
                        events[name] = [];
                    }
                    events[name].push(e);
                },
                addObservers: function (name, obs) {
                    if (observers[name] === undefined) {
                        observers[name] = [];
                    }
                    if (obs) {
                        $.each(obs, function (i, v) {
                            observerService.addObserver(name, v)
                        });
                    }
                },
                addEvents: function (name, evts) {
                    if (events[name] === undefined) {
                        events[name] = [];
                    }
                    if (evts) {
                        $.each(evts, function (i, v) {
                            observerService.addEvent(name, v)
                        });
                    }
                },
                getObservers: function (name) {
                    return observers[name];
                },
                getBmsIds: function (selector, element) {
                    var bmsid = element.attr("data-bms-id");
                    if (bmsidCache[bmsid] === undefined) {
                        bmsidCache[bmsid] = {};
                    }
                    if (bmsidCache[bmsid][selector] === undefined) {
                        var bmsids = $(element).find(selector).map(function () {
                            return $(this).attr("data-bms-id");
                        });
                        bmsidCache[bmsid][selector] = bmsids;
                    }
                    return bmsidCache[bmsid][selector];
                },
                checkObserver: function (observer, container, stateid) {
                    var defer = $q.defer();
                    var observerInstance = $injector.get(observer.type, "");
                    if (observerInstance) {
                        observerInstance.check(observer, container, stateid).then(function (data) {
                            defer.resolve(data);
                        });
                    }
                    return defer.promise;
                },
                checkObservers: function (observers, container, stateid) {

                    var defer = $q.defer();

                    var formulaObservers = [];
                    var predicateObservers = [];
                    var promises = [];

                    angular.forEach(observers, function (o) {
                        if (o.type === 'formula') {
                            formulaObservers.push(o);
                        } else if (o.type === 'predicate') {
                            predicateObservers.push(o);
                        } else {
                            var observerInstance = $injector.get(o.type, "");
                            if (observerInstance) {
                                promises.push(observerInstance.check(o, container, stateid));
                            }
                        }
                    });

                    // Special case for formula observers
                    if (!$.isEmptyObject(formulaObservers)) {
                        // Execute formula observer at once (performance boost)
                        var observerInstance = $injector.get("formula", "");
                        promises.push(observerInstance.check(formulaObservers, container, stateid));
                    }

                    // Special case for predicate observers
                    if (!$.isEmptyObject(predicateObservers)) {
                        // Execute predicate observer at once (performance boost)
                        var observerInstance = $injector.get("predicate", "");
                        promises.push(observerInstance.check(predicateObservers, container, stateid));
                    }

                    $q.all(promises).then(function (data) {
                        defer.resolve(data);
                    });

                    return defer.promise;

                }
            };
            return observerService;
        }])
        .service('csp-event', ['ws', '$q', 'bmsObserverService', function (ws, $q, bmsObserverService) {

            var replaceParameter = function (str, para) {
                var fstr = str;
                angular.forEach(para, function (p, i) {
                    var find = '{{a' + (i + 1) + '}}';
                    var re = new RegExp(find, 'g');
                    fstr = fstr.replace(re, p);
                });
                return fstr;
            };

            return {
                check: function (observer, element, stateid) {

                    var defer = $q.defer();
                    ws.emit("observeCSPTrace", {
                        data: {
                            observers: observer.data.observers,
                            stateid: stateid
                        }
                    }, function (result) {

                        var fmap = {};

                        angular.forEach(result.ops, function (t) {

                            angular.forEach(observer.data.observers, function (o) {

                                var exprArray = result.exp[o.exp].replace("{", "").replace("}", "").split(",");

                                if ($.inArray(t.name, exprArray) > -1) {

                                    angular.forEach(o.actions, function (a) {

                                        var selector = replaceParameter(a.selector, t.parameter);
                                        var attr = replaceParameter(a.attr, t.parameter);
                                        var value = replaceParameter(a.value, t.parameter);
                                        var bmsids = bmsObserverService.getBmsIds(selector, element);
                                        angular.forEach(bmsids, function (id) {
                                            if (fmap[id] === undefined) {
                                                fmap[id] = {};
                                            }
                                            fmap[id][attr] = value;
                                        });

                                    });

                                }

                            });

                        });
                        defer.resolve(fmap);
                    });

                    return defer.promise;
                }
            }
        }])
        .service('formula', ['ws', '$q', 'bmsObserverService', function (ws, $q, bmsObserverService) {

            var formulaObserver = {
                getFormulas: function (observer) {
                    return observer.data.formulas;
                },
                apply: function (observer, container, result) {
                    var defer = $q.defer();
                    if (observer.data.trigger !== undefined) {
                        var element = container.find("[data-bms-id=" + observer.bmsid + "]");
                        observer.data.trigger.call(this, $(element), result);
                        defer.resolve();
                    } else if (observer.data.getChanges !== undefined) {
                        var obj = {};
                        var rr = observer.data.getChanges.call(this, result);
                        if (rr) {
                            var bmsids = bmsObserverService.getBmsIds(observer.data.selector, container);
                            angular.forEach(bmsids, function (id) {
                                obj[id] = rr;
                            });
                        }
                        defer.resolve(obj);
                    } else {
                        defer.resolve();
                    }
                    return defer.promise;
                },
                check: function (observer, element, stateid) {

                    var defer = $q.defer();

                    if (Object.prototype.toString.call(observer) === '[object Array]') {

                        var oo = {};
                        angular.forEach(observer, function (o) {
                            angular.forEach(o.data.formulas, function (f) {
                                oo[f] = {};
                                // TODO: handle translate property ...
                            });
                        });
                        ws.emit("observe", {data: {observers: oo, stateId: stateid}}, function (data) {
                            var promises = [];
                            $.each(observer, function (i, o) {
                                var ff = [];
                                angular.forEach(o.data.formulas, function (f) {
                                    ff.push(data[f] ? data[f].result : null);
                                });
                                promises.push(formulaObserver.apply(o, element, ff));
                            });
                            var fvalues = {};
                            $q.all(promises).then(function (data) {
                                angular.forEach(data, function (value) {
                                    if (value !== undefined) {
                                        $.extend(true, fvalues, value);
                                    }
                                });
                                defer.resolve(fvalues);
                            });
                        });

                    } else {

                        var oo = {};
                        angular.forEach(observer.data.formulas, function (f) {
                            oo[f] = {};
                            // TODO: handle translate property ...
                        });

                        ws.emit("observe", {data: {observers: oo, stateId: stateid}}, function (res) {

                            var ff = [];
                            angular.forEach(observer.data.formulas, function (f) {
                                ff.push(res[f] ? res[f].result : null);
                            });
                            formulaObserver.apply(observer, element, ff).then(function (data) {
                                var fvalues = {};
                                angular.forEach(data, function (value) {
                                    if (value !== undefined) {
                                        $.extend(true, fvalues, value);
                                    }
                                });
                                defer.resolve(fvalues);
                            });

                        });

                    }

                    return defer.promise;

                }
            };

            return formulaObserver;

        }])
        .service('refinement', ['ws', '$q', 'bmsObserverService', function (ws, $q, bmsObserverService) {

            return {
                check: function (observer, element, stateid) {

                    var defer = $q.defer();

                    ws.emit("observeRefinement", {data: observer.data}, function (data) {

                        var obj = {};
                        var rr;

                        $.each(observer.data.refinements, function (i, v) {
                            if ($.inArray(v, data.refinements) > -1) {
                                rr = observer.data.enable;
                            } else {
                                rr = observer.data.disable;
                            }
                        });

                        if (rr) {
                            obj[observer.bmsid] = rr
                        }

                        defer.resolve(obj);

                    });

                    return defer.promise;
                }
            }

        }])
        .service('predicate', ['ws', '$q', 'bmsObserverService', function (ws, $q, bmsObserverService) {

            var observePredicateHelper = function (tf, element, observer) {
                if (Object.prototype.toString.call(tf) === '[object Object]') {
                    return tf;
                } else if (isFunction(tf)) {
                    var el = observer.element ? $(observer.element) : element.find(observer.data.selector);
                    el.each(function (i, v) {
                        tf.call(this, $(v))
                    });
                    return null;
                }
            };

            var predicateObserver = {

                getFormulas: function (observer) {
                    return [observer.data.predicate];
                },
                apply: function (observer, element, result) {
                    var defer = $q.defer();
                    var rr = {};
                    if (result[0] === "TRUE") {
                        rr = observePredicateHelper(observer.data.true, element, observer);
                    } else if (result[0] === "FALSE") {
                        rr = observePredicateHelper(observer.data.false, element, observer);
                    }
                    var obj = {};
                    if (rr) {
                        obj[observer.bmsid] = rr;
                    }
                    defer.resolve(obj);
                    return defer.promise;
                },
                check: function (observers, element, stateid) {
                    var defer = $q.defer();
                    var oo = {};
                    $.each(observers, function (i, o) {
                        oo[o.data.predicate] = {};
                    });
                    var promises = [];
                    //var startWebsocket = new Date().getTime();
                    ws.emit("observe", {data: {observers: oo, stateId: stateid}}, function (data) {
                        //var end = new Date().getTime();
                        //var time = end - startWebsocket;
                        //console.log('WEBSOCKET: ' + time);
                        //var startPredicate = new Date().getTime();
                        angular.forEach(observers, function (o) {
                            var r = data[o.data.predicate];
                            if (r) {
                                promises.push(predicateObserver.apply(o, element, [r.result]));
                            }
                        });
                        //var endPredicate = new Date().getTime();
                        //var time = endPredicate - startPredicate;
                        //console.log('PREDICATE OBSERVER: ' + time);
                        var fvalues = {};
                        $q.all(promises).then(function (data) {
                            angular.forEach(data, function (value) {
                                if (value !== undefined) {
                                    $.extend(true, fvalues, value);
                                }
                            });
                            defer.resolve(fvalues);
                        });
                    });
                    return defer.promise;
                }
            };

            return predicateObserver;

        }])
        .service('executeEvent', ['ws', '$q', function (ws, $q) {

            var ev = {

                executeEvent: function (data, origin) {
                    var settings = prob.normalize($.extend({
                        events: [],
                        callback: function () {
                        }
                    }, data), ["callback"], origin);
                    ws.emit("executeEvent", {data: settings}, function (result) {
                        settings.callback.call(this, result)
                    });
                    return settings
                },
                getTooltipContent: function (data, origin, api) {
                    var defer = $q.defer();
                    ws.emit('initTooltip', {
                        data: prob.normalize(data, ["callback"], origin)
                    }, function (data) {
                        var container = $('

');
                        $.each(data.events, function (i, v) {
                            var spanClass = v.canExecute ? 'glyphicon glyphicon-ok-circle' : 'glyphicon glyphicon-remove-circle'
                            var span = $('').addClass(spanClass);
                            var link = $(' ' + v.name + '(' + v.predicate + ')');
                            if (v.canExecute) {
                                link = $(' ' + v.name + '(' + v.predicate + ')').click(function () {
                                    ev.executeEvent({
                                        events: [{name: v.name, predicate: v.predicate}],
                                        callback: function () {
                                            api.hide();
                                        }
                                    })
                                });
                            }
                            container.append($('

').addClass(v.canExecute ? 'enabled' : 'disabled').append(span, link))
                        });
                        defer.resolve(container);
                    });
                    return defer.promise;
                },
                setup: function (event, element) {

                    var defer = $q.defer();

                    var settings = $.extend({
                        events: [],
                        tooltip: true,
                        callback: function () {
                        }
                    }, event.data);

                    var el = event.element ? $(event.element) : $(element).find(settings.selector);
                    el.each(function (i2, v) {
                        var e = $(v);
                        e.click(function (event) {
                            $(e).qtip('hide');
                            ev.executeEvent(settings, $(event.target));
                        }).css('cursor', 'pointer');
                        if (settings.tooltip) {
                            e.qtip({ // Grab some elements to apply the tooltip to
                                content: {
                                    text: function (event, api) {
                                        return ev.getTooltipContent(settings, event.target, api).then(function (container) {
                                            return container;
                                        });
                                    }
                                },
                                position: {
                                    my: 'bottom left',
                                    at: 'top right',
                                    effect: false,
                                    viewport: $(window)
                                },
                                show: {
                                    delay: 600
                                },
                                hide: {
                                    fixed: true,
                                    delay: 300

                                },
                                style: {
                                    classes: 'qtip-light qtip-bootstrap'
                                }
                            });
                        }
                        defer.resolve();
                    });
                    return defer.promise;
                }
            };

            return ev;

        }]);

});<|endoftext|>


<commit_before>(function() {
    function SongPlayer() {
        var SongPlayer = {};

        var currentSong = null;

        /**
		* @desc Buzz object audio file
		* @type {Object}
		*/
     	var currentBuzzObject = null;

     	/**
		* @function setSong
		* @desc Stops currently playing song and loads new audio file as currentBuzzObject
		* @param {Object} song
		*/
     	var setSong = function(song) {
		    if (currentBuzzObject) {
		        currentBuzzObject.stop();
		        currentSong.playing = null;
		    }

		    currentBuzzObject = new buzz.sound(song.audioUrl, {
		        formats: ['mp3'],
		        preload: true
		    });

		    currentSong = song;
		};

        SongPlayer.play = function(song) {
        	if (currentSong !== song) {
        		setSong(song);
		        currentBuzzObject.play();
		        song.playing = true;

        	} else if (currentSong === song) {

		        if (currentBuzzObject.isPaused()) {
		            currentBuzzObject.play();
		        }

		    }
	    };

	    SongPlayer.pause = function(song) {
		    currentBuzzObject.pause();
		    song.playing = false;
		};

        return SongPlayer;
    }

    angular
        .module('blocJams')
        .factory('SongPlayer', SongPlayer);
})();<commit_msg>Step 7 Assignment<commit_after>(function() {
    function SongPlayer() {
        var SongPlayer = {};

        var currentSong = null;

        /**
		* @desc Buzz object audio file
		* @type {Object}
		*/
     	var currentBuzzObject = null;

     	/**
		* @function setSong
		* @desc Stops currently playing song and loads new audio file as currentBuzzObject
		* @param {Object} song
		*/
     	var setSong = function(song) {
		    if (currentBuzzObject) {
		        currentBuzzObject.stop();
		        currentSong.playing = null;
		    }

		    currentBuzzObject = new buzz.sound(song.audioUrl, {
		        formats: ['mp3'],
		        preload: true
		    });

		    currentSong = song;
		};

		/**
		* @function playSong
		* @desc Plays the current Buzz object
		* @param {Object} song
		*/
		var playSong = function(song) {
			currentBuzzObject.play();
			song.playing = true;
		};

        SongPlayer.play = function(song) {
        	if (currentSong !== song) {
        		setSong(song);
		        playSong(song);

        	} else if (currentSong === song) {

		        if (currentBuzzObject.isPaused()) {
		            currentBuzzObject.play();
		        }

		    }
	    };

	    SongPlayer.pause = function(song) {
		    currentBuzzObject.pause();
		    song.playing = false;
		};

        return SongPlayer;
    }

    angular
        .module('blocJams')
        .factory('SongPlayer', SongPlayer);
})();<|endoftext|>


<commit_before>(function() {
	function SongPlayer() {

/**
* @desc (Public) Public name for SongPlayer object
* @type {Object}
*/
		var SongPlayer = {};
/**
* @desc (Private) Private name for 'current song' designated object
* @type {Object}
*/
		var currentSong = null;
/**
* @desc (Private) Buzz object audio file
* @type {Object}
*/
		var currentBuzzObject = null;
/**
* @function (Private) setSong
* @desc Stops currently playing song and loads new audio file as currentBuzzObject
* @param {Object} song
*/
		var setSong = function(song) {
			if (currentBuzzObject) {
				currentBuzzObject.stop();
				currentSong.playing = null;
			}
			currentBuzzObject = new buzz.sound(song.audioUrl,{
				formats: ['mp3'],
				preload: true
			});
			currentSong = song;
		};
/**
* @function (Private) playSong
* @desc Plays the current Buzz object and sets playing property of the song object to true
* @param {Object} song
*/
		var playSong = function(song){
			currentBuzzObject.play();
			song.playing = true;
		};
/**
* @function (Public) play
* @desc Plays a 'song' (new or current)
* @param {Object} song
*/
		SongPlayer.play = function(song) {
			if (currentSong !== song) {
				setSong(song);
				playSong(song);
			}
			else if (currentSong === song) {
				if (currentBuzzObject.isPaused()) {
					playSong(song);
				}
			}
		};
/**
* @function (Public) pause
* @desc Pauses a 'song' (new or current)
* @param {Object} song
*/
		SongPlayer.pause = function(song) {
			currentBuzzObject.pause();
			song.playing = false;
		};
		return SongPlayer;
	}

	angular
		.module('blocJams')
		.factory('SongPlayer', SongPlayer);
})();
//git checkout -b angular-checkpoint-8-Services-Part-3<commit_msg>Cleaning up 'SongPlayer.js' before movning onto Player Bar 'controller'...<commit_after>(function() {
	function SongPlayer() {

/**
* @desc (Public) Public name for SongPlayer object
* @type {Object}
*/
		var SongPlayer = {};
/**
* @desc (Private) Private name for 'current song' designated object
* @type {Object}
*/
		var currentSong = null;
/**
* @desc (Private) Buzz object audio file
* @type {Object}
*/
		var currentBuzzObject = null;
/**
* @function (Private) setSong
* @desc Stops currently playing song and loads new audio file as currentBuzzObject
* @param {Object} song
*/
		var setSong = function(song) {
			if (currentBuzzObject) {
				currentBuzzObject.stop();
				currentSong.playing = null;
			}
			currentBuzzObject = new buzz.sound(song.audioUrl,{
				formats: ['mp3'],
				preload: true
			});
			currentSong = song;
		};
/**
* @function (Private) playSong
* @desc Plays the current Buzz object and sets playing property of the song object to true
* @param {Object} song
*/
		var playSong = function(song){
			currentBuzzObject.play();
			song.playing = true;
		};
/**
* @function (Public) play
* @desc Plays a 'song' (new or current)
* @param {Object} song
*/
		SongPlayer.play = function(song) {
			if (currentSong !== song) {
				setSong(song);
				playSong(song);
			}
			else if (currentSong === song) {
				if (currentBuzzObject.isPaused()) {
					playSong(song);
				}
			}
		};
/**
* @function (Public) pause
* @desc Pauses a 'song' (new or current)
* @param {Object} song
*/
		SongPlayer.pause = function(song) {
			currentBuzzObject.pause();
			song.playing = false;
		};
		return SongPlayer;
	}

	angular
		.module('blocJams')
		.factory('SongPlayer', SongPlayer);
})();<|endoftext|>


<commit_before>(function() {
    function SongPlayer() {
        var SongPlayer = {};

        var currentSong = null;
        /**
        * @desc Buzz object audio file
        * @type {Object}
        */
        var currentBuzzObject = null;
        /**
        * @function setSong
        * @desc Stops currently playing song and loads new audio file as currentBuzzObject
        * @param {Object} song
        */
        var setSong = function(song) {
            if (currentBuzzObject) {
                currentBuzzObject.stop();
                currentSong.playing = null;
            }

            currentBuzzObject = new buzz.sound(song.audioURL, {
                formats: ['mp3'],
                preload: true
            });

            currentSong = song;
        };

        SongPlayer.play = function(song) {
            if (currentSong !== song) {
                setSong(song);
                currentBuzzObject.play();
                song.playing = true;
            } else if (currentSong === song) {
                if (currentBuzzObject.isPaused()) {
                    currentBuzzObject.play();
                }
            }
        };

        SongPlayer.pause = function(song) {
            currentBuzzObject.pause();
            song.playing = false;
        };

        return SongPlayer;
    }

    angular
        .module('blocJams')
        .factory('SongPlayer', SongPlayer);
})();<commit_msg>Angular Assignment 7: complete<commit_after>(function() {
    function SongPlayer() {
        var SongPlayer = {};
        /**
        * @desc Current song playing
        * @type {Object}
        */
        var currentSong = null;
        /**
        * @desc Buzz object audio file
        * @type {Object}
        */
        var currentBuzzObject = null;
        /**
        * @function setSong
        * @desc Stops currently playing song and loads new audio file as currentBuzzObject
        * @param {Object} song
        */
        var setSong = function(song) {
            if (currentBuzzObject) {
                currentBuzzObject.stop();
                currentSong.playing = null;
            }

            currentBuzzObject = new buzz.sound(song.audioURL, {
                formats: ['mp3'],
                preload: true
            });

            currentSong = song;
        };

        /**
        * @function playSong
        * @desc Starts playing the selected song and sets playing to true
        * @param {Object} song
        */
        var playSong = function(song){
            currentBuzzObject.play();
            song.playing = true;
        };

        SongPlayer.play = function(song) {
            if (currentSong !== song) {
                setSong(song);
                playSong(song);
            } else if (currentSong === song) {
                if (currentBuzzObject.isPaused()) {
                    currentBuzzObject.play();
                }
            }
        };

        SongPlayer.pause = function(song) {
            currentBuzzObject.pause();
            song.playing = false;
        };

        return SongPlayer;
    }

    angular
        .module('blocJams')
        .factory('SongPlayer', SongPlayer);
})();<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name marinaFrontendApp.cockpit.api
 * @description
 * # cockpit.api
 * Service in the marinaFrontendApp.
 */
angular.module('marinaFrontendApp')
  .factory('marinaApi', ['$resource', '$http', '$q', '$rootScope', '$state', '$localstorage',
    function ($resource, $http, $q, $rootScope, $state, $localstorage) {

      var localStorageBuildlogsKeyPrefix = 'marina.builds.logs.';

      var service = {

        getRepositories: function () {

          var deferred = $q.defer();

          $http.get('/api/v1/repos/').
            success(function (data) {
              deferred.resolve(data.repositories);
            }).
            error(function () {
              deferred.resolve(null);
            });
          return deferred.promise;
        },
      };
      return service;

    }]);
<commit_msg>remove local storage for now<commit_after>'use strict';

/**
 * @ngdoc service
 * @name marinaFrontendApp.cockpit.api
 * @description
 * # cockpit.api
 * Service in the marinaFrontendApp.
 */
angular.module('marinaFrontendApp')
  .factory('marinaApi', ['$resource', '$http', '$q', '$rootScope', '$state',
    function ($resource, $http, $q, $rootScope, $state) {

      var localStorageBuildlogsKeyPrefix = 'marina.builds.logs.';

      var service = {

        getRepositories: function () {

          var deferred = $q.defer();

          $http.get('/api/v1/repos/').
            success(function (data) {
              deferred.resolve(data.repositories);
            }).
            error(function () {
              deferred.resolve(null);
            });
          return deferred.promise;
        },
      };
      return service;

    }]);
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name otaniemi3dApp.SensorData
 * @description
 * # SensorData
 * Service in the otaniemi3dApp.
 */
angular.module('otaniemi3dApp')
  .service('SensorData', function ($http, $q) {

    this.get = function () {
      var deferred = $q.defer();
      var url = 'http://otaniemi3d.cs.hut.fi/omi/node/';
      //time = timeFrame || '';
      var debug = true;   //use local data if true

      if (debug) {
        $http.get('odf-requests/sample-response.xml')
          .success(function (xml) {
            deferred.resolve(parseData(xml));
          });
      } else {
        $http.get('odf-requests/data-all.xml')
          .success(function (xml) {

            $http.post(url, xml, {headers: {'Content-Type': 'application/xml'}})
              .success(function (data) {
                deferred.resolve(parseData(data));
              })
              .error(function () {
                console.log('Failed to fetch sensor data.');
                deferred.reject({});
              });
          });
      }
      return deferred.promise;
    };

    /*
     * Convert the sensor data xml to a javascript object and return it.
     */
    function parseData(xml) {
      var sensorData = {};

      xml = new DOMParser().parseFromString(xml, 'text/xml');

      var objects = evaluateXPath(xml, '//Object');

      if (objects.length === 0) {
        console.log('Couldn\'t fetch any sensor data from the server.');
      }

      for (var i = 0; i < objects.length; i++) {
        var id = objects[i].getElementsByTagName('id');

        if (id.length > 0) {
          id = id[0].textContent;
        } else {
          continue;
        }

        //Check if id starts with string 'room'
        if (id.lastIndexOf('room', 0) === 0) {
          var sensors = objects[i].children;
          var sensorList = [];

          for (var j = 0; j < sensors.length; j++) {
            if (sensors[j].tagName !== 'InfoItem') {
              continue;
            }
            var name = sensors[j].getAttribute('name');
            var value = Number(sensors[j].children[0].textContent);

            if (name && value) {
              sensorList.push({
                sensorId: name + '_' + id,
                type: name,
                value: value
              });
            }
          }

          if (sensorList.length > 0) {
            sensorData[id] = {
              name: id.split(/_(.+)/)[1],
              sensors: sensorList,
              node: null
            };
          }
        }
        //Break from the xpath iteration loop. There's no need to return
        //the list of elements.
        //return false;
      }
      return sensorData;
    }

    /*
     * Evaluate an XPath expression aExpr against a given DOM node
     * or Document object (aNode), returning the results as an array.
     * This function can also be given a callback that is called on every
     * element found.
     * https://developer.mozilla.org/en-US/docs/Using_XPath
     */
    function evaluateXPath(aNode, aExpr, fn) {
      var xpe = new XPathEvaluator();
      var nsResolver = xpe.createNSResolver(aNode.ownerDocument === null ?
        aNode.documentElement : aNode.ownerDocument.documentElement);
      var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null);
      var found = [];
      var callback = (typeof fn === 'function');
      var res = result.iterateNext();

      while (res) {
        if (callback) {
          fn(res);
        }
        found.push(res);
        res = result.iterateNext();
      }

      return found;
    }

  });

//curl http://otaniemi3d.cs.hut.fi/omi/node/ -H "Content-Type: text/xml" --data msg="<?xml version="1.0" encoding="UTF-8"?><omi:omiEnvelope version="1.0" ttl="10"><omi:read><omi:msg></omi:msg></omi:read></omi:omiEnvelope>"<commit_msg>Remove comment<commit_after>'use strict';

/**
 * @ngdoc service
 * @name otaniemi3dApp.SensorData
 * @description
 * # SensorData
 * Service in the otaniemi3dApp.
 */
angular.module('otaniemi3dApp')
  .service('SensorData', function ($http, $q) {

    this.get = function () {
      var deferred = $q.defer();
      var url = 'http://otaniemi3d.cs.hut.fi/omi/node/';
      //time = timeFrame || '';
      var debug = true;   //use local data if true

      if (debug) {
        $http.get('odf-requests/sample-response.xml')
          .success(function (xml) {
            deferred.resolve(parseData(xml));
          });
      } else {
        $http.get('odf-requests/data-all.xml')
          .success(function (xml) {

            $http.post(url, xml, {headers: {'Content-Type': 'application/xml'}})
              .success(function (data) {
                deferred.resolve(parseData(data));
              })
              .error(function () {
                console.log('Failed to fetch sensor data.');
                deferred.reject({});
              });
          });
      }
      return deferred.promise;
    };

    /*
     * Convert the sensor data xml to a javascript object and return it.
     */
    function parseData(xml) {
      var sensorData = {};

      xml = new DOMParser().parseFromString(xml, 'text/xml');

      var objects = evaluateXPath(xml, '//Object');

      if (objects.length === 0) {
        console.log('Couldn\'t fetch any sensor data from the server.');
      }

      for (var i = 0; i < objects.length; i++) {
        var id = objects[i].getElementsByTagName('id');

        if (id.length > 0) {
          id = id[0].textContent;
        } else {
          continue;
        }

        //Check if id starts with string 'room'
        if (id.lastIndexOf('room', 0) === 0) {
          var sensors = objects[i].children;
          var sensorList = [];

          for (var j = 0; j < sensors.length; j++) {
            if (sensors[j].tagName !== 'InfoItem') {
              continue;
            }
            var name = sensors[j].getAttribute('name');
            var value = Number(sensors[j].children[0].textContent);

            if (name && value) {
              sensorList.push({
                sensorId: name + '_' + id,
                type: name,
                value: value
              });
            }
          }

          if (sensorList.length > 0) {
            sensorData[id] = {
              name: id.split(/_(.+)/)[1],
              sensors: sensorList,
              node: null
            };
          }
        }
        //Break from the xpath iteration loop. There's no need to return
        //the list of elements.
        //return false;
      }
      return sensorData;
    }

    /*
     * Evaluate an XPath expression aExpr against a given DOM node
     * or Document object (aNode), returning the results as an array.
     * This function can also be given a callback that is called on every
     * element found.
     * https://developer.mozilla.org/en-US/docs/Using_XPath
     */
    function evaluateXPath(aNode, aExpr, fn) {
      var xpe = new XPathEvaluator();
      var nsResolver = xpe.createNSResolver(aNode.ownerDocument === null ?
        aNode.documentElement : aNode.ownerDocument.documentElement);
      var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null);
      var found = [];
      var callback = (typeof fn === 'function');
      var res = result.iterateNext();

      while (res) {
        if (callback) {
          fn(res);
        }
        found.push(res);
        res = result.iterateNext();
      }

      return found;
    }

  });<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name dockstore.ui.WebService
 * @description
 * # WebService
 * Constant in the dockstore.ui.
 */

/*
 * >>>> DO NOT COMMIT THIS FILE <<<<, use locally:
 * git update-index --assume-unchanged app/scripts/services/webservice.js
 */

angular.module('dockstore.ui')
  .constant('WebService', {
    API_URI: 'http://localhost:8080',
    API_URI_DEBUG: 'http://localhost:9000/tests/dummy-data',

    GITHUB_AUTH_URL: 'https://github.com/login/oauth/authorize',
    GITHUB_CLIENT_ID: 'a70739297a7d67f915de',
    GITHUB_REDIRECT_URI: 'http://localhost:9000/login',
    GITHUB_SCOPE: 'read:org',

    QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize',
    QUAYIO_CLIENT_ID: 'RWCBI3Y6QUNXDPYKNLMC',
    QUAYIO_REDIRECT_URI: 'http://localhost:9000/auth/quay.io',
    QUAYIO_SCOPE: 'repo:read,user:read',

    BITBUCKET_AUTH_URL: 'https://bitbucket.org/site/oauth2/authorize',
    BITBUCKET_CLIENT_ID: 'K9VxydpaXKCgxxVpbx',

    DSCLI_RELEASE_URL: 'https://github.com/CancerCollaboratory/dockstore/' +
                        'releases/download/0.1.0/dockstore'
  });
<commit_msg>Increment CLI version number to v0.2.1<commit_after>'use strict';

/**
 * @ngdoc service
 * @name dockstore.ui.WebService
 * @description
 * # WebService
 * Constant in the dockstore.ui.
 */

/*
 * >>>> DO NOT COMMIT THIS FILE <<<<, use locally:
 * git update-index --assume-unchanged app/scripts/services/webservice.js
 */

angular.module('dockstore.ui')
  .constant('WebService', {
    API_URI: 'http://localhost:8080',
    API_URI_DEBUG: 'http://localhost:9000/tests/dummy-data',

    GITHUB_AUTH_URL: 'https://github.com/login/oauth/authorize',
    GITHUB_CLIENT_ID: 'a70739297a7d67f915de',
    GITHUB_REDIRECT_URI: 'http://localhost:9000/login',
    GITHUB_SCOPE: 'read:org',

    QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize',
    QUAYIO_CLIENT_ID: 'RWCBI3Y6QUNXDPYKNLMC',
    QUAYIO_REDIRECT_URI: 'http://localhost:9000/auth/quay.io',
    QUAYIO_SCOPE: 'repo:read,user:read',

    BITBUCKET_AUTH_URL: 'https://bitbucket.org/site/oauth2/authorize',
    BITBUCKET_CLIENT_ID: 'K9VxydpaXKCgxxVpbx',

    DSCLI_RELEASE_URL: 'https://github.com/CancerCollaboratory/dockstore/' +
                        'releases/download/0.2.1/dockstore'
  });
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name handbook.yqlService
 * @description
 * # yqlService
 * Factory in the handbook
 */
angular.module('handbook')
    .factory('yqlService', function ($http) {
        return {
            getTwitterGC: function() {
                return $http.get('https://query.yahooapis.com/v1/public/yql/astappev/handbook-gc_media?format=json&callback=');
            },
            getAnalytics: function() {
                return $http.get('https://query.yahooapis.com/v1/public/yql/astappev/gcbook-top50?format=json&callback=');
            }
        };
    });
<commit_msg>Update date range<commit_after>'use strict';

/**
 * @ngdoc service
 * @name handbook.yqlService
 * @description
 * # yqlService
 * Factory in the handbook
 */
angular.module('handbook')
    .factory('yqlService', function ($http) {
        return {
            getTwitterGC: function() {
                return $http.get('https://query.yahooapis.com/v1/public/yql/astappev/handbook-gc_media?format=json');
            },
            getAnalytics: function() {

                function getDay(date) {
                    var day = date.getDate();
                    return day < 10 ? '0' + day : day;
                }
                function getMonth(date) {
                    var month = date.getMonth() + 1;
                    return month < 10 ? '0' + month : month;
                }

                var start = new Date();
                var end = new Date();
                start.setMonth(start.getMonth() - 1);
                var endStr = end.getFullYear() + '-' + getMonth(end) + '-' + getDay(end);
                var startStr = start.getFullYear() + '-' + getMonth(start) + '-' + getDay(start);

                return $http.get('https://query.yahooapis.com/v1/public/yql/astappev/gcbook-analytics?start=' + startStr + '&end=' + endStr + '&format=json');
            }
        };
    });
<|endoftext|>


<commit_before>define(["jquery","backbone", "handlebars", "text!templates/login.html"],
	function($, Backbone, Handlebars, loginTemplate){

		var LoginView = Backbone.View.extend({

			template : Handlebars.compile(loginTemplate),
			className : "login",

			events : {
				"click .login-button" : "onLogin"
			},

			onLogin : function () {
				this.trigger("login");
			},

			render : function(){
				$(this.el).html(this.template());
				return this.el;
			}

		});

		return LoginView;

	}
);<commit_msg>login screen view annotated<commit_after>/*
	Initial login screen
		- triggers "login" event when login button is clicked
*/

define(["jquery","backbone", "handlebars", "text!templates/login.html"],
	function($, Backbone, Handlebars, loginTemplate){

		var LoginView = Backbone.View.extend({

			template : Handlebars.compile(loginTemplate),
			className : "login",

			events : {
				"click .login-button" : "onLogin"
			},

			onLogin : function () {
				this.trigger("login");
			},

			render : function(){
				$(this.el).html(this.template());
				return this.el;
			}

		});

		return LoginView;

	}
);<|endoftext|>


<commit_before>'use strict';

/**
 * Rhizome - The API that feeds grassroots movements
 *
 * @file app.js
 * @description App model definition.
 * @module Model
 * @exports model, schema, constants
 * @author Chris Bates-Keegan
 *
 */

var mongoose = require('mongoose');
var Model = require('../model');
// var Logging = require('../../logging');

/**
 * Constants
*/

var apps = ['google', 'facebook', 'twitter', 'linkedin'];
var App = {
  GOOGLE: apps[0],
  FACEBOOK: apps[1],
  TWITTER: apps[2],
  LINKEDIN: apps[3]
};

var constants = {
  App: App
};

/**
 * Schema
 */
var schema = new mongoose.Schema({
  app: String,
  appId: String,
  username: String,
  profileUrl: String,
  images: [String],
  email: String,
  locale: String,
  token: String,
  tokenSecret: String,
  extras: String
});

var ModelDef = null;

/**
 * Schema Virtual Methods
 */
schema.virtual('details').get(function() {
  return {
    id: this._id,
    name: this.name,
    type: this.type
  };
});

/**
 * Schema Static Methods
 */

/**
 * @param {Object} body - body passed through from a POST request
 * @return {Promise} - returns a promise that is fulfilled when the database request is completed
 */
schema.statics.add = body => {
  return new Promise((resolve, reject) => {
    var app = new Model({
      name: body.name,
      type: body.type,
      domain: body.domain
    });

    app.save().then(res => resolve(res.details), reject);
  });
};

ModelDef = mongoose.model('AppAuth', schema);

/**
 * Exports
 */
module.exports.constants = constants;
module.exports.schema = schema;
module.exports.model = ModelDef;
<commit_msg>- REFACTOR: support for profile and banner images per app<commit_after>'use strict';

/**
 * Rhizome - The API that feeds grassroots movements
 *
 * @file app.js
 * @description App model definition.
 * @module Model
 * @exports model, schema, constants
 * @author Chris Bates-Keegan
 *
 */

var mongoose = require('mongoose');
var Model = require('../model');
// var Logging = require('../../logging');

/**
 * Constants
*/

var apps = ['google', 'facebook', 'twitter', 'linkedin'];
var App = {
  GOOGLE: apps[0],
  FACEBOOK: apps[1],
  TWITTER: apps[2],
  LINKEDIN: apps[3]
};

var constants = {
  App: App
};

/**
 * Schema
 */
var schema = new mongoose.Schema({
  app: String,
  appId: String,
  username: String,
  profileUrl: String,
  images: {
    profile: String,
    banner: String
  },
  email: String,
  locale: String,
  token: String,
  tokenSecret: String,
  extras: String
});

var ModelDef = null;

/**
 * Schema Virtual Methods
 */
schema.virtual('details').get(function() {
  return {
    id: this._id,
    name: this.name,
    type: this.type
  };
});

/**
 * Schema Static Methods
 */

/**
 * @param {Object} body - body passed through from a POST request
 * @return {Promise} - returns a promise that is fulfilled when the database request is completed
 */
schema.statics.add = body => {
  return new Promise((resolve, reject) => {
    var app = new Model({
      name: body.name,
      type: body.type,
      domain: body.domain
    });

    app.save().then(res => resolve(res.details), reject);
  });
};

ModelDef = mongoose.model('AppAuth', schema);

/**
 * Exports
 */
module.exports.constants = constants;
module.exports.schema = schema;
module.exports.model = ModelDef;
<|endoftext|>


<commit_before>/**
 * Function to build status data
 * */
// const config = require('../config');
const async = require('async');
const utility = require('../util/utility');

module.exports = function buildStatus(db, redis, cb) {
  function generatePercentiles(arr) {
    // sort the list
    arr.sort((a, b) => Number(a) - Number(b));
    // console.log(arr);
    const percentiles = [50, 75, 90, 95, 99];
    const result = {};
    arr.forEach((time, i) => {
      if (i >= arr.length * (percentiles[0] / 100)) {
        result[percentiles[0]] = Number(time);
        // Pop the first element
        percentiles.shift();
      }
    });
    return result;
  }
  async.series({
    user_players(cb) {
      redis.zcard('visitors', cb);
    },
    tracked_players(cb) {
      redis.zcard('tracked', cb);
    },
    matches_last_day(cb) {
      utility.getRedisCountDay(redis, 'added_match', cb);
    },
    matches_last_hour(cb) {
      utility.getRedisCountHour(redis, 'added_match', cb);
    },
    retriever_matches_last_day(cb) {
      utility.getRedisCountDay(redis, 'retriever', cb);
    },
    parsed_matches_last_day(cb) {
      utility.getRedisCountDay(redis, 'parser', cb);
    },
    requests_last_day(cb) {
      utility.getRedisCountDay(redis, 'request', cb);
    },
    api_hits_last_day(cb) {
      utility.getRedisCountDay(redis, 'api_hits', cb);
    },
    api_hits_ui_last_day(cb) {
      utility.getRedisCountDay(redis, 'api_hits_ui', cb);
    },
    fhQueue(cb) {
      redis.llen('fhQueue', cb);
    },
    gcQueue(cb) {
      redis.llen('gcQueue', cb);
    },
    mmrQueue(cb) {
      redis.llen('mmrQueue', cb);
    },
    scenariosQueue(cb) {
      redis.llen('scenariosQueue', cb);
    },
    retriever(cb) {
      redis.zrangebyscore('retrieverCounts', '-inf', 'inf', 'WITHSCORES', (err, results) => {
        if (err) {
          return cb(err);
        }
        const response = [];
        results.forEach((result, i) => {
          if (i % 2 === 0) {
            response.push({
              hostname: result.split('.')[0],
              count: results[i + 1],
            });
          }
        });
        return cb(err, response);
      });
    },
    api_paths(cb) {
      redis.zrangebyscore('api_paths', '-inf', 'inf', 'WITHSCORES', (err, results) => {
        if (err) {
          return cb(err);
        }
        const response = [];
        results.forEach((result, i) => {
          if (i % 2 === 0) {
            response.push({
              hostname: result.split('.')[0],
              count: results[i + 1],
            });
          }
        });
        return cb(err, response);
      });
    },
    last_added(cb) {
      redis.lrange('matches_last_added', 0, -1, (err, result) => {
        cb(err, result.map(r => JSON.parse(r)));
      });
    },
    last_parsed(cb) {
      redis.lrange('matches_last_parsed', 0, -1, (err, result) => {
        cb(err, result.map(r => JSON.parse(r)));
      });
    },
    load_times(cb) {
      redis.lrange('load_times', 0, -1, (err, arr) => {
        cb(err, generatePercentiles(arr));
      });
    },
    health(cb) {
      redis.hgetall('health', (err, result) => {
        if (err) {
          return cb(err);
        }
        const response = result || {};
        Object.keys(response).forEach((key) => {
          response[key] = JSON.parse(response[key]);
        });
        return cb(err, response);
      });
    },
  }, (err, results) => {
    cb(err, results);
  });
};
<commit_msg>Update buildStatus.js<commit_after>/**
 * Function to build status data
 * */
// const config = require('../config');
const async = require('async');
const utility = require('../util/utility');

module.exports = function buildStatus(db, redis, cb) {
  function generatePercentiles(arr) {
    // sort the list
    arr.sort((a, b) => Number(a) - Number(b));
    // console.log(arr);
    const percentiles = [50, 75, 90, 95, 99];
    const result = {};
    arr.forEach((time, i) => {
      if (i >= arr.length * (percentiles[0] / 100)) {
        result[percentiles[0]] = Number(time);
        // Pop the first element
        percentiles.shift();
      }
    });
    return result;
  }
  async.series({
    user_players(cb) {
      redis.zcard('visitors', cb);
    },
    tracked_players(cb) {
      redis.zcard('tracked', cb);
    },
    matches_last_day(cb) {
      utility.getRedisCountDay(redis, 'added_match', cb);
    },
    matches_last_hour(cb) {
      utility.getRedisCountHour(redis, 'added_match', cb);
    },
    retriever_matches_last_day(cb) {
      utility.getRedisCountDay(redis, 'retriever', cb);
    },
    parsed_matches_last_day(cb) {
      utility.getRedisCountDay(redis, 'parser', cb);
    },
    requests_last_day(cb) {
      utility.getRedisCountDay(redis, 'request', cb);
    },
    api_hits_last_day(cb) {
      utility.getRedisCountDay(redis, 'api_hits', cb);
    },
    api_hits_ui_last_day(cb) {
      utility.getRedisCountDay(redis, 'api_hits_ui', cb);
    },
    fhQueue(cb) {
      redis.llen('fhQueue', cb);
    },
    gcQueue(cb) {
      redis.llen('gcQueue', cb);
    },
    mmrQueue(cb) {
      redis.llen('mmrQueue', cb);
    },
    countsQueue(cb) {
      redis.llen('countsQueue', cb);
    },
    scenariosQueue(cb) {
      redis.llen('scenariosQueue', cb);
    },
    retriever(cb) {
      redis.zrangebyscore('retrieverCounts', '-inf', 'inf', 'WITHSCORES', (err, results) => {
        if (err) {
          return cb(err);
        }
        const response = [];
        results.forEach((result, i) => {
          if (i % 2 === 0) {
            response.push({
              hostname: result.split('.')[0],
              count: results[i + 1],
            });
          }
        });
        return cb(err, response);
      });
    },
    api_paths(cb) {
      redis.zrangebyscore('api_paths', '-inf', 'inf', 'WITHSCORES', (err, results) => {
        if (err) {
          return cb(err);
        }
        const response = [];
        results.forEach((result, i) => {
          if (i % 2 === 0) {
            response.push({
              hostname: result.split('.')[0],
              count: results[i + 1],
            });
          }
        });
        return cb(err, response);
      });
    },
    last_added(cb) {
      redis.lrange('matches_last_added', 0, -1, (err, result) => {
        cb(err, result.map(r => JSON.parse(r)));
      });
    },
    last_parsed(cb) {
      redis.lrange('matches_last_parsed', 0, -1, (err, result) => {
        cb(err, result.map(r => JSON.parse(r)));
      });
    },
    load_times(cb) {
      redis.lrange('load_times', 0, -1, (err, arr) => {
        cb(err, generatePercentiles(arr));
      });
    },
    health(cb) {
      redis.hgetall('health', (err, result) => {
        if (err) {
          return cb(err);
        }
        const response = result || {};
        Object.keys(response).forEach((key) => {
          response[key] = JSON.parse(response[key]);
        });
        return cb(err, response);
      });
    },
  }, (err, results) => {
    cb(err, results);
  });
};
<|endoftext|>


<commit_before>var expect = require("chai").expect;

function toNumber(word){
  if ( word === "zero" ){
    return 0;
  }
  if ( word === "one" ){
    return 1;
  }
  if ( word === "two" ){
    return 2;
  }
  if ( word === "three" ){
    return 3;
  }
  if ( word === "four" ){
    return 4;
  }
  if ( word === "five" ){
    return 5;
  }
  if ( word === "six" ){
    return 6;
  }
  if ( word === "seven" ){
    return 7;
  }
  if ( word === "eight" ){
    return 8;
  }
  if ( word === "nine" ){
    return 9;
  }
}

function plus(A, B){
  return (toNumber(A) + toNumber(B));
}

function minus(A, B){
  return (toNumber(A) - toNumber(B));
}

function multiply(A, B){
  return (toNumber(A) * toNumber(B));
}

function divide(A, B){
  return (toNumber(A) / toNumber(B));
}

expect(toNumber("zero")).to.equal(0);
expect(toNumber("one")).to.equal(1);
expect(toNumber("two")).to.equal(2);
expect(toNumber("three")).to.equal(3);
expect(toNumber("four")).to.equal(4);
expect(toNumber("five")).to.equal(5);
expect(toNumber("six")).to.equal(6);
expect(toNumber("seven")).to.equal(7);
expect(toNumber("eight")).to.equal(8);
expect(toNumber("nine")).to.equal(9);

expect(plus).to.exist;
expect(plus("zero", "zero")).to.equal(0);
expect(plus("zero", "one")).to.equal(1);
expect(plus("zero", "two")).to.equal(2);

expect(minus).to.exist;
expect(minus("four", "two")).to.equal(2);

expect(multiply).to.exist;
expect(multiply("five", "three")).to.equal(15);

console.log(multiply("three", "four"))

expect(divide).to.exist;
expect(divide("five", "one").to.equal(5)
<commit_msg>pairing with @mstaehling<commit_after>var expect = require("chai").expect;

function toNumber(word){
  if ( word === "zero" ){
    return 0;
  }
  if ( word === "one" ){
    return 1;
  }
  if ( word === "two" ){
    return 2;
  }
  if ( word === "three" ){
    return 3;
  }
  if ( word === "four" ){
    return 4;
  }
  if ( word === "five" ){
    return 5;
  }
  if ( word === "six" ){
    return 6;
  }
  if ( word === "seven" ){
    return 7;
  }
  if ( word === "eight" ){
    return 8;
  }
  if ( word === "nine" ){
    return 9;
  }
}

function add(A, B){
  if (A === "zero" && B === "zero"){
    return 0
  }
  if (A === "zero" && B === "one"){
    return 1;
  }
  if (A === "zero" && B === "two"){
    return 2;
  }
  if (A === "zero" && B === "three"){
    return 3;
  }
  if (A === "zero" && B === "four"){
    return 4;
  }
  if (A === "zero" && B === "five"){
    return 5;
  }
  if (A === "zero" && B === "six"){
    return 6;
  }
  if (A === "zero" && B === "seven"){
    return 7;
  }
  if (A === "zero" && B === "eight"){
    return 8;
  }
  if (A === "zero" && B === "nine"){
    return 9;
  }

}

expect(add).to.exist;
expect(add("zero", "zero")).to.equal(0);

console.log(add("zero", "zero"))

// NIGHTMARE MODE

/* function plus(A, B){
  return (toNumber(A) + toNumber(B));
}

function minus(A, B){
  return (toNumber(A) - toNumber(B));
}

function multiply(A, B){
  return (toNumber(A) * toNumber(B));
}

function divide(A, B){
  return (toNumber(A) / toNumber(B));
}

expect(toNumber("zero")).to.equal(0);
expect(toNumber("one")).to.equal(1);
expect(toNumber("two")).to.equal(2);
expect(toNumber("three")).to.equal(3);
expect(toNumber("four")).to.equal(4);
expect(toNumber("five")).to.equal(5);
expect(toNumber("six")).to.equal(6);
expect(toNumber("seven")).to.equal(7);
expect(toNumber("eight")).to.equal(8);
expect(toNumber("nine")).to.equal(9);

expect(plus).to.exist;
expect(plus("zero", "zero")).to.equal(0);
expect(plus("zero", "one")).to.equal(1);
expect(plus("zero", "two")).to.equal(2);

expect(minus).to.exist;
expect(minus("four", "two")).to.equal(2);

expect(multiply).to.exist;
expect(multiply("five", "three")).to.equal(15);

console.log(multiply("three", "four"))

expect(divide).to.exist;
expect(divide("five", "one").to.equal(5) */
<|endoftext|>


<commit_before>var ResourceTemplate = function(obj, config) {
    var i, pt;

    this._id = null;
    this._classLabel = null;
    this._labelProperty = null;
    this._classID = null;
    this._propertyTemplates = [];
    this._relation = null;

    if (typeof obj.id !== "undefined") {
        this._id = obj.id;
    }

    if (typeof obj.class !== "undefined") {
        if (typeof obj.class.id !== "undefined") {
            this._classID = obj.class.id;
        }

        if (typeof obj.class.classLabel !== "undefined") {
            this._classLabel = obj.class.classLabel;
        }

        if (typeof obj.class.labelProperty !== "undefined") {
            this._labelProperty = obj.class.labelProperty;
        }

        // @@@There could probably be a complex type around relations
        if (typeof config.relations !== "undefined") {
            for (i in config.relations) {
                if (typeof obj.class[i] !== "undefined") {
                    this._relation = obj.class[i];
                    break;
                }
            }
        }

        if (typeof obj.class.propertyTemplate !== "undefined") {
            for (i = 0; i < obj.class.propertyTemplate.length; i++) {
                pt = new PropertyTemplate(obj.class.propertyTemplate[i]);
                this._propertyTemplates.push(pt);
            }
        }
    }
};

ResourceTemplate.prototype.getID = function() {
    return this._id;
};

ResourceTemplate.prototype.getClassID = function() {
    return this._classID;
};

ResourceTemplate.prototype.getLabel = function() {
    return this._classLabel;
};

ResourceTemplate.prototype.getLabelProperty = function() {
    return this._labelProperty;
};

ResourceTemplate.prototype.getFirstClass = function(classes, superClass) {
    if (classes.indexOf(superClass) >= 0) {
        return superClass;
    } else if (classes.indexOf(this.getClassID()) >= 0) {
        return this.getClassID();
    } else {
        return null;
    }
};

ResourceTemplate.prototype.getPropertyTemplates = function() {
    return this._propertyTemplates;
};

ResourceTemplate.prototype.hasProperty = function(prop) {
    var i, iprop, result = false;
    for (i = 0; i < this._propertyTemplates.length; i++) {
        iprop = this._propertyTemplates[i];
        if (prop === iprop.getProperty()) {
            result = true;
            break;
        }
    }
    return result;
};

ResourceTemplate.prototype.getRelation = function() {
    return this._relation;
};

ResourceTemplate.prototype.mergeTemplate = function(tmpl) {
    this._propertyTemplates = tmpl.getPropertyTemplates().concat(this._propertyTemplates);
};
<commit_msg>correct method based on tests<commit_after>var ResourceTemplate = function(obj, config) {
    var i, pt;

    this._id = null;
    this._classLabel = null;
    this._labelProperty = null;
    this._classID = null;
    this._propertyTemplates = [];
    this._relation = null;

    if (typeof obj.id !== "undefined") {
        this._id = obj.id;
    }

    if (typeof obj.class !== "undefined") {
        if (typeof obj.class.id !== "undefined") {
            this._classID = obj.class.id;
        }

        if (typeof obj.class.classLabel !== "undefined") {
            this._classLabel = obj.class.classLabel;
        }

        if (typeof obj.class.labelProperty !== "undefined") {
            this._labelProperty = obj.class.labelProperty;
        }

        // @@@There could probably be a complex type around relations
        if (typeof config.relations !== "undefined") {
            for (i in config.relations) {
                if (typeof obj.class[i] !== "undefined") {
                    this._relation = obj.class[i];
                    break;
                }
            }
        }

        if (typeof obj.class.propertyTemplate !== "undefined") {
            for (i = 0; i < obj.class.propertyTemplate.length; i++) {
                pt = new PropertyTemplate(obj.class.propertyTemplate[i]);
                this._propertyTemplates.push(pt);
            }
        }
    }
};

ResourceTemplate.prototype.getID = function() {
    return this._id;
};

ResourceTemplate.prototype.getClassID = function() {
    return this._classID;
};

ResourceTemplate.prototype.getLabel = function() {
    return this._classLabel;
};

ResourceTemplate.prototype.getLabelProperty = function() {
    return this._labelProperty;
};

ResourceTemplate.prototype.getFirstClass = function(classes, superClass) {
    if (classes.indexOf(superClass) >= 0) {
        return superClass;
    } else if (classes.indexOf(this.getClassID()) >= 0) {
        return this.getClassID();
    } else {
        return null;
    }
};

ResourceTemplate.prototype.getPropertyTemplates = function() {
    return this._propertyTemplates;
};

ResourceTemplate.prototype.hasProperty = function(prop) {
    var i, iprop, result = false;
    for (i = 0; i < this._propertyTemplates.length; i++) {
        iprop = this._propertyTemplates[i];
        if (prop === iprop.getProperty().getID()) {
            result = true;
            break;
        }
    }
    return result;
};

ResourceTemplate.prototype.getRelation = function() {
    return this._relation;
};

ResourceTemplate.prototype.mergeTemplate = function(tmpl) {
    this._propertyTemplates = tmpl.getPropertyTemplates().concat(this._propertyTemplates);
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright (c) 2017 Abdón Rodríguez Davila (@abdonrd). All rights reserved.
 * This code may only be used under the MIT style license found at https://abdonrd.github.io/LICENSE.txt
 */

/* eslint-env node */

module.exports = {
  staticFileGlobs: [
    'bower_components/webcomponentsjs/webcomponents-loader.js',
    'images/*',
    'index.html',
    'manifest.json'
  ],
  runtimeCaching: [
    {
      urlPattern: /\/bower_components\/webcomponentsjs\/.*.js/,
      handler: 'fastest',
      options: {
        cache: {
          name: 'webcomponentsjs-polyfills-cache'
        }
      }
    },
    {
      urlPattern: /\/data\/.*json/,
      handler: 'fastest',
      options: {
        cache: {
          maxEntries: 100,
          name: 'data-cache'
        }
      }
    }
  ],
  navigateFallback: 'index.html'
};
<commit_msg>Remove unneded index.html from sw-precache-config<commit_after>/**
 * @license
 * Copyright (c) 2017 Abdón Rodríguez Davila (@abdonrd). All rights reserved.
 * This code may only be used under the MIT style license found at https://abdonrd.github.io/LICENSE.txt
 */

/* eslint-env node */

module.exports = {
  staticFileGlobs: [
    'bower_components/webcomponentsjs/webcomponents-loader.js',
    'images/*',
    'manifest.json'
  ],
  runtimeCaching: [
    {
      urlPattern: /\/bower_components\/webcomponentsjs\/.*.js/,
      handler: 'fastest',
      options: {
        cache: {
          name: 'webcomponentsjs-polyfills-cache'
        }
      }
    },
    {
      urlPattern: /\/data\/.*json/,
      handler: 'fastest',
      options: {
        cache: {
          maxEntries: 100,
          name: 'data-cache'
        }
      }
    }
  ]
};
<|endoftext|>