<commit_before>/*$AMPERSAND_VERSION*/
var includes = require('lodash.includes');
var difference = require('lodash.difference');
var forEach = require('lodash.foreach');
var every = require('lodash.every');
var assign = require('lodash.assign');
var isArray = require('lodash.isarray');
var isEqual = require('lodash.isequal');
var keys = require('lodash.keys');
var reduce = require('lodash.reduce');
var sortBy = require('lodash.sortBy');
var sortedIndex = require('lodash.sortedindex');
var union = require('lodash.union');
var classExtend = require('ampersand-class-extend');
var Events = require('ampersand-events');

var slice = Array.prototype.slice;

function FilteredCollection(collection, spec) {
    this.collection = collection;
    this.indexes = collection.indexes || [];
    this._indexes = {};
    this._resetIndexes(this._indexes);
    this.mainIndex = collection.mainIndex;
    this.models = []; //Our filtered, models
    this.configure(spec || {}, true);
    this.listenTo(this.collection, 'all', this._onCollectionEvent);
}

assign(FilteredCollection.prototype, Events, {
    // Public API

    // add a filter function directly
    addFilter: function (filter) {
        this.swapFilters([filter], []);
    },

    // remove filter function directly
    removeFilter: function (filter) {
        this.swapFilters([], [filter]);
    },

    // clears filters fires events for each add/remove
    clearFilters: function () {
        this._resetFilters();
        this._runFilters();
    },

    // Swap out a set of old filters with a set of
    // new filters
    swapFilters: function (newFilters, oldFilters) {
        var self = this;

        if (!oldFilters) {
            oldFilters = this._filters;
        } else if (!isArray(oldFilters)) {
            oldFilters = [oldFilters];
        }

        if (!newFilters) {
            newFilters = [];
        } else if (!isArray(newFilters)) {
            newFilters = [newFilters];
        }

        oldFilters.forEach(function (filter) {
            self._removeFilter(filter);
        });

        newFilters.forEach(function (filter) {
            self._addFilter(filter);
        });

        this._runFilters();
    },

    // Update config with potentially new filters/where/etc
    configure: function (opts, clear) {
        if (clear) this._resetFilters(clear);
        this._parseSpec(opts);
        if (clear) this._runFilters();
    },

    // gets a model at a given index
    at: function (index) {
        return this.models[index];
    },

    // proxy `get` method to the underlying collection
    get: function (query, indexName) {
        var model = this.collection.get(query, indexName);
        if (model && includes(this.models, model)) return model;
    },

    // clear all filters, reset everything
    reset: function () {
        this.configure({}, true);
    },

    // Internal API

    // try to get a model by index
    _indexedGet: function (query, indexName) {
        if (!query) return;
        var index = this._indexes[indexName || this.mainIndex];
        return index[query] || index[query[this.mainIndex]] || this._indexes.cid[query] || this._indexes.cid[query.cid];
    },

    _parseSpec: function (spec) {
        if (spec.watched) this._watch(spec.watched);
        //this.comparator = this.collection.comparator;
        if (spec.comparator) this.comparator = spec.comparator;
        if (spec.where) {
            forEach(spec.where, function (value, item) {
                this._addFilter(function (model) {
                    return (model.get ? model.get(item) : model[item]) === value;
                });
            }, this);
            // also make sure we watch all `where` keys
            this._watch(keys(spec.where));
        }
        if (spec.filter) {
            this._addFilter(spec.filter);
        }
        if (spec.filters) {
            spec.filters.forEach(this._addFilter, this);
        }
    },
    // internal method registering new filter function
    _addFilter: function (filter) {
        this._filters.push(filter);
    },

    // remove filter if found
    _removeFilter: function (filter) {
        var index = this._filters.indexOf(filter);
        if (index !== -1) {
            this._filters.splice(index, 1);
        }
    },

    // just reset filters, no model changes
    _resetFilters: function (resetComparator) {
        this._filters = [];
        this._watched = [];
        if (resetComparator) this.comparator = undefined;
    },

    // adds a property or array of properties to watch, ensures uniquness.
    _watch: function (items) {
        this._watched = union(this._watched, items);
    },

    // removes a watched property
    _unwatch: function (item) {
        this._watched = difference(this._watched, isArray(item) ? item : [item]);
    },

    _sortModels: function (newModels) {
        var comparator = this.comparator || this.collection.comparator;
        if (comparator) {
            newModels = sortBy(newModels, comparator);
        } else {
            // This only happens when parent got a .set with options.at defined
            this._runFilters();
        }
        return newModels;
    },

    //Add a model to this filtered collection that has already passed the filters
    _addModel: function (model, options, eventName) {
        var newModels = slice.call(this.models);
        var comparator = this.comparator || this.collection.comparator;
        //Whether or not we are to expect a sort event from our collection later
        var sortable = eventName === 'add' && this.collection.comparator && (options.at == null) && options.sort !== false;
        if (!sortable) {
            var index = sortedIndex(newModels, model, comparator);
            newModels.splice(index, 0, model);
        } else {
            newModels.push(model);
            if (options.at) newModels = this._sortModels(newModels);
        }

        this.models = newModels;
        this._addIndex(this._indexes, model);
        if (this.comparator && !sortable) {
            this.trigger('sort', this);
        }
    },

    //Remove a model if it's in this filtered collection
    _removeModel: function (model) {
        var newModels = slice.call(this.models);
        var modelIndex = newModels.indexOf(model);
        if (modelIndex > -1) {
            newModels.splice(modelIndex, 1);
            this.models = newModels;
            this._removeIndex(this._indexes, model);
            return true;
        }
        return false;
    },

    //Test if a model passes our filters
    _testModel: function (model) {
        if (this._filters.length === 0) {
            return true;
        }
        return every(this._filters, function (filter) {
            return filter(model);
        });
    },

    _addIndex: function (newIndexes, model) {
        for (var name in this._indexes) {
            var indexVal = model[name] || (model.get && model.get(name));
            if (indexVal) newIndexes[name][indexVal] = model;
        }
    },

    _removeIndex: function (newIndexes, model) {
        for (var name in this._indexes) {
            delete this._indexes[name][model[name] || (model.get && model.get(name))];
        }
    },

    _resetIndexes: function (newIndexes) {
        var list = slice.call(this.indexes);
        list.push(this.mainIndex);
        list.push('cid');
        for (var i = 0; i < list.length; i++) {
            newIndexes[list[i]] = {};
        }
    },

    // Re-run the filters on all our parent's models
    _runFilters: function () {
        // make a copy of the array for comparisons
        var existingModels = slice.call(this.models);
        var rootModels = slice.call(this.collection.models);
        var newIndexes = {};
        var newModels, toAdd, toRemove;

        this._resetIndexes(newIndexes);

        // reduce base model set by applying filters
        if (this._filters.length) {
            newModels = reduce(this._filters, function (startingArray, filterFunc) {
                return startingArray.filter(filterFunc);
            }, rootModels);
        } else {
            newModels = slice.call(rootModels);
        }

        // sort it
        if (this.comparator) newModels = sortBy(newModels, this.comparator);

        newModels.forEach(function (model) {
            this._addIndex(newIndexes, model);
        }, this);

        // Cache a reference to the full filtered set to allow this._filtered.length. Ref: #6
        if (rootModels.length) {
            this._filtered = newModels;
            this._indexes = newIndexes;
        } else {
            this._filtered = [];
            this._resetIndexes(this._indexes);
        }

        // now we've got our new models time to compare
        toAdd = difference(newModels, existingModels);
        toRemove = difference(existingModels, newModels);

        // save 'em
        this.models = newModels;

        forEach(toRemove, function (model) {
            this.trigger('remove', model, this);
        }, this);

        forEach(toAdd, function (model) {
            this.trigger('add', model, this);
        }, this);

        // unless we have the same models in same order trigger `sort`
        if (!isEqual(existingModels, newModels) && this.comparator) {
            this.trigger('sort', this);
        }
    },

    _onCollectionEvent: function (eventName, model, that, options) {
        /*jshint -W030 */
        options || (options = {});
        var accepted;
        var propName = eventName.split(':')[1];
        var action = eventName;
        var alreadyHave = this._indexedGet(model);
        //Whether or not we are to expect a sort event from our collection later
        var sortable = this.collection.comparator && (options.at == null) && (options.sort !== false);
        var add = options.add;
        var remove = options.remove;
        var ordered = !sortable && add && remove;

        if (
            (propName !== undefined && propName === this.comparator) ||
            includes(this._watched, propName)
        ) { //If a property we care about changed
            accepted = this._testModel(model);

            if (!alreadyHave && accepted) {
                action = 'add';
            } else if (alreadyHave && !accepted) {
                action = 'remove';
            } else {
                action = 'ignore';
            }
        } else if (action === 'add') { //See if we really want to add
            if (!this._testModel(model) || alreadyHave) {
                action = 'ignore';
            }
        }

        // action has now passed the filters

        if (action === 'reset') return this._runFilters();

        if (action === 'add') {
            if (this.models.length === 0) {
                this._runFilters();
            } else {
                this._addModel(model, options, eventName);
                this.trigger('add', model, this);
            }
            return;
        }

        if (action === 'remove') {
           if (this._removeModel(model)) {
               this.trigger('remove', model, this);
           }
           return;
        }

        if (action !== 'ignore') this.trigger.apply(this, arguments);

        //If we were asked to sort, or we aren't gonna get a sort later and had a sortable property change
        if (action === 'sort' || (propName && !sortable && includes([this.comparator, this.collection.comparator]), propName))
       {
            if (ordered && model.isNew) return; //We'll get a sort later
            this.models = this._sortModels(this.models);
            if (this.comparator && action !== 'sort') {
                this.trigger('sort', this);
            }
        }

    }

});

Object.defineProperty(FilteredCollection.prototype, 'length', {
    get: function () {
        return this.models.length;
    }
});

Object.defineProperty(FilteredCollection.prototype, 'isCollection', {
    get: function () {
        return true;
    }
});

FilteredCollection.extend = classExtend;

module.exports = FilteredCollection;
<commit_msg>typo fix<commit_after>/*$AMPERSAND_VERSION*/
var includes = require('lodash.includes');
var difference = require('lodash.difference');
var forEach = require('lodash.foreach');
var every = require('lodash.every');
var assign = require('lodash.assign');
var isArray = require('lodash.isarray');
var isEqual = require('lodash.isequal');
var keys = require('lodash.keys');
var reduce = require('lodash.reduce');
var sortBy = require('lodash.sortby');
var sortedIndex = require('lodash.sortedindex');
var union = require('lodash.union');
var classExtend = require('ampersand-class-extend');
var Events = require('ampersand-events');

var slice = Array.prototype.slice;

function FilteredCollection(collection, spec) {
    this.collection = collection;
    this.indexes = collection.indexes || [];
    this._indexes = {};
    this._resetIndexes(this._indexes);
    this.mainIndex = collection.mainIndex;
    this.models = []; //Our filtered, models
    this.configure(spec || {}, true);
    this.listenTo(this.collection, 'all', this._onCollectionEvent);
}

assign(FilteredCollection.prototype, Events, {
    // Public API

    // add a filter function directly
    addFilter: function (filter) {
        this.swapFilters([filter], []);
    },

    // remove filter function directly
    removeFilter: function (filter) {
        this.swapFilters([], [filter]);
    },

    // clears filters fires events for each add/remove
    clearFilters: function () {
        this._resetFilters();
        this._runFilters();
    },

    // Swap out a set of old filters with a set of
    // new filters
    swapFilters: function (newFilters, oldFilters) {
        var self = this;

        if (!oldFilters) {
            oldFilters = this._filters;
        } else if (!isArray(oldFilters)) {
            oldFilters = [oldFilters];
        }

        if (!newFilters) {
            newFilters = [];
        } else if (!isArray(newFilters)) {
            newFilters = [newFilters];
        }

        oldFilters.forEach(function (filter) {
            self._removeFilter(filter);
        });

        newFilters.forEach(function (filter) {
            self._addFilter(filter);
        });

        this._runFilters();
    },

    // Update config with potentially new filters/where/etc
    configure: function (opts, clear) {
        if (clear) this._resetFilters(clear);
        this._parseSpec(opts);
        if (clear) this._runFilters();
    },

    // gets a model at a given index
    at: function (index) {
        return this.models[index];
    },

    // proxy `get` method to the underlying collection
    get: function (query, indexName) {
        var model = this.collection.get(query, indexName);
        if (model && includes(this.models, model)) return model;
    },

    // clear all filters, reset everything
    reset: function () {
        this.configure({}, true);
    },

    // Internal API

    // try to get a model by index
    _indexedGet: function (query, indexName) {
        if (!query) return;
        var index = this._indexes[indexName || this.mainIndex];
        return index[query] || index[query[this.mainIndex]] || this._indexes.cid[query] || this._indexes.cid[query.cid];
    },

    _parseSpec: function (spec) {
        if (spec.watched) this._watch(spec.watched);
        //this.comparator = this.collection.comparator;
        if (spec.comparator) this.comparator = spec.comparator;
        if (spec.where) {
            forEach(spec.where, function (value, item) {
                this._addFilter(function (model) {
                    return (model.get ? model.get(item) : model[item]) === value;
                });
            }, this);
            // also make sure we watch all `where` keys
            this._watch(keys(spec.where));
        }
        if (spec.filter) {
            this._addFilter(spec.filter);
        }
        if (spec.filters) {
            spec.filters.forEach(this._addFilter, this);
        }
    },
    // internal method registering new filter function
    _addFilter: function (filter) {
        this._filters.push(filter);
    },

    // remove filter if found
    _removeFilter: function (filter) {
        var index = this._filters.indexOf(filter);
        if (index !== -1) {
            this._filters.splice(index, 1);
        }
    },

    // just reset filters, no model changes
    _resetFilters: function (resetComparator) {
        this._filters = [];
        this._watched = [];
        if (resetComparator) this.comparator = undefined;
    },

    // adds a property or array of properties to watch, ensures uniquness.
    _watch: function (items) {
        this._watched = union(this._watched, items);
    },

    // removes a watched property
    _unwatch: function (item) {
        this._watched = difference(this._watched, isArray(item) ? item : [item]);
    },

    _sortModels: function (newModels) {
        var comparator = this.comparator || this.collection.comparator;
        if (comparator) {
            newModels = sortBy(newModels, comparator);
        } else {
            // This only happens when parent got a .set with options.at defined
            this._runFilters();
        }
        return newModels;
    },

    //Add a model to this filtered collection that has already passed the filters
    _addModel: function (model, options, eventName) {
        var newModels = slice.call(this.models);
        var comparator = this.comparator || this.collection.comparator;
        //Whether or not we are to expect a sort event from our collection later
        var sortable = eventName === 'add' && this.collection.comparator && (options.at == null) && options.sort !== false;
        if (!sortable) {
            var index = sortedIndex(newModels, model, comparator);
            newModels.splice(index, 0, model);
        } else {
            newModels.push(model);
            if (options.at) newModels = this._sortModels(newModels);
        }

        this.models = newModels;
        this._addIndex(this._indexes, model);
        if (this.comparator && !sortable) {
            this.trigger('sort', this);
        }
    },

    //Remove a model if it's in this filtered collection
    _removeModel: function (model) {
        var newModels = slice.call(this.models);
        var modelIndex = newModels.indexOf(model);
        if (modelIndex > -1) {
            newModels.splice(modelIndex, 1);
            this.models = newModels;
            this._removeIndex(this._indexes, model);
            return true;
        }
        return false;
    },

    //Test if a model passes our filters
    _testModel: function (model) {
        if (this._filters.length === 0) {
            return true;
        }
        return every(this._filters, function (filter) {
            return filter(model);
        });
    },

    _addIndex: function (newIndexes, model) {
        for (var name in this._indexes) {
            var indexVal = model[name] || (model.get && model.get(name));
            if (indexVal) newIndexes[name][indexVal] = model;
        }
    },

    _removeIndex: function (newIndexes, model) {
        for (var name in this._indexes) {
            delete this._indexes[name][model[name] || (model.get && model.get(name))];
        }
    },

    _resetIndexes: function (newIndexes) {
        var list = slice.call(this.indexes);
        list.push(this.mainIndex);
        list.push('cid');
        for (var i = 0; i < list.length; i++) {
            newIndexes[list[i]] = {};
        }
    },

    // Re-run the filters on all our parent's models
    _runFilters: function () {
        // make a copy of the array for comparisons
        var existingModels = slice.call(this.models);
        var rootModels = slice.call(this.collection.models);
        var newIndexes = {};
        var newModels, toAdd, toRemove;

        this._resetIndexes(newIndexes);

        // reduce base model set by applying filters
        if (this._filters.length) {
            newModels = reduce(this._filters, function (startingArray, filterFunc) {
                return startingArray.filter(filterFunc);
            }, rootModels);
        } else {
            newModels = slice.call(rootModels);
        }

        // sort it
        if (this.comparator) newModels = sortBy(newModels, this.comparator);

        newModels.forEach(function (model) {
            this._addIndex(newIndexes, model);
        }, this);

        // Cache a reference to the full filtered set to allow this._filtered.length. Ref: #6
        if (rootModels.length) {
            this._filtered = newModels;
            this._indexes = newIndexes;
        } else {
            this._filtered = [];
            this._resetIndexes(this._indexes);
        }

        // now we've got our new models time to compare
        toAdd = difference(newModels, existingModels);
        toRemove = difference(existingModels, newModels);

        // save 'em
        this.models = newModels;

        forEach(toRemove, function (model) {
            this.trigger('remove', model, this);
        }, this);

        forEach(toAdd, function (model) {
            this.trigger('add', model, this);
        }, this);

        // unless we have the same models in same order trigger `sort`
        if (!isEqual(existingModels, newModels) && this.comparator) {
            this.trigger('sort', this);
        }
    },

    _onCollectionEvent: function (eventName, model, that, options) {
        /*jshint -W030 */
        options || (options = {});
        var accepted;
        var propName = eventName.split(':')[1];
        var action = eventName;
        var alreadyHave = this._indexedGet(model);
        //Whether or not we are to expect a sort event from our collection later
        var sortable = this.collection.comparator && (options.at == null) && (options.sort !== false);
        var add = options.add;
        var remove = options.remove;
        var ordered = !sortable && add && remove;

        if (
            (propName !== undefined && propName === this.comparator) ||
            includes(this._watched, propName)
        ) { //If a property we care about changed
            accepted = this._testModel(model);

            if (!alreadyHave && accepted) {
                action = 'add';
            } else if (alreadyHave && !accepted) {
                action = 'remove';
            } else {
                action = 'ignore';
            }
        } else if (action === 'add') { //See if we really want to add
            if (!this._testModel(model) || alreadyHave) {
                action = 'ignore';
            }
        }

        // action has now passed the filters

        if (action === 'reset') return this._runFilters();

        if (action === 'add') {
            if (this.models.length === 0) {
                this._runFilters();
            } else {
                this._addModel(model, options, eventName);
                this.trigger('add', model, this);
            }
            return;
        }

        if (action === 'remove') {
           if (this._removeModel(model)) {
               this.trigger('remove', model, this);
           }
           return;
        }

        if (action !== 'ignore') this.trigger.apply(this, arguments);

        //If we were asked to sort, or we aren't gonna get a sort later and had a sortable property change
        if (action === 'sort' || (propName && !sortable && includes([this.comparator, this.collection.comparator]), propName))
       {
            if (ordered && model.isNew) return; //We'll get a sort later
            this.models = this._sortModels(this.models);
            if (this.comparator && action !== 'sort') {
                this.trigger('sort', this);
            }
        }

    }

});

Object.defineProperty(FilteredCollection.prototype, 'length', {
    get: function () {
        return this.models.length;
    }
});

Object.defineProperty(FilteredCollection.prototype, 'isCollection', {
    get: function () {
        return true;
    }
});

FilteredCollection.extend = classExtend;

module.exports = FilteredCollection;
<|endoftext|>


<commit_before>'use strict';

var genoBrowserServices = angular.module('genoBrowserServices', ['ngResource']);

genoBrowserServices.factory('Users', ['$resource',
  function($resource){
    return $resource('users/:id');
  }]);

genoBrowserServices.factory('Tracks', ['$resource',
  function($resource){
    return $resource('tracks/:id');
  }]);

<commit_msg>no functional change<commit_after>'use strict';

var genoBrowserServices = angular.module('genoBrowserServices', ['ngResource']);

genoBrowserServices.factory('Users', ['$resource',
  function($resource){
    return $resource('users/:id');
  }]);

genoBrowserServices.factory('Tracks', ['$resource',
  function($resource){
    return $resource('tracks/:id', {}, {headers: {'X-UserId':'1'}});
  }]);<|endoftext|>


<commit_before>'use strict';

angular.module('<%=angularAppName%>')
    .factory('Password', function ($resource) {
        return $resource('api/account/change_password', {}, {
        });
    });

angular.module('jhipsterApp')
    .factory('PasswordResetInit', function ($resource) {
        return $resource('api/account/reset_password/init', {}, {
        })
    });

angular.module('jhipsterApp')
    .factory('PasswordResetFinish', function ($resource) {
        return $resource('api/account/reset_password/finish', {}, {
        })
    });
<commit_msg>Correct static angular app name<commit_after>'use strict';

angular.module('<%=angularAppName%>')
    .factory('Password', function ($resource) {
        return $resource('api/account/change_password', {}, {
        });
    });

angular.module('<%=angularAppName%>')
    .factory('PasswordResetInit', function ($resource) {
        return $resource('api/account/reset_password/init', {}, {
        })
    });

angular.module('<%=angularAppName%>')
    .factory('PasswordResetFinish', function ($resource) {
        return $resource('api/account/reset_password/finish', {}, {
        })
    });
<|endoftext|>


<commit_before>appendArchivaVersion=function(){
  return "_archivaVersion="+window.archivaRuntimeInfo.version;
}

timestampNoCache=function(){
  if (window.archivaRuntimeInfo.version.match("SNAPSHOT$")=="SNAPSHOT"){
    return "&archivaTimestamp="+window.archivaRuntimeInfo.timestamp+(window.archivaRuntimeInfo.devMode?"&_="+jQuery.now():"");
  }
  return "";
}

appendTemplateUrl=function(){
  return appendArchivaVersion()+timestampNoCache();
}

appendJsNoCacheUrl=function(){
  return appendArchivaVersion()+timestampNoCache();
}

$.ajax({
    url: "restServices/archivaUiServices/runtimeInfoService/archivaRuntimeInfo/en",
    dataType: 'json',
    cache: false,
    success:function(data){

        window.archivaDevMode=data.devMode;
        window.archivaJavascriptLog=data.javascriptLog;
        window.archivaRuntimeInfo=data;

            requirejs.config({
                baseUrl: "js/",
                urlArgs: ""+appendJsNoCacheUrl(),
                shim: {
                      'sammy':['jquery','jquery.tmpl'],
                      'archiva.main':['jquery','sammy','jquery.tmpl'],
                      'utils':['jquery','jquery.tmpl'],
                      'archiva.templates': ['jquery','jquery.tmpl','utils'],
                      'redback.templates': ['jquery','jquery.tmpl','utils']
                      },
                paths: {
                    "i18n":"jquery.i18n.properties-1.0.9",
                    "jquery": "jquery-1.8.0.min",
                    "jquery.tmpl": "jquery.tmpl",
                    "utils": "archiva/utils",
                    "startup": "archiva/startup",
                    "jquery.ui": "jquery-ui-1.8.16.custom.min",
                    "jquery.ui.widget": "jquery.ui.widget-1.8.18",
                    "jquery.cookie": "jquery.cookie.1.0.0",
                    "bootstrap": "bootstrap.2.1.0",
                    "choosen": "chosen.jquery-0.9.8",
                    "jquery.validate": "jquery.validate-1.9.0",
                    "jquery.json": "jquery.json-2.3.min",
                    "knockout": "knockout-2.0.0.debug",
                    "knockout.simpleGrid": "knockout.simpleGrid",
                    "knockout.sortable": "knockout-sortable",
                    "jquery.iframe.transport": "jquery.iframe-transport-1.4",
                    "jquery.fileupload": "jquery.fileupload-5.10.0",
                    "jquery.fileupload.ip":"jquery.fileupload-ip-1.0.6",
                    "jquery.fileupload.ui":"jquery.fileupload-ui-6.6.3",
                    "tmpl": "tmpl.min",
                    "prettify": "prettify",
                    "sammy": "sammy.0.7.1",
                    "jqueryFileTree": "jqueryFileTree-1.0.1",
                    "redback": "redback/redback",
                    "redback.roles": "redback/roles",
                    "redback.user": "redback/user",
                    "redback.users": "redback/users",
                    "redback.templates": "redback/redback-tmpl",
                    "archiva.general-admin":"archiva/general-admin",
                    "archiva.templates": "archiva/main-tmpl",
                    "archiva.repositories": "archiva/repositories",
                    "archiva.network-proxies": "archiva/network-proxies",
                    "archiva.proxy-connectors": "archiva/proxy-connectors",
                    "archiva.repository-groups": "archiva/repository-groups",
                    "archiva.artifacts-management": "archiva/artifacts-management",
                    "archiva.search": "archiva/search",
                    "archiva.main": "archiva/main"
                }
            });

            requirejs(['jquery','jquery.tmpl','i18n','sammy','startup','utils','domReady!'], function (domReady) {
                loadi18n(function () {
                  $.ajax({
                      url: "restServices/archivaUiServices/runtimeInfoService/archivaRuntimeInfo/"+usedLang(),
                      dataType: 'json',
                      success:function(data){
                          window.archivaDevMode=data.devMode;
                          window.archivaJavascriptLog=data.javascriptLog;
                          window.archivaRuntimeInfo=data;

                          require(['sammy','jquery','jquery.tmpl','archiva.main','utils','domReady!'],function (domReady) {
                              startArchivaApplication();
                              $("#loadingDiv").hide();
                          })
                      }
                    })
                })
            });
    }
})
<commit_msg>missing license header<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

appendArchivaVersion=function(){
  return "_archivaVersion="+window.archivaRuntimeInfo.version;
}

timestampNoCache=function(){
  if (window.archivaRuntimeInfo.version.match("SNAPSHOT$")=="SNAPSHOT"){
    return "&archivaTimestamp="+window.archivaRuntimeInfo.timestamp+(window.archivaRuntimeInfo.devMode?"&_="+jQuery.now():"");
  }
  return "";
}

appendTemplateUrl=function(){
  return appendArchivaVersion()+timestampNoCache();
}

appendJsNoCacheUrl=function(){
  return appendArchivaVersion()+timestampNoCache();
}

$.ajax({
    url: "restServices/archivaUiServices/runtimeInfoService/archivaRuntimeInfo/en",
    dataType: 'json',
    cache: false,
    success:function(data){

        window.archivaDevMode=data.devMode;
        window.archivaJavascriptLog=data.javascriptLog;
        window.archivaRuntimeInfo=data;

            requirejs.config({
                baseUrl: "js/",
                urlArgs: ""+appendJsNoCacheUrl(),
                shim: {
                      'sammy':['jquery','jquery.tmpl'],
                      'archiva.main':['jquery','sammy','jquery.tmpl'],
                      'utils':['jquery','jquery.tmpl'],
                      'archiva.templates': ['jquery','jquery.tmpl','utils'],
                      'redback.templates': ['jquery','jquery.tmpl','utils']
                      },
                paths: {
                    "i18n":"jquery.i18n.properties-1.0.9",
                    "jquery": "jquery-1.8.0.min",
                    "jquery.tmpl": "jquery.tmpl",
                    "utils": "archiva/utils",
                    "startup": "archiva/startup",
                    "jquery.ui": "jquery-ui-1.8.16.custom.min",
                    "jquery.ui.widget": "jquery.ui.widget-1.8.18",
                    "jquery.cookie": "jquery.cookie.1.0.0",
                    "bootstrap": "bootstrap.2.1.0",
                    "choosen": "chosen.jquery-0.9.8",
                    "jquery.validate": "jquery.validate-1.9.0",
                    "jquery.json": "jquery.json-2.3.min",
                    "knockout": "knockout-2.0.0.debug",
                    "knockout.simpleGrid": "knockout.simpleGrid",
                    "knockout.sortable": "knockout-sortable",
                    "jquery.iframe.transport": "jquery.iframe-transport-1.4",
                    "jquery.fileupload": "jquery.fileupload-5.10.0",
                    "jquery.fileupload.ip":"jquery.fileupload-ip-1.0.6",
                    "jquery.fileupload.ui":"jquery.fileupload-ui-6.6.3",
                    "tmpl": "tmpl.min",
                    "prettify": "prettify",
                    "sammy": "sammy.0.7.1",
                    "jqueryFileTree": "jqueryFileTree-1.0.1",
                    "redback": "redback/redback",
                    "redback.roles": "redback/roles",
                    "redback.user": "redback/user",
                    "redback.users": "redback/users",
                    "redback.templates": "redback/redback-tmpl",
                    "archiva.general-admin":"archiva/general-admin",
                    "archiva.templates": "archiva/main-tmpl",
                    "archiva.repositories": "archiva/repositories",
                    "archiva.network-proxies": "archiva/network-proxies",
                    "archiva.proxy-connectors": "archiva/proxy-connectors",
                    "archiva.repository-groups": "archiva/repository-groups",
                    "archiva.artifacts-management": "archiva/artifacts-management",
                    "archiva.search": "archiva/search",
                    "archiva.main": "archiva/main"
                }
            });

            requirejs(['jquery','jquery.tmpl','i18n','sammy','startup','utils','domReady!'], function (domReady) {
                loadi18n(function () {
                  $.ajax({
                      url: "restServices/archivaUiServices/runtimeInfoService/archivaRuntimeInfo/"+usedLang(),
                      dataType: 'json',
                      success:function(data){
                          window.archivaDevMode=data.devMode;
                          window.archivaJavascriptLog=data.javascriptLog;
                          window.archivaRuntimeInfo=data;

                          require(['sammy','jquery','jquery.tmpl','archiva.main','utils','domReady!'],function (domReady) {
                              startArchivaApplication();
                              $("#loadingDiv").hide();
                          })
                      }
                    })
                })
            });
    }
})
<|endoftext|>


<commit_before>/**
 * PersonController
 *
 * @description :: Server-side logic for managing people
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */
function _GetFirstPerson(id, cb) {
  Person.find({ email: id }).populateAll()
        .exec(function(err, persons){
    reval = null;
    if (persons.length == 0)
    {
      CardIDToEmail.find({ card_id: id }).exec(function(err, result) {
        if (result.length != 0)
        {
          Person.find({ email: result[0].email }).populateAll()
                .exec( function(err, card_persons) {
            console.log(card_persons);
            if (card_persons.length != 0)
            {
              reval = card_persons[0];
              PopulateExtras.PopulateAll(reval, cb);
            }
            else
            {
              cb(reval);
            }
          });
        }
        else
        {
          cb(reval);
        }
      });
    } else {
      reval = persons[0];
      PopulateExtras.PopulateAll(reval, cb);
    }
  });
}

function get_search_values(values, search_attr)
{
    var search_values = {quit: false};
    search_attr.forEach(function(element) {
      if (element in values)
      {
        if (element != "old_email")
        {
          search_values[element] = values[element];
        }
        else
        {
          search_values["email"] = values[element];
        }
      }
      else
      {
        quit = true;
      }
    });
}

function login (req, res) {
  var bcrypt = require('bcrypt');

  Person.findOneByEmail(req.body.email).exec(function (err, person) {
    if (err)
    {
      return res.send(500, { error: "Database error for login" });
    }

    if (person)
    {
      bcrypt.compare(req.body.password, person.password, function (err, match) {
          if (err)
          {
            res.send(500);
          }

          if (match)
          {
            req.session.person = person.id;
            delete person.password;
            res.send(person);
          }
          else
          {
            if (req.session.person)
            {
              req.session.person = null;
            }

            res.send(400, { error: "Invalid password" });
          }
      });
    }
    else
    {
      res.send(404, { error: "Person not found" });
    }

  });
};

module.exports = {
  CheckIfUserExist: function (req, res) {
    _GetFirstPerson(req.params.id, function (result) {
      res.send( result != null );
    });
  },
  GetFirstPerson: function (req, res) {
    _GetFirstPerson(req.params.id, function (result) {
      res.send( result );
    });
  },
  GetClassBonusesByPerson: function (req, res) {
    _GetFirstPerson(req.params.id, function (result) {
      if ( result != null && result.length != 0 )
      {
        count = 0;
        result.class_bonuses.forEach(function (bonus) {
          ClassBonus.find(bonus.class_bonus_id).limit(1).exec(function(err, this_classbonus) {
            if (this_classbonus.length != 0)
            {
              bonus.course_code = this_classbonus[0].course_code;
            }

            count += 1;
            if (count == result.class_bonuses.length)
            {
              return res.send(result);
            }
          });
        });
      }
      else
      {
        res.send( result );
      }
    });
  },
  UpdateEmail: function (req, res) {
    var values = req.allParams();

    // Don't allow these values
    if ( "new_email" in values )
    {
      var allowed = {email: values.new_email};
    }
    else
    {
      return res.send(400, { error: "There is no new email field" } );
    }

    search_values = get_search_values(values, ["old_email", "first_name", "last_name"]);

    if (search_values.quit)
    {
      return res.send(400, { error: "Values needed were not given" } );
    }
    else
    {
      delete search_values.quit;
    }

    Person.update(search_values).set(allowed).then( function (newProduct) {
      CardIDToEmail.update({email: search_values.email})
                   .set(allowed).then( function( newProduct ) {
      });

      return res.send(newProduct);
    });
  },
  InsertPerson: function (req, res) {
    var values = req.allParams();
    delete values.id;

    if ("email" in values)
    {
      if (! "first_name" in values)
      {
        return res.send(400, { error: "First name not given" } );
      }

      if (! "last_name" in values)
      {
        return res.send(400, {error: "Last name not given" } );
      }

      var search_query = {first_name: values.first_name, last_name: values.last_name};

      Person.find({ where: search_query }).exec(function (err, persons) {
        if ( persons.length == 0 )
        {
          Person.create(values).exec(function (err, newPerson) {
            return res.send(newPerson);
          });
        }
        else
        {
          // Make the update query for the user
          values.old_email = persons[0].email;
          values.new_email = values.email;
          delete values.email;

          return res.send(409, { error: "PossibleDuplicatePerson", query: values } )
        }
      });
    }
    else
    {
      return res.send(400, { error: "Email not given" } );
    }
  },
  DeletePerson: function (req, res) {
    _GetFirstPerson(req.params.id, function (result) {
      if (reval == null)
      {
        return res.send(400, { error: "Could not find user" } );
      }

      Person.destroy({email: result.email}).exec(function (err) {
        CardIDToEmail.destroy({email: result.email}).exec( function (err) {
            console.log("Email " + result.email + " has been deleted.");
            return res.send(result);
        });
      });
    });
  },
  findWithExtras: function (req, res) {
    Person.find(req.params.id).populateAll().exec(function (err, rows) {
      PopulateExtras.PopulateAll(rows, function ( result ) {
        res.send(result);
      });
    });
  },
  _GetFirstPerson: _GetFirstPerson,
  login: login
};

<commit_msg>Changed login to accept hash instead of plain text password<commit_after>/**
 * PersonController
 *
 * @description :: Server-side logic for managing people
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */
function _GetFirstPerson(id, cb) {
  Person.find({ email: id }).populateAll()
        .exec(function(err, persons){
    reval = null;
    if (persons.length == 0)
    {
      CardIDToEmail.find({ card_id: id }).exec(function(err, result) {
        if (result.length != 0)
        {
          Person.find({ email: result[0].email }).populateAll()
                .exec( function(err, card_persons) {
            console.log(card_persons);
            if (card_persons.length != 0)
            {
              reval = card_persons[0];
              delete reval.password;
              PopulateExtras.PopulateAll(reval, cb);
            }
            else
            {
              cb(reval);
            }
          });
        }
        else
        {
          cb(reval);
        }
      });
    } else {
      reval = persons[0];
      delete reval.password;
      PopulateExtras.PopulateAll(reval, cb);
    }
  });
}

function get_search_values(values, search_attr)
{
    var search_values = {quit: false};
    search_attr.forEach(function(element) {
      if (element in values)
      {
        if (element != "old_email")
        {
          search_values[element] = values[element];
        }
        else
        {
          search_values["email"] = values[element];
        }
      }
      else
      {
        quit = true;
      }
    });
}

function login (req, res) {
  var bcrypt = require('bcrypt');

  Person.findOneByEmail(req.body.email).exec(function (err, person) {
    if (err)
    {
      return res.send(500, { error: "Database error for login" });
    }

    if (person)
    {
      if ( req.body.password == person.password ) {
        req.session.person = person.id;
        delete person.password;
        res.send(person);
      }
      else
      {
        if (req.session.person)
        {
          req.session.person = null;
        }

        res.send(400, { error: "Invalid password" });
      }
    }
    else
    {
      res.send(404, { error: "Person not found" });
    }

  });
};

module.exports = {
  CheckIfUserExist: function (req, res) {
    _GetFirstPerson(req.params.id, function (result) {
      res.send( result != null );
    });
  },
  GetFirstPerson: function (req, res) {
    _GetFirstPerson(req.params.id, function (result) {
      res.send( result );
    });
  },
  GetClassBonusesByPerson: function (req, res) {
    _GetFirstPerson(req.params.id, function (result) {
      if ( result != null && result.length != 0 )
      {
        count = 0;
        result.class_bonuses.forEach(function (bonus) {
          ClassBonus.find(bonus.class_bonus_id).limit(1).exec(function(err, this_classbonus) {
            if (this_classbonus.length != 0)
            {
              bonus.course_code = this_classbonus[0].course_code;
            }

            count += 1;
            if (count == result.class_bonuses.length)
            {
              return res.send(result);
            }
          });
        });
      }
      else
      {
        res.send( result );
      }
    });
  },
  UpdateEmail: function (req, res) {
    var values = req.allParams();

    // Don't allow these values
    if ( "new_email" in values )
    {
      var allowed = {email: values.new_email};
    }
    else
    {
      return res.send(400, { error: "There is no new email field" } );
    }

    search_values = get_search_values(values, ["old_email", "first_name", "last_name"]);

    if (search_values.quit)
    {
      return res.send(400, { error: "Values needed were not given" } );
    }
    else
    {
      delete search_values.quit;
    }

    Person.update(search_values).set(allowed).then( function (newProduct) {
      CardIDToEmail.update({email: search_values.email})
                   .set(allowed).then( function( newProduct ) {
      });

      return res.send(newProduct);
    });
  },
  InsertPerson: function (req, res) {
    var values = req.allParams();
    delete values.id;

    if ("email" in values)
    {
      if (! "first_name" in values)
      {
        return res.send(400, { error: "First name not given" } );
      }

      if (! "last_name" in values)
      {
        return res.send(400, {error: "Last name not given" } );
      }

      var search_query = {first_name: values.first_name, last_name: values.last_name};

      Person.find({ where: search_query }).exec(function (err, persons) {
        if ( persons.length == 0 )
        {
          Person.create(values).exec(function (err, newPerson) {
            return res.send(newPerson);
          });
        }
        else
        {
          // Make the update query for the user
          values.old_email = persons[0].email;
          values.new_email = values.email;
          delete values.email;

          return res.send(409, { error: "PossibleDuplicatePerson", query: values } )
        }
      });
    }
    else
    {
      return res.send(400, { error: "Email not given" } );
    }
  },
  DeletePerson: function (req, res) {
    _GetFirstPerson(req.params.id, function (result) {
      if (reval == null)
      {
        return res.send(400, { error: "Could not find user" } );
      }

      Person.destroy({email: result.email}).exec(function (err) {
        CardIDToEmail.destroy({email: result.email}).exec( function (err) {
            console.log("Email " + result.email + " has been deleted.");
            return res.send(result);
        });
      });
    });
  },
  findWithExtras: function (req, res) {
    Person.find(req.params.id).populateAll().exec(function (err, rows) {
      PopulateExtras.PopulateAll(rows, function ( result ) {
        res.send(result);
      });
    });
  },
  _GetFirstPerson: _GetFirstPerson,
  login: login
};

<|endoftext|>


<commit_before>var express = require('express');
var jsend = require('jsend');
var bodyParser = require('body-parser');

var Score = require('./../models/score')

var router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });

router.use(jsend.middleware);

/**
 * GET /scores
 * Get a list of scores
 */
router.get('/', function(req, res, next) {
    Score.find(function(err, scores) {
	if (err)
	    res.fail(err);
	res.status(200).jsend.success(scores);
    });
});

/**
 * GET /scores/:scoreId
 * Get a scores based on the passed score ID
 */
router.get('/:scoreId', function(req, res) {
    Score.findById(req.params.scoreId, function(err, score) {
	if (err)
	    res.fail(err);
	res.status(200).jsend.success(score);
    });
});

/**
 * POST /scores
 * Create a score
 */
router.post('/', urlencodedParser, function(req, res) {
    if (!req.body.login || !req.body.address || !req.body.date || !req.body.numberOfHours
       || !req.body.firstName || !req.body.lastName) {
	return res.status(400).jsend.fail({ error_code: 'missing_parameters'});
    }

    var score = new Score();

    var st = req.body.date;
    var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
    var dt = new Date(st.replace(pattern,'$3-$2-$1'));

    score.login = req.body.login;
    score.address = req.body.address;
    score.date = dt;
    score.numberOfHours = req.body.numberOfHours;
    score.worker.firstName = req.body.firstName;
    score.worker.lastName = req.body.lastName;

    score.save(function(err) {
	if (err)
	    res.send(err);
	res.status(201).jsend.success({ message: 'Score created!' });
    });
});

router.post('/import', urlencodedParser, function(req, res, next) {
    if (!req.body.body) {
	return res.status(400).jsend.fail({ error_code: 'missing_parameters'});
    }

    var score = new Score();

    var scores = [];

    // var body = "[{login: 'id001', address: '1 rue blabla', date:'10-12-2016', numberOfHours: '2', worker: { firstName:'Samuel', lastName: 'JOSET'} }, {login: 'id002', address: '6 rue ha', date:'2-10-2006', numberOfHours: '4', worker: { firstName:'David', lastName: 'Haga'} }]";

    var body = JSON.stringify(eval("(" + req.body.body + ")"));

    body = JSON.parse(body);

    for (var i = 0; i < body.length; i++) {

	var st = body[i].date;
	var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
	var dt = new Date(st.replace(pattern,'$3-$2-$1'));

	var score = {
	    login: body[i].login,
	    address: body[i].address,
	    date: dt,
	    numberOfHours: body[i].numberOfHours,
	    worker: {
		firstName: body[i].worker.firstName,
		lastName: body[i].worker.lastName
	    }
	};

	scores.push(score);
    	// console.log("lastName = " + obj[i][8] + " ;firstName = " + obj[i][9] + " ;identifiant = " + obj[i][1]);
    }

    console.log(scores);
    Score.collection.insert(scores, function(err) {
	if (err) {
	    console.log(err);
	    return res.jsend.fail(err);
	}
	res.status(201).jsend.success({ message: 'Scores created!' });
    });

    // res.status(200).jsend.success(obj);
});

/**
 * PUT /scoress/:scoreId
 * Modify a score based on the passed scores ID
 */
router.put('/:scoreId', function(req, res) {
    // TODO: Modify a score based on the passed score ID
    res.status(501).jsend.success(null);
});

/**
 * DELETE /scores/:scoreId
 * Delete a score based on the passed score ID
 */
router.delete('/:scoreId', function(req, res) {
    Score.remove({
	_id: req.params.scoreId
    }, function(err, score) {
	if (err)
	    res.send(err);
	res.status(204).jsend.success({ message: 'Score deleted!' });
    });
});

module.exports = router;
<commit_msg>modif<commit_after>var express = require('express');
var jsend = require('jsend');
var bodyParser = require('body-parser');

var Score = require('./../models/score')

var router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });

router.use(jsend.middleware);

/**
 * GET /scores
 * Get a list of scores
 */
router.get('/', function(req, res, next) {
    Score.find(function(err, scores) {
	if (err)
	    res.fail(err);
	res.status(200).jsend.success(scores);
    });
});

/**
 * GET /scores/:scoreId
 * Get a scores based on the passed score ID
 */
router.get('/:scoreId', function(req, res) {
    Score.findById(req.params.scoreId, function(err, score) {
	if (err)
	    res.fail(err);
	res.status(200).jsend.success(score);
    });
});

/**
 * POST /scores
 * Create a score
 */
router.post('/', urlencodedParser, function(req, res) {
    if (!req.body.login || !req.body.address || !req.body.date || !req.body.numberOfHours
       || !req.body.firstName || !req.body.lastName) {
	return res.status(400).jsend.fail({ error_code: 'missing_parameters'});
    }

    var score = new Score();

    var st = req.body.date;
    var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
    var dt = new Date(st.replace(pattern,'$3-$2-$1'));

    score.login = req.body.login;
    score.address = req.body.address;
    score.date = dt;
    score.numberOfHours = req.body.numberOfHours;
    score.worker.firstName = req.body.firstName;
    score.worker.lastName = req.body.lastName;

    score.save(function(err) {
	if (err)
	    res.send(err);
	res.status(201).jsend.success({ message: 'Score created!' });
    });
});

router.post('/import', urlencodedParser, function(req, res, next) {
    if (!req.body.body) {
	return res.status(400).jsend.fail({ error_code: 'missing_parameters'});
    }

    var score = new Score();

    var scores = [];

    // var body = "[{login: 'id001', address: '1 rue blabla', date:'10-12-2016', numberOfHours: '2', worker: { firstName:'Samuel', lastName: 'JOSET'} }, {login: 'id002', address: '6 rue ha', date:'2-10-2006', numberOfHours: '4', worker: { firstName:'David', lastName: 'Haga'} }]";

    var body = JSON.stringify(eval("(" + req.body.body + ")"));

    body = JSON.parse(body);

    for (var i = 0; i < body.length; i++) {

	var st = body[i].date;
	var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
	var dt = new Date(st.replace(pattern,'$3-$2-$1'));

	var score = {
	    login: body[i].login,
	    address: body[i].address,
	    date: dt,
	    numberOfHours: body[i].numberOfHours,
	    worker: {
		firstName: body[i].worker.firstName,
		lastName: body[i].worker.lastName
	    }
	};

	scores.push(score);
    	// console.log("lastName = " + obj[i][8] + " ;firstName = " + obj[i][9] + " ;identifiant = " + obj[i][1]);
    }

    // console.log(scores);
    Score.collection.insert(scores, function(err) {
	if (err) {
	    // console.log(err);
	    return res.jsend.fail(err);
	}
	res.status(201).jsend.success({ message: 'Scores created!' });
    });

    // res.status(200).jsend.success(obj);
});

/**
 * PUT /scoress/:scoreId
 * Modify a score based on the passed scores ID
 */
router.put('/:scoreId', function(req, res) {
    // TODO: Modify a score based on the passed score ID
    res.status(501).jsend.success(null);
});

/**
 * DELETE /scores/:scoreId
 * Delete a score based on the passed score ID
 */
router.delete('/:scoreId', function(req, res) {
    Score.remove({
	_id: req.params.scoreId
    }, function(err, score) {
	if (err)
	    res.send(err);
	res.status(204).jsend.success({ message: 'Score deleted!' });
    });
});

module.exports = router;
<|endoftext|>


<commit_before>/**
 * SearchController
 *
 * @description :: Server-side logic for searching
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var Promise = require('bluebird');
var _ = require('lodash');
var striptags = require('striptags');
var querystring = require('querystring');
var numeral = require('numeral');

module.exports = {

  quickSearch: function(req, res) {
    var token = req.body.token;

    es.msearch({
      body: [
        { index: 'rdoc', type: 'package_version' },
        { query: {
            bool: {
              should: [

                {
                  "has_parent" : {
                    "query" : {
                      "function_score" : {
                        "functions": [
                          {
                            "filter": { "missing" : { "field" : "part_of_r" } },
                            "field_value_factor": {
                              "field":    "last_month_downloads",
                              "modifier": "log1p"
                            }
                          },
                          {
                            "filter": { "term" : { "part_of_r" : 0 } },
                            "field_value_factor": {
                              "field":    "last_month_downloads",
                              "modifier": "log1p"
                            }
                          },
                          {
                            "filter": { "term" : { "part_of_r" : 1 } },
                            "field_value_factor": {
                              "field":    "part_of_r",
                              "modifier": "log1p",
                              "factor": 300000
                            }
                          }
                        ],
                        "boost_mode": "multiply"
                      }
                    },

                    "parent_type" : "package",
                    "score_mode" : "score"
                  }
                }
              ],
              "minimum_number_should_match": 2,
              filter: {
                bool: {
                  must: [
                    {
                      match_phrase_prefix : {
                        "package_name" : {
                            "query" : token,
                            "max_expansions" : 20,
                        }
                      }
                    },
                    {
                      term: { latest_version: 1 }
                    }
                  ]
                }

              }
            }
          },
          size: 5,
          fields: ['package_name', 'version']
        },

        { index: 'rdoc', type: 'topic' },
        { query: {

            bool: {
              should: [
                {
                  "multi_match" : {
                    "query":    token,
                    "fields": [ "aliases^2", "name" ]
                  }
                },
                {
                  "multi_match" : {
                    "fields" : ["aliases^2", "name"],
                    "query" : token,
                    "type" : "phrase_prefix"
                  }
                },
                {
                  has_parent : {
                    "parent_type" : "package_version",
                    "score_mode": "score",
                    query : {
                      "has_parent" : {
                        "query" : {
                          "function_score" : {
                            "functions": [
                              {
                                "filter": { "missing" : { "field" : "part_of_r" } },
                                "field_value_factor": {
                                  "field":    "last_month_downloads",
                                  "modifier": "log1p"
                                }
                              },
                              {
                                "filter": { "term" : { "part_of_r" : 0 } },
                                "field_value_factor": {
                                  "field":    "last_month_downloads",
                                  "modifier": "log1p"
                                }
                              },
                              {
                                "filter": { "term" : { "part_of_r" : 1 } },
                                "field_value_factor": {
                                  "field":    "part_of_r",
                                  "modifier": "log1p",
                                  "factor": 300000
                                }
                              }
                            ],
                            "boost_mode": "replace"
                          }
                        },

                        "parent_type" : "package",
                        "score_mode" : "score"
                      }
                    }
                  }
                }
              ],
              "minimum_number_should_match": 1,
              filter: {
                has_parent : {
                  parent_type : "package_version",
                  query : {
                    term : {
                        latest_version : 1
                    }
                  },
                  inner_hits : { fields: ['package_name', 'version', 'latest_version'] }
                }
              }
            }

          },
          size: 5,
          fields: ['name']
        },

    ]}).then(function(response) {
      var packageResult = response.responses[0];
      var topicResult = response.responses[1];
      var packages = _.map(packageResult.hits.hits, function(hit) {
        var name = hit.fields.package_name[0];
        var version = hit.fields.version[0];
        var uri = sails.getUrlFor({ target: 'PackageVersion.findByNameVersion' })
          .replace(':name', encodeURIComponent(name))
          .replace(':version', encodeURIComponent(version))
          .replace('/api/', '/');
        return { uri: uri,  name: name };
      });

      var topics = _.map(topicResult.hits.hits, function(hit) {
        var name = hit.fields.name[0];
        var id = hit._id;
        var inner_hit = hit.inner_hits.package_version.hits.hits[0];
        var package_name = inner_hit.fields.package_name[0];
        var version = inner_hit.fields.version[0];
        var uri = '/api/packages/:name/versions/:version/topics/:topic'
          .replace(':name', encodeURIComponent(package_name))
          .replace(':version', encodeURIComponent(version))
          .replace(':topic', encodeURIComponent(name))
          .replace('/api/', '/');
        return { uri: uri,  name: name, package_name: package_name, package_version: version };
      });
      return res.json({packages: packages, topics: topics});
    }).catch(function(err) {
      return res.negotiate(err);
    });

  },

  keywordSearch: function(req, res) {
    var keyword = req.param('keyword');
    var page = parseInt(req.param('page')) || 1;
    var perPage = parseInt(req.param('perPage')) || 10;
    var offset = (page - 1) * perPage;
    var nextPageQuery = _.clone(req.query);
    nextPageQuery.page = page + 1;

    var prevPageQuery = _.clone(req.query);
    prevPageQuery.page = page - 1;

    es.search({
      index: 'rdoc',
      body:{
        query: {
          bool: {
            filter: {
              type : {
                value : "topic"
              }
            },
            must: [
              {
                term: {
                  keywords:  keyword
                }
              },
              {
                has_parent : {
                  parent_type : "package_version",
                  query : {
                    term : {
                        latest_version : 1
                    }
                  },
                  inner_hits : { fields: ['package_name', 'version', 'latest_version'] }
                }
              }
            ]
          }
        },
        highlight : {
          pre_tags : [""],
          post_tags : [""],
          "fields" : {
            "keywords": {
              highlight_query: {
                term: {
                  keywords:  keyword
                }
              }
            },

          }
        },
        from: offset,
        size: perPage,
        fields: ['title', 'name', 'description', 'keywords']
      }

    }).then(function(response) {
      //return res.json(response);
      var hits = response.hits.hits.map(function(hit) {
        var fields = {};
        var highlight = hit.highlight;
        var inner_hits_fields = hit.inner_hits.package_version.hits.hits[0].fields;

        fields.package_name = inner_hits_fields.package_name[0];
        fields.version = inner_hits_fields.version[0];
        fields.name = hit.fields.name[0];

        highlight.title = hit.fields.title[0];
        highlight.description = hit.fields.description[0];

        return {
          fields: fields,
          type: hit._type,
          score: hit._score,
          highlight: hit.highlight
        };
      });
      return res.ok({
        total: numeral(response.hits.total).format('0,0'),
        hits: hits,
        perPage: perPage,
        currentPage: page,
        prevPageUrl: req.path + '?' + querystring.stringify(prevPageQuery),
        nextPageUrl: req.path + '?' + querystring.stringify(nextPageQuery),
        striptags: striptags,
        pageTitle: 'Search Results'
      }, 'search/keyword_result.ejs');
    });

  },

  packageSearch: function(req,res){
    var query = req.param('q');
    var page = parseInt(req.param('page')) || 1;
    var perPage = parseInt(req.param('perPage')) || 10;
    var offset = (page - 1) * perPage;

    return es.search({
      index: 'rdoc',
      body: {
        query: {
          bool: {
            filter:[
              {
                type : {
                  value : "package_version"
                }
              },
              { term: { latest_version: 1 } }
            ],
            should:[
              {
                multi_match: {
                  query: query,
                  type: "best_fields",
                  fields: ['package_name^6', 'title^4', 'maintainer.name^4', 'collaborators.name^3', 'description^3', 'license', 'url', 'copyright']
                },
              },
              {
                "has_parent" : {
                  "query" : {
                    "function_score" : {
                      "functions": [
                        {
                          "filter": { "missing" : { "field" : "part_of_r" } },
                          "field_value_factor": {
                            "field":    "last_month_downloads",
                            "modifier": "log1p"
                          }
                        },
                        {
                          "filter": { "term" : { "part_of_r" : 0 } },
                          "field_value_factor": {
                            "field":    "last_month_downloads",
                            "modifier": "log1p"
                          }
                        },
                        {
                          "filter": {  "term" : { "part_of_r" : 1 } },
                          "field_value_factor": {
                            "field":    "part_of_r",
                            "modifier": "log1p",
                            "factor": 300000,
                          }
                        }
                      ],
                      "boost_mode": "replace"
                    }
                  },

                  "parent_type" : "package",
                  "score_mode" : "score"
                }
              }
            ],
            minimum_should_match : 1,
          }
        },
        highlight : {
          pre_tags : [""],
          post_tags : [""],
          "require_field_match": false,
          "fields" : {
            "title" : {highlight_query: {
               match : {
                  title : query
              }
            }},
            "description": {
              "number_of_fragments" : 0,
              highlight_query: {
                match: { description: query }
              }
            },
            "collaborators.name": {highlight_query: {
               match : {
                  "collaborators.name" : query
              }
            }},
            "maintainer.name": {highlight_query: {
               match : {
                  "maintainer.name" : query
              }
            }}
          }
        },
        from: offset,
        size: perPage,
        fields: ['package_name', 'version', 'description', 'maintainer.name']
      }
    }).then(function(result){
      var packages  = [];
      result.hits.hits.forEach(function(hit) {
        console.log(hit);
          var fields = {};
          fields.package_name = hit.fields.package_name[0];
          fields.version = hit.fields.version[0];
          fields.maintainer = hit.fields['maintainer.name'];
          var highlights = _.mapValues(hit.highlight, function(highlight) {
            return striptags(highlight.toString(),'');
          });

          var description = highlights.description || hit.fields.description[0];

          highlights = _.omit(highlights, 'description');

          packages.push({
            description: description,
            fields: fields,
            score: hit._score,
            highlight: highlights
          });
        });
      return res.view('search/package_results.ejs', { data: {packages: packages, hits: numeral(result.hits.total).format('0,0')}, layout:null});
    }).catch(function(err) {
      return res.negotiate(err);
    });
  },

  functionSearch: function(req,res){
    var query = req.param('q');
    var page = parseInt(req.param('page')) || 1;
    var perPage = parseInt(req.param('perPage')) || 10;
    var offset = (page - 1) * perPage;
    var searchTopicQuery = {
      multi_match: {
        query: query,
        type: "best_fields",
        boost: 0.7,
        fields: [
          'aliases^6',
          'name^2',
          'title^2', 'description', 'keywords^2',
          'arguments.name', 'arguments.description',
          'details', 'value',
          'note', 'author']
      }
    };
    return es.search({
      index: 'rdoc',
      body: {
        query: {
          bool : {
            should : [
              {
                bool: {
                  filter:[
                    {
                      type : {
                        value : "topic"
                      }
                    },
                    {
                      has_parent : {
                        parent_type : "package_version",
                        query : {  term : { latest_version : 1 } }
                      }
                    }
                  ],
                  should: [
                    searchTopicQuery,
                    {
                      has_parent : {
                        parent_type : "package_version",
                        score_mode: "score",

                        query : {
                          "has_parent" : {
                            "parent_type" : "package",
                            "score_mode" : "score",
                            "query" : {
                              "function_score" : {
                                "functions": [
                                  {
                                    "filter": { "missing" : { "field" : "part_of_r" } },
                                    "field_value_factor": {
                                      "field":    "last_month_downloads",
                                      "modifier": "log1p"
                                    }
                                  },
                                  {
                                    "filter": { "term" : { "part_of_r" : 0 } },
                                    "field_value_factor": {
                                      "field":    "last_month_downloads",
                                      "modifier": "log1p"
                                    }
                                  },
                                  {
                                    "filter": { "term" : { "part_of_r" : 1 } },
                                    "field_value_factor": {
                                      "field":    "part_of_r",
                                      "modifier": "log1p",
                                      "factor": 300000,
                                    }
                                  }
                                ],
                                "boost_mode": "replace"
                              }
                            }
                          }
                        },
                        inner_hits : { fields: ['package_name', 'version', 'latest_version', 'maintainer.name'] }
                      }
                    }
                  ],
                  minimum_should_match : 1,
                }
              }],
            minimum_should_match : 1,
          }
        },
        highlight : {
          pre_tags : [""],
          post_tags : [""],
          "fields" : {
            "note": {highlight_query: searchTopicQuery},
            "keywords": {highlight_query: searchTopicQuery},
            "aliases": {highlight_query: searchTopicQuery},
            "author": {highlight_query: searchTopicQuery},
            "references": {highlight_query: searchTopicQuery},
            "value": {highlight_query: searchTopicQuery},
            "details": {highlight_query: searchTopicQuery},
            "description": {highlight_query: searchTopicQuery},
            "title" : {highlight_query: searchTopicQuery},
            "name": {highlight_query: searchTopicQuery},
          }
        },
        from: offset,
        size: perPage,
        fields: ['package_name', 'version', 'name', 'maintainer.name']
      }
    }).then(function(result){
      var functions  = [];
      result.hits.hits.forEach(function(hit) {
          var fields = {};
          var inner_hits_fields = hit.inner_hits.package_version.hits.hits[0].fields;
          console.log(inner_hits_fields);
          fields.package_name = inner_hits_fields.package_name[0];
          fields.version = inner_hits_fields.version[0];
          fields.name = hit.fields.name[0];
          fields.maintainer = inner_hits_fields['maintainer.name'][0];
          var stripped={};
          for(var highlight in hit.highlight){
            stripped[highlight] = striptags(hit.highlight[highlight].toString(),'');
          }
          functions.push({
            fields: fields,
            score: hit._score,
            highlight: stripped
          });
        });
      return res.view('search/function_results.ejs', {data: {functions: functions, hits: numeral(result.hits.total).format('0,0')}, layout: null});
    }).catch(function(err) {
        return res.negotiate(err);
    });
  },

  fullSearch: function(req, res) {
    return res.ok({query: req.param('q'),current: req.path+ '?' +querystring.stringify(req.query)},'search/result.ejs');
  }

};
<commit_msg>remove logs<commit_after>/**
 * SearchController
 *
 * @description :: Server-side logic for searching
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var Promise = require('bluebird');
var _ = require('lodash');
var striptags = require('striptags');
var querystring = require('querystring');
var numeral = require('numeral');

module.exports = {

  quickSearch: function(req, res) {
    var token = req.body.token;

    es.msearch({
      body: [
        { index: 'rdoc', type: 'package_version' },
        { query: {
            bool: {
              should: [

                {
                  "has_parent" : {
                    "query" : {
                      "function_score" : {
                        "functions": [
                          {
                            "filter": { "missing" : { "field" : "part_of_r" } },
                            "field_value_factor": {
                              "field":    "last_month_downloads",
                              "modifier": "log1p"
                            }
                          },
                          {
                            "filter": { "term" : { "part_of_r" : 0 } },
                            "field_value_factor": {
                              "field":    "last_month_downloads",
                              "modifier": "log1p"
                            }
                          },
                          {
                            "filter": { "term" : { "part_of_r" : 1 } },
                            "field_value_factor": {
                              "field":    "part_of_r",
                              "modifier": "log1p",
                              "factor": 300000
                            }
                          }
                        ],
                        "boost_mode": "multiply"
                      }
                    },

                    "parent_type" : "package",
                    "score_mode" : "score"
                  }
                }
              ],
              "minimum_number_should_match": 2,
              filter: {
                bool: {
                  must: [
                    {
                      match_phrase_prefix : {
                        "package_name" : {
                            "query" : token,
                            "max_expansions" : 20,
                        }
                      }
                    },
                    {
                      term: { latest_version: 1 }
                    }
                  ]
                }

              }
            }
          },
          size: 5,
          fields: ['package_name', 'version']
        },

        { index: 'rdoc', type: 'topic' },
        { query: {

            bool: {
              should: [
                {
                  "multi_match" : {
                    "query":    token,
                    "fields": [ "aliases^2", "name" ]
                  }
                },
                {
                  "multi_match" : {
                    "fields" : ["aliases^2", "name"],
                    "query" : token,
                    "type" : "phrase_prefix"
                  }
                },
                {
                  has_parent : {
                    "parent_type" : "package_version",
                    "score_mode": "score",
                    query : {
                      "has_parent" : {
                        "query" : {
                          "function_score" : {
                            "functions": [
                              {
                                "filter": { "missing" : { "field" : "part_of_r" } },
                                "field_value_factor": {
                                  "field":    "last_month_downloads",
                                  "modifier": "log1p"
                                }
                              },
                              {
                                "filter": { "term" : { "part_of_r" : 0 } },
                                "field_value_factor": {
                                  "field":    "last_month_downloads",
                                  "modifier": "log1p"
                                }
                              },
                              {
                                "filter": { "term" : { "part_of_r" : 1 } },
                                "field_value_factor": {
                                  "field":    "part_of_r",
                                  "modifier": "log1p",
                                  "factor": 300000
                                }
                              }
                            ],
                            "boost_mode": "replace"
                          }
                        },

                        "parent_type" : "package",
                        "score_mode" : "score"
                      }
                    }
                  }
                }
              ],
              "minimum_number_should_match": 1,
              filter: {
                has_parent : {
                  parent_type : "package_version",
                  query : {
                    term : {
                        latest_version : 1
                    }
                  },
                  inner_hits : { fields: ['package_name', 'version', 'latest_version'] }
                }
              }
            }

          },
          size: 5,
          fields: ['name']
        },

    ]}).then(function(response) {
      var packageResult = response.responses[0];
      var topicResult = response.responses[1];
      var packages = _.map(packageResult.hits.hits, function(hit) {
        var name = hit.fields.package_name[0];
        var version = hit.fields.version[0];
        var uri = sails.getUrlFor({ target: 'PackageVersion.findByNameVersion' })
          .replace(':name', encodeURIComponent(name))
          .replace(':version', encodeURIComponent(version))
          .replace('/api/', '/');
        return { uri: uri,  name: name };
      });

      var topics = _.map(topicResult.hits.hits, function(hit) {
        var name = hit.fields.name[0];
        var id = hit._id;
        var inner_hit = hit.inner_hits.package_version.hits.hits[0];
        var package_name = inner_hit.fields.package_name[0];
        var version = inner_hit.fields.version[0];
        var uri = '/api/packages/:name/versions/:version/topics/:topic'
          .replace(':name', encodeURIComponent(package_name))
          .replace(':version', encodeURIComponent(version))
          .replace(':topic', encodeURIComponent(name))
          .replace('/api/', '/');
        return { uri: uri,  name: name, package_name: package_name, package_version: version };
      });
      return res.json({packages: packages, topics: topics});
    }).catch(function(err) {
      return res.negotiate(err);
    });

  },

  keywordSearch: function(req, res) {
    var keyword = req.param('keyword');
    var page = parseInt(req.param('page')) || 1;
    var perPage = parseInt(req.param('perPage')) || 10;
    var offset = (page - 1) * perPage;
    var nextPageQuery = _.clone(req.query);
    nextPageQuery.page = page + 1;

    var prevPageQuery = _.clone(req.query);
    prevPageQuery.page = page - 1;

    es.search({
      index: 'rdoc',
      body:{
        query: {
          bool: {
            filter: {
              type : {
                value : "topic"
              }
            },
            must: [
              {
                term: {
                  keywords:  keyword
                }
              },
              {
                has_parent : {
                  parent_type : "package_version",
                  query : {
                    term : {
                        latest_version : 1
                    }
                  },
                  inner_hits : { fields: ['package_name', 'version', 'latest_version'] }
                }
              }
            ]
          }
        },
        highlight : {
          pre_tags : [""],
          post_tags : [""],
          "fields" : {
            "keywords": {
              highlight_query: {
                term: {
                  keywords:  keyword
                }
              }
            },

          }
        },
        from: offset,
        size: perPage,
        fields: ['title', 'name', 'description', 'keywords']
      }

    }).then(function(response) {
      //return res.json(response);
      var hits = response.hits.hits.map(function(hit) {
        var fields = {};
        var highlight = hit.highlight;
        var inner_hits_fields = hit.inner_hits.package_version.hits.hits[0].fields;

        fields.package_name = inner_hits_fields.package_name[0];
        fields.version = inner_hits_fields.version[0];
        fields.name = hit.fields.name[0];

        highlight.title = hit.fields.title[0];
        highlight.description = hit.fields.description[0];

        return {
          fields: fields,
          type: hit._type,
          score: hit._score,
          highlight: hit.highlight
        };
      });
      return res.ok({
        total: numeral(response.hits.total).format('0,0'),
        hits: hits,
        perPage: perPage,
        currentPage: page,
        prevPageUrl: req.path + '?' + querystring.stringify(prevPageQuery),
        nextPageUrl: req.path + '?' + querystring.stringify(nextPageQuery),
        striptags: striptags,
        pageTitle: 'Search Results'
      }, 'search/keyword_result.ejs');
    });

  },

  packageSearch: function(req,res){
    var query = req.param('q');
    var page = parseInt(req.param('page')) || 1;
    var perPage = parseInt(req.param('perPage')) || 10;
    var offset = (page - 1) * perPage;

    return es.search({
      index: 'rdoc',
      body: {
        query: {
          bool: {
            filter:[
              {
                type : {
                  value : "package_version"
                }
              },
              { term: { latest_version: 1 } }
            ],
            should:[
              {
                multi_match: {
                  query: query,
                  type: "best_fields",
                  fields: ['package_name^6', 'title^4', 'maintainer.name^4', 'collaborators.name^3', 'description^3', 'license', 'url', 'copyright']
                },
              },
              {
                "has_parent" : {
                  "query" : {
                    "function_score" : {
                      "functions": [
                        {
                          "filter": { "missing" : { "field" : "part_of_r" } },
                          "field_value_factor": {
                            "field":    "last_month_downloads",
                            "modifier": "log1p"
                          }
                        },
                        {
                          "filter": { "term" : { "part_of_r" : 0 } },
                          "field_value_factor": {
                            "field":    "last_month_downloads",
                            "modifier": "log1p"
                          }
                        },
                        {
                          "filter": {  "term" : { "part_of_r" : 1 } },
                          "field_value_factor": {
                            "field":    "part_of_r",
                            "modifier": "log1p",
                            "factor": 300000,
                          }
                        }
                      ],
                      "boost_mode": "replace"
                    }
                  },

                  "parent_type" : "package",
                  "score_mode" : "score"
                }
              }
            ],
            minimum_should_match : 1,
          }
        },
        highlight : {
          pre_tags : [""],
          post_tags : [""],
          "require_field_match": false,
          "fields" : {
            "title" : {highlight_query: {
               match : {
                  title : query
              }
            }},
            "description": {
              "number_of_fragments" : 0,
              highlight_query: {
                match: { description: query }
              }
            },
            "collaborators.name": {highlight_query: {
               match : {
                  "collaborators.name" : query
              }
            }},
            "maintainer.name": {highlight_query: {
               match : {
                  "maintainer.name" : query
              }
            }}
          }
        },
        from: offset,
        size: perPage,
        fields: ['package_name', 'version', 'description', 'maintainer.name']
      }
    }).then(function(result){
      var packages  = [];
      result.hits.hits.forEach(function(hit) {
          var fields = {};
          fields.package_name = hit.fields.package_name[0];
          fields.version = hit.fields.version[0];
          fields.maintainer = hit.fields['maintainer.name'];
          var highlights = _.mapValues(hit.highlight, function(highlight) {
            return striptags(highlight.toString(),'');
          });

          var description = highlights.description || hit.fields.description[0];

          highlights = _.omit(highlights, 'description');

          packages.push({
            description: description,
            fields: fields,
            score: hit._score,
            highlight: highlights
          });
        });
      return res.view('search/package_results.ejs', { data: {packages: packages, hits: numeral(result.hits.total).format('0,0')}, layout:null});
    }).catch(function(err) {
      return res.negotiate(err);
    });
  },

  functionSearch: function(req,res){
    var query = req.param('q');
    var page = parseInt(req.param('page')) || 1;
    var perPage = parseInt(req.param('perPage')) || 10;
    var offset = (page - 1) * perPage;
    var searchTopicQuery = {
      multi_match: {
        query: query,
        type: "best_fields",
        boost: 0.7,
        fields: [
          'aliases^6',
          'name^2',
          'title^2', 'description', 'keywords^2',
          'arguments.name', 'arguments.description',
          'details', 'value',
          'note', 'author']
      }
    };
    return es.search({
      index: 'rdoc',
      body: {
        query: {
          bool : {
            should : [
              {
                bool: {
                  filter:[
                    {
                      type : {
                        value : "topic"
                      }
                    },
                    {
                      has_parent : {
                        parent_type : "package_version",
                        query : {  term : { latest_version : 1 } }
                      }
                    }
                  ],
                  should: [
                    searchTopicQuery,
                    {
                      has_parent : {
                        parent_type : "package_version",
                        score_mode: "score",

                        query : {
                          "has_parent" : {
                            "parent_type" : "package",
                            "score_mode" : "score",
                            "query" : {
                              "function_score" : {
                                "functions": [
                                  {
                                    "filter": { "missing" : { "field" : "part_of_r" } },
                                    "field_value_factor": {
                                      "field":    "last_month_downloads",
                                      "modifier": "log1p"
                                    }
                                  },
                                  {
                                    "filter": { "term" : { "part_of_r" : 0 } },
                                    "field_value_factor": {
                                      "field":    "last_month_downloads",
                                      "modifier": "log1p"
                                    }
                                  },
                                  {
                                    "filter": { "term" : { "part_of_r" : 1 } },
                                    "field_value_factor": {
                                      "field":    "part_of_r",
                                      "modifier": "log1p",
                                      "factor": 300000,
                                    }
                                  }
                                ],
                                "boost_mode": "replace"
                              }
                            }
                          }
                        },
                        inner_hits : { fields: ['package_name', 'version', 'latest_version', 'maintainer.name'] }
                      }
                    }
                  ],
                  minimum_should_match : 1,
                }
              }],
            minimum_should_match : 1,
          }
        },
        highlight : {
          pre_tags : [""],
          post_tags : [""],
          "fields" : {
            "note": {highlight_query: searchTopicQuery},
            "keywords": {highlight_query: searchTopicQuery},
            "aliases": {highlight_query: searchTopicQuery},
            "author": {highlight_query: searchTopicQuery},
            "references": {highlight_query: searchTopicQuery},
            "value": {highlight_query: searchTopicQuery},
            "details": {highlight_query: searchTopicQuery},
            "description": {highlight_query: searchTopicQuery},
            "title" : {highlight_query: searchTopicQuery},
            "name": {highlight_query: searchTopicQuery},
          }
        },
        from: offset,
        size: perPage,
        fields: ['package_name', 'version', 'name', 'maintainer.name']
      }
    }).then(function(result){
      var functions  = [];
      result.hits.hits.forEach(function(hit) {
          var fields = {};
          var inner_hits_fields = hit.inner_hits.package_version.hits.hits[0].fields;
          fields.package_name = inner_hits_fields.package_name[0];
          fields.version = inner_hits_fields.version[0];
          fields.name = hit.fields.name[0];
          fields.maintainer = inner_hits_fields['maintainer.name'][0];
          var stripped={};
          for(var highlight in hit.highlight){
            stripped[highlight] = striptags(hit.highlight[highlight].toString(),'');
          }
          functions.push({
            fields: fields,
            score: hit._score,
            highlight: stripped
          });
        });
      return res.view('search/function_results.ejs', {data: {functions: functions, hits: numeral(result.hits.total).format('0,0')}, layout: null});
    }).catch(function(err) {
        return res.negotiate(err);
    });
  },

  fullSearch: function(req, res) {
    return res.ok({query: req.param('q'),current: req.path+ '?' +querystring.stringify(req.query)},'search/result.ejs');
  }

};
<|endoftext|>