<commit_before>/**
 * Copyright 2016 - 2021 SigScale Global Inc.
 * 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.
 */

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/iron-ajax/iron-ajax.js';
import '@polymer/paper-dialog/paper-dialog.js';
import '@polymer/app-layout/app-toolbar/app-toolbar.js';
import '@polymer/paper-progress/paper-progress.js';
import '@polymer/paper-input/paper-input.js';
import '@polymer/paper-button/paper-button.js';
import '@polymer/paper-tooltip/paper-tooltip.js';
import './style-element.js';

class prefixAdd extends PolymerElement {
	static get template() {
		return html`

			<paper-dialog class="dialog" id="addPrefixModal" modal>
				<app-toolbar>

Add Prefix

				</app-toolbar>
				<paper-progress
						id="progressId"
						indeterminate
						class="slow red"
						disabled="{{!loading}}">
				</paper-progress>

						<paper-input
								allowed-pattern="[0-9+]"
								label="Prefix"
								value="{{addPre}}">
						</paper-input>
						<paper-tooltip>
							Leading digits to match against an origination, destination or VPLMN address.
						</paper-tooltip>

						<paper-input
								label="Description"
								value="{{addPreDesc}}">
						</paper-input>
						<paper-tooltip>
							Description of addresses matching this prefix.
						</paper-tooltip>

						<paper-input
								type="number"
								label="Rate"
								value="{{addPreRate}}">
						</paper-input>
						<paper-tooltip>
							Price per unit to apply when this prefix matches an address.
						</paper-tooltip>

					<paper-button dialog-confirm
							raised
							on-tap="_tableRow"
							class="submit-button">
						Submit
					</paper-button>
					<paper-button
							class="cancel-button"
							on-tap="_cancel"
							dialog-dismiss>
						Cancel
					</paper-button>

			</paper-dialog>
			<iron-ajax
					id="addTableRow"
					content-type="application/json"
					on-loading-changed="_onLoadingChanged"
					on-response="_addTableResponse"
					on-error="_addTableError">
			</iron-ajax>
		`;
	}
	static get properties() {
		return {
			loading: {
				type: Boolean,
				value: false
			},
			addPre: {
				type: String,
			},
			addPreDesc: {
				type: String,
			},
			addPreRate: {
				type: String,
			}
		}
	}

	ready() {
		super.ready()
	}

	_tableRow(event) {
		var prefixList = document.body.querySelector('sig-app').shadowRoot.getElementById('prefixList');
		var ajax = this.$.addTableRow;
		ajax.method = "POST";
		ajax.url = "/resourceInventoryManagement/v1/resource/";
		var tar = new Object();
		var rel = new Array();
		var relObj = new Object();
		relObj.id = prefixList.activeTableId;
		relObj.href = "/resourceInventoryManagement/v1/resourceRelationship/" + relObj.id;
		relObj.name = prefixList.activeTableName;
      var relObj1 = new Object();
      relObj1.relationshipType = "contained";
      relObj1.resource = relObj
		rel.push(relObj1);
		tar.resourceRelationship = rel

		var resource = new Array();
		var resPre = new Object();
		resPre.name = "prefix";
		resPre.value = this.addPre;
		resource.push(resPre);
		var resDes = new Object();
		resDes.name = "description";
		resDes.value = this.addPreDesc;
		resource.push(resDes);
		var resRate = new Object();
		resRate.name = "rate";
		resRate.value = parseInt(this.addPreRate);
		resource.push(resRate);
		tar.resourceCharacteristic = resource;

		var spec = new Object();
		spec.id = "2";
		spec.name = "TariffTableRow";
		spec.href = "resourceCatalogManagement/v2/resourceSpecification/" + "2";
		tar.resourceSpecification = spec;
		ajax.body = tar;
		ajax.generateRequest();
		this.$.addPrefixModal.close();
		document.body.querySelector('sig-app').shadowRoot.getElementById('prefixList').shadowRoot.getElementById('prefixGrid').clearCache();
	}

	_addTableResponse(event) {
		this.$.addPrefixModal.close();
		document.body.querySelector('sig-app').shadowRoot.getElementById('prefixList').shadowRoot.getElementById('prefixGrid').clearCache();
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = "Success";
		toast.open();
	}

	_addTableError(event) {
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = "Error";
		toast.open();
	}

	_cancel() {
		this.addPre = null;
		this.addDesc = null;
		this.addRateRow = null;
	}

	_onLoadingChanged(event) {
		if (this.$.addTableRow.loading) {
			this.$.progressId.disabled = false;
		} else {
			this.$.progressId.disabled = true;
		}
	}
}

window.customElements.define('sig-prefix-add', prefixAdd);
<commit_msg>fix pattern for tarrif prefix table<commit_after>/**
 * Copyright 2016 - 2021 SigScale Global Inc.
 * 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.
 */

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/iron-ajax/iron-ajax.js';
import '@polymer/paper-dialog/paper-dialog.js';
import '@polymer/app-layout/app-toolbar/app-toolbar.js';
import '@polymer/paper-progress/paper-progress.js';
import '@polymer/paper-input/paper-input.js';
import '@polymer/paper-button/paper-button.js';
import '@polymer/paper-tooltip/paper-tooltip.js';
import './style-element.js';

class prefixAdd extends PolymerElement {
	static get template() {
		return html`

			<paper-dialog class="dialog" id="addPrefixModal" modal>
				<app-toolbar>

Add Prefix

				</app-toolbar>
				<paper-progress
						id="progressId"
						indeterminate
						class="slow red"
						disabled="{{!loading}}">
				</paper-progress>

						<paper-input
								allowed-pattern="[+0-9]"
								pattern="^[+]?[0-9]+"
                        auto-validate
								label="Prefix"
								value="{{addPre}}">
						</paper-input>
						<paper-tooltip>
							Leading digits to match against an origination, destination or VPLMN address.
						</paper-tooltip>

						<paper-input
								label="Description"
								value="{{addPreDesc}}">
						</paper-input>
						<paper-tooltip>
							Description of addresses matching this prefix.
						</paper-tooltip>

						<paper-input
								type="number"
								label="Rate"
								value="{{addPreRate}}">
						</paper-input>
						<paper-tooltip>
							Price per unit to apply when this prefix matches an address.
						</paper-tooltip>

					<paper-button dialog-confirm
							raised
							on-tap="_tableRow"
							class="submit-button">
						Submit
					</paper-button>
					<paper-button
							class="cancel-button"
							on-tap="_cancel"
							dialog-dismiss>
						Cancel
					</paper-button>

			</paper-dialog>
			<iron-ajax
					id="addTableRow"
					content-type="application/json"
					on-loading-changed="_onLoadingChanged"
					on-response="_addTableResponse"
					on-error="_addTableError">
			</iron-ajax>
		`;
	}
	static get properties() {
		return {
			loading: {
				type: Boolean,
				value: false
			},
			addPre: {
				type: String,
			},
			addPreDesc: {
				type: String,
			},
			addPreRate: {
				type: String,
			}
		}
	}

	ready() {
		super.ready()
	}

	_tableRow(event) {
		var prefixList = document.body.querySelector('sig-app').shadowRoot.getElementById('prefixList');
		var ajax = this.$.addTableRow;
		ajax.method = "POST";
		ajax.url = "/resourceInventoryManagement/v1/resource/";
		var tar = new Object();
		var rel = new Array();
		var relObj = new Object();
		relObj.id = prefixList.activeTableId;
		relObj.href = "/resourceInventoryManagement/v1/resourceRelationship/" + relObj.id;
		relObj.name = prefixList.activeTableName;
      var relObj1 = new Object();
      relObj1.relationshipType = "contained";
      relObj1.resource = relObj
		rel.push(relObj1);
		tar.resourceRelationship = rel

		var resource = new Array();
		var resPre = new Object();
		resPre.name = "prefix";
		resPre.value = this.addPre;
		resource.push(resPre);
		var resDes = new Object();
		resDes.name = "description";
		resDes.value = this.addPreDesc;
		resource.push(resDes);
		var resRate = new Object();
		resRate.name = "rate";
		resRate.value = parseInt(this.addPreRate);
		resource.push(resRate);
		tar.resourceCharacteristic = resource;

		var spec = new Object();
		spec.id = "2";
		spec.name = "TariffTableRow";
		spec.href = "resourceCatalogManagement/v2/resourceSpecification/" + "2";
		tar.resourceSpecification = spec;
		ajax.body = tar;
		ajax.generateRequest();
		this.$.addPrefixModal.close();
		document.body.querySelector('sig-app').shadowRoot.getElementById('prefixList').shadowRoot.getElementById('prefixGrid').clearCache();
	}

	_addTableResponse(event) {
		this.$.addPrefixModal.close();
		document.body.querySelector('sig-app').shadowRoot.getElementById('prefixList').shadowRoot.getElementById('prefixGrid').clearCache();
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = "Success";
		toast.open();
	}

	_addTableError(event) {
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = "Error";
		toast.open();
	}

	_cancel() {
		this.addPre = null;
		this.addDesc = null;
		this.addRateRow = null;
	}

	_onLoadingChanged(event) {
		if (this.$.addTableRow.loading) {
			this.$.progressId.disabled = false;
		} else {
			this.$.progressId.disabled = true;
		}
	}
}

window.customElements.define('sig-prefix-add', prefixAdd);
<|endoftext|>


<commit_before>module.exports = {
    asyncMiddleware,
    checkLicenceMiddleWare
};

function asyncMiddleware(fn) {
    return (req, res, next) => {
        Promise
            .resolve(fn(req, res, next))
            .catch(next);
    };
}

function checkLicenceMiddleWare(licenceService) {
    return async(req, res, next) => {
        try {
            const nomisId = req.params.nomisId;
            const licence = await licenceService.getLicence(nomisId);
            if(!licence) {
                res.redirect('/');
            }
            res.locals.licence = licence;
            next();
        } catch(error) {
            // TODO proper error handling
            console.error('Error collecting licence from checkLicence');
            res.redirect('/');
        }
    };
}
<commit_msg>returned redirect from check licence middleware to avoid sending headers twice<commit_after>module.exports = {
    asyncMiddleware,
    checkLicenceMiddleWare
};

function asyncMiddleware(fn) {
    return (req, res, next) => {
        Promise
            .resolve(fn(req, res, next))
            .catch(next);
    };
}

function checkLicenceMiddleWare(licenceService) {
    return async(req, res, next) => {
        try {
            const nomisId = req.params.nomisId;
            const licence = await licenceService.getLicence(nomisId);
            if(!licence) {
                return res.redirect('/');
            }
            res.locals.licence = licence;
            next();
        } catch(error) {
            // TODO proper error handling
            console.error('Error collecting licence from checkLicence');
            res.redirect('/');
        }
    };
}
<|endoftext|>


<commit_before>angular.module('pdb.habits2')
//.controller('ChartComponentController', ['$scope', 'habitsAPI', 'userAPI',
//	function($scope, habitsAPI, userAPI) {
.controller('ChartComponentController', ['habitsAPI', 'userAPI',
	function(habitsAPI, userAPI) {
		var _this = this;
		this.habitTimeframe = 30;//days prior to today
		this.filter = 'daily';//daily or moving2WeekAverage
		this.habitsLineChart = null;

		this.update = function(){
			var startDate = '0000-00-00';//default startDate ("all time")
			var recentHabitLogs = null;
			if(_this.habitTimeframe){
				startDate = habitsAPI.daysAgoToDate(_this.habitTimeframe);
			}

			var combinedData = {
				labels: [],
				data: []
			};
			if(_this.filter === 'moving2WeekAverage'){
				combinedData = getMoving2WeekAverageData(startDate);
			}else{
				combinedData = getDailyData(startDate);
			}

			//get habit logs then update chart
			habitsAPI.getHabitLogs(startDate).then(
				function(response){
					if(response
					&& response.data
					&& response.data['responseCode'] == 'success'){
						recentHabitLogs = response.data['habitLogs'];
					}//else display some error message?
					var labels = [];
					var data = [];
					var count = 0;
					for(var key in recentHabitLogs){
						labels[count] = recentHabitLogs[key]['logDate'];
						data[count] = recentHabitLogs[key]['score'];
						count++;
					}
					updateChart(labels, data);

				}
			);
		};

		this.test1 = function test1(){
			//var start = moment("2016-01-04","YYYY-MM-DD");
			//var end = moment("2016-01-11","YYYY-MM-DD");

			getMoving2WeekAverageData(_this.habitTimeframe);
		};

	//======== private functions ============
		function updateChart(labels, data){
			console.log('updating chart component');
			var ctx = document.getElementById("habitsLineChart");
			//destroy old chart instance, if exist
			if(_this.habitsLineChart){
				_this.habitsLineChart.destroy();
			}
			_this.habitsLineChart = new Chart(ctx, {
				type: 'line',
				data: {
					labels: labels,
					datasets: [{
						label: 'Habit Score',
						data: data
					}]
				},
				options:{
					legend:{display: false},
					scales:{
						yAxes:[{ticks:{beginAtZero:true}}],
						xAxes:[{
							ticks:{
								autoSkip: false, //let the callback do label skipping
								maxRotation: 45,
								//called on tick, return value is set as label
								callback: function(tickValue, index, ticks) {
									//if there are more than 8 labels, only show every 4th
									if(ticks.length > 8){
										if((index % 4) === 1
										|| index === 1){
											return tickValue;
										}else{
											return '';
										}
									}else{
										return tickValue;
									}
								}
							}
						}]
					}
				}
			});
		};

		function getMoving2WeekAverageData(startDate){
			var combinedData = {
				labels: [],
				data: []
			};
			//use startDate to get labels starting from startDate - 14days
			var adjustedStartDate = moment(startDate,"YYYY-MM-DD").subtract(14, 'days');

			//get habit logs
			habitsAPI.getHabitLogs(adjustedStartDate.format('YYYY-MM-DD')).then(
				function(response){
					if(response
					&& response.data
					&& response.data['responseCode'] == 'success'){
						recentHabitLogs = response.data['habitLogs'];
					}//else display some error message?
					var logs = [];//assoc. array [logDate => score]
					for(var key in recentHabitLogs){
						logs[recentHabitLogs[key]['logDate']] = recentHabitLogs[key]['score'];
					}
					//DEBUG
					console.log('logs: ' + PDB.utils.stringifySafe(logs));

					var averageScores = [];//assoc. array [date => 2weekAvgScore]

					//calculate first 2-week average

					//calculate sum of first two weeks
					var sum = 0;
					var date = moment(adjustedStartDate);//d will be iterated
					while(date.diff(startDate,'days') >= 1){
						if(logs[date.format('YYYY-MM-DD')]){
							sum +=logs[date.format('YYYY-MM-DD')];
						}
						date.add(1, 'days');
					}
					console.log('sum of first 14 days of logs: ' + sum);

					//calculate 2wk average for each day between startDate and now
					var avgPeriodStartDate = moment(adjustedStartDate);
					var date = moment(startDate);
					while(date.diff(startDate,'days') >= 1){
						averageScores[d.format('YYYY-MM-DD')] = sum/14;
						//DEBUG
						console.log('average score for '
							+ date.format('YYYY-MM-DD')
							+ ': ' + sum/14);
						//iterate sum
							//subtract first score from sum
							sum -= logs(avgPeriodStartDate.format('YYYY-MM-DD'));
							//add score of date that was just averaged
							if(logs[d.format('YYYY-MM-DD')]){
								sum += logs[date.format('YYYY-MM-DD')];
							}
						//iterate dates
							avgPeriodStartDate.add(1, 'days');
							date.add(1, 'days');
					}
					//DEBUG
					console.log('averageScores[]: '
						+ PDB.utils.stringifySafe(averageScores));
				}
			);
		};
		function getDailyData(startDate){

		};

		function setHabitTimeframe(daysAgo){
			habitTimeframe = parseInt(daysAgo);
			console.log('new habit timeframe: ' + habitTimeframe);
		};

		function setFilter(f){
			filter = f;
		};

	//====== init =======
		this.update();

	}
])
.directive('chartComponent', function(){
	return{
		scope: {},
		bindToController: {

		},
		controller: 'ChartComponentController',
		controllerAs: 'ctrl',
		templateUrl: 'habits2/habits-linechart-component.html'
	};
});
<commit_msg>avg score chart contd<commit_after>angular.module('pdb.habits2')
//.controller('ChartComponentController', ['$scope', 'habitsAPI', 'userAPI',
//	function($scope, habitsAPI, userAPI) {
.controller('ChartComponentController', ['habitsAPI', 'userAPI',
	function(habitsAPI, userAPI) {
		var _this = this;
		this.habitTimeframe = 30;//days prior to today
		this.filter = 'daily';//daily or moving2WeekAverage
		this.habitsLineChart = null;

		this.update = function(){
			var startDate = '0000-00-00';//default startDate ("all time")
			var recentHabitLogs = null;
			if(_this.habitTimeframe){
				startDate = habitsAPI.daysAgoToDate(_this.habitTimeframe);
			}

			var combinedData = {
				labels: [],
				data: []
			};
			if(_this.filter === 'moving2WeekAverage'){
				combinedData = getMoving2WeekAverageData(startDate);
			}else{
				combinedData = getDailyData(startDate);
			}

			//get habit logs then update chart
			habitsAPI.getHabitLogs(startDate).then(
				function(response){
					if(response
					&& response.data
					&& response.data['responseCode'] == 'success'){
						recentHabitLogs = response.data['habitLogs'];
					}//else display some error message?
					var labels = [];
					var data = [];
					var count = 0;
					for(var key in recentHabitLogs){
						labels[count] = recentHabitLogs[key]['logDate'];
						data[count] = recentHabitLogs[key]['score'];
						count++;
					}
					updateChart(labels, data);
				}
			);
		};

		this.test1 = function test1(){
			//var start = moment("2016-01-04","YYYY-MM-DD");
			//var end = moment("2016-01-11","YYYY-MM-DD");

			getMoving2WeekAverageData(habitsAPI.daysAgoToDate(_this.habitTimeframe));
		};

	//======== private functions ============
		function updateChart(labels, data){
			console.log('updating chart component');
			var ctx = document.getElementById("habitsLineChart");
			//destroy old chart instance, if exist
			if(_this.habitsLineChart){
				_this.habitsLineChart.destroy();
			}
			_this.habitsLineChart = new Chart(ctx, {
				type: 'line',
				data: {
					labels: labels,
					datasets: [{
						label: 'Habit Score',
						data: data
					}]
				},
				options:{
					legend:{display: false},
					scales:{
						yAxes:[{ticks:{beginAtZero:true}}],
						xAxes:[{
							ticks:{
								autoSkip: false, //let the callback do label skipping
								maxRotation: 45,
								//called on tick, return value is set as label
								callback: function(tickValue, index, ticks) {
									//if there are more than 8 labels, only show every 4th
									if(ticks.length > 8){
										if((index % 4) === 1
										|| index === 1){
											return tickValue;
										}else{
											return '';
										}
									}else{
										return tickValue;
									}
								}
							}
						}]
					}
				}
			});
		};

		function getMoving2WeekAverageData(startDate){
			var combinedData = {
				labels: [],
				data: []
			};
			var endDate = moment();

			//use startDate to get labels starting from startDate - 14days
			var adjustedStartDate = moment(startDate,"YYYY-MM-DD").subtract(14, 'days');

			//get habit logs
			habitsAPI.getHabitLogs(adjustedStartDate.format('YYYY-MM-DD')).then(
				function(response){
					if(response
					&& response.data
					&& response.data['responseCode'] == 'success'){
						recentHabitLogs = response.data['habitLogs'];
					}//else display some error message?

					//DEBUG
					//console.log('response: ' + PDB.utils.stringifySafe(response));

					//DEBUG
					//console.log('recentHabitLogs: ' + PDB.utils.stringifySafe(recentHabitLogs));

					var logs = [];//assoc. array [logDate => score]
					for(var key in recentHabitLogs){
						logs[recentHabitLogs[key]['logDate']] = recentHabitLogs[key]['score'];
					}

					//DEBUG
					/*
					for(var key in logs){
						console.log('logs[' + key + ']: ' + logs[key]);
					}
					*/

					var averageScores = [];//assoc. array [date => 2weekAvgScore]

					//calculate first 2-week average

					//calculate sum of first two weeks
					var sum = 0;
					var date = moment(adjustedStartDate);//date to be iterated during loops

					//DEBUG
					//console.log('sum loop start date: ' + PDB.utils.stringifySafe(date)
					//	+ ', diff in days from ' + PDB.utils.stringifySafe(startDate)
					//	+ ': ' + date.diff(startDate,'days'));

					//continue to sum scores up to startDate (exclusive)
					//diff should start at -14
					while(date.diff(startDate,'days') <= -1){
						if(logs[date.format('YYYY-MM-DD')]){
							sum += parseFloat(logs[date.format('YYYY-MM-DD')]);
						}
						date.add(1, 'days');
					}
					console.log('sum of first 14 days of logs: ' + sum);

					//calculate 2wk average for each day between startDate and endDate (inclusive)
					var avgPeriodStartDate = moment(adjustedStartDate);
					date = moment(startDate);

					//DEBUG
					console.log('average scores between ' + date.format('YYYY-MM-DD')
					+ ' and ' + endDate.format('YYYY-MM-DD'));

					//TODO: why does setting it to <= 0 add two days?
					while(date.diff(endDate,'days') <= -1){
						averageScores[date.format('YYYY-MM-DD')] = sum/14;
						//DEBUG
						console.log('average score for '
							+ date.format('YYYY-MM-DD')
							+ ': ' + sum/14);
						//subtract first score from sum
						sum -= parseFloat(logs[avgPeriodStartDate.format('YYYY-MM-DD')]);
						//add score of date that was just averaged
						if(logs[date.format('YYYY-MM-DD')]){
							sum += parseFloat(logs[date.format('YYYY-MM-DD')]);
						}
						//iterate dates
						avgPeriodStartDate.add(1, 'days');
						date.add(1, 'days');
					}

					//DEBUG
					//for(var key in averageScores){
					//	console.log('avg. on ' + key + ': ' + averageScores[key]);
					//}
				}
			);
		};
		function getDailyData(startDate){

		};

		function setHabitTimeframe(daysAgo){
			habitTimeframe = parseInt(daysAgo);
			console.log('new habit timeframe: ' + habitTimeframe);
		};

		function setFilter(f){
			filter = f;
		};

	//====== init =======
		this.update();

	}
])
.directive('chartComponent', function(){
	return{
		scope: {},
		bindToController: {

		},
		controller: 'ChartComponentController',
		controllerAs: 'ctrl',
		templateUrl: 'habits2/habits-linechart-component.html'
	};
});
<|endoftext|>


<commit_before>/**
 * Copyright 2017 CA
 *
 * 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.
 */

/* @flow */
import color from '../colors';
import createColorRamp from './createColorRamp';
import fontSize_base from './fontSizeBase';
import pxToEm from '../styles/pxToEm';

type Colors =
  | 'blue'
  | 'dusk'
  | 'gray'
  | 'green'
  | 'indigo'
  | 'lime'
  | 'magenta'
  | 'orange'
  | 'purple'
  | 'red'
  | 'sky'
  | 'slate'
  | 'teal'
  | 'yellow';

const spacing_quarter = pxToEm(2);
const spacing_half = pxToEm(4);
const spacing_1x = pxToEm(8);
const spacing_2x = pxToEm(16);
const spacing_3x = pxToEm(24);
const spacing_4x = pxToEm(32);
const spacing_8x = pxToEm(64);

const grays = createColorRamp('gray', 'color_gray', color);

export default function createTheme(
  baseColor?: Colors = 'blue',
  overrides?: { [string]: any } = {}
): { [string]: any } {
  /* Theme key naming convention:
   *
   *   [property]_[target]_[variant]_[state]
   *
   * E.g., A key for the border-color on focused "success" buttons and inputs
   * would look like the following.
   *
   *   borderColor_success_focus
   *
   * Only [property] is required. Irrelevant parts are skipped.
   */

  const primaries = createColorRamp(baseColor, 'color_theme', color);

  return {
    backgroundColor_disabled: color.gray_20,
    backgroundColor_danger: color.red_60,
    backgroundColor_danger_active: color.red_70,
    backgroundColor_danger_activeMuted: color.red_30,
    backgroundColor_danger_focus: color.red_60,
    backgroundColor_danger_hover: color.red_50,
    backgroundColor_success: color.green_80,
    backgroundColor_success_active: color.green_90,
    backgroundColor_success_activeMuted: color.green_30,
    backgroundColor_success_focus: color.green_80,
    backgroundColor_success_hover: color.green_70,
    backgroundColor_warning: color.orange_60,
    backgroundColor_warning_active: color.orange_70,
    backgroundColor_warning_activeMuted: color.orange_30,
    backgroundColor_warning_focus: color.orange_60,
    backgroundColor_warning_hover: color.orange_50,

    backgroundColor_input: color.white,

    backgroundColor_link_focus: color.gray_30,

    borderColor: color.gray_40,
    borderColor_active: primaries.color_theme_60,
    borderColor_focus: primaries.color_theme_60,
    borderColor_hover: primaries.color_theme_60,
    borderColor_danger: color.red_60,
    borderColor_danger_active: color.red_70,
    borderColor_danger_focus: color.red_70,
    borderColor_danger_hover: color.red_70,
    borderColor_success: color.green_70,
    borderColor_success_active: color.green_80,
    borderColor_success_focus: color.green_80,
    borderColor_success_hover: color.green_80,
    borderColor_warning: color.orange_60,
    borderColor_warning_active: color.orange_70,
    borderColor_warning_focus: color.orange_70,
    borderColor_warning_hover: color.orange_70,

    borderRadius_1: pxToEm(3),

    color_black: color.black,

    color_caption: color.gray_80,

    ...grays,

    color_placeholder: color.gray_60,

    ...primaries,

    color_text: color.gray_100,
    color_text_disabled: color.gray_50,
    color_text_danger: color.red_60,
    color_text_danger_active: color.red_70,
    color_text_danger_focus: color.red_60,
    color_text_danger_hover: color.red_50,
    color_text_ondanger: color.white,
    color_text_primary: primaries.color_theme_60,
    color_text_primary_active: primaries.color_theme_70,
    color_text_primary_focus: primaries.color_theme_60,
    color_text_primary_hover: primaries.color_theme_50,
    color_text_onprimary: color.white,
    color_text_success: color.green_90,
    color_text_success_active: color.green_100,
    color_text_success_focus: color.green_90,
    color_text_success_hover: color.green_80,
    color_text_onsuccess: color.white,
    color_text_warning: color.orange_70,
    color_text_warning_active: color.orange_80,
    color_text_warning_focus: color.orange_70,
    color_text_warning_hover: color.orange_60,
    color_text_onwarning: color.white,

    color_white: color.white,

    direction: 'ltr',

    fontFamily: 'Open Sans',
    fontFamily_system:
      '-apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',
    fontFamily_monospace:
      '"SF Mono", "Droid Sans Mono", "Source Code Pro", Monaco, Consolas, "Courier New", Courier, monospace',

    fontSize_base,
    fontSize_h1: pxToEm(34),
    fontSize_h2: pxToEm(28),
    fontSize_h3: pxToEm(22),
    fontSize_h4: pxToEm(18),
    fontSize_h5: pxToEm(14),
    fontSize_h6: pxToEm(14),
    fontSize_mouse: pxToEm(11),
    fontSize_prose: pxToEm(16),
    fontSize_ui: pxToEm(14),

    fontWeight_regular: 400,
    fontWeight_semiBold: 600,
    fontWeight_bold: 700,
    fontWeight_extraBold: 800,

    lineHeight: 1.25,
    lineHeight_prose: 1.5,

    shadow_1: '0 1px 2px 0 rgba(0,0,0,0.4)',
    shadow_2: '0 2px 4px 0 rgba(0,0,0,0.2), 0 1px 2px 0 rgba(0,0,0,0.4)',
    shadow_3: '0 4px 8px 0 rgba(0,0,0,0.2), 0 2px 4px 0 rgba(0,0,0,0.4)',
    shadow_4: '0 8px 16px 0 rgba(0,0,0,0.2), 0 4px 8px 0 rgba(0,0,0,0.4)',
    shadow_5: '0 24px 24px -8px rgba(0,0,0,0.4), 0 8px 16px 0 rgba(0,0,0,0.4)',

    size_small: pxToEm(24),
    size_medium: pxToEm(32),
    size_large: pxToEm(40),
    size_jumbo: pxToEm(52),

    space_inline_xxs: spacing_quarter,
    space_inline_xs: spacing_half,
    space_inline_sm: spacing_1x,
    space_inline_md: spacing_2x,
    space_inline_lg: spacing_3x,
    space_inline_xl: spacing_4x,
    space_inline_xxl: spacing_8x,

    space_inset_sm: spacing_1x,
    space_inset_md: spacing_2x,
    space_inset_lg: spacing_3x,

    space_stack_xxs: spacing_quarter,
    space_stack_xs: spacing_half,
    space_stack_sm: spacing_1x,
    space_stack_md: spacing_2x,
    space_stack_lg: spacing_3x,
    space_stack_xl: spacing_4x,
    space_stack_xxl: spacing_8x,

    zIndex_100: 100,
    zIndex_200: 200,
    zIndex_400: 400,
    zIndex_800: 800,
    zIndex_1600: 1600,

    ...overrides
  };
}
<commit_msg>feat(themes): Add/update theme variables<commit_after>/**
 * Copyright 2017 CA
 *
 * 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.
 */

/* @flow */
import color from '../colors';
import createColorRamp from './createColorRamp';
import fontSize_base from './fontSizeBase';
import pxToEm from '../styles/pxToEm';

type Colors =
  | 'blue'
  | 'dusk'
  | 'gray'
  | 'green'
  | 'indigo'
  | 'lime'
  | 'magenta'
  | 'orange'
  | 'purple'
  | 'red'
  | 'sky'
  | 'slate'
  | 'teal'
  | 'yellow';

const spacing_quarter = pxToEm(2);
const spacing_half = pxToEm(4);
const spacing_1x = pxToEm(8);
const spacing_2x = pxToEm(16);
const spacing_3x = pxToEm(24);
const spacing_4x = pxToEm(32);
const spacing_8x = pxToEm(64);

const grays = createColorRamp('gray', 'color_gray', color);

export default function createTheme(
  baseColor?: Colors = 'blue',
  overrides?: { [string]: any } = {}
): { [string]: any } {
  /* Theme key naming convention:
   *
   *   [property]_[target]_[variant]_[state]
   *
   * E.g., A key for the border-color on focused "success" buttons and inputs
   * would look like the following.
   *
   *   borderColor_success_focus
   *
   * Only [property] is required. Irrelevant parts are skipped.
   */

  const primaries = createColorRamp(baseColor, 'color_theme', color);

  // prettier-ignore
  return {
    backgroundColor_disabled: color.gray_20,
    backgroundColor_danger: color.red_60,
    backgroundColor_danger_muted: color.red_20,
    backgroundColor_danger_active: color.red_70,
    backgroundColor_danger_activeMuted: color.red_30,
    backgroundColor_danger_focus: color.red_60,
    backgroundColor_danger_hover: color.red_50,
    backgroundColor_success: color.green_80,
    backgroundColor_success_muted: color.green_20,
    backgroundColor_success_active: color.green_90,
    backgroundColor_success_activeMuted: color.green_30,
    backgroundColor_success_focus: color.green_80,
    backgroundColor_success_hover: color.green_70,
    backgroundColor_warning: color.orange_60,
    backgroundColor_warning_muted: color.orange_20,
    backgroundColor_warning_active: color.orange_70,
    backgroundColor_warning_activeMuted: color.orange_30,
    backgroundColor_warning_focus: color.orange_60,
    backgroundColor_warning_hover: color.orange_50,

    backgroundColor_input: color.white,

    backgroundColor_link_focus: color.gray_30,

    borderColor: color.gray_40,
    borderColor_active: primaries.color_theme_60,
    borderColor_focus: primaries.color_theme_60,
    borderColor_hover: primaries.color_theme_60,
    borderColor_danger: color.red_60,
    borderColor_danger_active: color.red_70,
    borderColor_danger_focus: color.red_70,
    borderColor_danger_hover: color.red_70,
    borderColor_danger_muted: color.red_40,
    borderColor_success: color.green_70,
    borderColor_success_active: color.green_80,
    borderColor_success_focus: color.green_80,
    borderColor_success_hover: color.green_80,
    borderColor_success_muted: color.green_40,
    borderColor_warning: color.orange_60,
    borderColor_warning_active: color.orange_70,
    borderColor_warning_focus: color.orange_70,
    borderColor_warning_hover: color.orange_70,
    borderColor_warning_muted: color.orange_40,

    borderRadius_1: pxToEm(3),

    color_black: color.black,

    color_caption: color.gray_80,

    ...grays,

    color_placeholder: color.gray_60,

    ...primaries,

    color_text: color.gray_100,
    color_text_disabled: color.gray_50,
    color_text_danger: color.red_60,
    color_text_danger_active: color.red_70,
    color_text_danger_focus: color.red_60,
    color_text_danger_hover: color.red_50,
    color_text_ondanger: color.white,
    color_text_primary: primaries.color_theme_60,
    color_text_primary_active: primaries.color_theme_70,
    color_text_primary_focus: primaries.color_theme_60,
    color_text_primary_hover: primaries.color_theme_50,
    color_text_onprimary: color.white,
    color_text_success: color.green_90,
    color_text_success_active: color.green_100,
    color_text_success_focus: color.green_90,
    color_text_success_hover: color.green_80,
    color_text_onsuccess: color.white,
    color_text_warning: color.orange_70,
    color_text_warning_active: color.orange_80,
    color_text_warning_focus: color.orange_70,
    color_text_warning_hover: color.orange_60,
    color_text_onwarning: color.white,

    color_white: color.white,

    direction: 'ltr',

    fontFamily: 'Open Sans',
    fontFamily_system: '-apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',
    fontFamily_monospace: '"SF Mono", "Droid Sans Mono", "Source Code Pro", Monaco, Consolas, "Courier New", Courier, monospace',

    fontSize_base,
    fontSize_h1: pxToEm(34),
    fontSize_h2: pxToEm(28),
    fontSize_h3: pxToEm(22),
    fontSize_h4: pxToEm(18),
    fontSize_h5: pxToEm(14),
    fontSize_h6: pxToEm(14),
    fontSize_mouse: pxToEm(11),
    fontSize_prose: pxToEm(16),
    fontSize_ui: pxToEm(14),

    fontWeight_regular: 400,
    fontWeight_semiBold: 600,
    fontWeight_bold: 700,
    fontWeight_extraBold: 800,

    lineHeight: 1.25,
    lineHeight_prose: 1.5,

    shadow_1: '0 1px 2px 0 rgba(0,0,0,0.2), 0 2px 4px 0 rgba(0,0,0,0.2)',
    shadow_2: '0 2px 4px 0 rgba(0,0,0,0.2), 0 4px 8px 0 rgba(0,0,0,0.2)',
    shadow_3: '0 4px 8px 0 rgba(0,0,0,0.2), 0 8px 16px 0 rgba(0,0,0,0.2)',
    shadow_4: '0 8px 16px 0 rgba(0,0,0,0.2), 0 20px 16px -8px rgba(0,0,0,0.2)',
    shadow_5: '0 16px 24px 0 rgba(0,0,0,0.2), 0 32px 24px -16px rgba(0,0,0,0.2)',

    size_small: pxToEm(24),
    size_medium: pxToEm(32),
    size_large: pxToEm(40),
    size_jumbo: pxToEm(52),

    space_inline_xxs: spacing_quarter,
    space_inline_xs: spacing_half,
    space_inline_sm: spacing_1x,
    space_inline_md: spacing_2x,
    space_inline_lg: spacing_3x,
    space_inline_xl: spacing_4x,
    space_inline_xxl: spacing_8x,

    space_inset_sm: spacing_1x,
    space_inset_md: spacing_2x,
    space_inset_lg: spacing_3x,

    space_stack_xxs: spacing_quarter,
    space_stack_xs: spacing_half,
    space_stack_sm: spacing_1x,
    space_stack_md: spacing_2x,
    space_stack_lg: spacing_3x,
    space_stack_xl: spacing_4x,
    space_stack_xxl: spacing_8x,

    zIndex_100: 100,
    zIndex_200: 200,
    zIndex_400: 400,
    zIndex_800: 800,
    zIndex_1600: 1600,

    ...overrides
  };
}
<|endoftext|>


<commit_before><commit_msg>extracted add car and edit car logic<commit_after><|endoftext|>


<commit_before>/*globals $WowheadPower */
'use strict';

(function() {

    angular
        .module('simpleArmoryApp')
        .controller('AdminMissing', AdminMissing);

    function AdminMissing($scope, AdminService, SettingsService) {
        $scope.settings = SettingsService;

        // TODO: might not need customization here
        $scope.col1Title = "Missing";
        $scope.col2Title = "Categories";
        $scope.moveDisabled = true;

        // TODO: take mount specific shit out of it
        // TODO: rename to missing in controller and html
        // TODO: will need to add ids to achievement categories
        // TODO: fix route to including missing

        // TODO: have support for both mount and achievements
        if ($scope.section === 'mounts') {
            AdminService.getMountData().then(function(data){
                var categories = [];

                for(var i=0; i<data.length; i++) {
                    var cat = data[i];

                    categories.push(cat);
                }

                $scope.categories = categories;
            });

            AdminService.getMissingMounts().then(function(data){
                $scope.missing = data;
            });
        } else if ($scope.section === 'achievements') {
            AdminService.getAchievementData().then(function(data){

                $scope.categories = [];
                for (var i=0; i < data.supercats.length; i++) {
                    var supercat = data.supercats[i];
                    for (var j in supercat.cats) {
                         var cat = supercat.cats[j];
                         for (var k in cat.subcats) {
                            var subcat = cat.subcats[k];

                            $scope.categories.push({ label: supercat.name + '\\' + cat.name + '\\' + subcat.name, subcat:subcat });
                         }
                     }
                }

                $scope.categorySelected = $scope.categories[0];
                $scope.data = data;
            });

            // TMP
            $scope.missing = [
                { 'id': '4476', 'icon': 'Achievement_Arena_2v2_3' },
                { 'id': '4477', 'icon': 'Achievement_Arena_3v3_4' },
                { 'id': '4478', 'icon': 'Achievement_Arena_5v5_3' }
            ]

        }

        $scope.getImageSrc = function(item) {
            return '//wow.zamimg.com/images/wow/icons/medium/' + item.icon.toLowerCase() + '.jpg';
        };

        $scope.clicked = function(event, item) {
            event.preventDefault();
            $WowheadPower.hideTooltip();

            if (item.selected !== true) {
                $(event.currentTarget).addClass('missingItemSelected');
                item.selected = true;
            } else {
                $(event.currentTarget).removeClass('missingItemSelected');
                item.selected = false;
            }

            $scope.moveDisabled = $scope.missing.filter(item => item.selected === true).length == 0;
        };

        $scope.move = function() {
            for (var i=0; i < $scope.missing.length; i++) {
                var item = $scope.missing[i];

                if (item.selected && item.selected === true) {
                    console.log('adding ' + item.id + ' to ' + $scope.categorySelected.subcat.name);

                    // TODO: turn back on when I have time, hurt my brain
                    // notify(item.id, $scope.categorySelected.subcat.name);
                }
            }

            $scope.$parent.canSave($scope.section, $scope.data);
        }

        // TODO: cleanup
        $scope.dragDone = function(subcatId) {

            // find drop target obj
            var subCatObj;
            for (var i=0; i<$scope.categories.length; i++) {
                var cat = $scope.categories[i];
                for (var k2 in cat.subcats) {
                    var subcat = cat.subcats[k2];
                    if (subcat.id === subcatId) {
                        subCatObj = subcat;
                    }
                }
            }

            // show the info alert, and hide after 2s
            $scope.notifyIn = true;
            $scope.notifyOut = false;
            $scope.notify = {
                'name': draggedItem.name,
                'subcat': subCatObj.name
            };
            window.setTimeout(function() {
                $scope.$apply(function () {
                    $scope.notifyIn = false;
                    $scope.notifyOut = true;
                });
            }, 2100);

            // save to category (minus the name)
            delete draggedItem['name'];
            subCatObj.items.push(draggedItem);

            // remove from scope
            $scope.missing = $scope.missing.filter(function(item) {
                if (draggedItem.itemId) {
                    return item.itemId !== draggedItem.itemId;
                }
                else {
                    return item.spellid !== draggedItem.spellid;
                }
            });

            // enable the save button
            $scope.$parent.canSave('mounts', $scope.categories);
        };

        $scope.getLink  = function(item) {
            var link = 'spell='+item.spellId;

            if (item.id) {
                link = 'achievement='+item.id;
            } else if (item.itemId) {
                link = 'item='+item.itemId;
            }

            return link;
        };

        function notify(name, category) {

            // show the info alert, and hide after 2s
            $scope.notifyIn = true;
            $scope.notifyOut = false;
            $scope.notify = {
                'name': name,
                'subcat': category
            };
            window.setTimeout(function() {
                $scope.$apply(function () {
                    $scope.notifyIn = false;
                    $scope.notifyOut = true;
                });
            }, 2100);
        }
    }
})();<commit_msg>save to item section and remove from missing scope<commit_after>/*globals $WowheadPower */
'use strict';

(function() {

    angular
        .module('simpleArmoryApp')
        .controller('AdminMissing', AdminMissing);

    function AdminMissing($scope, AdminService, SettingsService) {
        $scope.settings = SettingsService;

        // TODO: might not need customization here
        $scope.col1Title = "Missing";
        $scope.col2Title = "Categories";
        $scope.moveDisabled = true;

        // TODO: take mount specific shit out of it
        // TODO: rename to missing in controller and html
        // TODO: will need to add ids to achievement categories
        // TODO: fix route to including missing

        // TODO: have support for both mount and achievements
        if ($scope.section === 'mounts') {
            AdminService.getMountData().then(function(data){
                var categories = [];

                for(var i=0; i<data.length; i++) {
                    var cat = data[i];

                    categories.push(cat);
                }

                $scope.categories = categories;
            });

            AdminService.getMissingMounts().then(function(data){
                $scope.missing = data;
            });
        } else if ($scope.section === 'achievements') {
            AdminService.getAchievementData().then(function(data){

                $scope.categories = [];
                for (var i=0; i < data.supercats.length; i++) {
                    var supercat = data.supercats[i];
                    for (var j in supercat.cats) {
                         var cat = supercat.cats[j];
                         for (var k in cat.subcats) {
                            var subcat = cat.subcats[k];

                            $scope.categories.push({ label: supercat.name + '\\' + cat.name + '\\' + subcat.name, subcat:subcat });
                         }
                     }
                }

                $scope.categorySelected = $scope.categories[0];
                $scope.data = data;

                $scope.createItem = function(ach) {

                    return {
                        'id': ach.id,
                        'icon': ach.icon,
                        'side': getFactionSymbol(ach.id, ach.factionId),
                        'obtainable': true,
                        'points': ach.points,
                        'criteria': {}
                    };
                }
            });

            // TMP
            $scope.missing = [
                { 'id': '4476', 'icon': 'Achievement_Arena_2v2_3', 'factionId': 2, points:5 },
                { 'id': '4477', 'icon': 'Achievement_Arena_3v3_4', 'factionId': 2, points:5 },
                { 'id': '4478', 'icon': 'Achievement_Arena_5v5_3', 'factionId': 2, points:5 }
            ]

        }

        $scope.getImageSrc = function(item) {
            return '//wow.zamimg.com/images/wow/icons/medium/' + item.icon.toLowerCase() + '.jpg';
        };

        $scope.clicked = function(event, item) {
            event.preventDefault();
            $WowheadPower.hideTooltip();

            if (item.selected !== true) {
                $(event.currentTarget).addClass('missingItemSelected');
                item.selected = true;
            } else {
                $(event.currentTarget).removeClass('missingItemSelected');
                item.selected = false;
            }

            $scope.moveDisabled = $scope.missing.filter(item => item.selected === true).length == 0;
        };

        $scope.move = function() {
            for (var i=0; i < $scope.missing.length; i++) {
                var item = $scope.missing[i];

                if (item.selected && item.selected === true) {
                    console.log('adding ' + item.id + ' to ' + $scope.categorySelected.subcat.name);

                    var itemToSave = $scope.createItem(item);
                    $scope.categorySelected.subcat.items.push(item);

                    // remove from scope
                    $scope.missing = $scope.missing.filter(function(missing) {
                        if (item.id) {
                            return item.id !== missing.id;
                        }
                        else {
                            return item.spellid !== missing.spellid;
                        }
                    });

                    // TODO: turn back on when I have time, hurt my brain
                    // notify(item.id, $scope.categorySelected.subcat.name);
                }
            }

            $scope.$parent.canSave($scope.section, $scope.data);
        }

        $scope.getLink  = function(item) {
            var link = 'spell='+item.spellId;

            if (item.id) {
                link = 'achievement='+item.id;
            } else if (item.itemId) {
                link = 'item='+item.itemId;
            }

            return link;
        };

        function notify(name, category) {

            // show the info alert, and hide after 2s
            $scope.notifyIn = true;
            $scope.notifyOut = false;
            $scope.notify = {
                'name': name,
                'subcat': category
            };
            window.setTimeout(function() {
                $scope.$apply(function () {
                    $scope.notifyIn = false;
                    $scope.notifyOut = true;
                });
            }, 2100);
        }

        function getFactionSymbol(id, factionId) {
            // 0 is alliance
            // 1 is horde
            // 2 is anyone
            if (factionId === 0) {
                return 'A';
            }
            else if (factionId === 1) {
                return 'H';
            }
            else if (factionId === 2) {
                return '';
            }
            else {
                console.log('UNKNOWN FACTION: ' + factionId + ' for ' + id);
            }
        }
    }
})();<|endoftext|>


<commit_before>
/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 */

function setup(env) {
	createDebug.debug = createDebug;
	createDebug.default = createDebug;
	createDebug.coerce = coerce;
	createDebug.disable = disable;
	createDebug.enable = enable;
	createDebug.enabled = enabled;
	createDebug.humanize = require('ms');
	createDebug.destroy = destroy;

	Object.keys(env).forEach(key => {
		createDebug[key] = env[key];
	});

	/**
	* The currently active debug mode names, and names to skip.
	*/

	createDebug.names = [];
	createDebug.skips = [];

	/**
	* Map of special "%n" handling functions, for the debug "format" argument.
	*
	* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
	*/
	createDebug.formatters = {};

	/**
	* Selects a color for a debug namespace
	* @param {String} namespace The namespace string for the for the debug instance to be colored
	* @return {Number|String} An ANSI color code for the given namespace
	* @api private
	*/
	function selectColor(namespace) {
		let hash = 0;

		for (let i = 0; i < namespace.length; i++) {
			hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
			hash |= 0; // Convert to 32bit integer
		}

		return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
	}
	createDebug.selectColor = selectColor;

	/**
	* Create a debugger with the given `namespace`.
	*
	* @param {String} namespace
	* @return {Function}
	* @api public
	*/
	function createDebug(namespace) {
		let prevTime;
		let enableOverride = null;
		let namespacesCache;
		let enabledCache;

		function debug(...args) {
			// Disabled?
			if (!debug.enabled) {
				return;
			}

			const self = debug;

			// Set `diff` timestamp
			const curr = Number(new Date());
			const ms = curr - (prevTime || curr);
			self.diff = ms;
			self.prev = prevTime;
			self.curr = curr;
			prevTime = curr;

			args[0] = createDebug.coerce(args[0]);

			if (typeof args[0] !== 'string') {
				// Anything else let's inspect with %O
				args.unshift('%O');
			}

			// Apply any `formatters` transformations
			let index = 0;
			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
				// If we encounter an escaped % then don't increase the array index
				if (match === '%%') {
					return '%';
				}
				index++;
				const formatter = createDebug.formatters[format];
				if (typeof formatter === 'function') {
					const val = args[index];
					match = formatter.call(self, val);

					// Now we need to remove `args[index]` since it's inlined in the `format`
					args.splice(index, 1);
					index--;
				}
				return match;
			});

			// Apply env-specific formatting (colors, etc.)
			createDebug.formatArgs.call(self, args);

			const logFn = self.log || createDebug.log;
			logFn.apply(self, args);
		}

		debug.namespace = namespace;
		debug.useColors = createDebug.useColors();
		debug.color = createDebug.selectColor(namespace);
		debug.extend = extend;
		debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.

		Object.defineProperty(debug, 'enabled', {
			enumerable: true,
			configurable: false,
			get: () => {
				if (enableOverride !== null) {
					return enableOverride;
				}
				if (namespacesCache !== createDebug.namespaces) {
					namespacesCache = createDebug.namespaces;
					enabledCache = createDebug.enabled(namespace);
				}

				return enabledCache;
			},
			set: v => {
				enableOverride = v;
			}
		});

		// Env-specific initialization logic for debug instances
		if (typeof createDebug.init === 'function') {
			createDebug.init(debug);
		}

		return debug;
	}

	function extend(namespace, delimiter) {
		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
		newDebug.log = this.log;
		return newDebug;
	}

	/**
	* Enables a debug mode by namespaces. This can include modes
	* separated by a colon and wildcards.
	*
	* @param {String} namespaces
	* @api public
	*/
	function enable(namespaces) {
		createDebug.save(namespaces);
		createDebug.namespaces = namespaces;

		createDebug.names = [];
		createDebug.skips = [];

		let i;
		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
		const len = split.length;

		for (i = 0; i < len; i++) {
			if (!split[i]) {
				// ignore empty strings
				continue;
			}

			namespaces = split[i].replace(/\*/g, '.*?');

			if (namespaces[0] === '-') {
				createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
			} else {
				createDebug.names.push(new RegExp('^' + namespaces + '$'));
			}
		}
	}

	/**
	* Disable debug output.
	*
	* @return {String} namespaces
	* @api public
	*/
	function disable() {
		const namespaces = [
			...createDebug.names.map(toNamespace),
			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
		].join(',');
		createDebug.enable('');
		return namespaces;
	}

	/**
	* Returns true if the given mode name is enabled, false otherwise.
	*
	* @param {String} name
	* @return {Boolean}
	* @api public
	*/
	function enabled(name) {
		if (name[name.length - 1] === '*') {
			return true;
		}

		let i;
		let len;

		for (i = 0, len = createDebug.skips.length; i < len; i++) {
			if (createDebug.skips[i].test(name)) {
				return false;
			}
		}

		for (i = 0, len = createDebug.names.length; i < len; i++) {
			if (createDebug.names[i].test(name)) {
				return true;
			}
		}

		return false;
	}

	/**
	* Convert regexp to namespace
	*
	* @param {RegExp} regxep
	* @return {String} namespace
	* @api private
	*/
	function toNamespace(regexp) {
		return regexp.toString()
			.substring(2, regexp.toString().length - 2)
			.replace(/\.\*\?$/, '*');
	}

	/**
	* Coerce `val`.
	*
	* @param {Mixed} val
	* @return {Mixed}
	* @api private
	*/
	function coerce(val) {
		if (val instanceof Error) {
			return val.stack || val.message;
		}
		return val;
	}

	/**
	* XXX DO NOT USE. This is a temporary stub function.
	* XXX It WILL be removed in the next major release.
	*/
	function destroy() {
		console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
	}

	createDebug.enable(createDebug.load());

	return createDebug;
}

module.exports = setup;
<commit_msg>Remove accidental epizeuxis<commit_after>
/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 */

function setup(env) {
	createDebug.debug = createDebug;
	createDebug.default = createDebug;
	createDebug.coerce = coerce;
	createDebug.disable = disable;
	createDebug.enable = enable;
	createDebug.enabled = enabled;
	createDebug.humanize = require('ms');
	createDebug.destroy = destroy;

	Object.keys(env).forEach(key => {
		createDebug[key] = env[key];
	});

	/**
	* The currently active debug mode names, and names to skip.
	*/

	createDebug.names = [];
	createDebug.skips = [];

	/**
	* Map of special "%n" handling functions, for the debug "format" argument.
	*
	* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
	*/
	createDebug.formatters = {};

	/**
	* Selects a color for a debug namespace
	* @param {String} namespace The namespace string for the debug instance to be colored
	* @return {Number|String} An ANSI color code for the given namespace
	* @api private
	*/
	function selectColor(namespace) {
		let hash = 0;

		for (let i = 0; i < namespace.length; i++) {
			hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
			hash |= 0; // Convert to 32bit integer
		}

		return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
	}
	createDebug.selectColor = selectColor;

	/**
	* Create a debugger with the given `namespace`.
	*
	* @param {String} namespace
	* @return {Function}
	* @api public
	*/
	function createDebug(namespace) {
		let prevTime;
		let enableOverride = null;
		let namespacesCache;
		let enabledCache;

		function debug(...args) {
			// Disabled?
			if (!debug.enabled) {
				return;
			}

			const self = debug;

			// Set `diff` timestamp
			const curr = Number(new Date());
			const ms = curr - (prevTime || curr);
			self.diff = ms;
			self.prev = prevTime;
			self.curr = curr;
			prevTime = curr;

			args[0] = createDebug.coerce(args[0]);

			if (typeof args[0] !== 'string') {
				// Anything else let's inspect with %O
				args.unshift('%O');
			}

			// Apply any `formatters` transformations
			let index = 0;
			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
				// If we encounter an escaped % then don't increase the array index
				if (match === '%%') {
					return '%';
				}
				index++;
				const formatter = createDebug.formatters[format];
				if (typeof formatter === 'function') {
					const val = args[index];
					match = formatter.call(self, val);

					// Now we need to remove `args[index]` since it's inlined in the `format`
					args.splice(index, 1);
					index--;
				}
				return match;
			});

			// Apply env-specific formatting (colors, etc.)
			createDebug.formatArgs.call(self, args);

			const logFn = self.log || createDebug.log;
			logFn.apply(self, args);
		}

		debug.namespace = namespace;
		debug.useColors = createDebug.useColors();
		debug.color = createDebug.selectColor(namespace);
		debug.extend = extend;
		debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.

		Object.defineProperty(debug, 'enabled', {
			enumerable: true,
			configurable: false,
			get: () => {
				if (enableOverride !== null) {
					return enableOverride;
				}
				if (namespacesCache !== createDebug.namespaces) {
					namespacesCache = createDebug.namespaces;
					enabledCache = createDebug.enabled(namespace);
				}

				return enabledCache;
			},
			set: v => {
				enableOverride = v;
			}
		});

		// Env-specific initialization logic for debug instances
		if (typeof createDebug.init === 'function') {
			createDebug.init(debug);
		}

		return debug;
	}

	function extend(namespace, delimiter) {
		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
		newDebug.log = this.log;
		return newDebug;
	}

	/**
	* Enables a debug mode by namespaces. This can include modes
	* separated by a colon and wildcards.
	*
	* @param {String} namespaces
	* @api public
	*/
	function enable(namespaces) {
		createDebug.save(namespaces);
		createDebug.namespaces = namespaces;

		createDebug.names = [];
		createDebug.skips = [];

		let i;
		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
		const len = split.length;

		for (i = 0; i < len; i++) {
			if (!split[i]) {
				// ignore empty strings
				continue;
			}

			namespaces = split[i].replace(/\*/g, '.*?');

			if (namespaces[0] === '-') {
				createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
			} else {
				createDebug.names.push(new RegExp('^' + namespaces + '$'));
			}
		}
	}

	/**
	* Disable debug output.
	*
	* @return {String} namespaces
	* @api public
	*/
	function disable() {
		const namespaces = [
			...createDebug.names.map(toNamespace),
			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
		].join(',');
		createDebug.enable('');
		return namespaces;
	}

	/**
	* Returns true if the given mode name is enabled, false otherwise.
	*
	* @param {String} name
	* @return {Boolean}
	* @api public
	*/
	function enabled(name) {
		if (name[name.length - 1] === '*') {
			return true;
		}

		let i;
		let len;

		for (i = 0, len = createDebug.skips.length; i < len; i++) {
			if (createDebug.skips[i].test(name)) {
				return false;
			}
		}

		for (i = 0, len = createDebug.names.length; i < len; i++) {
			if (createDebug.names[i].test(name)) {
				return true;
			}
		}

		return false;
	}

	/**
	* Convert regexp to namespace
	*
	* @param {RegExp} regxep
	* @return {String} namespace
	* @api private
	*/
	function toNamespace(regexp) {
		return regexp.toString()
			.substring(2, regexp.toString().length - 2)
			.replace(/\.\*\?$/, '*');
	}

	/**
	* Coerce `val`.
	*
	* @param {Mixed} val
	* @return {Mixed}
	* @api private
	*/
	function coerce(val) {
		if (val instanceof Error) {
			return val.stack || val.message;
		}
		return val;
	}

	/**
	* XXX DO NOT USE. This is a temporary stub function.
	* XXX It WILL be removed in the next major release.
	*/
	function destroy() {
		console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
	}

	createDebug.enable(createDebug.load());

	return createDebug;
}

module.exports = setup;
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter,
    util = require('util'),
    spawn = require('child_process').spawn,
    http = require('http');

var Speakable = function Speakable(credentials, options) {
  EventEmitter.call(this);

  options = options || {}

  this.recBuffer = [];
  this.recRunning = false;
  this.apiResult = {};
  this.apiLang = options.lang || "en-US";
  this.apiKey = credentials.key
  this.cmd = __dirname + '/sox';
  this.cmdArgs = [
    '-q',
    '-b','16',
    '-d','-t','flac','-',
    'rate','16000','channels','1',
    'silence','1','0.1',(options.threshold || '0.1')+'%','1','1.0',(options.threshold || '0.1')+'%'
  ];
};

util.inherits(Speakable, EventEmitter);
module.exports = Speakable;

Speakable.prototype.postVoiceData = function() {
  var self = this;

  var options = {
    hostname: 'www.google.com',
    path: '/speech-api/v2/recognize?client=chromium&key=' + self.apiKey + '&maxresults=1&lang=' + self.apiLang,
    method: 'POST',
    headers: {
      'Content-type': 'audio/x-flac; rate=16000'
    }
  };

  var req = http.request(options, function(res) {
    self.recBuffer = [];
    if(res.statusCode !== 200) {
      return self.emit(
        'error',
        'Non-200 answer from Google Speech API (' + res.statusCode + ')'
      );
    }
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      self.apiResult = JSON.parse(chunk);
    });
    res.on('end', function() {
      self.parseResult();
    });
  });

  req.on('error', function(e) {
    self.emit('error', e);
  });

  // write data to request body
  console.log('Posting voice data...');
  for(var i in self.recBuffer) {
    if(self.recBuffer.hasOwnProperty(i)) {
      req.write(new Buffer(self.recBuffer[i],'binary'));
    }
  }
  req.end();
};

Speakable.prototype.recordVoice = function() {
  var self = this;
  var rec = spawn(self.cmd, self.cmdArgs, {
						stdio:['pipe',
							'pipe',
							'pipe'],
						env:process.env
		});

  // Process stdout

  rec.stdout.on('readable', function() {
    self.emit('speechReady');
  });

  rec.stdout.setEncoding('binary');
  rec.stdout.on('data', function(data) {
    if(! self.recRunning) {
      self.emit('speechStart');
      self.recRunning = true;
    }
    self.recBuffer.push(data);
  });

  // Process stdin

  rec.stderr.setEncoding('utf8');
  rec.stderr.on('data', function(data) {
    console.log(data)
  });

  rec.on('close', function(code) {
    self.recRunning = false;
    if(code) {
      self.emit('error', 'sox exited with code ' + code);
    }
    self.emit('speechStop');
    self.postVoiceData();
  });
};

Speakable.prototype.resetVoice = function() {
  var self = this;
  self.recBuffer = [];
}

Speakable.prototype.parseResult = function() {
  var recognizedWords = [], apiResult = this.apiResult.result;
  if(apiResult && apiResult.length > 0 && apiResult[0].alternative && apiResult[0].alternative[0]) {
    recognizedWords = apiResult[0].alternative[0].transcript.split(' ');
    this.emit('speechResult', recognizedWords);
  } else {
    this.emit('speechResult', []);
  }
}
<commit_msg>fix sox<commit_after>var EventEmitter = require('events').EventEmitter,
    util = require('util'),
    spawn = require('child_process').spawn,
    http = require('http');

var Speakable = function Speakable(credentials, options) {
  EventEmitter.call(this);

  options = options || {}

  this.recBuffer = [];
  this.recRunning = false;
  this.apiResult = {};
  this.apiLang = options.lang || "en-US";
  this.apiKey = credentials.key
  this.cmd = '/usr/bin/sox';
  this.cmdArgs = [
    '-q',
    '-b','16',
    '-d','-t','flac','-',
    'rate','16000','channels','1',
    'silence','1','0.1',(options.threshold || '0.1')+'%','1','1.0',(options.threshold || '0.1')+'%'
  ];
};

util.inherits(Speakable, EventEmitter);
module.exports = Speakable;

Speakable.prototype.postVoiceData = function() {
  var self = this;

  var options = {
    hostname: 'www.google.com',
    path: '/speech-api/v2/recognize?client=chromium&key=' + self.apiKey + '&maxresults=1&lang=' + self.apiLang,
    method: 'POST',
    headers: {
      'Content-type': 'audio/x-flac; rate=16000'
    }
  };

  var req = http.request(options, function(res) {
    self.recBuffer = [];
    if(res.statusCode !== 200) {
      return self.emit(
        'error',
        'Non-200 answer from Google Speech API (' + res.statusCode + ')'
      );
    }
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      self.apiResult = JSON.parse(chunk);
    });
    res.on('end', function() {
      self.parseResult();
    });
  });

  req.on('error', function(e) {
    self.emit('error', e);
  });

  // write data to request body
  console.log('Posting voice data...');
  for(var i in self.recBuffer) {
    if(self.recBuffer.hasOwnProperty(i)) {
      req.write(new Buffer(self.recBuffer[i],'binary'));
    }
  }
  req.end();
};

Speakable.prototype.recordVoice = function() {
  var self = this;
  var rec = spawn(self.cmd, self.cmdArgs, {
						stdio:['pipe',
							'pipe',
							'pipe'],
						env:process.env
		});

  // Process stdout

  rec.stdout.on('readable', function() {
    self.emit('speechReady');
  });

  rec.stdout.setEncoding('binary');
  rec.stdout.on('data', function(data) {
    if(! self.recRunning) {
      self.emit('speechStart');
      self.recRunning = true;
    }
    self.recBuffer.push(data);
  });

  // Process stdin

  rec.stderr.setEncoding('utf8');
  rec.stderr.on('data', function(data) {
    console.log(data)
  });

  rec.on('close', function(code) {
    self.recRunning = false;
    if(code) {
      self.emit('error', 'sox exited with code ' + code);
    }
    self.emit('speechStop');
    self.postVoiceData();
  });
};

Speakable.prototype.resetVoice = function() {
  var self = this;
  self.recBuffer = [];
}

Speakable.prototype.parseResult = function() {
  var recognizedWords = [], apiResult = this.apiResult.result;
  if(apiResult && apiResult.length > 0 && apiResult[0].alternative && apiResult[0].alternative[0]) {
    recognizedWords = apiResult[0].alternative[0].transcript.split(' ');
    this.emit('speechResult', recognizedWords);
  } else {
    this.emit('speechResult', []);
  }
}
<|endoftext|>


<commit_before>/* Copyright 2014 Open Ag Data Alliance
 *
 * 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.
 */

/**
 *	@oadaLogin
 *
 *	Client side Javascript library for logging in to an OADA service provider.
 *
 *	@author Alex Layton
 *	@copyright Purdue University 2014
 *	@license Apache Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
 */

var oadaLogin = (function() {
	"use strict";

	// Object for the instance of this module
	var mod = {};

	var options = {
		// TODO: Handle a "default" redirect to self
		response_type: "token id_token",
		display: "popup",
	};

	var state, conf;

	var loginCallback = function(){};

	mod.init = function(opts) {
		for (var opt in opts) {
			options[opt] = opts[opt];
		}
	};

	mod.login = function(domain, callback, opts) {
		state = Math.random();

		// Override options
		opts = typeof opts !== 'undefined' ? opts : {};
		for (var opt in options) {
			if (typeof opts[opt] === 'undefined') {
				opts[opt] = options[opt];
			}
		}

		// Can't open windows in callbacks lest we anger the popup blockers
		var loginWindow = window.open("", "_blank", "width=500,height=400");

		// Get OADA configuration
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = receiveConfig;
		xmlhttp.open("GET", "http://" + domain +
				"/.well-known/oada-configuration", true);
		xmlhttp.send();

		// Called with GET result
		function receiveConfig() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				conf = JSON.parse(xmlhttp.responseText);

				// Construct URL
				var url = conf.authorization_endpoint +
					"?state=" + encodeURIComponent(state);
				for (var opt in opts) {
					url += "&" + opt + "=" + encodeURIComponent(opts[opt]);
				}

				loginCallback = typeof callback !== 'undefined' ?
						callback : function(){};

				// Use window opened before callback
				loginWindow.location.assign(url);
			}
		}
	};

	mod.setParameters = function(params) {
		if (params.state === state.toString()) {
			loginCallback(conf, params);
		}
	};

	mod.handleRedirect = function() {
		var REGEX = /([^&=]+)=([^&]*)/g;

		var hash = window.location.hash;
		var params = {};
		var m;
		while ((m = REGEX.exec(hash.substr(1))) !== null) {
			var key = decodeURIComponent(m[1]);
			var value = decodeURIComponent(m[2]);
			params[key] = value;
		}

		// Gross?
		window.opener.oadaLogin.setParameters(params);
		window.close();
	};

	return mod;

}());

<commit_msg>Make popup less early<commit_after>/* Copyright 2014 Open Ag Data Alliance
 *
 * 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.
 */

/**
 *	@oadaLogin
 *
 *	Client side Javascript library for logging in to an OADA service provider.
 *
 *	@author Alex Layton
 *	@copyright Purdue University 2014
 *	@license Apache Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
 */

var oadaLogin = (function() {
	"use strict";

	// Object for the instance of this module
	var mod = {};

	var options = {
		// TODO: Handle a "default" redirect to self
		response_type: "token id_token",
		display: "popup",
	};

	var state, conf;

	var loginCallback = function(){};

	mod.init = function(opts) {
		for (var opt in opts) {
			options[opt] = opts[opt];
		}
	};

	mod.login = function(domain, callback, opts) {
		state = Math.random();

		// Override options
		opts = typeof opts !== 'undefined' ? opts : {};
		for (var opt in options) {
			if (typeof opts[opt] === 'undefined') {
				opts[opt] = options[opt];
			}
		}

		// Get OADA configuration
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = receiveConfig;
		xmlhttp.open("GET", "http://" + domain +
				"/.well-known/oada-configuration", true);
		xmlhttp.send();

		// Can't open windows in callbacks lest we anger the popup blockers
		var loginWindow = window.open("", "_blank", "width=500,height=400");

		// Called with GET result
		function receiveConfig() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				conf = JSON.parse(xmlhttp.responseText);

				// Construct URL
				var url = conf.authorization_endpoint +
					"?state=" + encodeURIComponent(state);
				for (var opt in opts) {
					url += "&" + opt + "=" + encodeURIComponent(opts[opt]);
				}

				loginCallback = typeof callback !== 'undefined' ?
						callback : function(){};

				// Use window opened before callback
				loginWindow.location.assign(url);
			}
		}
	};

	mod.setParameters = function(params) {
		if (params.state === state.toString()) {
			loginCallback(conf, params);
		}
	};

	mod.handleRedirect = function() {
		var REGEX = /([^&=]+)=([^&]*)/g;

		var hash = window.location.hash;
		var params = {};
		var m;
		while ((m = REGEX.exec(hash.substr(1))) !== null) {
			var key = decodeURIComponent(m[1]);
			var value = decodeURIComponent(m[2]);
			params[key] = value;
		}

		// Gross?
		window.opener.oadaLogin.setParameters(params);
		window.close();
	};

	return mod;

}());

<|endoftext|>


<commit_before>(function (require, request) {

	var
		manifest = {},
		resolved = {},
		entries = [];

	require = window.require = require || function (name) {

		var
			id = name,
			entry,
			method,
			map,
			data,
			require_,
			request_;

		if (typeof (entry = manifest[id]) == 'string') {
			id = entry;
		}

		if ((entry = resolved[id])) return entry;
		if (!(entry = manifest[id])) throw 'unable to find module ' + name;
		method = entry[0];
		map = entry[1];
		data = {exports: {}};
		require_ = function (n) {
			return require(map[n] == null ? n : map[n]);
		};
		request_ = function (n) {
			return request(map[n] == null ? n : map[n]);
		};
		method(data, data.exports, window, require_, request_);
		return (resolved[id] = data.exports);
	};

	request = window.request = request || function (name, loading) {
		if (!(this instanceof request)) return new request(name, loading);

		var
			id = name,
			callbacks = [],
			entry,
			el,
			finish,
			fired = false,
			finished = false,
			relay;

		if (typeof (entry = manifest[id]) == 'string') {
			id = entry;
		}

		this.then = function (cb) {
			callbacks.push(cb);
			if (finished) {
				relay(name);
			} else {
				if (!fired) finish();
			}
			return this;
		};

		relay = function (id) {
			setTimeout(function () {
				var cb = callbacks.shift();
				while (cb) {
					cb(id && require(id));
					cb = callbacks.shift();
				}
			}, 0);
		};

		finish = function () {

			fired = true;

			if (entry.bundles && entry.bundles.length) {
				var next = entry.bundles.shift();
				return request(next, true).then(finish);
			};

			if (entry.source) {
				el = document.createElement('script');
				el.onload = function () {
					finished = true;
					relay(!loading && name);
				};
				el.onerror = function () { throw 'failed to retrieve requested bundle for module ' + name + ' from ' + entry.source; };
				el.async = true;
				el.src = entry.source;
				document.head.appendChild(el);
			}

			if (entry.style) {
				el = document.createElement('link');
				el.rel = 'stylesheet';
				el.href = entry.style;
				document.head.appendChild(el);
			}
		};

		if ((entry = resolved[id])) {
			finished = true;
			return;
		}

		if (typeof (entry = manifest[id]) != 'object') throw 'unable to find bundle for module ' + name;
	};

	if (require.manifest) {
		for (var id in manifest) {
			var prev = require.manifest[id];
			if (!prev || !(prev instanceof Array)) require.manifest[id] = manifest[id];
		}
		manifest = require.manifest;
	} else require.manifest = manifest;

	for (var i = 0; i < entries.length; ++i) require(entries[i]);
})(window.require, window.request);<commit_msg>remove unnecessary file<commit_after><|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */

/**
 * CORS hook
 */

const defaults = require('./defaults.json');

module.exports = strapi => {
  return {
    /**
     * Initialize the hook
     */

    initialize: function(cb) {
      strapi.app.use(
        async (ctx, next) => {
          if (ctx.request.admin) {
            return strapi.koaMiddlewares.kcors({
              origin: '*',
              exposeHeaders: defaults.cors.expose,
              maxAge: defaults.cors.maxAge,
              credentials: defaults.cors.credentials,
              allowMethods: defaults.cors.methods,
              allowHeaders: defaults.cors.headers,
              keepHeadersOnError: defaults.cors.keepHeadersOnError
            })(ctx, next);
          } else if (strapi.config.currentEnvironment.security.cors.enabled) {
            return strapi.koaMiddlewares.kcors({
              origin: strapi.config.middleware.settings.cors.origin,
              exposeHeaders: strapi.config.middleware.settings.cors.expose,
              maxAge: strapi.config.middleware.settings.cors.maxAge,
              credentials: strapi.config.middleware.settings.cors.credentials,
              allowMethods: strapi.config.middleware.settings.cors.methods,
              allowHeaders: strapi.config.middleware.settings.cors.headers,
              keepHeadersOnError: strapi.config.middleware.settings.cors.keepHeadersOnError
            })(ctx, next);
          }

          await next();
        }
      );

      cb();
    }
  };
};
<commit_msg>Fix so you can choose multiple domains for the cors<commit_after>'use strict';

/**
 * Module dependencies
 */

/**
 * CORS hook
 */

const defaults = require('./defaults.json');

module.exports = strapi => {
  return {
    /**
     * Initialize the hook
     */

    initialize: function(cb) {
      strapi.app.use(
        async (ctx, next) => {
          if (ctx.request.admin) {
            return strapi.koaMiddlewares.kcors({
              origin: '*',
              exposeHeaders: defaults.cors.expose,
              maxAge: defaults.cors.maxAge,
              credentials: defaults.cors.credentials,
              allowMethods: defaults.cors.methods,
              allowHeaders: defaults.cors.headers,
              keepHeadersOnError: defaults.cors.keepHeadersOnError
            })(ctx, next);
          } else if (strapi.config.currentEnvironment.security.cors.enabled) {
            return strapi.koaMiddlewares.kcors({
              origin:function(ctx) {
                const whitelist =strapi.config.middleware.settings.cors.origin.split(',');
                const requestOrigin = ctx.accept.headers.origin;
                if (!whitelist.includes(requestOrigin)) {
                        return ctx.throw(`  ${requestOrigin} is not a valid origin`);
                }
                return requestOrigin;
             },
              exposeHeaders: strapi.config.middleware.settings.cors.expose,
              maxAge: strapi.config.middleware.settings.cors.maxAge,
              credentials: strapi.config.middleware.settings.cors.credentials,
              allowMethods: strapi.config.middleware.settings.cors.methods,
              allowHeaders: strapi.config.middleware.settings.cors.headers,
              keepHeadersOnError: strapi.config.middleware.settings.cors.keepHeadersOnError
            })(ctx, next);
          }

          await next();
        }
      );

      cb();
    }
  };
};
<|endoftext|>


<commit_before>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');

const config = {
    entry: {
        'src/main.js': [
            'babel-polyfill',
            './src/main.js',
        ],
    },

    output: process.env.NODE_ENV === 'production'
        ? {
            path: path.resolve(__dirname, 'dist'),
            filename: '[name][chunkhash].js',
        }
        : {
            path: '/',
            filename: '[name]',
        },

    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: [
                    /(node_modules)/,
                    /(packages\/react-accessible-tooltip)/,
                ],
                use: [
                    'babel-loader',
                    'eslint-loader',
                ],
            },
            {
                test: /\.scss$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins() {
                                return [
                                    autoprefixer,
                                    cssnano,
                                ];
                            },
                        },
                    },
                    'sass-loader',
                ],
            },
            {
                test: /\.html$/,
                loader: 'html-loader',
            },
        ],
    },

    plugins: (() => {
        // Generate a root HTML file with a <script> appended to the <body> tag.
        let plugins = [
            new HtmlWebpackPlugin({
                template: 'src/index.html',
                inject: 'body',
            }),
        ];

        if (process.env.NODE_ENV === 'production') {
            // When we're not in DEV mode set some vars so React knows we're in prod.
            plugins = plugins.concat([
                new webpack.DefinePlugin({
                    'process.env': {
                        NODE_ENV: JSON.stringify('production'),
                    },
                }),
            ]);
        } else {
            // Add webpack HMR stuff when we're in DEV mode.
            plugins = plugins.concat([
                new webpack.HotModuleReplacementPlugin(),
            ]);
        }

        return plugins;
    })(),

    devtool: 'source-map',

    devServer: {
        port: 3000,
        hot: true,
    },
};

module.exports = config;
<commit_msg>Fix wepback to serve over local network<commit_after>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');

const config = {
    entry: {
        'src/main.js': ['babel-polyfill', './src/main.js'],
    },

    output:
        process.env.NODE_ENV === 'production'
            ? {
                  path: path.resolve(__dirname, 'dist'),
                  filename: '[name][chunkhash].js',
              }
            : {
                  path: '/',
                  filename: '[name]',
              },

    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: [
                    /(node_modules)/,
                    /(packages\/react-accessible-tooltip)/,
                ],
                use: ['babel-loader', 'eslint-loader'],
            },
            {
                test: /\.scss$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins() {
                                return [autoprefixer, cssnano];
                            },
                        },
                    },
                    'sass-loader',
                ],
            },
            {
                test: /\.html$/,
                loader: 'html-loader',
            },
        ],
    },

    plugins: (() => {
        // Generate a root HTML file with a <script> appended to the <body> tag.
        let plugins = [
            new HtmlWebpackPlugin({
                template: 'src/index.html',
                inject: 'body',
            }),
        ];

        if (process.env.NODE_ENV === 'production') {
            // When we're not in DEV mode set some vars so React knows we're in prod.
            plugins = plugins.concat([
                new webpack.DefinePlugin({
                    'process.env': {
                        NODE_ENV: JSON.stringify('production'),
                    },
                }),
            ]);
        } else {
            // Add webpack HMR stuff when we're in DEV mode.
            plugins = plugins.concat([
                new webpack.HotModuleReplacementPlugin(),
            ]);
        }

        return plugins;
    })(),

    devtool: 'source-map',

    devServer: {
        host: '0.0.0.0',
        port: 3000,
        hot: true,
    },
};

module.exports = config;
<|endoftext|>


<commit_before>function sortProject(changeEvent) {

    var data = {};

    // Get old and new index from event
    data.oldIndex = changeEvent.oldIndex;
    data.newIndex = changeEvent.newIndex;

    // Get filters
    data.filters = {};
    data.filters = getCurrentFilters();

    // Get project id from event item
    data.projectId = $(changeEvent.item).children('input.cb-completed').val();

    console.log(data);

    // Make AJAX call to sort

    // TODO: Function to match index with task
    // TODO: Function to update sequences on update

    // TODO: make this queue-able
}

<commit_msg>Clean up unfinished work + conflict<commit_after>function sortProject(changeEvent) {

    var data = {};

    // Get old and new index from event
    data.oldIndex = changeEvent.oldIndex;
    data.newIndex = changeEvent.newIndex;

    // Get filters
    data.filters = {};
    data.filters = getCurrentFilters();

    // Get project id from event item
    data.projectId = $(changeEvent.item).children('input.cb-completed').val();

    console.log(data);

    // Make AJAX call to sort

    // TODO: Function to match index with task
    // TODO: Function to update sequences on update

    // TODO: make this queue-able

}
<|endoftext|>


<commit_before>/*
 * Copyright 2018 Crown Copyright
 *
 * 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.
 */
import { createActions, handleActions } from 'redux-actions';

import {
  assignRandomUuids,
  updateItemInTree,
  addItemsToTree,
  deleteItemFromTree,
  moveItemsInTree,
} from 'lib/treeUtils';
import { createActionHandlerPerId } from 'lib/reduxFormUtils';

// Expression Editors
const actionCreators = createActions({
  EXPRESSION_EDITOR_CREATED: expressionId => ({
    expressionId,
  }),
  EXPRESSION_EDITOR_DESTROYED: expressionId => ({
    expressionId,
  }),
  EXPRESSION_SET_EDITABLE_BY_USER: (expressionId, isEditableUserSet) => ({
    expressionId,
    isEditableUserSet,
  }),
  EXPRESSION_CHANGED: (expressionId, expression) => ({
    expressionId,
    expression,
  }),
  EXPRESSION_TERM_ADDED: (expressionId, operatorId) => ({
    expressionId,
    operatorId,
  }),
  EXPRESSION_OPERATOR_ADDED: (expressionId, operatorId) => ({ expressionId, operatorId }),
  EXPRESSION_ITEM_UPDATED: (expressionId, itemId, updates) => ({ expressionId, itemId, updates }),
  EXPRESSION_ITEM_DELETED: (expressionId, itemId) => ({ expressionId, itemId }),
  EXPRESSION_ITEM_MOVED: (expressionId, itemToMove, destination) => ({
    expressionId,
    itemToMove,
    destination,
  }),
});

const NEW_TERM = {
  type: 'term',
  condition: 'EQUALS',
  enabled: true,
};

const NEW_OPERATOR = {
  type: 'operator',
  op: 'AND',
  enabled: true,
  children: [],
};

const defaultStatePerExpression = {
  pendingDeletionOperatorId: undefined,
  expression: NEW_OPERATOR,
};

// expressions, keyed on ID, there may be several expressions on a page
const defaultState = {};

/**
 * These constants and functions are used to generate Doc Ref pickerId values
 * that can carry the Dictionary choices for expression terms.
 * The Expression ID and the Term UUID must be carried inside the picker ID.
 */
const EXPRESSION_PREFIX = 'EXP';
const PICKER_DELIM = '_';

/**
 * Given the value of a docRef pickerId. Attempts to parse out the expression ID and term UUID.
 * Looks for the format composed in the join function below.
 * @param {string} value May or may not be a value generated by the joinDictionaryTermId function below
 * @return {object}
 *  {
 *      isExpressionBased : {boolean} to indicate that the input value is a dictionary term value
 *      expressionId : the parsed expression ID. Will be populated if isExpressionBased === true
 *      termUuid : the parsed term UUID. Will be populated if isExpressionBased === true
 *  }
 */
const splitDictionaryTermId = (value) => {
  const p = value.split(PICKER_DELIM);
  let isExpressionBased = false;
  let expressionId = null;
  let termUuid = null;
  if (p.length === 3 && p[0] === EXPRESSION_PREFIX) {
    isExpressionBased = true;
    expressionId = p[1];
    termUuid = p[2];
  }
  return {
    isExpressionBased,
    expressionId,
    termUuid,
  };
};

/**
 * Create the combined picker ID with the appropriate PREFIX and DELIMTER
 * that allow for unambiguous detection in the splitter function.
 *
 * @param {string} expressionId The ID of the expression to which this picker belong
 * @param {string} termUuid The UUID of the term that the picker is being used to pick a value for.
 */
const joinDictionaryTermId = (expressionId, termUuid) =>
  EXPRESSION_PREFIX + PICKER_DELIM + expressionId + PICKER_DELIM + termUuid;

const getCurrentExpression = (state, action) =>
  (state[action.payload.expressionId] ? state[action.payload.expressionId].expression : {});

const byExpressionId = createActionHandlerPerId(
  ({ payload: expressionId }) => expressionId,
  defaultStatePerExpression,
);

const reducer = handleActions(
  {
    // Expression Changed
    EXPRESSION_CHANGED: byExpressionId((state, action) => ({
      expression: assignRandomUuids(action.payload.expression),
    })),

    // Expression Term Added
    EXPRESSION_TERM_ADDED: byExpressionId((state, action) => ({
      expression: addItemsToTree(getCurrentExpression(state, action), action.payload.operatorId, [
        NEW_TERM,
      ]),
    })),

    // Expression Operator Added
    EXPRESSION_OPERATOR_ADDED: byExpressionId((state, action) => ({
      expression: addItemsToTree(getCurrentExpression(state, action), action.payload.operatorId, [
        NEW_OPERATOR,
      ]),
    })),

    // Expression Term Updated
    EXPRESSION_ITEM_UPDATED: byExpressionId((state, action) => ({
      expression: updateItemInTree(
        getCurrentExpression(state, action),
        action.payload.itemId,
        action.payload.updates,
      ),
    })),

    // Expression Item Deleted
    EXPRESSION_ITEM_DELETED: byExpressionId((state, action) => ({
      expression: deleteItemFromTree(getCurrentExpression(state, action), action.payload.itemId),
    })),

    // Expression Item Moved
    EXPRESSION_ITEM_MOVED: byExpressionId((state, action) => ({
      expression: moveItemsInTree(getCurrentExpression(state, action), action.payload.destination, [
        action.payload.itemToMove,
      ]),
    })),
  },
  defaultState,
);

export { actionCreators, reducer, joinDictionaryTermId };
<commit_msg>Fix reference to expressionId<commit_after>/*
 * Copyright 2018 Crown Copyright
 *
 * 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.
 */
import { createActions, handleActions } from 'redux-actions';

import {
  assignRandomUuids,
  updateItemInTree,
  addItemsToTree,
  deleteItemFromTree,
  moveItemsInTree,
} from 'lib/treeUtils';
import { createActionHandlerPerId } from 'lib/reduxFormUtils';

// Expression Editors
const actionCreators = createActions({
  EXPRESSION_EDITOR_CREATED: expressionId => ({
    expressionId,
  }),
  EXPRESSION_EDITOR_DESTROYED: expressionId => ({
    expressionId,
  }),
  EXPRESSION_SET_EDITABLE_BY_USER: (expressionId, isEditableUserSet) => ({
    expressionId,
    isEditableUserSet,
  }),
  EXPRESSION_CHANGED: (expressionId, expression) => ({
    expressionId,
    expression,
  }),
  EXPRESSION_TERM_ADDED: (expressionId, operatorId) => ({
    expressionId,
    operatorId,
  }),
  EXPRESSION_OPERATOR_ADDED: (expressionId, operatorId) => ({ expressionId, operatorId }),
  EXPRESSION_ITEM_UPDATED: (expressionId, itemId, updates) => ({ expressionId, itemId, updates }),
  EXPRESSION_ITEM_DELETED: (expressionId, itemId) => ({ expressionId, itemId }),
  EXPRESSION_ITEM_MOVED: (expressionId, itemToMove, destination) => ({
    expressionId,
    itemToMove,
    destination,
  }),
});

const NEW_TERM = {
  type: 'term',
  condition: 'EQUALS',
  enabled: true,
};

const NEW_OPERATOR = {
  type: 'operator',
  op: 'AND',
  enabled: true,
  children: [],
};

const defaultStatePerExpression = {
  pendingDeletionOperatorId: undefined,
  expression: NEW_OPERATOR,
};

// expressions, keyed on ID, there may be several expressions on a page
const defaultState = {};

/**
 * These constants and functions are used to generate Doc Ref pickerId values
 * that can carry the Dictionary choices for expression terms.
 * The Expression ID and the Term UUID must be carried inside the picker ID.
 */
const EXPRESSION_PREFIX = 'EXP';
const PICKER_DELIM = '_';

/**
 * Given the value of a docRef pickerId. Attempts to parse out the expression ID and term UUID.
 * Looks for the format composed in the join function below.
 * @param {string} value May or may not be a value generated by the joinDictionaryTermId function below
 * @return {object}
 *  {
 *      isExpressionBased : {boolean} to indicate that the input value is a dictionary term value
 *      expressionId : the parsed expression ID. Will be populated if isExpressionBased === true
 *      termUuid : the parsed term UUID. Will be populated if isExpressionBased === true
 *  }
 */
const splitDictionaryTermId = (value) => {
  const p = value.split(PICKER_DELIM);
  let isExpressionBased = false;
  let expressionId = null;
  let termUuid = null;
  if (p.length === 3 && p[0] === EXPRESSION_PREFIX) {
    isExpressionBased = true;
    expressionId = p[1];
    termUuid = p[2];
  }
  return {
    isExpressionBased,
    expressionId,
    termUuid,
  };
};

/**
 * Create the combined picker ID with the appropriate PREFIX and DELIMTER
 * that allow for unambiguous detection in the splitter function.
 *
 * @param {string} expressionId The ID of the expression to which this picker belong
 * @param {string} termUuid The UUID of the term that the picker is being used to pick a value for.
 */
const joinDictionaryTermId = (expressionId, termUuid) =>
  EXPRESSION_PREFIX + PICKER_DELIM + expressionId + PICKER_DELIM + termUuid;

const getCurrentExpression = (state, action) =>
  (state[action.payload.expressionId] ? state[action.payload.expressionId].expression : {});

const byExpressionId = createActionHandlerPerId(
  ({ payload }) => payload.expressionId,
  defaultStatePerExpression,
);

const reducer = handleActions(
  {
    // Expression Changed
    EXPRESSION_CHANGED: byExpressionId((state, action) => ({
      expression: assignRandomUuids(action.payload.expression),
    })),

    // Expression Term Added
    EXPRESSION_TERM_ADDED: byExpressionId((state, action) => ({
      expression: addItemsToTree(getCurrentExpression(state, action), action.payload.operatorId, [
        NEW_TERM,
      ]),
    })),

    // Expression Operator Added
    EXPRESSION_OPERATOR_ADDED: byExpressionId((state, action) => ({
      expression: addItemsToTree(getCurrentExpression(state, action), action.payload.operatorId, [
        NEW_OPERATOR,
      ]),
    })),

    // Expression Term Updated
    EXPRESSION_ITEM_UPDATED: byExpressionId((state, action) => ({
      expression: updateItemInTree(
        getCurrentExpression(state, action),
        action.payload.itemId,
        action.payload.updates,
      ),
    })),

    // Expression Item Deleted
    EXPRESSION_ITEM_DELETED: byExpressionId((state, action) => ({
      expression: deleteItemFromTree(getCurrentExpression(state, action), action.payload.itemId),
    })),

    // Expression Item Moved
    EXPRESSION_ITEM_MOVED: byExpressionId((state, action) => ({
      expression: moveItemsInTree(getCurrentExpression(state, action), action.payload.destination, [
        action.payload.itemToMove,
      ]),
    })),
  },
  defaultState,
);

export { actionCreators, reducer, joinDictionaryTermId };
<|endoftext|>