<commit_before>
var request = require('request');

var utils = require('./utils'),
    Options = require('./options');

var c = {
    providers: require('../config/providers'),
    options: require('./provider/index')
};

function Provider (options) {
    if (!options || !options.provider)
        throw new Error('TinyRest: provider option is required!');
    if (!c.providers[options.provider]) {
        throw new Error('TinyRest: non existing provider!');
    }

    this.options = new Options();

    if (c.options.indexOf(options.provider) != -1) {
        var provider = require('./provider/'+options.provider);
        provider.call(this);
    }

    this.consumerKey = options.consumerKey||null;
    this.consumerSecret = options.consumerSecret||null;

    this.api = options.api||'';
    this.version = options.version||c.providers[options.provider].version||'';
    this.domain = options.domain||c.providers[options.provider].domain||'';

    this.name = options.provider;
    this[options.provider] = true;
}

Provider.prototype.createPath = function (api, options) {
    switch (true) {
        case this.bitly: case this.linkedin: case this.stackexchange:
        case this.gmaps: case this.yahoo:
            return ['', this.version, api].join('/');
        case this.facebook: case this.github: case this.wikimapia:
            return ['', api].join('/');
        case this.stocktwits: case this.rubygems:
            return ['/api', this.version, api+'.json'].join('/');
        case this.twitter:
            return ['', this.version, api+'.json'].join('/');
        case this.soundcloud: case this.coderbits:
            return ['', api+'.json'].join('/');
        case this.google:
            var version = options.version||c.providers.google.api[options.api||this.api];
            return ['', options.api||this.api, version, api].join('/');
    }
}

Provider.prototype.url = function (api, options) {
    var domain = this.yahoo ? c.providers.yahoo[options.api].domain : this.domain;
    return domain + this.createPath(api, options);
}

Provider.prototype.get = function (uri, options, callback) {
    var params = request.initParams(uri, options, callback);
    var api = params.uri,
        options = params.options;

    options.method = 'GET';
    options.headers = options.headers||{};
    options.json = true;

    this.options.get.call(this, api, options);

    return request(this.url(api, options), options, utils.response(params.callback));
    // return request(params.uri || null, params.options, params.callback);
}
Provider.prototype.post = function (uri, options, callback) {
    var params = request.initParams(uri, options, callback);
    var api = params.uri,
        options = params.options;

    options.method = 'POST';
    options.headers = options.headers||{};
    options.json = true;

    this.options.post.call(this, api, options);
    this.options.upload(this, api, options);

    return request(this.url(api, options), options, utils.response(params.callback));
    // return request(params.uri || null, params.options, params.callback);
}

// Provider.prototype.put = function (uri, options, callback) {
//   var params = request.initParams(uri, options, callback)
//   params.options.method = 'PUT'
//   // code
//   return request(params.uri || null, params.options, params.callback)
// }
// Provider.prototype.patch = function (uri, options, callback) {
//   var params = request.initParams(uri, options, callback)
//   params.options.method = 'PATCH'
//   // code
//   return request(params.uri || null, params.options, params.callback)
// }
// Provider.prototype.head = function (uri, options, callback) {
//   var params = request.initParams(uri, options, callback)
//   params.options.method = 'HEAD'
//   if (params.options.body ||
//       params.options.requestBodyStream ||
//       (params.options.json && typeof params.options.json !== 'boolean') ||
//       params.options.multipart) {
//     throw new Error("HTTP HEAD requests MUST NOT include a request body.")
//   }
//   // code
//   return request(params.uri || null, params.options, params.callback)
// }
// Provider.prototype.del = function (uri, options, callback) {
//   var params = request.initParams(uri, options, callback)
//   params.options.method = 'DELETE'
//   if(typeof params.options._requester === 'function') {
//     request = params.options._requester
//   }
//   // code
//   return request(params.uri || null, params.options, params.callback)
// }

Provider.request = request;
exports = module.exports = Provider;
<commit_msg>Expose only get and post methods for now<commit_after>
var request = require('request');

var utils = require('./utils'),
    Options = require('./options');

var c = {
    providers: require('../config/providers'),
    options: require('./provider/index')
};

function Provider (options) {
    if (!options || !options.provider)
        throw new Error('TinyRest: provider option is required!');
    if (!c.providers[options.provider]) {
        throw new Error('TinyRest: non existing provider!');
    }

    this.options = new Options();

    if (c.options.indexOf(options.provider) != -1) {
        var provider = require('./provider/'+options.provider);
        provider.call(this);
    }

    this.consumerKey = options.consumerKey||null;
    this.consumerSecret = options.consumerSecret||null;

    this.api = options.api||'';
    this.version = options.version||c.providers[options.provider].version||'';
    this.domain = options.domain||c.providers[options.provider].domain||'';

    this.name = options.provider;
    this[options.provider] = true;
}

Provider.prototype.createPath = function (api, options) {
    switch (true) {
        case this.bitly: case this.linkedin: case this.stackexchange:
        case this.gmaps: case this.yahoo:
            return ['', this.version, api].join('/');
        case this.facebook: case this.github: case this.wikimapia:
            return ['', api].join('/');
        case this.stocktwits: case this.rubygems:
            return ['/api', this.version, api+'.json'].join('/');
        case this.twitter:
            return ['', this.version, api+'.json'].join('/');
        case this.soundcloud: case this.coderbits:
            return ['', api+'.json'].join('/');
        case this.google:
            var version = options.version||c.providers.google.api[options.api||this.api];
            return ['', options.api||this.api, version, api].join('/');
    }
}

Provider.prototype.url = function (api, options) {
    var domain = this.yahoo ? c.providers.yahoo[options.api].domain : this.domain;
    return domain + this.createPath(api, options);
}

Provider.prototype.get = function (uri, options, callback) {
    var params = request.initParams(uri, options, callback);
    var api = params.uri,
        options = params.options;

    options.method = 'GET';
    options.headers = options.headers||{};
    options.json = true;

    this.options.get.call(this, api, options);

    return request(this.url(api, options), options, utils.response(params.callback));
}

Provider.prototype.post = function (uri, options, callback) {
    var params = request.initParams(uri, options, callback);
    var api = params.uri,
        options = params.options;

    options.method = 'POST';
    options.headers = options.headers||{};
    options.json = true;

    this.options.post.call(this, api, options);
    this.options.upload(this, api, options);

    return request(this.url(api, options), options, utils.response(params.callback));
}

Provider.request = request;
exports = module.exports = Provider;
<|endoftext|>


<commit_before>module('lively.ide.codeeditor.Completions').requires('lively.ide.codeeditor.ace').toRun(function() {

Object.extend(lively.ide.codeeditor.Completions, {
    setupCompletions: function(thenDo) {
        module('lively.ide');

        var words = {};
        function wordsFromFiles(next) {
            Functions.forkInWorker(
                function(whenDone, options) {
                    module('lively.lang.Closure').load();
                    module('lively.ide.CommandLineInterface').load();
                    function wordsFromFiles() {
                        var files = lively.ide.CommandLineSearch.findFiles('*js', {sync:true}),
                            livelyJSFiles = files.grep('core/'),
                            urls = livelyJSFiles.map(function(fn) { return URL.root.withFilename(fn).withRelativePartsResolved(); }),
                            splitRegex = /[^a-zA-Z_0-9\$\-]+/,
                            words = {}, parseTimes = {};
                        urls.forEach(function(url) {
                            var t1 = new Date(),
                                content = url.asWebResource().get().content,
                                wordsInFile = content.split(splitRegex);
                            wordsInFile.forEach(function(word) {
                                if (word.length === 0) return;
                                var first = word[0].toLowerCase();
                                if (!words[first]) words[first] = {};
                                if (!words[first][word]) words[first][word] = 0;
                                words[first][word]++;
                            });
                            parseTimes[url] = (new Date() - t1);
                        });
                        return words;
                    }
                    try { whenDone(null, wordsFromFiles()); } catch(e) { whenDone(e.stack, null); }
                }, {args: [], whenDone: function(err, result) { if (err) show(err); words = result; next(); }
            });
        }

        function installCompleter(next) {
            // 1) define completer
            lively.ide.WordCompleter = {wordsFromFiles: words};
            Object.extend(lively.ide.WordCompleter, {
                getCompletions: function(editor, session, pos, prefix, callback) {
                    if (prefix.length === 0) { callback(null, []); return }
                    var startLetter = prefix[0].toLowerCase(),
                        wordList = this.wordsFromFiles[startLetter], result = [];
                    for (var word in wordList) {
                        if (word.lastIndexOf(prefix, 0) !== 0) continue;
                        result.push({
                            name: word,
                            value: word,
                            score: wordList[word],
                            meta: "lively"
                        });
                    }
                    callback(null, result);
                }
            });
            // 2) register completer
            var langTools = lively.ide.ace.require('ace/ext/language_tools');
            langTools.addCompleter(lively.ide.WordCompleter);
            next();
        }

        function done(next) { alertOK('Word completion installed!'); next(); }

        [wordsFromFiles, installCompleter, done].doAndContinue(null, thenDo);
    }
});

(function setupCompletionsOnLoad() {
    if (UserAgent.isNodejs
     || UserAgent.isWorker
     || !lively.Config.get('computeCodeEditorCompletionsOnStartup'))
     return;

    lively.ide.codeeditor.Completions.setupCompletions();
})();

}) // end of module
<commit_msg>ide: extending currently used completions with lively.ide.codeeditor.Completions.addWorldsFromString<commit_after>module('lively.ide.codeeditor.Completions').requires('lively.ide.codeeditor.ace').toRun(function() {

Object.extend(lively.ide.codeeditor.Completions, {

    addWordsFromString: function(string) {
        var splitRegex = /[^a-zA-Z_0-9\$\-]+/,
            words = lively.ide.WordCompleter ? lively.ide.WordCompleter.wordsFromFiles : {};
        string.split(splitRegex)
            .filter(function(w) { return !!w.length })
            .uniq()
            .forEach(function(word) {
                var first = word[0].toLowerCase()
                if (!words[first]) words[first] = {};
                if (!words[first][word]) words[first][word] = 0;
                words[first][word]++;
            });
        return words;
    },

    setupCompletions: function(thenDo) {
        module('lively.ide');

        var words = {};
        function wordsFromFiles(next) {
            Functions.forkInWorker(
                function(whenDone, options) {
                    module('lively.lang.Closure').load();
                    module('lively.ide.CommandLineInterface').load();
                    function wordsFromFiles() {
                        var files = lively.ide.CommandLineSearch.findFiles('*js', {sync:true}),
                            livelyJSFiles = files.grep('core/'),
                            urls = livelyJSFiles.map(function(fn) { return URL.root.withFilename(fn).withRelativePartsResolved(); }),
                            splitRegex = /[^a-zA-Z_0-9\$\-]+/,
                            words = {}, parseTimes = {};
                        urls.forEach(function(url) {
                            var t1 = new Date(),
                                content = url.asWebResource().get().content,
                                wordsInFile = content.split(splitRegex);
                            wordsInFile.forEach(function(word) {
                                if (word.length === 0) return;
                                var first = word[0].toLowerCase();
                                if (!words[first]) words[first] = {};
                                if (!words[first][word]) words[first][word] = 0;
                                words[first][word]++;
                            });
                            parseTimes[url] = (new Date() - t1);
                        });
                        return words;
                    }
                    try { whenDone(null, wordsFromFiles()); } catch(e) { whenDone(e.stack, null); }
                }, {args: [], whenDone: function(err, result) { if (err) show(err); words = result; next(); }
            });
        }

        function installCompleter(next) {
            // 1) define completer
            lively.ide.WordCompleter = {wordsFromFiles: words};
            Object.extend(lively.ide.WordCompleter, {
                getCompletions: function(editor, session, pos, prefix, callback) {
                    if (prefix.length === 0) { callback(null, []); return }
                    var startLetter = prefix[0].toLowerCase(),
                        wordList = this.wordsFromFiles[startLetter], result = [];
                    for (var word in wordList) {
                        if (word.lastIndexOf(prefix, 0) !== 0) continue;
                        result.push({
                            name: word,
                            value: word,
                            score: wordList[word],
                            meta: "lively"
                        });
                    }
                    callback(null, result);
                }
            });
            // 2) register completer
            var langTools = lively.ide.ace.require('ace/ext/language_tools');
            langTools.addCompleter(lively.ide.WordCompleter);
            next();
        }

        function done(next) { alertOK('Word completion installed!'); next(); }

        [wordsFromFiles, installCompleter, done].doAndContinue(null, thenDo);
    }
});

(function setupCompletionsOnLoad() {
    if (UserAgent.isNodejs
     || UserAgent.isWorker
     || !lively.Config.get('computeCodeEditorCompletionsOnStartup'))
     return;

    lively.ide.codeeditor.Completions.setupCompletions();
})();

}) // end of module
<|endoftext|>


<commit_before>(function () {
    angular.module("directives").directive("mmFullcalendar", ["$http", "$compile", function ($http, $compile) {
        return {
            //restrict: "A",
            scope: {
                itemssource: '=',
                selectedday: '=',
                daySelected: "&",
                selectedevent: '=',
                eventSelected: "&",
                viewChanged: "&",
                fetchItems: "&",
                rerender: '=',
            },
            link: function (scope, element, attrs, ctrls) {

                scope.$watch("rerender", function (newdata, olddata) {
                    if (scope.rerender && scope.rerender == true) {
                        $(element).fullCalendar('render')
                        scope.refreshrender = false;
                    }
                });

                scope.$watch("itemssource", function (newdata, olddata) {
                    var startParam = "start";
                    var endParam = "end";
                    if (attrs.startParam) { startParam = attrs.startParam; }
                    if (attrs.endParam) { endParam = attrs.endParam; }

                    if (newdata && newdata.length && newdata.length > 0) {
                        load(scope.itemssource, startParam, endParam);
                    } else {
                        load(null, startParam, endParam);
                    }
                });
                var lastview = {};
                var loaded = false;
                var daySelectedHandler = scope.daySelected();
                var eventSelectedHandler = scope.eventSelected();
                var viewChangedHandler = scope.viewChanged();
                var fetchItemsHandler = scope.fetchItems();
                var load = function (items, startParam, endParam) {
                    if (loaded) {
                        events = function (start, end, callback) {
                            if (fetchItemsHandler) {
                                var results = fetchItemsHandler(start, end);
                                if (results) { callback(results); }
                            } else { callback(items); }
                        };

                        // $(element).fullCalendar('rerenderEvents');
                        //$('#calendar').fullCalendar('removeEventSource', events);
                        //$('#calendar').fullCalendar('addEventSource', events);
                        if (items && items.length && items.length > 0) {

                            //Error happining Here

                            try {
                                $(element).fullCalendar('refetchEvents');
                            }
                            catch (err) {
                                console.log(err);
                               // alert(err);
                             //   document.getElementById("demo").innerHTML = err.message;
                            }

                        }
                        return;
                    } else {
                        loaded = true;
                        $(element).fullCalendar({
                            disableDragging: true,
                            header: {
                                left: 'prev,next today',
                                center: 'title',
                                right: 'month,agendaWeek,agendaDay'
                            },
                            editable: true,
                            startParam: startParam,
                            endParam:endParam,
                            events: function (start, end, callback) {
                                if (fetchItemsHandler) {
                                    var results = fetchItemsHandler(start, end);
                                    if (results) {
                                        callback(results);
                                    }
                                } else {
                                    callback(scope.itemssource);
                                }
                            },
                            eventClick: function (calEvent, jsEvent, view) {

                                if (scope.selectedevent != undefined) {
                                    scope.$apply(function () { scope.selectedevent = calEvent; });
                                } else if (attrs.selectedevent) {
                                    scope.$apply(function() {
                                        scope.selectedevent = {};
                                        scope.selectedevent = calEvent;
                                    });

                                    scope.$apply(function () {
                                        scope.selectedevent = {};
                                        scope.selectedevent = calEvent;
                                    });
                                }
                                if (eventSelectedHandler) {
                                    eventSelectedHandler(calEvent);
                                };
                            },
                            dayClick: function (a) {
                                if (scope.selectedday != undefined) {
                                    scope.$apply(function () { scope.selectedday = a; });
                                } else {
                                    if (attrs.selectedday) {
                                        scope.selectedday = {};
                                        scope.$apply(function () { scope.selectedday = a; });
                                    }
                                }
                                if (daySelectedHandler) {
                                    daySelectedHandler(a);
                                };
                            },
                            viewRender: function (view, element) {
                                if ((!lastview.visStart || !lastview.visEnd) || (lastview.visStart.toString() != view.visStart.toString() || lastview.visEnd.toString() != view.visEnd.toString())) {
                                    lastview.visStart = view.visStart;
                                    lastview.visEnd = view.visEnd;
                                    if (viewChangedHandler) {
                                        viewChangedHandler(view);
                                    }
                                }
                            },
                        });
                    }
                }
            },
            //controller: function ($scope, $element, $attrs) {},
        };
    }]);
})();<commit_msg>Full calendar v2 has 4 params on events function<commit_after>(function () {
    angular.module("directives").directive("mmFullcalendar", ["$http", "$compile", function ($http, $compile) {
        return {
            //restrict: "A",
            scope: {
                itemssource: '=',
                selectedday: '=',
                daySelected: "&",
                selectedevent: '=',
                eventSelected: "&",
                viewChanged: "&",
                fetchItems: "&",
                rerender: '=',
            },
            link: function (scope, element, attrs, ctrls) {

                scope.$watch("rerender", function (newdata, olddata) {
                    if (scope.rerender && scope.rerender == true) {
                        $(element).fullCalendar('render')
                        scope.refreshrender = false;
                    }
                });

                scope.$watch("itemssource", function (newdata, olddata) {
                    var startParam = "start";
                    var endParam = "end";
                    if (attrs.startParam) { startParam = attrs.startParam; }
                    if (attrs.endParam) { endParam = attrs.endParam; }

                    if (newdata && newdata.length && newdata.length > 0) {
                        load(scope.itemssource, startParam, endParam);
                    } else {
                        load(null, startParam, endParam);
                    }
                });
                var lastview = {};
                var loaded = false;
                var daySelectedHandler = scope.daySelected();
                var eventSelectedHandler = scope.eventSelected();
                var viewChangedHandler = scope.viewChanged();
                var fetchItemsHandler = scope.fetchItems();
                var load = function (items, startParam, endParam) {
                    if (loaded) {
                        events = function (start, end,timezone, callback) {
                            if (fetchItemsHandler) {
                                var results = fetchItemsHandler(start, end);
                                if (results) { callback(results); }
                            } else { callback(items); }
                        };

                        // $(element).fullCalendar('rerenderEvents');
                        //$('#calendar').fullCalendar('removeEventSource', events);
                        //$('#calendar').fullCalendar('addEventSource', events);
                        if (items && items.length && items.length > 0) {

                            //Error happining Here

                            try {
                                $(element).fullCalendar('refetchEvents');
                            }
                            catch (err) {
                                console.log(err);
                               // alert(err);
                             //   document.getElementById("demo").innerHTML = err.message;
                            }

                        }
                        return;
                    } else {
                        loaded = true;
                        $(element).fullCalendar({
                            disableDragging: true,
                            header: {
                                left: 'prev,next today',
                                center: 'title',
                                right: 'month,agendaWeek,agendaDay'
                            },
                            editable: true,
                            startParam: startParam,
                            endParam:endParam,
                            events: function (start, end,timezone ,callback) {
                                if (fetchItemsHandler) {
                                    var results = fetchItemsHandler(start, end);
                                    if (results) {
                                        callback(results);
                                    }
                                } else {
                                    callback(scope.itemssource);
                                }
                            },
                            eventClick: function (calEvent, jsEvent, view) {

                                if (scope.selectedevent != undefined) {
                                    scope.$apply(function () { scope.selectedevent = calEvent; });
                                } else if (attrs.selectedevent) {
                                    scope.$apply(function() {
                                        scope.selectedevent = {};
                                        scope.selectedevent = calEvent;
                                    });

                                    scope.$apply(function () {
                                        scope.selectedevent = {};
                                        scope.selectedevent = calEvent;
                                    });
                                }
                                if (eventSelectedHandler) {
                                    eventSelectedHandler(calEvent);
                                };
                            },
                            dayClick: function (a) {
                                if (scope.selectedday != undefined) {
                                    scope.$apply(function () { scope.selectedday = a; });
                                } else {
                                    if (attrs.selectedday) {
                                        scope.selectedday = {};
                                        scope.$apply(function () { scope.selectedday = a; });
                                    }
                                }
                                if (daySelectedHandler) {
                                    daySelectedHandler(a);
                                };
                            },
                            viewRender: function (view, element) {
                                if ((!lastview.visStart || !lastview.visEnd) || (lastview.visStart.toString() != view.visStart.toString() || lastview.visEnd.toString() != view.visEnd.toString())) {
                                    lastview.visStart = view.visStart;
                                    lastview.visEnd = view.visEnd;
                                    if (viewChangedHandler) {
                                        viewChangedHandler(view);
                                    }
                                }
                            },
                        });
                    }
                }
            },
            //controller: function ($scope, $element, $attrs) {},
        };
    }]);
})();
<|endoftext|>


<commit_before>var assert = require('assert');
var expect = require('chai').expect;
var waitForOncoprint = require('./../specUtils').waitForOncoprint;
var setOncoprintMutationsMenuOpen = require('./../specUtils').setOncoprintMutationsMenuOpen;
var goToUrlAndSetLocalStorage = require('./../specUtils').goToUrlAndSetLocalStorage;
var waitForNetworkQuiet = require('./../specUtils').waitForNetworkQuiet;
var sessionServiceIsEnabled = require('./../specUtils').sessionServiceIsEnabled;
var assertScreenShotMatch = require('../../lib/testUtils').assertScreenShotMatch;

const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");

function waitForAndCheckPlotsTab() {
    browser.waitForVisible('div[data-test="PlotsTabPlotDiv"]', 10000);
    var res = browser.checkElement('div[data-test="PlotsTabEntireDiv"]', { hide:['.qtip'] });
    assertScreenShotMatch(res);
}

function runResultsTestSuite(prefix){

    it(`${prefix} render the oncoprint`, function(){
        waitForOncoprint(10000);
        var res = browser.checkElement('.oncoprintContainer', { hide:['.oncoprint__controls']}); // just hide the controls bc for some reason they keep showing up transparent in this test only
        assertScreenShotMatch(res);
    });

    // can't get it to pass reliably
    it.skip(`${prefix} igv_tab tab`, function(){
        browser.click("a.tabAnchor_cnSegments");
        browser.waitForExist('#cnSegmentsFrame', 20000);
        var res = browser.checkElement('.cnSegmentsMSKTabs',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} cancer type summary`, function(){
        browser.click("a.tabAnchor_cancerTypesSummary");
        browser.waitForVisible('[data-test="cancerTypeSummaryChart"]',10000);
        browser.waitForExist('[data-test="cancerTypeSummaryWrapper"]', 5000);
        var res = browser.checkElement('[data-test="cancerTypeSummaryWrapper"]', { hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} mutex tab`, function(){
        browser.click("a.tabAnchor_mutualExclusivity");
        var res = browser.checkElement('[data-test="mutualExclusivityTabDiv"]',{ hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} plots tab`, function(){
        browser.click("a.tabAnchor_plots");
        waitForAndCheckPlotsTab();
    });

    it(`${prefix} mutation tab`, function(){
        browser.click("a.tabAnchor_mutations");
        browser.waitForVisible('.borderedChart svg',20000);
        var res = browser.checkElement('[data-test="mutationsTabDiv"]',{hide:['.qtip', '[data-test=view3DStructure]', '[data-test=GeneSummaryUniProt]'], viewportChangePause:4000}); // hide these things because the timing of data loading makes this test so flaky
        assertScreenShotMatch(res);
    });

    it(`${prefix} coexpression tab`, function(){
        browser.click("a.tabAnchor_coexpression");
        browser.waitForVisible('div[data-test="CoExpressionPlot"]',10000);
        var res = browser.checkElement('[data-test="coExpressionTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it(`${prefix} enrichments tab`, function(){
        browser.click("a.tabAnchor_enrichments");
        browser.waitForVisible('div[data-test="MutationEnrichmentsTab"]',10000);
        browser.click('b=CDK14');
        browser.waitForExist('[data-test="enrichmentsTabDiv"]', 10000);
        var res = browser.checkElement('[data-test="enrichmentsTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it(`${prefix} survival tab`, function(){
        browser.click("a.tabAnchor_survival");
        browser.waitForVisible('[data-test=SurvivalChart] svg',10000);
        var res = browser.checkElement('[data-test="survivalTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it.skip(`${prefix} network tab`, function(){
        // TODO: unskip this when bug is fixed

        browser.click("a.tabAnchor_network");

        browser.waitForExist('iframe#networkFrame', 10000);

        browser.frame('networkFrame', function(err, result) {
                if (err) console.log(err);
            });
        browser.waitForVisible('#cytoscapeweb canvas',60000);
        browser.execute(function(){
            $("<style>canvas { visibility: hidden} </style>").appendTo("body");
        });
        browser.frame(null);
        var res = browser.checkElement("#networkFrame",{hide:['.qtip','canvas'] });

        assertScreenShotMatch(res);
    });

    it.skip(`${prefix} data_download tab`, function(){
        browser.click("a.tabAnchor_download");
        //  browser.pause(1000);
        browser.waitForExist("#text_area_gene_alteration_freq",20000);
        browser.waitUntil(function(){ return browser.getValue("#text_area_gene_alteration_freq").length > 0 },20000);
        var res = browser.checkElement('[data-test="downloadTabDiv"]',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
}

describe('result page screenshot tests', function(){
    before(function(){
        var url = `${CBIOPORTAL_URL}/index.do?tab_index=tab_visualize&cancer_study_list=coadread_tcga_pub&cancer_study_id=coadread_tcga_pub&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=coadread_tcga_pub_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=coadread_tcga_pub_gistic&Z_SCORE_THRESHOLD=2.0&case_set_id=coadread_tcga_pub_nonhypermut&case_ids=&gene_list=KRAS+NRAS+BRAF&gene_set_choice=user-defined-list&Action=Submit&show_samples=false&`;
        goToUrlAndSetLocalStorage(url);
        waitForOncoprint(10000);
    });

    runResultsTestSuite('no session')

});

describe('expression tab', function() {
    it("expression tab with complex oql", ()=>{
        goToUrlAndSetLocalStorage(`${CBIOPORTAL_URL}/results/expression?cancer_study_id=all&Z_SCORE_THRESHOLD=2&RPPA_SCORE_THRESHOLD=2&data_priority=0&case_set_id=all&gene_list=TP53%3AMUT%3B&geneset_list=%20&tab_index=tab_visualize&Action=Submit&cancer_study_list=acc_tcga%2Cchol_tcga%2Cesca_tcga&show_samples=false`);
        browser.waitForExist(".borderedChart svg", 60000);
        var res = browser.checkElement('[data-test="expressionTabDiv"]');
        assertScreenShotMatch(res);
    });
});

describe("download tab screenshot tests", function() {
    it("download tab - msk_impact_2017 with ALK and SOS1 - SOS1 should be not sequenced", function() {
        var url = `${CBIOPORTAL_URL}/index.do?cancer_study_id=msk_impact_2017&Z_SCORE_THRESHOLD=2&RPPA_SCORE_THRESHOLD=2&data_priority=0&case_set_id=msk_impact_2017_all&gene_list=ALK%2520SOS1&geneset_list=+&tab_index=tab_visualize&Action=Submit&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=msk_impact_2017_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=msk_impact_2017_cna`;
        goToUrlAndSetLocalStorage(url);
        browser.waitForExist("a.tabAnchor_download", 10000);
        browser.click("a.tabAnchor_download");
        browser.waitForExist('[data-test="dataDownloadGeneAlterationTable"] tr > td > svg', 20000);
        browser.waitForExist('[data-test="downloadTabDiv"]', 5000);
        var res = browser.checkElement('[data-test="downloadTabDiv"]',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
});

describe('patient view page screenshot test', function(){
    before(function(){
        var url = `${CBIOPORTAL_URL}/patient?studyId=lgg_ucsf_2014&caseId=P04`;
        goToUrlAndSetLocalStorage(url);
    });

    it('patient view lgg_ucsf_2014 P04', function() {
        // find oncokb image
        var oncokbIndicator = $('[data-test="oncogenic-icon-image"]');
        oncokbIndicator.waitForExist(30000);
        // find vaf plot
        var vafPlot = $('.vafPlot');
        vafPlot.waitForExist(30000);

        var res = browser.checkElement('#mainColumn', {hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
});

describe("enrichments tab screenshot tests", function() {
    before(function() {
        var url = `${CBIOPORTAL_URL}/results/enrichments?tab_index=tab_visualize&cancer_study_list=coadread_tcga_pub&cancer_study_id=coadread_tcga_pub&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=coadread_tcga_pub_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=coadread_tcga_pub_gistic&Z_SCORE_THRESHOLD=2.0&case_set_id=coadread_tcga_pub_nonhypermut&case_ids=&gene_list=KRAS+NRAS+BRAF&gene_set_choice=user-defined-list&Action=Submit`;
        goToUrlAndSetLocalStorage(url);
    });
    it('enrichments tab coadread_tcga_pub mRNA profile', function(){
        browser.waitForVisible('div[data-test="MutationEnrichmentsTab"]',10000);
        browser.waitForVisible('a=mRNA', 10000);
        browser.click('a=mRNA');
        browser.waitForVisible('div[data-test="MRNAEnrichmentsTab"]',20000);
        browser.waitForVisible('b=MERTK', 10000);
        browser.click('b=MERTK');
        browser.waitForVisible('div[data-test="MiniBoxPlot"]', 20000);
        var res = browser.checkElement('[data-test="enrichmentsTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });
});

describe('result page tabs, loading from session id', function(){
    before(function(){
        // only run these tests if session service is enabled
        if (sessionServiceIsEnabled() === false) {
            this.skip();
        }

        var url = `${CBIOPORTAL_URL}/results?session_id=5bbe8197498eb8b3d5684271`;
        goToUrlAndSetLocalStorage(url);
        waitForOncoprint(10000);
    });

    runResultsTestSuite('session');
});
<commit_msg>Skip tests related to civic<commit_after>var assert = require('assert');
var expect = require('chai').expect;
var waitForOncoprint = require('./../specUtils').waitForOncoprint;
var setOncoprintMutationsMenuOpen = require('./../specUtils').setOncoprintMutationsMenuOpen;
var goToUrlAndSetLocalStorage = require('./../specUtils').goToUrlAndSetLocalStorage;
var waitForNetworkQuiet = require('./../specUtils').waitForNetworkQuiet;
var sessionServiceIsEnabled = require('./../specUtils').sessionServiceIsEnabled;
var assertScreenShotMatch = require('../../lib/testUtils').assertScreenShotMatch;

const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");

function waitForAndCheckPlotsTab() {
    browser.waitForVisible('div[data-test="PlotsTabPlotDiv"]', 10000);
    var res = browser.checkElement('div[data-test="PlotsTabEntireDiv"]', { hide:['.qtip'] });
    assertScreenShotMatch(res);
}

function runResultsTestSuite(prefix){

    it(`${prefix} render the oncoprint`, function(){
        waitForOncoprint(10000);
        var res = browser.checkElement('.oncoprintContainer', { hide:['.oncoprint__controls']}); // just hide the controls bc for some reason they keep showing up transparent in this test only
        assertScreenShotMatch(res);
    });

    // can't get it to pass reliably
    it.skip(`${prefix} igv_tab tab`, function(){
        browser.click("a.tabAnchor_cnSegments");
        browser.waitForExist('#cnSegmentsFrame', 20000);
        var res = browser.checkElement('.cnSegmentsMSKTabs',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} cancer type summary`, function(){
        browser.click("a.tabAnchor_cancerTypesSummary");
        browser.waitForVisible('[data-test="cancerTypeSummaryChart"]',10000);
        browser.waitForExist('[data-test="cancerTypeSummaryWrapper"]', 5000);
        var res = browser.checkElement('[data-test="cancerTypeSummaryWrapper"]', { hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} mutex tab`, function(){
        browser.click("a.tabAnchor_mutualExclusivity");
        var res = browser.checkElement('[data-test="mutualExclusivityTabDiv"]',{ hide:['.qtip'] });
        assertScreenShotMatch(res);
    });

    it(`${prefix} plots tab`, function(){
        browser.click("a.tabAnchor_plots");
        waitForAndCheckPlotsTab();
    });

    it.skip(`${prefix} mutation tab`, function(){
        browser.click("a.tabAnchor_mutations");
        browser.waitForVisible('.borderedChart svg',20000);
        var res = browser.checkElement('[data-test="mutationsTabDiv"]',{hide:['.qtip', '[data-test=view3DStructure]', '[data-test=GeneSummaryUniProt]'], viewportChangePause:4000}); // hide these things because the timing of data loading makes this test so flaky
        assertScreenShotMatch(res);
    });

    it(`${prefix} coexpression tab`, function(){
        browser.click("a.tabAnchor_coexpression");
        browser.waitForVisible('div[data-test="CoExpressionPlot"]',10000);
        var res = browser.checkElement('[data-test="coExpressionTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it(`${prefix} enrichments tab`, function(){
        browser.click("a.tabAnchor_enrichments");
        browser.waitForVisible('div[data-test="MutationEnrichmentsTab"]',10000);
        browser.click('b=CDK14');
        browser.waitForExist('[data-test="enrichmentsTabDiv"]', 10000);
        var res = browser.checkElement('[data-test="enrichmentsTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it(`${prefix} survival tab`, function(){
        browser.click("a.tabAnchor_survival");
        browser.waitForVisible('[data-test=SurvivalChart] svg',10000);
        var res = browser.checkElement('[data-test="survivalTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });

    it.skip(`${prefix} network tab`, function(){
        // TODO: unskip this when bug is fixed

        browser.click("a.tabAnchor_network");

        browser.waitForExist('iframe#networkFrame', 10000);

        browser.frame('networkFrame', function(err, result) {
                if (err) console.log(err);
            });
        browser.waitForVisible('#cytoscapeweb canvas',60000);
        browser.execute(function(){
            $("<style>canvas { visibility: hidden} </style>").appendTo("body");
        });
        browser.frame(null);
        var res = browser.checkElement("#networkFrame",{hide:['.qtip','canvas'] });

        assertScreenShotMatch(res);
    });

    it.skip(`${prefix} data_download tab`, function(){
        browser.click("a.tabAnchor_download");
        //  browser.pause(1000);
        browser.waitForExist("#text_area_gene_alteration_freq",20000);
        browser.waitUntil(function(){ return browser.getValue("#text_area_gene_alteration_freq").length > 0 },20000);
        var res = browser.checkElement('[data-test="downloadTabDiv"]',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
}

describe('result page screenshot tests', function(){
    before(function(){
        var url = `${CBIOPORTAL_URL}/index.do?tab_index=tab_visualize&cancer_study_list=coadread_tcga_pub&cancer_study_id=coadread_tcga_pub&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=coadread_tcga_pub_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=coadread_tcga_pub_gistic&Z_SCORE_THRESHOLD=2.0&case_set_id=coadread_tcga_pub_nonhypermut&case_ids=&gene_list=KRAS+NRAS+BRAF&gene_set_choice=user-defined-list&Action=Submit&show_samples=false&`;
        goToUrlAndSetLocalStorage(url);
        waitForOncoprint(10000);
    });

    runResultsTestSuite('no session')

});

describe('expression tab', function() {
    it("expression tab with complex oql", ()=>{
        goToUrlAndSetLocalStorage(`${CBIOPORTAL_URL}/results/expression?cancer_study_id=all&Z_SCORE_THRESHOLD=2&RPPA_SCORE_THRESHOLD=2&data_priority=0&case_set_id=all&gene_list=TP53%3AMUT%3B&geneset_list=%20&tab_index=tab_visualize&Action=Submit&cancer_study_list=acc_tcga%2Cchol_tcga%2Cesca_tcga&show_samples=false`);
        browser.waitForExist(".borderedChart svg", 60000);
        var res = browser.checkElement('[data-test="expressionTabDiv"]');
        assertScreenShotMatch(res);
    });
});

describe("download tab screenshot tests", function() {
    it("download tab - msk_impact_2017 with ALK and SOS1 - SOS1 should be not sequenced", function() {
        var url = `${CBIOPORTAL_URL}/index.do?cancer_study_id=msk_impact_2017&Z_SCORE_THRESHOLD=2&RPPA_SCORE_THRESHOLD=2&data_priority=0&case_set_id=msk_impact_2017_all&gene_list=ALK%2520SOS1&geneset_list=+&tab_index=tab_visualize&Action=Submit&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=msk_impact_2017_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=msk_impact_2017_cna`;
        goToUrlAndSetLocalStorage(url);
        browser.waitForExist("a.tabAnchor_download", 10000);
        browser.click("a.tabAnchor_download");
        browser.waitForExist('[data-test="dataDownloadGeneAlterationTable"] tr > td > svg', 20000);
        browser.waitForExist('[data-test="downloadTabDiv"]', 5000);
        var res = browser.checkElement('[data-test="downloadTabDiv"]',{hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
});

describe.skip('patient view page screenshot test', function(){
    before(function(){
        var url = `${CBIOPORTAL_URL}/patient?studyId=lgg_ucsf_2014&caseId=P04`;
        goToUrlAndSetLocalStorage(url);
    });

    it('patient view lgg_ucsf_2014 P04', function() {
        // find oncokb image
        var oncokbIndicator = $('[data-test="oncogenic-icon-image"]');
        oncokbIndicator.waitForExist(30000);
        // find vaf plot
        var vafPlot = $('.vafPlot');
        vafPlot.waitForExist(30000);

        var res = browser.checkElement('#mainColumn', {hide:['.qtip'] });
        assertScreenShotMatch(res);
    });
});

describe("enrichments tab screenshot tests", function() {
    before(function() {
        var url = `${CBIOPORTAL_URL}/results/enrichments?tab_index=tab_visualize&cancer_study_list=coadread_tcga_pub&cancer_study_id=coadread_tcga_pub&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=coadread_tcga_pub_mutations&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=coadread_tcga_pub_gistic&Z_SCORE_THRESHOLD=2.0&case_set_id=coadread_tcga_pub_nonhypermut&case_ids=&gene_list=KRAS+NRAS+BRAF&gene_set_choice=user-defined-list&Action=Submit`;
        goToUrlAndSetLocalStorage(url);
    });
    it('enrichments tab coadread_tcga_pub mRNA profile', function(){
        browser.waitForVisible('div[data-test="MutationEnrichmentsTab"]',10000);
        browser.waitForVisible('a=mRNA', 10000);
        browser.click('a=mRNA');
        browser.waitForVisible('div[data-test="MRNAEnrichmentsTab"]',20000);
        browser.waitForVisible('b=MERTK', 10000);
        browser.click('b=MERTK');
        browser.waitForVisible('div[data-test="MiniBoxPlot"]', 20000);
        var res = browser.checkElement('[data-test="enrichmentsTabDiv"]', { hide:['.qtip'] } );
        assertScreenShotMatch(res);
    });
});

describe('result page tabs, loading from session id', function(){
    before(function(){
        // only run these tests if session service is enabled
        if (sessionServiceIsEnabled() === false) {
            this.skip();
        }

        var url = `${CBIOPORTAL_URL}/results?session_id=5bbe8197498eb8b3d5684271`;
        goToUrlAndSetLocalStorage(url);
        waitForOncoprint(10000);
    });

    runResultsTestSuite('session');
});
<|endoftext|>


<commit_before>/**
	_moon.HighlightText_ is a control that displays an highlighted text.
	Identified string or chracter in content can be highlighted by onHighlight event.
	if content don't have any identical string, there is no change in display.

		{kind: "moon.HighlightText", content: "Hello World!"}

	Examples)

	_moon.HighlightText_ get event like below, then the "Hello" is highlighted.
		this.waterfall("onHighlight", {highlight: "Hello"});

	_moon.HighlightText_ get event like below, then the highlighted text is disapeared.
		this.waterfall("offHighlight");
*/
enyo.kind({
	name: "moon.HighlightText",
	published: {
        content: ""
	},
	handlers: {
		onHighlight: "onHighlightHandler",
        offHighlight: "offHighlightHandler"
	},
	//* @protected
	create: function() {
		this.inherited(arguments);
        this._content = this.content;
        this.allowHtml = true;
	},
    setContent:function(inValue) {
        this.inherited(arguments);
        this._content = inValue;
    },
    _setContent:function(inValue) {
        this.content = inValue;
        this.contentChanged();
    },
    getContent:function() {
        return this._content;
    },
	onHighlightHandler: function(inSender, inEvent) {
		var hlt = inEvent.highlight;
		var ort  = this.getContent();
        var sIdx = ort.indexOf(hlt);
        if(sIdx !== -1) {
            var text = ort.slice(0, sIdx) + "" + ort.slice(sIdx, sIdx+hlt.length) + "" + ort.slice(sIdx+hlt.length, ort.length);
            this._setContent(text);
        }
        return true;
	},
    offHighlightHandler: function(inSender, inEvent) {
        this.setContent(this._content);
        this.render();
        return true;
    }
});<commit_msg>Highlighting multiple identical string<commit_after>/**
	_moon.HighlightText_ is a control that displays an highlighted text.
	Identified string or chracter in content can be highlighted by onHighlight event.
	if content don't have any identical string, there is no change in display.

		{kind: "moon.HighlightText", content: "Hello World!"}

	Examples)

	_moon.HighlightText_ get event like below, then the "Hello" is highlighted.
		this.waterfall("onHighlight", {highlight: "Hello"});

	_moon.HighlightText_ get event like below, then the highlighted text is disapeared.
		this.waterfall("offHighlight");
*/
enyo.kind({
    name: "moon.HighlightText",
    published: {
        content: "",
        highlightClasses: "moon-highlight-text-highlighted"
    },
    handlers: {
        onHighlight: "onHighlightHandler",
        offHighlight: "offHighlightHandler"
    },
    //* @protected
    create: function() {
        this.inherited(arguments);
        this._content = this.content;
    },
    setContent:function(inValue) {
        this.inherited(arguments);
        this._content = inValue;
    },
    _setContent:function(inValue) {
        this.content = inValue;
        this.contentChanged();
    },
    getContent:function() {
        return this._content;
    },
    onHighlightHandler: function(inSender, inEvent) {
        this.allowHtml = true;
        var output = "",
            hlt = inEvent.highlight,
            ort = this.getContent(),
            eIdx = ort.length,
            sIdx = 0
        ;
        while(sIdx !== -1) {
            sIdx = ort.search(hlt);
            if(sIdx !== -1) {
                output += ort.slice(0, sIdx) + "";
                output += ort.slice(sIdx, sIdx+hlt.length) + "";
                sIdx = sIdx+hlt.length;
                ort = ort.slice(sIdx, eIdx);
            }
        }
        output += ort;
        this._setContent(output);

        return true;
    },
    offHighlightHandler: function(inSender, inEvent) {
        this.allowHtml = false;
        this.setContent(this._content);
        this.render();
        return true;
    }
});<|endoftext|>


<commit_before>#!/usr/bin/env node

var program = require('commander');
var package = require('../package.json');

var ren4plex = {

    // config
    config : {
        preview: false,
        splitChars : /[.,;!:() _+\-\[\]]/,
        separator : ' ',
        filesToParse : /[^\s]+\.(mkv|m4v|avi|mp4|srt)$/i,
        capitaliseFirstLetter : true,
        parseYear : true,
        parseEpisode: true,
        preReplace : [ { search: /H.265/gi, replace: '' } ],
        ignoreWords : [
            '','480p','720p','1080p',
            'ITA','ENG','Subs','Sub','iTALiAN','jap','ENGLiSH',
            'hdtv','BluRay','DLMux','BDMux','BRMux','DVDRip','BrRip','BdRip','x264','x265','h264','h265','xvid','MP4','WEBRIP','PROPER','WEB','DL','DMux','Mux',
            'AC3','Mp3','aac','2CH','DTS','Dts','2HD',
            // releaser
            'TrTd_Team','HEVC','kh','iGM','GiuseppeTnT','Marco','lol','SToNeD','AlgernonWood','NovaRip','Pir8','KILLERS','ZMachine','byR02','DarkSideMux','TeRRa',
            'FoV','IGM','SATOSHi','TLA','RiVER','oRo','by','IperB','rarbg','xXTenGXx','ASAP','TRL','NAHOM','BLUWORLD'
        ]
    },

    // Capitalise the first letter
    capitaliseFirstLetter: function(string) {
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    },

    // Extract extension from filename
    getExtension: function (filename) {
        var i = filename.lastIndexOf('.');
        return (i < 0) ? '' : filename.substr(i);
    },

    // Extract episode string from word (if match)
    getEpisode: function (word, filename){
        var e,s;
        if (filename.indexOf('lol') > -1){
            var int = parseInt(word);
            if (int > 99 && int < 9999){
                s = Math.floor(int / 100);
                e = int - (s * 100);
                return  's' + ('0' + s).slice(-2) + 'e' + ('0' + e).slice(-2);
            }
        }
        // x format (es. 2x11, 1X07)
        var match = /\d{1,2}x\d{2}/i.exec(word);
        if (match){
            var xPos = word.toLowerCase().indexOf('x');
            s = parseInt(word.substr(0,xPos));
            e = parseInt(word.substr(xPos + 1));
            return  's' + ('0' + s).slice(-2) + 'e' + ('0' + e).slice(-2);
        }
        // s format (es. s02e11, S01E07)
        match = /s\d{2}e\d{2}/i.exec(word);
        if (match){
            s = parseInt(word.substr(1,2));
            e = parseInt(word.substr(4));
            return  's' + ('0' + s).slice(-2) + 'e' + ('0' + e).slice(-2);
        }
        return '';
    },

    // Check if the word must be ignored
    isIgnored: function (word){
        word = word.toLowerCase();
        for (var i = 0; i < this.config.ignoreWords.length; i++) {
            if (this.config.ignoreWords[i].toLowerCase() === word){
                return true;
            }
        }
        return false;
    },

    preReplace: function (text){
        var res = text;
        for (var i = 0; i < this.config.preReplace.length; i++) {
            res = text.replace(this.config.preReplace[i].search,this.config.preReplace[i].replace)
        }
        return res;
    },

    // Get new filename
    getFilename: function (filename){
        // find extension
        var i = filename.lastIndexOf('.');
        var extension = (i > -1) ? filename.substr(i) : '';
        if (i > -1) filename = filename.substr(0,i);
        // pre-replace
        filename = this.preReplace(filename);
        // split on words
        var words = filename.split(this.config.splitChars);
        var result = '';
        var year = '';
        var episode = '';
        for (i = 0; i < words.length; i++) {
            // word not on ignore list
            if (this.isIgnored(words[i])) continue;
            // check if is year
            if (this.config.parseYear){
                var int = parseInt(words[i]);
                if (int > 1900 && int <= new Date().getFullYear()){
                    year = this.config.separator + '(' + int + ')';
                    continue;
                }
            }
            // check if episode
            if (this.config.parseEpisode && episode == ''){
                episode = this.getEpisode(words[i], filename);
                if (episode != '') {
                    result += (result.length > 0 ? this.config.separator : '') + episode;
                    continue;
                }
            }
            // add word to result
            result += (result.length > 0 ? this.config.separator : '') +
            (this.config.capitaliseFirstLetter ? this.capitaliseFirstLetter(words[i]) : words[i]);
        }
        return result + year + extension;
    },

    // Parse entire directory
    parseDir: function (path){
        var fs = require('fs')
        fs.readdir(path, function(err, files){
            if (err) return;
            console.log('rename files on ' + path + (ren4plex.config.preview ? ' [PREVIEW MODE]' : ''));
            // loop on files
            files.forEach(function(file){
                // check if file name match
                if (!ren4plex.config.filesToParse.test(file))
                    return;
                var newName = ren4plex.getFilename(file);
                if (ren4plex.config.preview){
                    console.log(file + '->' + newName);
                    return;
                }
                fs.rename(path + '/' + file, path + '/' + newName, function (err) {
                    if (err) throw err;
                    console.log(file + '->' + newName);
                });
            });
        });
    }

};
module.exports = ren4plex;

program
    .version(package.version, '-v, --version')
    .option('-p, --preview', 'Preview mode (don\'t rename)')
//    .option('-r, --recursive', 'Recurse on all sub-directories')
    .usage('[options] [dir]')
    .parse(process.argv);
ren4plex.config.preview = program.preview;
ren4plex.parseDir(program.args[0] ? program.args[0] : '.');
<commit_msg>Update ignore list<commit_after>#!/usr/bin/env node

var program = require('commander');
var package = require('../package.json');

var ren4plex = {

    // config
    config : {
        preview: false,
        splitChars : /[.,;!:() _+\-\[\]]/,
        separator : ' ',
        filesToParse : /[^\s]+\.(mkv|m4v|avi|mp4|srt)$/i,
        capitaliseFirstLetter : true,
        parseYear : true,
        parseEpisode: true,
        preReplace : [ { search: /H.265/gi, replace: '' } ],
        ignoreWords : [
            '','480p','720p','1080p',
            'ITA','ENG','Subs','Sub','iTALiAN','jap','ENGLiSH',
            'hdtv','BluRay','DLMux','BDMux','BRMux','DVDRip','BrRip','BdRip','x264','x265','h264','h265','xvid','MP4','WEBRIP','PROPER','WEB','DL','DMux','Mux','Rip','Dvd',
            'AC3','Mp3','aac','2CH','DTS','Dts','2HD',
            // releaser
            'TrTd_Team','HEVC','kh','iGM','GiuseppeTnT','Marco','lol','SToNeD','AlgernonWood','NovaRip','Pir8','KILLERS','ZMachine','byR02','DarkSideMux','TeRRa',
            'FoV','IGM','SATOSHi','TLA','RiVER','oRo','by','IperB','rarbg','xXTenGXx','ASAP','TRL','NAHOM','BLUWORLD','Kagome'
        ]
    },

    // Capitalise the first letter
    capitaliseFirstLetter: function(string) {
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    },

    // Extract extension from filename
    getExtension: function (filename) {
        var i = filename.lastIndexOf('.');
        return (i < 0) ? '' : filename.substr(i);
    },

    // Extract episode string from word (if match)
    getEpisode: function (word, filename){
        var e,s;
        if (filename.indexOf('lol') > -1){
            var int = parseInt(word);
            if (int > 99 && int < 9999){
                s = Math.floor(int / 100);
                e = int - (s * 100);
                return  's' + ('0' + s).slice(-2) + 'e' + ('0' + e).slice(-2);
            }
        }
        // x format (es. 2x11, 1X07)
        var match = /\d{1,2}x\d{2}/i.exec(word);
        if (match){
            var xPos = word.toLowerCase().indexOf('x');
            s = parseInt(word.substr(0,xPos));
            e = parseInt(word.substr(xPos + 1));
            return  's' + ('0' + s).slice(-2) + 'e' + ('0' + e).slice(-2);
        }
        // s format (es. s02e11, S01E07)
        match = /s\d{2}e\d{2}/i.exec(word);
        if (match){
            s = parseInt(word.substr(1,2));
            e = parseInt(word.substr(4));
            return  's' + ('0' + s).slice(-2) + 'e' + ('0' + e).slice(-2);
        }
        return '';
    },

    // Check if the word must be ignored
    isIgnored: function (word){
        word = word.toLowerCase();
        for (var i = 0; i < this.config.ignoreWords.length; i++) {
            if (this.config.ignoreWords[i].toLowerCase() === word){
                return true;
            }
        }
        return false;
    },

    preReplace: function (text){
        var res = text;
        for (var i = 0; i < this.config.preReplace.length; i++) {
            res = text.replace(this.config.preReplace[i].search,this.config.preReplace[i].replace)
        }
        return res;
    },

    // Get new filename
    getFilename: function (filename){
        // find extension
        var i = filename.lastIndexOf('.');
        var extension = (i > -1) ? filename.substr(i) : '';
        if (i > -1) filename = filename.substr(0,i);
        // pre-replace
        filename = this.preReplace(filename);
        // split on words
        var words = filename.split(this.config.splitChars);
        var result = '';
        var year = '';
        var episode = '';
        for (i = 0; i < words.length; i++) {
            // word not on ignore list
            if (this.isIgnored(words[i])) continue;
            // check if is year
            if (this.config.parseYear){
                var int = parseInt(words[i]);
                if (int > 1900 && int <= new Date().getFullYear()){
                    year = this.config.separator + '(' + int + ')';
                    continue;
                }
            }
            // check if episode
            if (this.config.parseEpisode && episode == ''){
                episode = this.getEpisode(words[i], filename);
                if (episode != '') {
                    result += (result.length > 0 ? this.config.separator : '') + episode;
                    continue;
                }
            }
            // add word to result
            result += (result.length > 0 ? this.config.separator : '') +
            (this.config.capitaliseFirstLetter ? this.capitaliseFirstLetter(words[i]) : words[i]);
        }
        return result + year + extension;
    },

    // Parse entire directory
    parseDir: function (path){
        var fs = require('fs')
        fs.readdir(path, function(err, files){
            if (err) return;
            console.log('rename files on ' + path + (ren4plex.config.preview ? ' [PREVIEW MODE]' : ''));
            // loop on files
            files.forEach(function(file){
                // check if file name match
                if (!ren4plex.config.filesToParse.test(file))
                    return;
                var newName = ren4plex.getFilename(file);
                if (ren4plex.config.preview){
                    console.log(file + '->' + newName);
                    return;
                }
                fs.rename(path + '/' + file, path + '/' + newName, function (err) {
                    if (err) throw err;
                    console.log(file + '->' + newName);
                });
            });
        });
    }

};
module.exports = ren4plex;

program
    .version(package.version, '-v, --version')
    .option('-p, --preview', 'Preview mode (don\'t rename)')
//    .option('-r, --recursive', 'Recurse on all sub-directories')
    .usage('[options] [dir]')
    .parse(process.argv);
ren4plex.config.preview = program.preview;
ren4plex.parseDir(program.args[0] ? program.args[0] : '.');
<|endoftext|>


<commit_before>import Cucumber from 'cucumber'

const CUCUMBER_EVENTS = [
    'handleBeforeFeatureEvent', 'handleAfterFeatureEvent',
    'handleBeforeScenarioEvent', 'handleAfterScenarioEvent',
    'handleBeforeStepEvent', 'handleStepResultEvent'
]

/**
 * Custom Cucumber Reporter
 */
class CucumberReporter {
    constructor (BaseListener, options, cid, specs) {
        this.listener = BaseListener
        this.capabilities = options.capabilities
        this.options = options
        this.cid = cid
        this.specs = specs
        this.failedCount = 0

        for (const fnName of CUCUMBER_EVENTS) {
            this.listener[fnName] = CucumberReporter.prototype[fnName].bind(this)
        }
    }

    handleBeforeFeatureEvent (event, callback) {
        const feature = event.getUri ? event : event.getPayloadItem('feature')
        this.featureStart = new Date()
        this.runningFeature = feature

        this.emit('suite:start', {
            uid: this.getUniqueIdentifier(feature),
            title: feature.getName(),
            type: 'suite',
            file: this.getUriOf(feature)
        })

        process.nextTick(callback)
    }

    handleBeforeScenarioEvent (event, callback) {
        const scenario = event.getUri ? event : event.getPayloadItem('scenario')
        this.runningScenario = scenario
        this.scenarioStart = new Date()
        this.testStart = new Date()

        this.emit('suite:start', {
            uid: this.getUniqueIdentifier(scenario),
            title: scenario.getName(),
            parent: this.getUniqueIdentifier(this.runningFeature),
            type: 'suite',
            file: this.getUriOf(scenario)
        })

        process.nextTick(callback)
    }

    handleBeforeStepEvent (event, callback) {
        const step = event.getUri ? event : event.getPayloadItem('step')
        this.testStart = new Date()

        this.emit('test:start', {
            uid: this.getUniqueIdentifier(step),
            title: step.getName(),
            type: 'test',
            file: step.getUri(),
            parent: this.getUniqueIdentifier(this.runningScenario),
            duration: new Date() - this.testStart
        })

        process.nextTick(callback)
    }

    handleStepResultEvent (event, callback) {
        const stepResult = event.getStep ? event : event.getPayloadItem('stepResult')
        let step = stepResult.getStep()
        let e = 'undefined'

        switch (stepResult.getStatus()) {
        case Cucumber.Status.FAILED:
        case Cucumber.Status.UNDEFINED:
            e = 'fail'
            break
        case Cucumber.Status.PASSED:
            e = 'pass'
            break
        case Cucumber.Status.PENDING:
        case Cucumber.Status.SKIPPED:
        case Cucumber.Status.AMBIGUOUS:
            e = 'pending'
        }
        let error = {}
        let stepTitle = step.getName() || step.getKeyword() || 'Undefined Step'

        /**
         * if step name is undefined we are dealing with a hook
         * don't report hooks if no error happened
         */
        if (!step.getName() && stepResult.getStatus() !== Cucumber.Status.FAILED) {
            return process.nextTick(callback)
        }

        if (stepResult.getStatus() === Cucumber.Status.UNDEFINED) {
            if (this.options.ignoreUndefinedDefinitions) {
                /**
                 * mark test as pending
                 */
                e = 'pending'
                stepTitle += ' (undefined step)'
            } else {
                /**
                 * mark test as failed
                 */
                this.failedCount++

                error = {
                    message: `Step "${stepTitle}" is not defined. You can ignore this error by setting
                              cucumberOpts.ignoreUndefinedDefinitions as true.`,
                    stack: `${step.getUri()}:${step.getLine()}`
                }
            }
        } else if (stepResult.getStatus() === Cucumber.Status.FAILED) {
            /**
             * cucumber failure exception can't get send to parent process
             * for some reasons
             */
            let err = stepResult.getFailureException()
            error = {
                message: err.message,
                stack: err.stack
            }
            this.failedCount++
        } else if (stepResult.getStatus() === Cucumber.Status.AMBIGUOUS && this.options.failAmbiguousDefinitions) {
            e = 'fail'
            this.failedCount++
            error = {
                message: `Step "${stepTitle}" is ambiguous. The following steps matched the step definition`,
                stack: stepResult.getAmbiguousStepDefinitions().map(step => `${step.getPattern().toString()} in ${step.getUri()}:${step.getLine()}`).join('\n')
            }
        }

        this.emit('test:' + e, {
            uid: this.getUniqueIdentifier(step),
            title: stepTitle.trim(),
            type: 'test',
            file: this.getUriOf(step),
            parent: this.getUniqueIdentifier(this.runningScenario),
            error: error,
            duration: new Date() - this.testStart
        })

        process.nextTick(callback)
    }

    handleAfterScenarioEvent (event, callback) {
        const scenario = event.getUri ? event : event.getPayloadItem('scenario')
        this.emit('suite:end', {
            uid: this.getUniqueIdentifier(scenario),
            title: scenario.getName(),
            parent: this.getUniqueIdentifier(this.runningFeature),
            type: 'suite',
            file: this.getUriOf(scenario),
            duration: new Date() - this.scenarioStart
        })

        process.nextTick(callback)
    }

    handleAfterFeatureEvent (event, callback) {
        const feature = event.getUri ? event : event.getPayloadItem('feature')
        this.emit('suite:end', {
            uid: this.getUniqueIdentifier(feature),
            title: feature.getName(),
            type: 'suite',
            file: this.getUriOf(feature),
            duration: new Date() - this.featureStart
        })

        process.nextTick(callback)
    }

    emit (event, payload) {
        let message = {
            event: event,
            cid: this.cid,
            uid: this.getUniqueIdentifier(payload),
            title: payload.title,
            pending: payload.pending || false,
            parent: payload.parent || null,
            type: payload.type,
            file: payload.file,
            err: payload.error || {},
            duration: payload.duration,
            runner: {},
            specs: this.specs
        }

        message.runner[this.cid] = this.capabilities
        this.send(message)
    }

    send (message) {
        return process.send(message)
    }

    getListener () {
        return this.listener
    }

    getUriOf (type) {
        if (!type || !type.getUri()) {
            return
        }

        return type.getUri().replace(process.cwd(), '')
    }

    getUniqueIdentifier (target) {
        return target.getName() +
                (target.getLine() || '')
    }
}

export default CucumberReporter
<commit_msg>Removed trailing space<commit_after>import Cucumber from 'cucumber'

const CUCUMBER_EVENTS = [
    'handleBeforeFeatureEvent', 'handleAfterFeatureEvent',
    'handleBeforeScenarioEvent', 'handleAfterScenarioEvent',
    'handleBeforeStepEvent', 'handleStepResultEvent'
]

/**
 * Custom Cucumber Reporter
 */
class CucumberReporter {
    constructor (BaseListener, options, cid, specs) {
        this.listener = BaseListener
        this.capabilities = options.capabilities
        this.options = options
        this.cid = cid
        this.specs = specs
        this.failedCount = 0

        for (const fnName of CUCUMBER_EVENTS) {
            this.listener[fnName] = CucumberReporter.prototype[fnName].bind(this)
        }
    }

    handleBeforeFeatureEvent (event, callback) {
        const feature = event.getUri ? event : event.getPayloadItem('feature')
        this.featureStart = new Date()
        this.runningFeature = feature

        this.emit('suite:start', {
            uid: this.getUniqueIdentifier(feature),
            title: feature.getName(),
            type: 'suite',
            file: this.getUriOf(feature)
        })

        process.nextTick(callback)
    }

    handleBeforeScenarioEvent (event, callback) {
        const scenario = event.getUri ? event : event.getPayloadItem('scenario')
        this.runningScenario = scenario
        this.scenarioStart = new Date()
        this.testStart = new Date()

        this.emit('suite:start', {
            uid: this.getUniqueIdentifier(scenario),
            title: scenario.getName(),
            parent: this.getUniqueIdentifier(this.runningFeature),
            type: 'suite',
            file: this.getUriOf(scenario)
        })

        process.nextTick(callback)
    }

    handleBeforeStepEvent (event, callback) {
        const step = event.getUri ? event : event.getPayloadItem('step')
        this.testStart = new Date()

        this.emit('test:start', {
            uid: this.getUniqueIdentifier(step),
            title: step.getName(),
            type: 'test',
            file: step.getUri(),
            parent: this.getUniqueIdentifier(this.runningScenario),
            duration: new Date() - this.testStart
        })

        process.nextTick(callback)
    }

    handleStepResultEvent (event, callback) {
        const stepResult = event.getStep ? event : event.getPayloadItem('stepResult')
        let step = stepResult.getStep()
        let e = 'undefined'

        switch (stepResult.getStatus()) {
        case Cucumber.Status.FAILED:
        case Cucumber.Status.UNDEFINED:
            e = 'fail'
            break
        case Cucumber.Status.PASSED:
            e = 'pass'
            break
        case Cucumber.Status.PENDING:
        case Cucumber.Status.SKIPPED:
        case Cucumber.Status.AMBIGUOUS:
            e = 'pending'
        }
        let error = {}
        let stepTitle = step.getName() || step.getKeyword() || 'Undefined Step'

        /**
         * if step name is undefined we are dealing with a hook
         * don't report hooks if no error happened
         */
        if (!step.getName() && stepResult.getStatus() !== Cucumber.Status.FAILED) {
            return process.nextTick(callback)
        }

        if (stepResult.getStatus() === Cucumber.Status.UNDEFINED) {
            if (this.options.ignoreUndefinedDefinitions) {
                /**
                 * mark test as pending
                 */
                e = 'pending'
                stepTitle += ' (undefined step)'
            } else {
                /**
                 * mark test as failed
                 */
                this.failedCount++

                error = {
                    message: `Step "${stepTitle}" is not defined. You can ignore this error by setting
                              cucumberOpts.ignoreUndefinedDefinitions as true.`,
                    stack: `${step.getUri()}:${step.getLine()}`
                }
            }
        } else if (stepResult.getStatus() === Cucumber.Status.FAILED) {
            /**
             * cucumber failure exception can't get send to parent process
             * for some reasons
             */
            let err = stepResult.getFailureException()
            error = {
                message: err.message,
                stack: err.stack
            }
            this.failedCount++
        } else if (stepResult.getStatus() === Cucumber.Status.AMBIGUOUS && this.options.failAmbiguousDefinitions) {
            e = 'fail'
            this.failedCount++
            error = {
                message: `Step "${stepTitle}" is ambiguous. The following steps matched the step definition`,
                stack: stepResult.getAmbiguousStepDefinitions().map(step => `${step.getPattern().toString()} in ${step.getUri()}:${step.getLine()}`).join('\n')
            }
        }

        this.emit('test:' + e, {
            uid: this.getUniqueIdentifier(step),
            title: stepTitle.trim(),
            type: 'test',
            file: this.getUriOf(step),
            parent: this.getUniqueIdentifier(this.runningScenario),
            error: error,
            duration: new Date() - this.testStart
        })

        process.nextTick(callback)
    }

    handleAfterScenarioEvent (event, callback) {
        const scenario = event.getUri ? event : event.getPayloadItem('scenario')
        this.emit('suite:end', {
            uid: this.getUniqueIdentifier(scenario),
            title: scenario.getName(),
            parent: this.getUniqueIdentifier(this.runningFeature),
            type: 'suite',
            file: this.getUriOf(scenario),
            duration: new Date() - this.scenarioStart
        })

        process.nextTick(callback)
    }

    handleAfterFeatureEvent (event, callback) {
        const feature = event.getUri ? event : event.getPayloadItem('feature')
        this.emit('suite:end', {
            uid: this.getUniqueIdentifier(feature),
            title: feature.getName(),
            type: 'suite',
            file: this.getUriOf(feature),
            duration: new Date() - this.featureStart
        })

        process.nextTick(callback)
    }

    emit (event, payload) {
        let message = {
            event: event,
            cid: this.cid,
            uid: this.getUniqueIdentifier(payload),
            title: payload.title,
            pending: payload.pending || false,
            parent: payload.parent || null,
            type: payload.type,
            file: payload.file,
            err: payload.error || {},
            duration: payload.duration,
            runner: {},
            specs: this.specs
        }

        message.runner[this.cid] = this.capabilities
        this.send(message)
    }

    send (message) {
        return process.send(message)
    }

    getListener () {
        return this.listener
    }

    getUriOf (type) {
        if (!type || !type.getUri()) {
            return
        }

        return type.getUri().replace(process.cwd(), '')
    }

    getUniqueIdentifier (target) {
        return target.getName() +
                (target.getLine() || '')
    }
}

export default CucumberReporter
<|endoftext|>


<commit_before>const t = require('../test-lib/test.js');
const assert = require('assert');
let apos;

describe('Pieces Pages', function() {

  this.timeout(t.timeout);

  after(async function() {
    return t.destroy(apos);
  });

  // EXISTENCE

  it('should initialize', async function() {
    apos = await t.create({
      root: module,
      modules: {
        event: {
          extend: '@apostrophecms/piece-type',
          options: {
            name: 'event',
            label: 'Event',
            alias: 'event',
            sort: { title: 1 }
          }
        },
        'event-page': {
          extend: '@apostrophecms/piece-page-type',
          options: {
            name: 'eventPage',
            label: 'Event',
            alias: 'eventPage',
            perPage: 10
          }
        },
        '@apostrophecms/page': {
          options: {
            park: [
              {
                title: 'Events',
                type: 'eventPage',
                slug: '/events',
                parkedId: 'events'
              }
            ]
          }
        }
      }
    });
  });

  it('should be able to use db to insert test pieces', async function() {
    assert(apos.modules.event);
    const testItems = [];
    const total = 100;
    for (let i = 1; (i <= total); i++) {
      const paddedInt = apos.launder.padInteger(i, 3);

      testItems.push({
        _id: 'event' + paddedInt,
        slug: 'event-' + paddedInt,
        visibility: 'public',
        type: 'event',
        title: 'Event ' + paddedInt,
        titleSortified: 'event ' + paddedInt,
        body: {
          metaType: 'area',
          _id: apos.util.generateId(),
          items: [
            {
              metaType: 'widget',
              type: '@apostrophecms/rich-text',
              content: '
This is some content.
'
            }
          ]
        }
      });
    }

    return apos.doc.db.insertMany(testItems);
  });

  it('should populate the ._url property of pieces in any docs query', async function() {
    const piece = await apos.doc.find(apos.task.getAnonReq(), {
      type: 'event',
      title: 'Event 001'
    }).toObject();
    assert(piece);
    assert(piece._url);
    assert(piece._url === '/events/event-001');
  });

  it('should not correctly populate the ._url property of pieces in a docs query with an inadequate projection', async function() {
    const piece = await apos.doc.find(apos.task.getAnonReq(), {
      type: 'event',
      title: 'Event 001'
    }, {
      project: {
        type: 1
      }
    }).toObject();
    assert(piece);
    assert((!piece._url) || (piece._url.match(/undefined/)));
  });

  it('should correctly populate the ._url property of pieces in a docs query if _url itself is "projected"', async function() {
    const piece = await apos.doc.find(apos.task.getAnonReq(), {
      type: 'event',
      title: 'Event 001'
    }, {
      project: {
        _url: 1
      }
    }).toObject();
    assert(piece);
    assert(piece._url);
    assert(piece._url === '/events/event-001');
  });

  it('should be able to access index page with first event on it, but not eleventh event', async function() {

    const body = await apos.http.get('/events');
    // Only page one events should show up
    assert(body.match(/event-001"/));
    assert(!body.match(/event-011"/));
  });

  it('should be able to access second page', async function() {
    const body = await apos.http.get('/events?page=2');
    // Only page two events should show up
    assert(body.match(/event-011"/));
    assert(!body.match(/event-001"/));
  });

  it('should be able to access "show" page for first event, should not also contain second event', async function() {
    const body = await apos.http.get('/events/event-001');
    // Only event 1's title should show up
    assert(body.match(/Event 001/));
    assert(!body.match(/Event 002/));
  });

});
<commit_msg>Add tests for fix<commit_after>const t = require('../test-lib/test.js');
const assert = require('assert');
let apos;

describe('Pieces Pages', function() {

  this.timeout(t.timeout);

  after(async function() {
    return t.destroy(apos);
  });

  // EXISTENCE

  it('should initialize', async function() {
    apos = await t.create({
      root: module,
      modules: {
        event: {
          extend: '@apostrophecms/piece-type',
          options: {
            name: 'event',
            label: 'Event',
            alias: 'event',
            sort: { title: 1 }
          }
        },
        'event-page': {
          extend: '@apostrophecms/piece-page-type',
          options: {
            name: 'eventPage',
            label: 'Event',
            alias: 'eventPage',
            perPage: 10
          }
        },
        root: {
          extend: '@apostrophecms/piece-type',
          options: {
            name: 'root',
            label: 'Root',
            alias: 'root',
            sort: { title: 1 }
          }
        },
        'root-piece-pages': {
          extend: '@apostrophecms/piece-page-type',
          options: {
            name: 'rootPiecePage',
            label: 'Root Piece Page',
            alias: 'rootPiecePage',
            perPage: 10
          }
        },
        '@apostrophecms/page': {
          options: {
            park: [
              {
                title: 'Events',
                type: 'eventPage',
                slug: '/events',
                parkedId: 'events'
              },
              {
                title: 'Root piece page',
                type: 'rootPiecePage',
                slug: '/',
                parkedId: 'root'
              }
            ]
          }
        }
      }
    });
  });

  it('should be able to use db to insert test pieces', async function() {
    assert(apos.modules.event);
    const testItems = [];
    const total = 100;
    for (let i = 1; (i <= total); i++) {
      const paddedInt = apos.launder.padInteger(i, 3);

      testItems.push({
        _id: 'event' + paddedInt,
        slug: 'event-' + paddedInt,
        visibility: 'public',
        type: 'event',
        title: 'Event ' + paddedInt,
        titleSortified: 'event ' + paddedInt,
        body: {
          metaType: 'area',
          _id: apos.util.generateId(),
          items: [
            {
              metaType: 'widget',
              type: '@apostrophecms/rich-text',
              content: '
This is some content.
'
            }
          ]
        }
      });
    }

    return apos.doc.db.insertMany(testItems);
  });

  it('should populate the ._url property of pieces in any docs query', async function() {
    const piece = await apos.doc.find(apos.task.getAnonReq(), {
      type: 'event',
      title: 'Event 001'
    }).toObject();
    assert(piece);
    assert(piece._url);
    assert(piece._url === '/events/event-001');
  });

  it('should not correctly populate the ._url property of pieces in a docs query with an inadequate projection', async function() {
    const piece = await apos.doc.find(apos.task.getAnonReq(), {
      type: 'event',
      title: 'Event 001'
    }, {
      project: {
        type: 1
      }
    }).toObject();
    assert(piece);
    assert((!piece._url) || (piece._url.match(/undefined/)));
  });

  it('should not create a double-slashed _url on a piece-page-type set as the homepage', async function() {
    const piece = await apos.doc.find(apos.task.getAnonReq(), {
      type: 'root',
      title: 'Root 001'
    }, {
      project: {
        type: 1
      }
    }).toObject();
    assert(piece);
    assert(piece._url === '/root-001');
  });

  it('should correctly populate the ._url property of pieces in a docs query if _url itself is "projected"', async function() {
    const piece = await apos.doc.find(apos.task.getAnonReq(), {
      type: 'event',
      title: 'Event 001'
    }, {
      project: {
        _url: 1
      }
    }).toObject();
    assert(piece);
    assert(piece._url);
    assert(piece._url === '/events/event-001');
  });

  it('should be able to access index page with first event on it, but not eleventh event', async function() {

    const body = await apos.http.get('/events');
    // Only page one events should show up
    assert(body.match(/event-001"/));
    assert(!body.match(/event-011"/));
  });

  it('should be able to access second page', async function() {
    const body = await apos.http.get('/events?page=2');
    // Only page two events should show up
    assert(body.match(/event-011"/));
    assert(!body.match(/event-001"/));
  });

  it('should be able to access "show" page for first event, should not also contain second event', async function() {
    const body = await apos.http.get('/events/event-001');
    // Only event 1's title should show up
    assert(body.match(/Event 001/));
    assert(!body.match(/Event 002/));
  });

});
<|endoftext|>