<commit_before>/**
 * QMiner - Open Source Analytics Platform
 *
 * Copyright (C) 2014 Jozef Stefan Institute
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

///////////////////////////////
//#
//# ### evaluation.js (use require)
//#
//# Evaluation metrics functions.
//# The library must be loaded using `var evaluation = require('evaluation.js');`.
//#
//# **Functions and properties:**
//#

// object for online metrics model
function createOnlineMetric(updateCallback) {
    var error = -1;
    var calcError = new updateCallback();
    // update function defined with callback function
    this.update = function (err) {
        error = calcError.update(err);
    }
    // getter for error
    this.getError = function () {
        return error;
    }
    return this;
}

//////////// MEAN ERROR
//#- `me = evaluation.newMeanError()` -- create new (online) mean error instance.
//#   - `me.update(num)` -- updates error with new sample `num`
//#   - `num = me.getError()` -- returns current error `num`
exports.newMeanError = function () {
    function calcError() {
        this.sumErr = 0;
        this.count = 0;
        // update function
        this.update = function (err) {
            this.sumErr += err;
            this.count++;
            var error = this.sumErr / this.count;
            return error;
        }
    }
    return new createOnlineMetric(calcError);
}

//////////// MEAN ABSOLUTE ERROR
//#- `mae = evaluation.newMeanAbsoluteError()` -- create new (online) mean absolute error instance.
//#   - `mae.update(num)` -- updates error with new sample `num`
//#   - `num = mae.getError()` -- returns current error `num`
exports.newMeanAbsoluteError = function () {
    function calcError () {
        this.sumErr = 0;
        this.count = 0;
        // update function
        this.update = function (err) {
            this.sumErr += Math.abs(err);
            this.count++;
            var error = this.sumErr / this.count;
            return error;
        }
    }
    return new createOnlineMetric(calcError);
}

//////////// MEAN SQUARE ERROR
//#- `mse = evaluation.newMeanSquareError()` -- create new (online) mean square error instance.
//#   - `mse.update(num)` -- updates error with new sample `num`
//#   - `num = mse.getError()` -- returns current error `num`
exports.newMeanSquareError = function () {
    function calcError() {
        this.sumErr = 0;
        this.count = 0;
        // update function
        this.update = function (err) {
            this.sumErr += (err*err);
            this.count++;
            var error = this.sumErr / this.count;
            return error;
        }
    }
    return new createOnlineMetric(calcError);
}

//////////// ROOT MEAN ABSOLUTE ERROR
//#- `rmse = evaluation.newRootMeanSquareError()` -- create new (online) root mean square error instance.
//#   - `rmse.update(num)` -- updates error with new sample `num`
//#   - `num = rmse.getError()` -- returns current error `num`
exports.newRootMeanSquareError = function () {
    function calcError() {
        this.sumErr = 0;
        this.count = 0;
        // update function
        this.update = function (err) {
            this.sumErr += (err * err);
            this.count++;
            var error = this.sumErr / this.count;
            return Math.sqrt(error);
        }
    }
    return new createOnlineMetric(calcError);
}

exports.newRSquare = function () {
    function rSquare() {
        this.sst = 0;
        this.sse = 0;
        this.mean = 0;
        this.count = 0;
        this.sumReal = 0;
        this.sumReal2 = 0;
        this.r2 = -1;
        // update function
        this.update = function (real, est) {
            this.count++;
            this.sumReal += real;
            this.sumReal2 += real * real;
            this.mean = this.sumReal / this.count;
            //calculate error
            this.sse += (real - est) * (real - est);
            this.sst = this.sumReal2 - this.count * this.mean * this.mean;
            if (this.sst == 0.0) {
                this.r2 = (this.sse == 0.0) ? this.r2 = 1.0 : this.r2 = 0.0;
            } else {
                this.r2 = (1 - this.sse / this.sst);
            }
        }
        // getter
        this.getError = function () {
            return this.r2;
        }
    }
    return new rSquare();
}

// About this module
exports.about = function () {
    var description = "Module with evalutaion metrics.";
    return description;
};<commit_msg>Minor changes in evaluation.js functions (extra input parameters - previous version still works).<commit_after>/**
 * QMiner - Open Source Analytics Platform
 *
 * Copyright (C) 2014 Jozef Stefan Institute
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

///////////////////////////////
//#
//# ### evaluation.js (use require)
//#
//# Evaluation metrics functions.
//# The library must be loaded using `var evaluation = require('evaluation.js');`.
//#
//# **Functions and properties:**
//#

// object for online metrics model
function createOnlineMetric(updateCallback) {
    var error = -1;
    var calcError = new updateCallback();
    // update function defined with callback function
    this.update = function (true_num, pred_num) {
        error = calcError.update(true_num, pred_num);
    }
    // getter for error
    this.getError = function () {
        return error;
    }
    return this;
}

//////////// MEAN ERROR
//#- `me = evaluation.newMeanError()` -- create new (online) mean error instance.
//#   - `me.update(true_num, pred_num)` -- updates metric with ground truth target value `true_num` and estimated target value `pred_num`.
//#   - `num = me.getError()` -- returns current error `num`
exports.newMeanError = function () {
    function calcError() {
        this.sumErr = 0;
        this.count = 0;
        // update function
        this.update = function (true_num, pred_num) {
            var err = true_num - pred_num;
            this.sumErr += err;
            this.count++;
            var error = this.sumErr / this.count;
            return error;
        }
    }
    return new createOnlineMetric(calcError);
}

//////////// MEAN ABSOLUTE ERROR
//#- `mae = evaluation.newMeanAbsoluteError()` -- create new (online) mean absolute error instance.
//#   - `mae.update(true_num, pred_num)` -- updates metric with ground truth target value `true_num` and estimated target value `pred_num`.
//#   - `num = mae.getError()` -- returns current error `num`
exports.newMeanAbsoluteError = function () {
    function calcError () {
        this.sumErr = 0;
        this.count = 0;
        // update function
        this.update = function (true_num, pred_num) {
            var err = true_num - pred_num;
            this.sumErr += Math.abs(err);
            this.count++;
            var error = this.sumErr / this.count;
            return error;
        }
    }
    return new createOnlineMetric(calcError);
}

//////////// MEAN SQUARE ERROR
//#- `mse = evaluation.newMeanSquareError()` -- create new (online) mean square error instance.
//#   - `mse.update(true_num, pred_num)` -- updates metric with ground truth target value `true_num` and estimated target value `pred_num`.
//#   - `num = mse.getError()` -- returns current error `num`
exports.newMeanSquareError = function () {
    function calcError() {
        this.sumErr = 0;
        this.count = 0;
        // update function
        this.update = function (true_num, pred_num) {
            var err = true_num - pred_num;
            this.sumErr += (err*err);
            this.count++;
            var error = this.sumErr / this.count;
            return error;
        }
    }
    return new createOnlineMetric(calcError);
}

//////////// ROOT MEAN ABSOLUTE ERROR
//#- `rmse = evaluation.newRootMeanSquareError()` -- create new (online) root mean square error instance.
//#   - `rmse.update(true_num, pred_num)` -- updates metric with ground truth target value `true_num` and estimated target value `pred_num`.
//#   - `num = rmse.getError()` -- returns current error `num`
exports.newRootMeanSquareError = function () {
    function calcError() {
        this.sumErr = 0;
        this.count = 0;
        // update function
        this.update = function (true_num, pred_num) {
            var err = true_num - pred_num;
            this.sumErr += (err * err);
            this.count++;
            var error = this.sumErr / this.count;
            return Math.sqrt(error);
        }
    }
    return new createOnlineMetric(calcError);
}

//////////// R SQUARED SCORE
//#- `r2 = evaluation.newRSquareScore()` -- create new (online) R Square instance. This statistic measures how successful the fit is in explaining the variation of the data. Best possible score is 1.0, lower values are worse.
//#   - `r2.update(num)` -- updates metric with ground truth target value `true_num` and estimated target value `pred_num`.
//#   - `num = rmse.getError()` -- returns current score `num`
exports.newRSquareScore = function () {
    function rSquare() {
        this.sst = 0;
        this.sse = 0;
        this.mean = 0;
        this.count = 0;
        this.sumTrue = 0;
        this.sumTrue2 = 0;
        // update function
        this.update = function (true_num, pred_num) {
            this.count++;
            this.sumTrue += true_num;
            this.sumTrue2 += true_num * true_num;
            this.mean = this.sumTrue / this.count;
            //calculate R squared score
            this.sse += (true_num - pred_num) * (true_num - pred_num);
            this.sst = this.sumTrue2 - this.count * this.mean * this.mean;
            if (this.sst == 0.0) {
                return (this.sse == 0.0) ? 1.0 : 0.0;
            }
            return 1 - this.sse / this.sst;
        }
    }
    return new createOnlineMetric(rSquare);
}

// About this module
exports.about = function () {
    var description = "Module with evalutaion metrics.";
    return description;
};<|endoftext|>


<commit_before>/*
	hide the tools toggle and use the header label to trigger it
*/
 (function() {
	var $tmtoggle = $('#tools-menu-toggle');
	var $headerlabel = $('#header-label');

	$tmtoggle.hide();

	$headerlabel.bind('click',
	function(e) {
		$tmtoggle
		// show it quickly at a certain position so we can position the menu
		.show()
		.css('left', '20px')
		.css('top', '21px')
		.css('opacity', 0);
		$tmtoggle.trigger(e);
		$tmtoggle.hide();
		return false;

	});

})();

// Make #entryform resizable
// TODO: Remember height in prefs
 (function() {
	var $body = $('body'),
		$timeline = $('#timeline-tabs-content, .TabbedPanelsContentGroup'),
		$entryForm = $('#entryform'),
		entryFormBottom = parseInt($entryForm.css('bottom'), 10),
		$entryBoxPopup = $('#entrybox-popup'),
		$resize = $('

'),
		resizing = false,
		maxEntryFormHeight = function() {
			return nativeWindow.height - 96;
		},
		setEntryFormHeight = function(newHeight) {
			$timeline.css('bottom', newHeight + 28);
			$entryForm.height(newHeight);
			$entryBoxPopup.css('bottom', newHeight - 1);

		},
		onMouseMove = function(ev) {
			if (!resizing) {
				return;
			}

			var newHeight = nativeWindow.height - ev.pageY - entryFormBottom;

			// Set max height: don't overlap header
			newHeight = Math.min(maxEntryFormHeight(), newHeight);

			// Set min height: fit at least one line of text
			newHeight = Math.max(35, newHeight);

			setEntryFormHeight(newHeight);

		},
		onMouseUp = function(ev) {
			resizing = false;
		},
		onMouseEnter = function(ev) {
			resizing = false;
		},
		onMouseOut = function(ev) {
			if (resizing && $(ev.target).is('body')) {
				resizing = false;

			}

		};

	$resize.prependTo($entryForm)
		.mousedown(function(ev) {
			sch.error('mousedown');
			resizing = true;
			$body
			.mouseout(onMouseOut)
			// Must bind this first so it runs first
			.mouseenter(onMouseEnter)
			// Backup for when body mouseout isn't caught
			.mouseup(onMouseUp)
			.mousemove(onMouseMove);

		})
		.mouseup(onMouseUp);

	window.nativeWindow.addEventListener(
		air.NativeWindowBoundsEvent.RESIZE,
		function() {
			sch.error('air.NativeWindowBoundsEvent.RESIZE');
			var max = maxEntryFormHeight();
			sch.error("max:"+max);
			$entryForm.height();
			if ($entryForm.height() > max) {
				setEntryFormHeight(max);
			}
		}
	);

})();

/**
 * bitmap emoticons are not 80s.
 */
(function() {
	Spaz.TimelineFilters.friends.removeFilter('emoticons');
	Spaz.TimelineFilters['public'].removeFilter('emoticons');
	Spaz.TimelineFilters.lists.removeFilter('emoticons');
	Spaz.TimelineFilters.search.removeFilter('emoticons');
	Spaz.TimelineFilters.other.removeFilter('emoticons');
})()

/**
 * change header label text
 */
(function() {
	var jqlabel = jQuery('#header-label');
	var html = jqlabel.html();
	html = html.replace('Spaz', 'READY.');
	jqlabel.html(html);
})();

<commit_msg>lintiness<commit_after>/*
	hide the tools toggle and use the header label to trigger it
*/
 (function() {
	var $tmtoggle = $('#tools-menu-toggle');
	var $headerlabel = $('#header-label');

	$tmtoggle.hide();

	$headerlabel.bind('click',
	function(e) {
		$tmtoggle
		// show it quickly at a certain position so we can position the menu
		.show()
		.css('left', '20px')
		.css('top', '21px')
		.css('opacity', 0);
		$tmtoggle.trigger(e);
		$tmtoggle.hide();
		return false;

	});

})();

// Make #entryform resizable
// TODO: Remember height in prefs
 (function() {
	var $body = $('body'),
		$timeline = $('#timeline-tabs-content, .TabbedPanelsContentGroup'),
		$entryForm = $('#entryform'),
		entryFormBottom = parseInt($entryForm.css('bottom'), 10),
		$entryBoxPopup = $('#entrybox-popup'),
		$resize = $('

'),
		resizing = false,
		maxEntryFormHeight = function() {
			return nativeWindow.height - 96;
		},
		setEntryFormHeight = function(newHeight) {
			$timeline.css('bottom', newHeight + 28);
			$entryForm.height(newHeight);
			$entryBoxPopup.css('bottom', newHeight - 1);

		},
		onMouseMove = function(ev) {
			if (!resizing) {
				return;
			}

			var newHeight = nativeWindow.height - ev.pageY - entryFormBottom;

			// Set max height: don't overlap header
			newHeight = Math.min(maxEntryFormHeight(), newHeight);

			// Set min height: fit at least one line of text
			newHeight = Math.max(35, newHeight);

			setEntryFormHeight(newHeight);

		},
		onMouseUp = function(ev) {
			resizing = false;
		},
		onMouseEnter = function(ev) {
			resizing = false;
		},
		onMouseOut = function(ev) {
			if (resizing && $(ev.target).is('body')) {
				resizing = false;

			}

		};

	$resize.prependTo($entryForm)
		.mousedown(function(ev) {
			sch.error('mousedown');
			resizing = true;
			$body
			.mouseout(onMouseOut)
			// Must bind this first so it runs first
			.mouseenter(onMouseEnter)
			// Backup for when body mouseout isn't caught
			.mouseup(onMouseUp)
			.mousemove(onMouseMove);

		})
		.mouseup(onMouseUp);

	window.nativeWindow.addEventListener(
		air.NativeWindowBoundsEvent.RESIZE,
		function() {
			sch.error('air.NativeWindowBoundsEvent.RESIZE');
			var max = maxEntryFormHeight();
			sch.error("max:"+max);
			$entryForm.height();
			if ($entryForm.height() > max) {
				setEntryFormHeight(max);
			}
		}
	);

})();

/**
 * bitmap emoticons are not 80s.
 */
(function() {
	Spaz.TimelineFilters.friends.removeFilter('emoticons');
	Spaz.TimelineFilters['public'].removeFilter('emoticons');
	Spaz.TimelineFilters.lists.removeFilter('emoticons');
	Spaz.TimelineFilters.search.removeFilter('emoticons');
	Spaz.TimelineFilters.other.removeFilter('emoticons');
})();

/**
 * change header label text
 */
(function() {
	var jqlabel = jQuery('#header-label');
	var html = jqlabel.html();
	html = html.replace('Spaz', 'READY.');
	jqlabel.html(html);
})();

<|endoftext|>


<commit_before>FLOW.permControl = Ember.Controller.create({
  perms: [],

  init: function () {
    this._super();
    this.initPermissions();
    this.setUserPermissions();
    this.setCurrentPermissions();
  },

  initPermissions: function () {
    this.perms.push(Ember.Object.create({
      perm: 'createSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'editSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'uploadSurveyZipData',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'importDataReport',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'viewMessages',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'publishSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'mapData',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'setDataPrivacy',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'editRawData',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'deleteRawData',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'runReport',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'deleteSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'deleteSurveyGroup',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'addUser',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'editUser',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'deleteUser',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'approveSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'editEditorialContent',
      value: false
    }));
  },

  setUserPermissions: function () {
    var user = true;
    if (user === true) {
      this.perms.findProperty('perm', 'createSurvey').value = true;
      this.perms.findProperty('perm', 'editSurvey').value = true;
      this.perms.findProperty('perm', 'uploadSurveyZipData').value = true;
      this.perms.findProperty('perm', 'viewMessages').value = true;
      this.perms.findProperty('perm', 'publishSurvey').value = true;
      this.perms.findProperty('perm', 'mapData').value = true;
      this.perms.findProperty('perm', 'setDataPrivacy').value = true;
      this.perms.findProperty('perm', 'runReport').value = true;
    }

    if (user === true) {
      this.perms.findProperty('perm', 'createSurvey').value = true;
      this.perms.findProperty('perm', 'editSurvey').value = true;
      this.perms.findProperty('perm', 'uploadSurveyZipData').value = true;
      this.perms.findProperty('perm', 'importDataReport').value = true;
      this.perms.findProperty('perm', 'viewMessages').value = true;
      this.perms.findProperty('perm', 'publishSurvey').value = true;
      this.perms.findProperty('perm', 'mapData').value = true;
      this.perms.findProperty('perm', 'setDataPrivacy').value = true;
      this.perms.findProperty('perm', 'runReport').value = true;
      this.perms.findProperty('perm', 'editRawData').value = true;
      this.perms.findProperty('perm', 'deleteRawData').value = true;
      this.perms.findProperty('perm', 'approveSurvey').value = true;
    }

    if (user === true) {
      this.perms.findProperty('perm', 'createSurvey').value = true;
      this.perms.findProperty('perm', 'editSurvey').value = true;
      this.perms.findProperty('perm', 'uploadSurveyZipData').value = true;
      this.perms.findProperty('perm', 'importDataReport').value = true;
      this.perms.findProperty('perm', 'viewMessages').value = true;
      this.perms.findProperty('perm', 'publishSurvey').value = true;
      this.perms.findProperty('perm', 'mapData').value = true;
      this.perms.findProperty('perm', 'setDataPrivacy').value = true;
      this.perms.findProperty('perm', 'runReport').value = true;
      this.perms.findProperty('perm', 'editRawData').value = true;
      this.perms.findProperty('perm', 'deleteRawData').value = true;
      this.perms.findProperty('perm', 'approveSurvey').value = true;
      this.perms.findProperty('perm', 'deleteSurvey').value = true;
      this.perms.findProperty('perm', 'deleteSurveyGroup').value = true;
      this.perms.findProperty('perm', 'addUser').value = true;
      this.perms.findProperty('perm', 'editUser').value = true;
      this.perms.findProperty('perm', 'deleteUser').value = true;
    }

  },

  setCurrentPermissions: function () {
    this.perms.forEach(function (item) {
      //this.set(item.perm,item.value);
    });
  }
});

FLOW.dialogControl = Ember.Object.create({
  delSG: "delSG",
  delS: "delS",
  delQG: "delQG",
  delQ: "delQ",
  delUser: "delUser",
  delAttr: "delAttr",
  delAssignment: "delAssignment",
  delDeviceGroup: "delDeviceGroup",
  delSI: "delSI",
  delSI2: "delSI2",
  delSL: "delSL",
  delCR: "delCR",
  makeMonitor: "makeMonitor",
  delForm: "delForm",
  showDialog: false,
  message: null,
  header: null,
  activeView: null,
  activeAction: null,
  showOK: true,
  showCANCEL: true,

  confirm: function (event) {
    this.set('activeView', event.view);
    this.set('activeAction', event.context);
    this.set('showOK', true);
    this.set('showCANCEL', true);

    switch (this.get('activeAction')) {
    case "delSG":
      this.set('header', Ember.String.loc('_sg_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delS":
      this.set('header', Ember.String.loc('_s_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delQG":
      this.set('header', Ember.String.loc('_qg_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delQ":
      this.set('header', Ember.String.loc('_q_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delUser":
      this.set('header', Ember.String.loc('_are_you_sure_you_want_to_delete_this_user'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delAttr":
      this.set('header', Ember.String.loc('_attr_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delAssignment":
      this.set('header', Ember.String.loc('_assignment_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delDeviceGroup":
      this.set('header', Ember.String.loc('_device_group_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delSI":
      this.set('header', Ember.String.loc('_delete_record_header'));
      this.set('message', Ember.String.loc('_are_you_sure_delete_this_data_record'));
      this.set('showDialog', true);
      break;

    case "delSI2":
      this.set('header', Ember.String.loc('_delete_record_header'));
      this.set('message', Ember.String.loc('_are_you_sure_delete_this_data_record'));
      this.set('showDialog', true);
      break;

    case "delSL":
        this.set('header', Ember.String.loc('_delete_data_point_header'));
        this.set('message', Ember.String.loc('_are_you_sure_delete_this_data_point'));
        this.set('showDialog', true);
        break;

    case "makeMonitor":
    	this.set('header', Ember.String.loc('_make_monitor_group_header'));
        this.set('message', Ember.String.loc('_make_monitor_group_text'));
        this.set('showDialog', true);
      break;

    case "delForm":
      this.set('header', "Delete form");
      this.set('message', "Are you sure you want to delete this form?");
      this.set('showDialog', true);
      break;

    case "delCR":
        this.set('header', Ember.String.loc('_delete_cascade_resource_header'));
        this.set('message', Ember.String.loc('_delete_cascade_resource_text'));
        this.set('showDialog', true);
      break;

    default:
    }
  },

  doOK: function (event) {
    this.set('header', null);
    this.set('message', null);
    this.set('showCANCEL', true);
    this.set('showDialog', false);
    var view = this.get('activeView');
    switch (this.get('activeAction')) {
    case "delSG":
      view.deleteSurveyGroup.apply(view, arguments);
      break;

    case "delS":
      view.deleteSurvey.apply(view, arguments);
      break;

    case "delQG":
      view.deleteQuestionGroup.apply(view, arguments);
      break;

    case "delQ":
      this.set('showDialog', false);
      view.deleteQuestion.apply(view, arguments);
      break;

    case "delUser":
      this.set('showDialog', false);
      view.deleteUser.apply(view, arguments);
      break;

    case "delAttr":
      this.set('showDialog', false);
      view.deleteAttribute.apply(view, arguments);
      break;

    case "delAssignment":
      this.set('showDialog', false);
      view.deleteSurveyAssignment.apply(view, arguments);
      break;

    case "delDeviceGroup":
      this.set('showDialog', false);
      view.deleteDeviceGroup.apply(view, arguments);
      break;

    case "delSI":
      this.set('showDialog', false);
      view.deleteSI.apply(view, arguments);
      break;

    case "delSI2":
      this.set('showDialog', false);
      view.deleteSI.apply(view, arguments);
      break;

    case "delSL":
        this.set('showDialog', false);
        view.deleteSL.apply(view, arguments);
        break;

    case "makeMonitor":
      this.set('showDialog', false);
      view.makeMonitorGroup.apply(view, arguments);
      break;

    case "delForm":
      this.set('showDialog', false);
      FLOW.surveyControl.deleteForm();
      break;

    case "delCR":
        this.set('showDialog', false);
        view.deleteResource(view, arguments);
        break;

    default:
    }
  },

  doCANCEL: function (event) {
    this.set('showDialog', false);
  }
});
<commit_msg>[#1124] Add `entityPermissions` to process permissions depending on an entity<commit_after>FLOW.permControl = Ember.Controller.create({
  perms: [],

  init: function () {
    this._super();
    this.initPermissions();
    this.setUserPermissions();
    this.setCurrentPermissions();
  },

  initPermissions: function () {
    this.perms.push(Ember.Object.create({
      perm: 'createSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'editSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'uploadSurveyZipData',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'importDataReport',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'viewMessages',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'publishSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'mapData',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'setDataPrivacy',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'editRawData',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'deleteRawData',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'runReport',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'deleteSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'deleteSurveyGroup',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'addUser',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'editUser',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'deleteUser',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'approveSurvey',
      value: false
    }));
    this.perms.push(Ember.Object.create({
      perm: 'editEditorialContent',
      value: false
    }));
  },

  setUserPermissions: function () {
    var user = true;
    if (user === true) {
      this.perms.findProperty('perm', 'createSurvey').value = true;
      this.perms.findProperty('perm', 'editSurvey').value = true;
      this.perms.findProperty('perm', 'uploadSurveyZipData').value = true;
      this.perms.findProperty('perm', 'viewMessages').value = true;
      this.perms.findProperty('perm', 'publishSurvey').value = true;
      this.perms.findProperty('perm', 'mapData').value = true;
      this.perms.findProperty('perm', 'setDataPrivacy').value = true;
      this.perms.findProperty('perm', 'runReport').value = true;
    }

    if (user === true) {
      this.perms.findProperty('perm', 'createSurvey').value = true;
      this.perms.findProperty('perm', 'editSurvey').value = true;
      this.perms.findProperty('perm', 'uploadSurveyZipData').value = true;
      this.perms.findProperty('perm', 'importDataReport').value = true;
      this.perms.findProperty('perm', 'viewMessages').value = true;
      this.perms.findProperty('perm', 'publishSurvey').value = true;
      this.perms.findProperty('perm', 'mapData').value = true;
      this.perms.findProperty('perm', 'setDataPrivacy').value = true;
      this.perms.findProperty('perm', 'runReport').value = true;
      this.perms.findProperty('perm', 'editRawData').value = true;
      this.perms.findProperty('perm', 'deleteRawData').value = true;
      this.perms.findProperty('perm', 'approveSurvey').value = true;
    }

    if (user === true) {
      this.perms.findProperty('perm', 'createSurvey').value = true;
      this.perms.findProperty('perm', 'editSurvey').value = true;
      this.perms.findProperty('perm', 'uploadSurveyZipData').value = true;
      this.perms.findProperty('perm', 'importDataReport').value = true;
      this.perms.findProperty('perm', 'viewMessages').value = true;
      this.perms.findProperty('perm', 'publishSurvey').value = true;
      this.perms.findProperty('perm', 'mapData').value = true;
      this.perms.findProperty('perm', 'setDataPrivacy').value = true;
      this.perms.findProperty('perm', 'runReport').value = true;
      this.perms.findProperty('perm', 'editRawData').value = true;
      this.perms.findProperty('perm', 'deleteRawData').value = true;
      this.perms.findProperty('perm', 'approveSurvey').value = true;
      this.perms.findProperty('perm', 'deleteSurvey').value = true;
      this.perms.findProperty('perm', 'deleteSurveyGroup').value = true;
      this.perms.findProperty('perm', 'addUser').value = true;
      this.perms.findProperty('perm', 'editUser').value = true;
      this.perms.findProperty('perm', 'deleteUser').value = true;
    }

  },

  setCurrentPermissions: function () {
    this.perms.forEach(function (item) {
      //this.set(item.perm,item.value);
    });
  },

  /* Given an entity, process the permissions settings for the current user
    and return the permissions associated with that entity.  Entity is an Ember object*/
  permissions: function(entity) {
    var keyId, ancestorIds, permissions = [], currentUserPermissions = FLOW.userControl.currentUserPathPermissions();

    if (!currentUserPermissions || !entity) { return []; }

    // first check current object id
    keyId = entity.get('keyId');
    if (keyId in currentUserPermissions) {
      permissions = permissions.concat(currentUserPermissions[keyId]);
    }

    // check ancestor permissions
    ancestorIds = entity.get('ancestorIds');
    if (!ancestorIds) {
      return permissions;
    }

    var i;
    for(i = 0; i < ancestorIds.length; i++){
      if (ancestorIds[i] in currentUserPermissions) {
        permissions = permissions.concat(currentUserPermissions[ancestorIds[i]]);
      }
    }

    return permissions;
  },
});

FLOW.dialogControl = Ember.Object.create({
  delSG: "delSG",
  delS: "delS",
  delQG: "delQG",
  delQ: "delQ",
  delUser: "delUser",
  delAttr: "delAttr",
  delAssignment: "delAssignment",
  delDeviceGroup: "delDeviceGroup",
  delSI: "delSI",
  delSI2: "delSI2",
  delSL: "delSL",
  delCR: "delCR",
  makeMonitor: "makeMonitor",
  delForm: "delForm",
  showDialog: false,
  message: null,
  header: null,
  activeView: null,
  activeAction: null,
  showOK: true,
  showCANCEL: true,

  confirm: function (event) {
    this.set('activeView', event.view);
    this.set('activeAction', event.context);
    this.set('showOK', true);
    this.set('showCANCEL', true);

    switch (this.get('activeAction')) {
    case "delSG":
      this.set('header', Ember.String.loc('_sg_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delS":
      this.set('header', Ember.String.loc('_s_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delQG":
      this.set('header', Ember.String.loc('_qg_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delQ":
      this.set('header', Ember.String.loc('_q_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delUser":
      this.set('header', Ember.String.loc('_are_you_sure_you_want_to_delete_this_user'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delAttr":
      this.set('header', Ember.String.loc('_attr_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delAssignment":
      this.set('header', Ember.String.loc('_assignment_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delDeviceGroup":
      this.set('header', Ember.String.loc('_device_group_delete_header'));
      this.set('message', Ember.String.loc('_this_cant_be_undo'));
      this.set('showDialog', true);
      break;

    case "delSI":
      this.set('header', Ember.String.loc('_delete_record_header'));
      this.set('message', Ember.String.loc('_are_you_sure_delete_this_data_record'));
      this.set('showDialog', true);
      break;

    case "delSI2":
      this.set('header', Ember.String.loc('_delete_record_header'));
      this.set('message', Ember.String.loc('_are_you_sure_delete_this_data_record'));
      this.set('showDialog', true);
      break;

    case "delSL":
        this.set('header', Ember.String.loc('_delete_data_point_header'));
        this.set('message', Ember.String.loc('_are_you_sure_delete_this_data_point'));
        this.set('showDialog', true);
        break;

    case "makeMonitor":
    	this.set('header', Ember.String.loc('_make_monitor_group_header'));
        this.set('message', Ember.String.loc('_make_monitor_group_text'));
        this.set('showDialog', true);
      break;

    case "delForm":
      this.set('header', "Delete form");
      this.set('message', "Are you sure you want to delete this form?");
      this.set('showDialog', true);
      break;

    case "delCR":
        this.set('header', Ember.String.loc('_delete_cascade_resource_header'));
        this.set('message', Ember.String.loc('_delete_cascade_resource_text'));
        this.set('showDialog', true);
      break;

    default:
    }
  },

  doOK: function (event) {
    this.set('header', null);
    this.set('message', null);
    this.set('showCANCEL', true);
    this.set('showDialog', false);
    var view = this.get('activeView');
    switch (this.get('activeAction')) {
    case "delSG":
      view.deleteSurveyGroup.apply(view, arguments);
      break;

    case "delS":
      view.deleteSurvey.apply(view, arguments);
      break;

    case "delQG":
      view.deleteQuestionGroup.apply(view, arguments);
      break;

    case "delQ":
      this.set('showDialog', false);
      view.deleteQuestion.apply(view, arguments);
      break;

    case "delUser":
      this.set('showDialog', false);
      view.deleteUser.apply(view, arguments);
      break;

    case "delAttr":
      this.set('showDialog', false);
      view.deleteAttribute.apply(view, arguments);
      break;

    case "delAssignment":
      this.set('showDialog', false);
      view.deleteSurveyAssignment.apply(view, arguments);
      break;

    case "delDeviceGroup":
      this.set('showDialog', false);
      view.deleteDeviceGroup.apply(view, arguments);
      break;

    case "delSI":
      this.set('showDialog', false);
      view.deleteSI.apply(view, arguments);
      break;

    case "delSI2":
      this.set('showDialog', false);
      view.deleteSI.apply(view, arguments);
      break;

    case "delSL":
        this.set('showDialog', false);
        view.deleteSL.apply(view, arguments);
        break;

    case "makeMonitor":
      this.set('showDialog', false);
      view.makeMonitorGroup.apply(view, arguments);
      break;

    case "delForm":
      this.set('showDialog', false);
      FLOW.surveyControl.deleteForm();
      break;

    case "delCR":
        this.set('showDialog', false);
        view.deleteResource(view, arguments);
        break;

    default:
    }
  },

  doCANCEL: function (event) {
    this.set('showDialog', false);
  }
});
<|endoftext|>


<commit_before>define([], function() {
    return function(source, sourceLayer, selectedResourceIds, visible, color, nodeids, filteredNodeids, hoverId, selectedLayerConfig) {

        var layerConfig = selectedLayerConfig;
        color = color || layerConfig.defaultcolor;
        hoverId = hoverId;
        var selectionColor = layerConfig.selectioncolor;
        var hoverColor = layerConfig.hovercolor;
        var colorPalette = layerConfig.colorpalette

        var createColorExpressions = function(defaultColor, colorPalette){
            if (nodeids) {
                var colorExpressions = ['case'];
                nodeids.forEach(function(nodeid, i) {
                    colorExpressions.push(['==', ['get', 'nodeid'], nodeid])
                    if (i <= colorPalette.length) {
                        colorExpressions.push(colorPalette[i]);
                    } else {
                        colorExpressions.push(colorPalette[Math.floor(Math.random() * Math.floor(colorPalette.length))]);
                    }
                });
                colorExpressions.push(color)
                return colorExpressions;
            } else {
                return defaultColor;
            }
        }
        color = createColorExpressions(color, colorPalette);
        var nodeFilter = ["!=", "resourceinstanceid", "x"] // just a placeholder if there are no filerNodeids
        if (filteredNodeids && nodeids.length > 1) {
            var nodeFilter = filteredNodeids.map(id => ["==", "nodeid", id])
            nodeFilter.splice(0, 0, 'any');
        }
        if (selectedResourceIds && selectedResourceIds.length > 0) {
            color = ['match', ['get', 'resourceinstanceid'], selectedResourceIds, selectionColor, color
            ];
        }
        if (hoverId) {
            color = ['match', ['get', 'resourceinstanceid'], hoverId, hoverColor, color
            ];
        }
        if (!source) return [];
        var layers = [{
            "id": "select-feature-polygon-fill",
            "type": "fill",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "Polygon"
                ], nodeFilter
            ],
            "paint": {
                "fill-color": color,
                "fill-outline-color": color,
                "fill-opacity": layerConfig.fillopacity
            },
            "layout": {
                "visibility": visible ? "visible": "none"
            }
        },  {
            "id": "select-feature-polygon-under-stroke",
            "type": "line",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "Polygon"
            ], nodeFilter],
            "layout": {
                "line-cap": "round",
                "line-join": "round",
                "visibility": visible ? "visible": "none"
            },
            "paint": {
                "line-color": layerConfig.strokecolor,
                "line-width": layerConfig.strokelinewidth
            }
        }, {
            "id": "select-feature-polygon-stroke",
            "type": "line",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "Polygon"
            ], nodeFilter],
            "layout": {
                "line-cap": "round",
                "line-join": "round",
                "visibility": visible ? "visible": "none"
            },
            "paint": {
                "line-color": color,
                "line-width": layerConfig.linewidth
            }
        }, {
            "id": "select-feature-line",
            "type": "line",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "LineString"
            ], nodeFilter],
            "layout": {
                "line-cap": "round",
                "line-join": "round",
                "visibility": visible ? "visible": "none"
            },
            "paint": {
                "line-color": color,
                "line-width": layerConfig.linewidth
            }
        }, {
            "id": "select-feature-point-point-stroke",
            "type": "circle",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',
                ["==", "$type", "Point"]
            ],
            "paint": {
                "circle-radius": layerConfig.strokepointradius,
                "circle-opacity": layerConfig.strokepointopacity,
                "circle-color": layerConfig.strokecolor
            },
            "layout": {
                "visibility": visible ? "visible": "none"
            }
        }, {
            "id": "select-feature-point",
            "type": "circle",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "Point"
            ], nodeFilter],
            "paint": {
                "circle-radius": layerConfig.pointradius,
                "circle-color": color
            },
            "layout": {
                "visibility": visible ? "visible": "none"
            }
        }];
        layers.forEach(function(layer) {
            layer["source"] = source;
            if (sourceLayer) layer["source-layer"] = sourceLayer;
        });
        console.log(layers);
        return layers;
    };
});
<commit_msg>Removes log statement<commit_after>define([], function() {
    return function(source, sourceLayer, selectedResourceIds, visible, color, nodeids, filteredNodeids, hoverId, selectedLayerConfig) {

        var layerConfig = selectedLayerConfig;
        color = color || layerConfig.defaultcolor;
        hoverId = hoverId;
        var selectionColor = layerConfig.selectioncolor;
        var hoverColor = layerConfig.hovercolor;
        var colorPalette = layerConfig.colorpalette

        var createColorExpressions = function(defaultColor, colorPalette){
            if (nodeids) {
                var colorExpressions = ['case'];
                nodeids.forEach(function(nodeid, i) {
                    colorExpressions.push(['==', ['get', 'nodeid'], nodeid])
                    if (i <= colorPalette.length) {
                        colorExpressions.push(colorPalette[i]);
                    } else {
                        colorExpressions.push(colorPalette[Math.floor(Math.random() * Math.floor(colorPalette.length))]);
                    }
                });
                colorExpressions.push(color)
                return colorExpressions;
            } else {
                return defaultColor;
            }
        }
        color = createColorExpressions(color, colorPalette);
        var nodeFilter = ["!=", "resourceinstanceid", "x"] // just a placeholder if there are no filerNodeids
        if (filteredNodeids && nodeids.length > 1) {
            var nodeFilter = filteredNodeids.map(id => ["==", "nodeid", id])
            nodeFilter.splice(0, 0, 'any');
        }
        if (selectedResourceIds && selectedResourceIds.length > 0) {
            color = ['match', ['get', 'resourceinstanceid'], selectedResourceIds, selectionColor, color
            ];
        }
        if (hoverId) {
            color = ['match', ['get', 'resourceinstanceid'], hoverId, hoverColor, color
            ];
        }
        if (!source) return [];
        var layers = [{
            "id": "select-feature-polygon-fill",
            "type": "fill",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "Polygon"
                ], nodeFilter
            ],
            "paint": {
                "fill-color": color,
                "fill-outline-color": color,
                "fill-opacity": layerConfig.fillopacity
            },
            "layout": {
                "visibility": visible ? "visible": "none"
            }
        },  {
            "id": "select-feature-polygon-under-stroke",
            "type": "line",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "Polygon"
            ], nodeFilter],
            "layout": {
                "line-cap": "round",
                "line-join": "round",
                "visibility": visible ? "visible": "none"
            },
            "paint": {
                "line-color": layerConfig.strokecolor,
                "line-width": layerConfig.strokelinewidth
            }
        }, {
            "id": "select-feature-polygon-stroke",
            "type": "line",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "Polygon"
            ], nodeFilter],
            "layout": {
                "line-cap": "round",
                "line-join": "round",
                "visibility": visible ? "visible": "none"
            },
            "paint": {
                "line-color": color,
                "line-width": layerConfig.linewidth
            }
        }, {
            "id": "select-feature-line",
            "type": "line",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "LineString"
            ], nodeFilter],
            "layout": {
                "line-cap": "round",
                "line-join": "round",
                "visibility": visible ? "visible": "none"
            },
            "paint": {
                "line-color": color,
                "line-width": layerConfig.linewidth
            }
        }, {
            "id": "select-feature-point-point-stroke",
            "type": "circle",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',
                ["==", "$type", "Point"]
            ],
            "paint": {
                "circle-radius": layerConfig.strokepointradius,
                "circle-opacity": layerConfig.strokepointopacity,
                "circle-color": layerConfig.strokecolor
            },
            "layout": {
                "visibility": visible ? "visible": "none"
            }
        }, {
            "id": "select-feature-point",
            "type": "circle",
            "minzoom": layerConfig.minzoom,
            "filter": ['all',[
                "==", "$type", "Point"
            ], nodeFilter],
            "paint": {
                "circle-radius": layerConfig.pointradius,
                "circle-color": color
            },
            "layout": {
                "visibility": visible ? "visible": "none"
            }
        }];
        layers.forEach(function(layer) {
            layer["source"] = source;
            if (sourceLayer) layer["source-layer"] = sourceLayer;
        });
        return layers;
    };
});
<|endoftext|>


<commit_before>var App;

module('Acceptances - Index', {
  setup: function(){
    App = startApp();
  },
  teardown: function() {
    Ember.run(App, 'destroy');
  }
});

test('index renders', function(){
  expect(3);

  visit('/').then(function(){
    var title = find('h2#title');
    var list = find('ul li');

    equal(title.text(), 'Welcome to Ember.js');

    equal(list.length, 3);
    equal(list.text(), 'redyellowblue');
  });
});
<commit_msg>Fix failing test<commit_after>var App;

module('Acceptances - Index', {
  setup: function(){
    App = startApp();
  },
  teardown: function() {
    Ember.run(App, 'destroy');
  }
});

test('index renders', function(){
  visit('/').then(function(){
    var title = find('a.navbar-brand');

    equal(title.text(), 'BruteHack alpha');
  });
});
<|endoftext|>


<commit_before>"use strict";
let _ = require("lodash");
let assert = require("assert");
let semver = require("semver");

let NODE_MIRROR = process.env.NVM_NODEJS_ORG_MIRROR || "https://nodejs.org/dist";
let IOJS_MIRROR = process.env.NVM_IOJS_ORG_MIRROR || "https://iojs.org/dist";
let ELECTRON_MIRROR = process.env.ELECTRON_MIRROR || "https://atom.io/download/atom-shell";

let runtimePaths = {
    node: function (targetOptions) {
        if (semver.lt(targetOptions.runtimeVersion, "4.0.0")) {
            return {
                externalPath: NODE_MIRROR + "/v" + targetOptions.runtimeVersion + "/",
                winLibs: [{
                    dir: targetOptions.isX64 ? "x64" : "",
                    name: targetOptions.runtime + ".lib"
                }],
                tarPath: targetOptions.runtime + "-v" + targetOptions.runtimeVersion + ".tar.gz",
                headerOnly: false
            };
        }
        else {
            return {
                externalPath: NODE_MIRROR + "/v" + targetOptions.runtimeVersion + "/",
                winLibs: [{
                    dir: targetOptions.isX64 ? "win-x64" : "win-x86",
                    name: targetOptions.runtime + ".lib"
                }],
                tarPath: targetOptions.runtime + "-v" + targetOptions.runtimeVersion + "-headers.tar.gz",
                headerOnly: true
            };
        }
    },
    iojs: function (targetOptions) {
        return {
            externalPath: IOJS_MIRROR + "/v" + targetOptions.runtimeVersion + "/",
            winLibs: [{
                dir: targetOptions.isX64 ? "win-x64" : "win-x86",
                name: targetOptions.runtime + ".lib"
            }],
            tarPath: targetOptions.runtime + "-v" + targetOptions.runtimeVersion + ".tar.gz",
            headerOnly: false
        };
    },
    nw: function (targetOptions) {
        if (semver.gte(targetOptions.runtimeVersion, "0.13.0")) {
            return {
                externalPath: "https://node-webkit.s3.amazonaws.com/v" + targetOptions.runtimeVersion + "/",
                winLibs: [
                    {
                        dir: targetOptions.isX64 ? "x64" : "",
                        name: targetOptions.runtime + ".lib"
                    },
                    {
                        dir: targetOptions.isX64 ? "x64" : "",
                        name: "node.lib"
                    }
                ],
                tarPath: "nw-headers-v" + targetOptions.runtimeVersion + ".tar.gz",
                headerOnly: false
            };
        }
        return {
            externalPath: "https://node-webkit.s3.amazonaws.com/v" + targetOptions.runtimeVersion + "/",
            winLibs: [{
                dir: targetOptions.isX64 ? "x64" : "",
                name: targetOptions.runtime + ".lib"
            }],
            tarPath: "nw-headers-v" + targetOptions.runtimeVersion + ".tar.gz",
            headerOnly: false
        };
    },
    electron: function (targetOptions) {
        return {
            externalPath: ELECTRON_MIRROR + "/v" + targetOptions.runtimeVersion + "/",
            winLibs: [{
                dir: targetOptions.isX64 ? "x64" : "",
                name: "node.lib"
            }],
            tarPath: "node" + "-v" + targetOptions.runtimeVersion + ".tar.gz",
            headerOnly: false
        };
    },
    get: function (targetOptions) {
        assert(_.isObject(targetOptions));

        let runtime = targetOptions.runtime;
        let func = runtimePaths[runtime];
        let paths;
        if (_.isFunction(func) && _.isPlainObject(paths = func(targetOptions))) {
            return paths;
        }
        throw new Error("Unknown runtime: " + runtime);
    }
};

module.exports = runtimePaths;<commit_msg>:wrench: Support Electron v4 (#152)<commit_after>"use strict";
let _ = require("lodash");
let assert = require("assert");
let semver = require("semver");

let NODE_MIRROR = process.env.NVM_NODEJS_ORG_MIRROR || "https://nodejs.org/dist";
let IOJS_MIRROR = process.env.NVM_IOJS_ORG_MIRROR || "https://iojs.org/dist";
let ELECTRON_MIRROR = process.env.ELECTRON_MIRROR || "https://atom.io/download/atom-shell";

let runtimePaths = {
    node: function (targetOptions) {
        if (semver.lt(targetOptions.runtimeVersion, "4.0.0")) {
            return {
                externalPath: NODE_MIRROR + "/v" + targetOptions.runtimeVersion + "/",
                winLibs: [{
                    dir: targetOptions.isX64 ? "x64" : "",
                    name: targetOptions.runtime + ".lib"
                }],
                tarPath: targetOptions.runtime + "-v" + targetOptions.runtimeVersion + ".tar.gz",
                headerOnly: false
            };
        }
        else {
            return {
                externalPath: NODE_MIRROR + "/v" + targetOptions.runtimeVersion + "/",
                winLibs: [{
                    dir: targetOptions.isX64 ? "win-x64" : "win-x86",
                    name: targetOptions.runtime + ".lib"
                }],
                tarPath: targetOptions.runtime + "-v" + targetOptions.runtimeVersion + "-headers.tar.gz",
                headerOnly: true
            };
        }
    },
    iojs: function (targetOptions) {
        return {
            externalPath: IOJS_MIRROR + "/v" + targetOptions.runtimeVersion + "/",
            winLibs: [{
                dir: targetOptions.isX64 ? "win-x64" : "win-x86",
                name: targetOptions.runtime + ".lib"
            }],
            tarPath: targetOptions.runtime + "-v" + targetOptions.runtimeVersion + ".tar.gz",
            headerOnly: false
        };
    },
    nw: function (targetOptions) {
        if (semver.gte(targetOptions.runtimeVersion, "0.13.0")) {
            return {
                externalPath: "https://node-webkit.s3.amazonaws.com/v" + targetOptions.runtimeVersion + "/",
                winLibs: [
                    {
                        dir: targetOptions.isX64 ? "x64" : "",
                        name: targetOptions.runtime + ".lib"
                    },
                    {
                        dir: targetOptions.isX64 ? "x64" : "",
                        name: "node.lib"
                    }
                ],
                tarPath: "nw-headers-v" + targetOptions.runtimeVersion + ".tar.gz",
                headerOnly: false
            };
        }
        return {
            externalPath: "https://node-webkit.s3.amazonaws.com/v" + targetOptions.runtimeVersion + "/",
            winLibs: [{
                dir: targetOptions.isX64 ? "x64" : "",
                name: targetOptions.runtime + ".lib"
            }],
            tarPath: "nw-headers-v" + targetOptions.runtimeVersion + ".tar.gz",
            headerOnly: false
        };
    },
    electron: function (targetOptions) {
        return {
            externalPath: ELECTRON_MIRROR + "/v" + targetOptions.runtimeVersion + "/",
            winLibs: [{
                dir: targetOptions.isX64 ? "x64" : "",
                name: "node.lib"
            }],
            tarPath: "node" + "-v" + targetOptions.runtimeVersion + ".tar.gz",
            headerOnly: semver.gte(targetOptions.runtimeVersion, '4.0.0-alpha')
        };
    },
    get: function (targetOptions) {
        assert(_.isObject(targetOptions));

        let runtime = targetOptions.runtime;
        let func = runtimePaths[runtime];
        let paths;
        if (_.isFunction(func) && _.isPlainObject(paths = func(targetOptions))) {
            return paths;
        }
        throw new Error("Unknown runtime: " + runtime);
    }
};

module.exports = runtimePaths;
<|endoftext|>


<commit_before>import { join } from "path"

import Sequelize from "sequelize"
import Umzug from "umzug"

import loggerServer from "./../../src/server/logger"
import { inject, connect as origConnect } from "./../../src/server/database"

const logger = loggerServer()

const orm = inject({
  database: `bughouse_test_${process.pid}`,
  dialect: "sqlite",
  storage: ":memory:",
  retry: {
    max: 0
  }
})

console.log(join(process.cwd(), "db", "schema.json"))

const umzug = new Umzug({
  storage: "sequelize",
  logging: logger.info.bind(logger),
  migrations: {
    path: join(process.cwd(), "db", "migrations"),
    params: [orm.getQueryInterface(), Sequelize]
  },
  storageOptions: {
    sequelize: orm,
  }
})

export const connect = async () => {
  await origConnect()
  await umzug.up()
}

export const close = () => orm.close()
<commit_msg>improve database logging<commit_after>import { join } from "path"

import Sequelize from "sequelize"
import Umzug from "umzug"

import loggerServer from "./../../src/server/logger"
import { inject, connect as origConnect } from "./../../src/server/database"

const logger = loggerServer()

const databaseName = `bughouse_test_${process.pid}`
logger.info(`Creating database: ${databaseName}`)

const orm = inject({
  database: databaseName,
  dialect: "sqlite",
  storage: ":memory:",
  logging: (msg, ms) => logger.info(`Executed SQL on (${databaseName}) (${ms} ms): ${msg}`),
  retry: {
    max: 0
  }
})

const umzug = new Umzug({
  storage: "sequelize",
  logging: (msg) => logger.info(`Migration on (${databaseName}): ${msg}`),
  migrations: {
    path: join(process.cwd(), "db", "migrations"),
    params: [orm.getQueryInterface(), Sequelize]
  },
  storageOptions: {
    sequelize: orm,
  }
})

export const connect = async () => {
  await origConnect()
  await umzug.up()
}

export const close = () => orm.close()
<|endoftext|>


<commit_before>/* eslint-disable no-console */
/* eslint-disable camelcase */
const { Octokit } = require('@octokit/rest');

const { GITHUB_TOKEN: auth, GITHUB_REPOSITORY } = process.env;
const args = process.argv.slice(2);
const timeout = 2; // minutes
const commitSHA = args[0];
const [owner, repo] = GITHUB_REPOSITORY.split('/');

const octokit = new Octokit({ auth });

/**
 * uses octokit request for github action run_id provided
 * @param {number} run_id
 */
function getJobsFailed(run_id) {
  const params = {
    owner,
    repo,
    run_id,
  };
  return octokit.rest.actions
    .listJobsForWorkflowRun(params)
    .then(response => {
      if (response.status !== 200) {
        throw new Error(
          `Response ${response.status} from ${response.url}. Aborting.`,
        );
      }
      return response.data;
    })
    .then(({ jobs }) => {
      jobs.forEach(({ name, html_url, conclusion }) => {
        if (conclusion === 'success') return;
        console.error(
          `::error::Job "${name}" has failed. For more details, please see ${html_url}`,
        );
      });
    });
}

/**
 * uses octokit request for github action to get workflow with matching SHA
 * @param {number} page
 */
function getLatestWorkflow(page) {
  const params = {
    owner,
    repo,
    workflow_id: 'continuous-integration.yml',
    branch: 'master',
    per_page: '50',
    page,
  };
  return octokit.rest.actions
    .listWorkflowRuns(params)
    .then(response => {
      if (response.status !== 200) {
        throw new Error(
          `Response ${response.status} from ${response.url}. Aborting.`,
        );
      }
      return response.data;
    })
    .then(({ workflow_runs }) => {
      if (workflow_runs.length === 0) {
        throw new Error('No workflows found. Aborting.');
      }

      const workflow = workflow_runs.find(
        ({ head_sha }) => head_sha === commitSHA,
      );
      if (workflow) return workflow;
      console.log('Workflow not found in current page. Checking next page.');
      return getLatestWorkflow(page + 1);
    });
}

function sleep(minutes) {
  return new Promise(resolve => setTimeout(resolve, minutes * 60 * 1000));
}

/**
 * Validates the workflow
 * @param {Object} workflow
 * @returns true, false, undefined
 */
function validateWorkflowSuccess(workflow) {
  const { status, conclusion, head_commit, html_url } = workflow;
  console.log(`Validating commit ${head_commit.id}. Workflow: ${html_url}`);

  if (conclusion === 'failure') return false;

  const isWorkflowInProgress =
    status === 'in_progress' || status === null || status === 'queued';

  if (isWorkflowInProgress) return undefined;

  if (conclusion === 'success') {
    console.log('All checks succeeded');
    return true;
  }

  throw new Error(
    `Unexpected workflow result: ${JSON.stringify({ status, conclusion })}`,
  );
}

/**
 * Checks Github Actions url. Loops recursively until error is thrown.
 */
async function main() {
  try {
    const page = 1;
    const workflow = await getLatestWorkflow(page);
    const success = validateWorkflowSuccess(workflow);

    if (success === undefined) {
      console.log(`Check runs still pending. Sleeping for ${timeout} minutes`);
      await sleep(timeout);
      await main();
      return;
    }

    if (!success) {
      await getJobsFailed(workflow.id);
      process.exit(1);
    }
  } catch (e) {
    console.error(e);
    process.exit(1);
  }
}

main();
<commit_msg>Github Actions (validate-build-status) -- clearer output on job failed (#17866)<commit_after>/* eslint-disable no-console */
/* eslint-disable camelcase */
const { Octokit } = require('@octokit/rest');

const { GITHUB_TOKEN: auth, GITHUB_REPOSITORY } = process.env;
const args = process.argv.slice(2);
const timeout = 2; // minutes
const commitSHA = args[0];
const [owner, repo] = GITHUB_REPOSITORY.split('/');

const octokit = new Octokit({ auth });

/**
 * uses octokit request for github action run_id provided
 * @param {number} run_id
 */
function getJobsFailed(run_id) {
  const params = {
    owner,
    repo,
    run_id,
  };
  return octokit.rest.actions
    .listJobsForWorkflowRun(params)
    .then(response => {
      if (response.status !== 200) {
        throw new Error(
          `Response ${response.status} from ${response.url}. Aborting.`,
        );
      }
      return response.data;
    })
    .then(({ jobs }) => {
      jobs.forEach(({ name, html_url, conclusion }) => {
        if (conclusion === 'success') return;
        const isFailure = conclusion === 'failure';
        const annotationMessage = isFailure
          ? `::error::Job "${name}" has failed`
          : `::warning::Job "${name}" has been cancelled`;
        console.log(
          `${annotationMessage}. For more details, please see ${html_url}`,
        );
      });
    });
}

/**
 * uses octokit request for github action to get workflow with matching SHA
 * @param {number} page
 */
function getLatestWorkflow(page) {
  const params = {
    owner,
    repo,
    workflow_id: 'continuous-integration.yml',
    branch: 'master',
    per_page: '50',
    page,
  };
  return octokit.rest.actions
    .listWorkflowRuns(params)
    .then(response => {
      if (response.status !== 200) {
        throw new Error(
          `Response ${response.status} from ${response.url}. Aborting.`,
        );
      }
      return response.data;
    })
    .then(({ workflow_runs }) => {
      if (workflow_runs.length === 0) {
        throw new Error('No workflows found. Aborting.');
      }

      const workflow = workflow_runs.find(
        ({ head_sha }) => head_sha === commitSHA,
      );
      if (workflow) return workflow;
      console.log('Workflow not found in current page. Checking next page.');
      return getLatestWorkflow(page + 1);
    });
}

function sleep(minutes) {
  return new Promise(resolve => setTimeout(resolve, minutes * 60 * 1000));
}

/**
 * Validates the workflow
 * @param {Object} workflow
 * @returns true, false, undefined
 */
function validateWorkflowSuccess(workflow) {
  const { status, conclusion, head_commit, html_url } = workflow;
  console.log(`Validating commit ${head_commit.id}. Workflow: ${html_url}`);

  if (conclusion === 'failure') return false;

  const isWorkflowInProgress =
    status === 'in_progress' || status === null || status === 'queued';

  if (isWorkflowInProgress) return undefined;

  if (conclusion === 'success') {
    console.log('All checks succeeded');
    return true;
  }

  throw new Error(
    `Unexpected workflow result: ${JSON.stringify({ status, conclusion })}`,
  );
}

/**
 * Checks Github Actions url. Loops recursively until error is thrown.
 */
async function main() {
  try {
    const page = 1;
    const workflow = await getLatestWorkflow(page);
    const success = validateWorkflowSuccess(workflow);

    if (success === undefined) {
      console.log(`Check runs still pending. Sleeping for ${timeout} minutes`);
      await sleep(timeout);
      await main();
      return;
    }

    if (!success) {
      await getJobsFailed(workflow.id);
      process.exit(1);
    }
  } catch (e) {
    console.error(e);
    process.exit(1);
  }
}

main();
<|endoftext|>


<commit_before>/**
 * @license
 * Fuse - Lightweight fuzzy-search
 *
 * Copyright (c) 2012-2016 Kirollos Risk <kirollos@gmail.com>.
 * All Rights Reserved. Apache Software License 2.0
 *
 * Licensed 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.
 */
;(function (global) {
  'use strict'

  function log () {
    console.log.apply(console, arguments)
  }

  var defaultOptions = {
    // The name of the identifier property. If specified, the returned result will be a list
    // of the items' dentifiers, otherwise it will be a list of the items.
    id: null,

    // Indicates whether comparisons should be case sensitive.

    caseSensitive: false,

    // An array of values that should be included from the searcher's output. When this array
    // contains elements, each result in the list will be of the form `{ item: ..., include1: ..., include2: ... }`.
    // Values you can include are `score`, `matchedLocations`
    include: [],

    // Whether to sort the result list, by score
    shouldSort: true,

    // The search function to use
    // Note that the default search function ([[Function]]) must conform to the following API:
    //
    //  @param pattern The pattern string to search
    //  @param options The search option
    //  [[Function]].constructor = function(pattern, options)
    //
    //  @param text: the string to search in for the pattern
    //  @return Object in the form of:
    //    - isMatch: boolean
    //    - score: Int
    //  [[Function]].prototype.search = function(text)
    searchFn: BitapSearcher,

    // Default sort function
    sortFn: function (a, b) {
      return a.score - b.score
    },

    // The get function to use when fetching an object's properties.
    // The default will search nested paths *ie foo.bar.baz*
    getFn: deepValue,

    // List of properties that will be searched. This also supports nested properties.
    keys: [],

    // Will print to the console. Useful for debugging.
    verbose: false,

    // When true, the search algorithm will search individual words **and** the full string,
    // computing the final score as a function of both. Note that when `tokenize` is `true`,
    // the `threshold`, `distance`, and `location` are inconsequential for individual tokens.
    tokenize: false,

    // When true, the result set will only include records that match all tokens. Will only work
    // if `tokenize` is also true.
    matchAllTokens: false,

    // Regex used to separate words when searching. Only applicable when `tokenize` is `true`.
    tokenSeparator: / +/g
  }

  function Fuse (list, options) {
    var i
    var len
    var key
    var keys

    this.list = list
    this.options = options = options || {}

    // Add boolean type options
    for (i = 0, keys = ['sort', 'shouldSort', 'verbose', 'tokenize'], len = keys.length; i < len; i++) {
      key = keys[i]
      this.options[key] = key in options ? options[key] : defaultOptions[key]
    }
    // Add all other options
    for (i = 0, keys = ['searchFn', 'sortFn', 'keys', 'getFn', 'include', 'tokenSeparator'], len = keys.length; i < len; i++) {
      key = keys[i]
      this.options[key] = options[key] || defaultOptions[key]
    }
  }

  Fuse.VERSION = '2.5.0'

  /**
   * Sets a new list for Fuse to match against.
   * @param {Array} list
   * @return {Array} The newly set list
   * @public
   */
  Fuse.prototype.set = function (list) {
    this.list = list
    return list
  }

  Fuse.prototype.search = function (pattern) {
    if (this.options.verbose) log('\nSearch term:', pattern, '\n')

    this.pattern = pattern
    this.results = []
    this.resultMap = {}
    this._keyMap = null

    this._prepareSearchers()
    this._startSearch()
    this._computeScore()
    this._sort()

    var output = this._format()
    return output
  }

  Fuse.prototype._prepareSearchers = function () {
    var options = this.options
    var pattern = this.pattern
    var searchFn = options.searchFn
    var tokens = pattern.split(options.tokenSeparator)
    var i = 0
    var len = tokens.length

    if (this.options.tokenize) {
      this.tokenSearchers = []
      for (; i < len; i++) {
        this.tokenSearchers.push(new searchFn(tokens[i], options))
      }
    }
    this.fullSeacher = new searchFn(pattern, options)
  }

  Fuse.prototype._startSearch = function () {
    var options = this.options
    var getFn = options.getFn
    var list = this.list
    var listLen = list.length
    var keys = this.options.keys
    var keysLen = keys.length
    var key
    var weight
    var item = null
    var i
    var j

    // Check the first item in the list, if it's a string, then we assume
    // that every item in the list is also a string, and thus it's a flattened array.
    if (typeof list[0] === 'string') {
      // Iterate over every item
      for (i = 0; i < listLen; i++) {
        this._analyze('', list[i], i, i)
      }
    } else {
      this._keyMap = {}
      // Otherwise, the first item is an Object (hopefully), and thus the searching
      // is done on the values of the keys of each item.
      // Iterate over every item
      for (i = 0; i < listLen; i++) {
        item = list[i]
        // Iterate over every key
        for (j = 0; j < keysLen; j++) {
          key = keys[j]
          if (typeof key !== 'string') {
            weight = (1 - key.weight) || 1
            this._keyMap[key.name] = {
              weight: weight
            }
            if (key.weight <= 0 || key.weight > 1) {
              throw new Error('Key weight has to be > 0 and <= 1')
            }
            key = key.name
          } else {
            this._keyMap[key] = {
              weight: 1
            }
          }
          this._analyze(key, getFn(item, key, []), item, i)
        }
      }
    }
  }

  Fuse.prototype._analyze = function (key, text, entity, index) {
    var options = this.options
    var words
    var scores
    var exists = false
    var existingResult
    var averageScore
    var finalScore
    var scoresLen
    var mainSearchResult
    var tokenSearcher
    var termScores
    var word
    var tokenSearchResult
    var hasMatchInText
    var checkTextMatches
    var i
    var j

    // Check if the text can be searched
    if (text === undefined || text === null) {
      return
    }

    scores = []

    var numTextMatches = 0

    if (typeof text === 'string') {
      words = text.split(options.tokenSeparator)

      if (options.verbose) log('---------\nKey:', key)

      if (this.options.tokenize) {
        for (i = 0; i < this.tokenSearchers.length; i++) {
          tokenSearcher = this.tokenSearchers[i]

          if (options.verbose) log('Pattern:', tokenSearcher.pattern)

          termScores = []
          hasMatchInText = false

          for (j = 0; j < words.length; j++) {
            word = words[j]
            tokenSearchResult = tokenSearcher.search(word)
            var obj = {}
            if (tokenSearchResult.isMatch) {
              obj[word] = tokenSearchResult.score
              exists = true
              hasMatchInText = true
              scores.push(tokenSearchResult.score)
            } else {
              obj[word] = 1
              if (!this.options.matchAllTokens) {
                scores.push(1)
              }
            }
            termScores.push(obj)
          }

          if (hasMatchInText) {
            numTextMatches++
          }

          if (options.verbose) log('Token scores:', termScores)
        }

        averageScore = scores[0]
        scoresLen = scores.length
        for (i = 1; i < scoresLen; i++) {
          averageScore += scores[i]
        }
        averageScore = averageScore / scoresLen

        if (options.verbose) log('Token score average:', averageScore)
      }

      mainSearchResult = this.fullSeacher.search(text)
      if (options.verbose) log('Full text score:', mainSearchResult.score)

      finalScore = mainSearchResult.score
      if (averageScore !== undefined) {
        finalScore = (finalScore + averageScore) / 2
      }

      if (options.verbose) log('Score average:', finalScore)

      checkTextMatches = (this.options.tokenize && this.options.matchAllTokens) ? numTextMatches >= this.tokenSearchers.length : true

      if (options.verbose) log('Check Matches', checkTextMatches)

      // If a match is found, add the item to <rawResults>, including its score
      if ((exists || mainSearchResult.isMatch) && checkTextMatches) {
        // Check if the item already exists in our results
        existingResult = this.resultMap[index]

        if (existingResult) {
          // Use the lowest score
          // existingResult.score, bitapResult.score
          existingResult.output.push({
            key: key,
            score: finalScore,
            matchedIndices: mainSearchResult.matchedIndices
          })
        } else {
          // Add it to the raw result list
          this.resultMap[index] = {
            item: entity,
            output: [{
              key: key,
              score: finalScore,
              matchedIndices: mainSearchResult.matchedIndices
            }]
          }

          this.results.push(this.resultMap[index])
        }
      }
    } else if (isArray(text)) {
      for (i = 0; i < text.length; i++) {
        this._analyze(key, text[i], entity, index)
      }
    }
  }

  Fuse.prototype._computeScore = function () {
    var i
    var j
    var keyMap = this._keyMap
    var totalScore
    var output
    var scoreLen
    var score
    var weight
    var results = this.results
    var bestScore
    var nScore

    if (this.options.verbose) log('\n\nComputing score:\n')

    for (i = 0; i < results.length; i++) {
      totalScore = 0
      output = results[i].output
      scoreLen = output.length

      bestScore = 1

      for (j = 0; j < scoreLen; j++) {
        score = output[j].score
        weight = keyMap ? keyMap[output[j].key].weight : 1

        nScore = score * weight

        if (weight !== 1) {
          bestScore = Math.min(bestScore, nScore)
        } else {
          totalScore += nScore
          output[j].nScore = nScore
        }
      }

      if (bestScore === 1) {
        results[i].score = totalScore / scoreLen
      } else {
        results[i].score = bestScore
      }

      if (this.options.verbose) log(results[i])
    }
  }

  Fuse.prototype._sort = function () {
    var options = this.options
    if (options.shouldSort) {
      if (options.verbose) log('\n\nSorting....')
      this.results.sort(options.sortFn)
    }
  }

  Fuse.prototype._format = function () {
    var options = this.options
    var getFn = options.getFn
    var finalOutput = []
    var item
    var i
    var len
    var results = this.results
    var replaceValue
    var getItemAtIndex
    var include = options.include

    if (options.verbose) log('\n\nOutput:\n\n', results)

    // Helper function, here for speed-up, which replaces the item with its value,
    // if the options specifies it,
    replaceValue = options.id ? function (index) {
      results[index].item = getFn(results[index].item, options.id, [])[0]
    } : function () {}

    getItemAtIndex = function (index) {
      var record = results[index]
      var data
      var j
      var output
      var _item
      var _result

      // If `include` has values, put the item in the result
      if (include.length > 0) {
        data = {
          item: record.item
        }
        if (include.indexOf('matches') !== -1) {
          output = record.output
          data.matches = []
          for (j = 0; j < output.length; j++) {
            _item = output[j]
            _result = {
              indices: _item.matchedIndices
            }
            if (_item.key) {
              _result.key = _item.key
            }
            data.matches.push(_result)
          }
        }

        if (include.indexOf('score') !== -1) {
          data.score = results[index].score
        }

      } else {
        data = record.item
      }

      return data
    }

    // From the results, push into a new array only the item identifier (if specified)
    // of the entire item.  This is because we don't want to return the <results>,
    // since it contains other metadata
    for (i = 0, len = results.length; i < len; i++) {
      replaceValue(i)
      item = getItemAtIndex(i)
      finalOutput.push(item)
    }

    return finalOutput
  }

  // Helpers

  function deepValue (obj, path, list) {
    var firstSegment
    var remaining
    var dotIndex
    var value
    var i
    var len

    if (!path) {
      // If there's no path left, we've gotten to the object we care about.
      list.push(obj)
    } else {
      dotIndex = path.indexOf('.')

      if (dotIndex !== -1) {
        firstSegment = path.slice(0, dotIndex)
        remaining = path.slice(dotIndex + 1)
      } else {
        firstSegment = path
      }

      value = obj[firstSegment]
      if (value !== null && value !== undefined) {
        if (!remaining && (typeof value === 'string' || typeof value === 'number')) {
          list.push(value)
        } else if (isArray(value)) {
          // Search each item in the array.
          for (i = 0, len = value.length; i < len; i++) {
            deepValue(value[i], remaining, list)
          }
        } else if (remaining) {
          // An object. Recurse further.
          deepValue(value, remaining, list)
        }
      }
    }

    return list
  }

  function isArray (obj) {
    return Object.prototype.toString.call(obj) === '[object Array]'
  }

  /**
   * Adapted from "Diff, Match and Patch", by Google
   *
   *   http://code.google.com/p/google-diff-match-patch/
   *
   * Modified by: Kirollos Risk <kirollos@gmail.com>
   * -----------------------------------------------
   * Details: the algorithm and structure was modified to allow the creation of
   * <Searcher> instances with a <search> method which does the actual
   * bitap search. The <pattern> (the string that is searched for) is only defined
   * once per instance and thus it eliminates redundant re-creation when searching
   * over a list of strings.
   *
   * Licensed under the Apache License, Version 2.0 (the "License")
   * you may not use this file except in compliance with the License.
   */
  function BitapSearcher (pattern, options) {
    options = options || {}
    this.options = options
    this.options.location = options.location || BitapSearcher.defaultOptions.location
    this.options.distance = 'distance' in options ? options.distance : BitapSearcher.defaultOptions.distance
    this.options.threshold = 'threshold' in options ? options.threshold : BitapSearcher.defaultOptions.threshold
    this.options.maxPatternLength = options.maxPatternLength || BitapSearcher.defaultOptions.maxPatternLength

    this.pattern = options.caseSensitive ? pattern : pattern.toLowerCase()
    this.patternLen = pattern.length

    if (this.patternLen <= this.options.maxPatternLength) {
      this.matchmask = 1 << (this.patternLen - 1)
      this.patternAlphabet = this._calculatePatternAlphabet()
    }
  }

  BitapSearcher.defaultOptions = {
    // Approximately where in the text is the pattern expected to be found?
    location: 0,

    // Determines how close the match must be to the fuzzy location (specified above).
    // An exact letter match which is 'distance' characters away from the fuzzy location
    // would score as a complete mismatch. A distance of '0' requires the match be at
    // the exact location specified, a threshold of '1000' would require a perfect match
    // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.
    distance: 100,

    // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match
    // (of both letters and location), a threshold of '1.0' would match anything.
    threshold: 0.6,

    // Machine word size
    maxPatternLength: 32
  }

  /**
   * Initialize the alphabet for the Bitap algorithm.
   * @return {Object} Hash of character locations.
   * @private
   */
  BitapSearcher.prototype._calculatePatternAlphabet = function () {
    var mask = {},
      i = 0

    for (i = 0; i < this.patternLen; i++) {
      mask[this.pattern.charAt(i)] = 0
    }

    for (i = 0; i < this.patternLen; i++) {
      mask[this.pattern.charAt(i)] |= 1 << (this.pattern.length - i - 1)
    }

    return mask
  }

  /**
   * Compute and return the score for a match with `e` errors and `x` location.
   * @param {number} errors Number of errors in match.
   * @param {number} location Location of match.
   * @return {number} Overall score for match (0.0 = good, 1.0 = bad).
   * @private
   */
  BitapSearcher.prototype._bitapScore = function (errors, location) {
    var accuracy = errors / this.patternLen,
      proximity = Math.abs(this.options.location - location)

    if (!this.options.distance) {
      // Dodge divide by zero error.
      return proximity ? 1.0 : accuracy
    }
    return accuracy + (proximity / this.options.distance)
  }

  /**
   * Compute and return the result of the search
   * @param {String} text The text to search in
   * @return {Object} Literal containing:
   *                          {Boolean} isMatch Whether the text is a match or not
   *                          {Decimal} score Overall score for the match
   * @public
   */
  BitapSearcher.prototype.search = function (text) {
    var options = this.options
    var i
    var j
    var textLen
    var location
    var threshold
    var bestLoc
    var binMin
    var binMid
    var binMax
    var start, finish
    var bitArr
    var lastBitArr
    var charMatch
    var score
    var locations
    var matches
    var isMatched
    var matchMask
    var matchedIndices
    var matchesLen
    var match

    text = options.caseSensitive ? text : text.toLowerCase()

    if (this.pattern === text) {
      // Exact match
      return {
        isMatch: true,
        score: 0,
        matchedIndices: [[0, text.length - 1]]
      }
    }

    // When pattern length is greater than the machine word length, just do a a regex comparison
    if (this.patternLen > options.maxPatternLength) {
      matches = text.match(new RegExp(this.pattern.replace(options.tokenSeparator, '|')))
      isMatched = !!matches

      if (isMatched) {
        matchedIndices = []
        for (i = 0, matchesLen = matches.length; i < matchesLen; i++) {
          match = matches[i]
          matchedIndices.push([text.indexOf(match), match.length - 1])
        }
      }

      return {
        isMatch: isMatched,
        // TODO: revisit this score
        score: isMatched ? 0.5 : 1,
        matchedIndices: matchedIndices
      }
    }

    location = options.location
    // Set starting location at beginning text and initialize the alphabet.
    textLen = text.length
    // Highest score beyond which we give up.
    threshold = options.threshold
    // Is there a nearby exact match? (speedup)
    bestLoc = text.indexOf(this.pattern, location)

    // a mask of the matches
    matchMask = []
    for (i = 0; i < textLen; i++) {
      matchMask[i] = 0
    }

    if (bestLoc != -1) {
      threshold = Math.min(this._bitapScore(0, bestLoc), threshold)
      // What about in the other direction? (speed up)
      bestLoc = text.lastIndexOf(this.pattern, location + this.patternLen)

      if (bestLoc != -1) {
        threshold = Math.min(this._bitapScore(0, bestLoc), threshold)
      }
    }

    bestLoc = -1
    score = 1
    locations = []
    binMax = this.patternLen + textLen

    for (i = 0; i < this.patternLen; i++) {
      // Scan for the best match; each iteration allows for one more error.
      // Run a binary search to determine how far from the match location we can stray
      // at this error level.
      binMin = 0
      binMid = binMax
      while (binMin < binMid) {
        if (this._bitapScore(i, location + binMid) <= threshold) {
          binMin = binMid
        } else {
          binMax = binMid
        }
        binMid = Math.floor((binMax - binMin) / 2 + binMin)
      }

      // Use the result from this iteration as the maximum for the next.
      binMax = binMid
      start = Math.max(1, location - binMid + 1)
      finish = Math.min(location + binMid, textLen) + this.patternLen

      // Initialize the bit array
      bitArr = Array(finish + 2)

      bitArr[finish + 1] = (1 << i) - 1

      for (j = finish; j >= start; j--) {
        charMatch = this.patternAlphabet[text.charAt(j - 1)]

        if (charMatch) {
          matchMask[j - 1] = 1
        }

        if (i === 0) {
          // First pass: exact match.
          bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch
        } else {
          // Subsequent passes: fuzzy match.
          bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch | (((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1) | lastBitArr[j + 1]
        }
        if (bitArr[j] & this.matchmask) {
          score = this._bitapScore(i, j - 1)

          // This match will almost certainly be better than any existing match.
          // But check anyway.
          if (score <= threshold) {
            // Indeed it is
            threshold = score
            bestLoc = j - 1
            locations.push(bestLoc)

            if (bestLoc > location) {
              // When passing loc, don't exceed our current distance from loc.
              start = Math.max(1, 2 * location - bestLoc)
            } else {
              // Already passed loc, downhill from here on in.
              break
            }
          }
        }
      }

      // No hope for a (better) match at greater error levels.
      if (this._bitapScore(i + 1, location) > threshold) {
        break
      }
      lastBitArr = bitArr
    }

    matchedIndices = this._getMatchedIndices(matchMask)

    // Count exact matches (those with a score of 0) to be "almost" exact
    return {
      isMatch: bestLoc >= 0,
      score: score === 0 ? 0.001 : score,
      matchedIndices: matchedIndices
    }
  }

  BitapSearcher.prototype._getMatchedIndices = function (matchMask) {
    var matchedIndices = []
    var start = -1
    var end = -1
    var i = 0
    var match
    var len = matchMask.length
    for (; i < len; i++) {
      match = matchMask[i]
      if (match && start === -1) {
        start = i
      } else if (!match && start !== -1) {
        end = i - 1
        matchedIndices.push([start, end])
        start = -1
      }
    }
    if (matchMask[i - 1]) {
      matchedIndices.push([start, i - 1])
    }
    return matchedIndices
  }

  // Export to Common JS Loader
  if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = Fuse
  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(function () {
      return Fuse
    })
  } else {
    // Browser globals (root is window)
    global.Fuse = Fuse
  }

})(this);
<commit_msg>Removed fuzzy search library<commit_after><|endoftext|>


<commit_before>var Sequelize = require('Sequelize');
var sequelize = new Sequelize("mssql://szy0syz0yngf2017:xQnWdw3u4BOgwTuU@192.168.97.199:1433/YNNZ2011001");
//var sequelize = new Sequelize("mssql://szy0syz0yngf2017:xQnWdw3u4BOgwTuU@192.168.97.199:1433/YNNZ2011001_20160912");
var SaleIssueEntry = sequelize.import('./models/SaleIssueEntry');

var sqlCommand = require('./db/sqlCommand');
var sqlConditions = require('./db/sqlConditions');

//{ type: sequelize.QueryTypes.SELECT} 只返回Sequelize查询到结果，不返回数据库的元数据。
var query = sequelize.query(sqlCommand, {
    type: sequelize.QueryTypes.SELECT,
    model: SaleIssueEntry
    ,replacements: sqlConditions
});

query.then(function(res) {
  var rept = {
    sumQty: 0,
    sumAmount: 0,

    sumNQty: 0,
    sumNAmount: 0,

    sumUreaQty: 0,
    sumUreaAmount: 0,

    sumPQty: 0,
    sumPAmount: 0,

    sumKQty: 0,
    sumKAmount: 0,

    sumNPKQty: 0,
    sumNPKAmount: 0,

    sumNPKhQty: 0,
    sumNPKhAmount: 0

  }

  var brandFString = ['尿素','碳铵','硫铵','氯化铵','硝磷铵','普钙','重钙','钙镁','磷铵','富钙','硫酸钾','氯化钾','硫酸钾肥','高含量','低含量']
  var brandF = [];

  brandFString.forEach(function(s,i) {
    var o = {
      name: s,
      sumQty: 0,
      sumAmount: 0
    };
    brandF.push(o);
  })

  console.log(brandF);

  var arrUrea = arrN = arrP = arrK = arrNPK = arrNPKh = [],
    itemType = '';

  console.log('rows: '+res.length);
  res.forEach(function(item, index) {
    rept.sumQty +=  item.FBaseQty;
    rept.sumAmount +=  item.FAmount;
    itemType = item.FMaterialType0.split('_');
    if(itemType[1] == '氮肥') {
      arrN.push(item);
      rept.sumNAmount += item.FAmount;
      rept.sumNQty += item.FBaseQty;
    }
    if(itemType[2] == '尿素') {
      arrUrea.push(item);
      rept.sumUreaAmount += item.FAmount;
      rept.sumUreaQty += item.FBaseQty;
    }
    if(itemType[1] == '磷肥') {
      arrP.push(item);
      rept.sumPAmount += item.FAmount;
      rept.sumPQty += item.FBaseQty;
    }
    if(itemType[1] == '钾肥') {
      arrP.push(item);
      rept.sumKAmount += item.FAmount;
      rept.sumKQty += item.FBaseQty;
    }
    if(itemType[1] == '复合肥') {
      arrNPK.push(item);
      rept.sumNPKAmount += item.FAmount;
      rept.sumNPKQty += item.FBaseQty;
    }
    if(item.FBrandFertilizer == '高含量') {
      arrNPKh.push(item);
      rept.sumNPKhQty += item.FBaseQty;
      rept.sumNPKhAmount += item.FAmount;
    }
  });

  console.log(rept)
});

// // ---no~~~
// function getData() {
//   var data;
//   return query.then(function(result) {
//     data = result;
//   }).return(data);
// }

//     .then(function(rows) {
//         console.log(Object.prototype.toString.call(rows[0])); //array
//         console.log(rows.length);
//     })<commit_msg>修改算法2-初步成功<commit_after>var Sequelize = require('Sequelize');
var sequelize = new Sequelize("mssql://szy0syz0yngf2017:xQnWdw3u4BOgwTuU@192.168.97.199:1433/YNNZ2011001");
//var sequelize = new Sequelize("mssql://szy0syz0yngf2017:xQnWdw3u4BOgwTuU@192.168.97.199:1433/YNNZ2011001_20160912");
var SaleIssueEntry = sequelize.import('./models/SaleIssueEntry');

var sqlCommand = require('./db/sqlCommand');
var sqlConditions = require('./db/sqlConditions');

//{ type: sequelize.QueryTypes.SELECT} 只返回Sequelize查询到结果，不返回数据库的元数据。
var query = sequelize.query(sqlCommand, {
    type: sequelize.QueryTypes.SELECT,
    model: SaleIssueEntry
    ,replacements: sqlConditions
});

query.then(function(res) {
  var rept = {
    sumQty: 0,
    sumAmount: 0,

    sumNQty: 0,
    sumNAmount: 0,

    sumUreaQty: 0,
    sumUreaAmount: 0,

    sumPQty: 0,
    sumPAmount: 0,

    sumKQty: 0,
    sumKAmount: 0,

    sumNPKQty: 0,
    sumNPKAmount: 0,

    sumNPKhQty: 0,
    sumNPKhAmount: 0

  }

  //以后这里从数据库取，不要写死！
  var brandFString = ['尿素','碳铵','硫铵','氯化铵','硝磷铵','普钙','重钙','钙镁','磷铵','富钙','硫酸钾','氯化钾','硫酸钾肥','高含量','低含量']
  var brandF = [];

  brandFString.forEach(function(s,i) {
    var o = {
      name: s,
      sumQty: 0,
      sumAmount: 0
    };
    brandF.push(o);
  })

  //console.log(brandF);

  var arrUrea = arrN = arrP = arrK = arrNPK = arrNPKh = [],
    itemType = '';

  console.log('rows: '+res.length);

  res.forEach(function(item, index) {
    brandF.forEach(function(brand,i) {
      if(item.FBrandFertilizer == brand.name) {
        brand.sumQty += item.FBaseQty;
        brand.sumAmount += item.FAmount;
      }
    });
  });

  res.forEach(function(item, index) {
    rept.sumQty +=  item.FBaseQty;
    rept.sumAmount +=  item.FAmount;
    itemType = item.FMaterialType0.split('_');
    if(itemType[1] == '氮肥') {
      arrN.push(item);
      rept.sumNAmount += item.FAmount;
      rept.sumNQty += item.FBaseQty;
    }
    if(itemType[2] == '尿素') {
      arrUrea.push(item);
      rept.sumUreaAmount += item.FAmount;
      rept.sumUreaQty += item.FBaseQty;
    }
    if(itemType[1] == '磷肥') {
      arrP.push(item);
      rept.sumPAmount += item.FAmount;
      rept.sumPQty += item.FBaseQty;
    }
    if(itemType[1] == '钾肥') {
      arrP.push(item);
      rept.sumKAmount += item.FAmount;
      rept.sumKQty += item.FBaseQty;
    }
    if(itemType[1] == '复合肥') {
      arrNPK.push(item);
      rept.sumNPKAmount += item.FAmount;
      rept.sumNPKQty += item.FBaseQty;
    }
    if(item.FBrandFertilizer == '高含量') {
      arrNPKh.push(item);
      rept.sumNPKhQty += item.FBaseQty;
      rept.sumNPKhAmount += item.FAmount;
    }
  });

  console.log(rept)
});

// // ---no~~~
// function getData() {
//   var data;
//   return query.then(function(result) {
//     data = result;
//   }).return(data);
// }

//     .then(function(rows) {
//         console.log(Object.prototype.toString.call(rows[0])); //array
//         console.log(rows.length);
//     })<|endoftext|>