<commit_before>'use strict';
/**
 * todo: chart height as option
 *
 */
var $ = require('jquery'),
	utils = require('./utils.js'),
	yUtils = require('yasgui-utils');

var root = module.exports = function(yasr){

	var options = $.extend(true, {}, root.defaults);
	var id = yasr.container.closest('[id]').attr('id');

	var editor = null;

	var initEditor = function(callback) {
		var google = require('google');
		editor = new google.visualization.ChartEditor();
		google.visualization.events.addListener(editor, 'ok', function(){
				var chartWrapper, tmp;
				chartWrapper = editor.getChartWrapper();
				tmp = chartWrapper.getDataTable();
				chartWrapper.setDataTable(null);
				//ugly: need to parse json string to json obj again, as google chart does not provide access to object directly
				options.chartConfig = JSON.parse(chartWrapper.toJSON());
				//remove container ID though, for portability
				if (options.chartConfig.containerId) delete options.chartConfig['containerId'];
				yasr.store();
				chartWrapper.setDataTable(tmp);
				chartWrapper.setOption("width", options.width);
				chartWrapper.setOption("height", options.height);
				chartWrapper.draw();
				yasr.updateHeader();
			});
			if (callback) callback();
	};

	return {
		name: "Google Chart",
		hideFromSelection: false,
		priority: 7,
		options: options,
		getPersistentSettings: function() {
			return {
				chartConfig: options.chartConfig,
				motionChartState: options.motionChartState
			}
		},
		setPersistentSettings: function(persSettings) {
			if (persSettings['chartConfig']) options.chartConfig = persSettings['chartConfig'];
			if (persSettings['motionChartState']) options.motionChartState = persSettings['motionChartState'];
		},
		canHandleResults: function(yasr){
			var results, variables;
			return (results = yasr.results) != null && (variables = results.getVariables()) && variables.length > 0;
		},
		getDownloadInfo: function() {
			if (!yasr.results) return null;
			var svgEl = yasr.resultsContainer.find('svg');
			if (svgEl.length > 0) {
				return {
					getContent: function(){
						if (svgEl[0].outerHTML) {
							return svgEl[0].outerHTML;
						} else {
							//outerHTML not supported. use workaround
							return $('
').append(svgEl.clone()).html();
						}
					},
					filename: "queryResults.svg",
					contentType: "image/svg+xml",
					buttonTitle: "Download SVG Image"
				};
			}
			//ok, not a svg. is it a table?
			var $table = yasr.resultsContainer.find('.google-visualization-table-table');
			if ($table.length > 0) {
				return {
					getContent: function(){
						return $table.tableToCsv();
					},
					filename: "queryResults.csv",
					contentType: "text/csv",
					buttonTitle: "Download as CSV"
				};
			}
		},
		getEmbedHtml: function() {
			if (!yasr.results) return null;

			var svgEl = yasr.resultsContainer.find('svg')
				.clone()//create clone, as we'd like to remove height/width attributes
				.removeAttr('height').removeAttr('width')
				.css('height', '').css('width','');
			if (svgEl.length == 0) return null;

			var htmlString = svgEl[0].outerHTML;
			if (!htmlString) {
				//outerHTML not supported. use workaround
				htmlString = $('
').append(svgEl.clone()).html();
			}
			//wrap in div, so users can more easily tune width/height
			//don't use jquery, so we can easily influence indentation
			return '
\n' + htmlString + '\n
';
		},
		draw: function(){
			var doDraw = function () {
				//clear previous results (if any)
				yasr.resultsContainer.empty();
				var wrapperId = id + '_gchartWrapper';
				var wrapper = null;

				yasr.resultsContainer.append(
					$('<button>', {class: 'openGchartBtn yasr_btn'})
						.text('Chart Config')
						.click(function() {
							editor.openDialog(wrapper);
						})
				).append(
					$('
', {id: wrapperId, class: 'gchartWrapper'})
				);
				var dataTable = new google.visualization.DataTable();
				var jsonResults = yasr.results.getAsJson();

				jsonResults.head.vars.forEach(function(variable) {
					var type = 'string';
					try {
						type = utils.getGoogleTypeForBindings(jsonResults.results.bindings, variable);
					} catch(e) {
						if (e instanceof require('./exceptions.js').GoogleTypeException) {
							yasr.warn(e.toHtml())
						} else {
							throw e;
						}
					}
					dataTable.addColumn(type, variable);
				});
				var usedPrefixes = null;
				if (yasr.options.getUsedPrefixes) {
					usedPrefixes = (typeof yasr.options.getUsedPrefixes == "function"? yasr.options.getUsedPrefixes(yasr):  yasr.options.getUsedPrefixes);
				}
				jsonResults.results.bindings.forEach(function(binding) {
					var row = [];
					jsonResults.head.vars.forEach(function(variable, columnId) {
						row.push(utils.castGoogleType(binding[variable], usedPrefixes, dataTable.getColumnType(columnId)));
					})
					dataTable.addRow(row);
				});

				if (options.chartConfig && options.chartConfig.chartType) {
					options.chartConfig.containerId = wrapperId;
					wrapper = new google.visualization.ChartWrapper(options.chartConfig);
					if (wrapper.getChartType() === "MotionChart" && options.motionChartState) {
						wrapper.setOption("state", options.motionChartState);
						google.visualization.events.addListener(wrapper, 'ready', function(){
							var motionChart;
							motionChart = wrapper.getChart();
							google.visualization.events.addListener(motionChart, 'statechange', function(){
								options.motionChartState = motionChart.getState();
								yasr.store();
							});
						});
					}
					wrapper.setDataTable(dataTable);
				} else {
					wrapper = new google.visualization.ChartWrapper({
						chartType: 'Table',
						dataTable: dataTable,
						containerId: wrapperId
					});
				}
				wrapper.setOption("width", options.width);
				wrapper.setOption("height", options.height);
				wrapper.draw();
				google.visualization.events.addListener(wrapper, 'ready', yasr.updateHeader);
			}

			if (!require('google') || !require('google').visualization || !editor) {
				require('./gChartLoader.js')
					.on('done', function() {
						initEditor();
						doDraw();
					})
					.on('error', function() {
						//TODO: disable or something?
					})
					.googleLoad();
			} else {
				//everything (editor as well) is already initialized
				doDraw();
			}
		}
	};
};
root.defaults = {
	height: "100%",
	width: "100%",
	persistencyId: 'gchart',
	chartConfig: null,
	motionChartState: null
};

function deepEq$(x, y, type){
	var toString = {}.toString, hasOwnProperty = {}.hasOwnProperty,
	    has = function (obj, key) { return hasOwnProperty.call(obj, key); };
  var first = true;
  return eq(x, y, []);
  function eq(a, b, stack) {
    var className, length, size, result, alength, blength, r, key, ref, sizeB;
    if (a == null || b == null) { return a === b; }
    if (a.__placeholder__ || b.__placeholder__) { return true; }
    if (a === b) { return a !== 0 || 1 / a == 1 / b; }
    className = toString.call(a);
    if (toString.call(b) != className) { return false; }
    switch (className) {
      case '[object String]': return a == String(b);
      case '[object Number]':
        return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
      case '[object Date]':
      case '[object Boolean]':
        return +a == +b;
      case '[object RegExp]':
        return a.source == b.source &&
               a.global == b.global &&
               a.multiline == b.multiline &&
               a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != 'object' || typeof b != 'object') { return false; }
    length = stack.length;
    while (length--) { if (stack[length] == a) { return true; } }
    stack.push(a);
    size = 0;
    result = true;
    if (className == '[object Array]') {
      alength = a.length;
      blength = b.length;
      if (first) {
        switch (type) {
        case '===': result = alength === blength; break;
        case '<==': result = alength <= blength; break;
        case '<<=': result = alength < blength; break;
        }
        size = alength;
        first = false;
      } else {
        result = alength === blength;
        size = alength;
      }
      if (result) {
        while (size--) {
          if (!(result = size in a == size in b && eq(a[size], b[size], stack))){ break; }
        }
      }
    } else {
      if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) {
        return false;
      }
      for (key in a) {
        if (has(a, key)) {
          size++;
          if (!(result = has(b, key) && eq(a[key], b[key], stack))) { break; }
        }
      }
      if (result) {
        sizeB = 0;
        for (key in b) {
          if (has(b, key)) { ++sizeB; }
        }
        if (first) {
          if (type === '<<=') {
            result = size < sizeB;
          } else if (type === '<==') {
            result = size <= sizeB
          } else {
            result = size === sizeB;
          }
        } else {
          first = false;
          result = size === sizeB;
        }
      }
    }
    stack.pop();
    return result;
  }
}<commit_msg>Fix google chart plugin configuration persistence<commit_after>'use strict';
/**
 * todo: chart height as option
 *
 */
var $ = require('jquery'),
	utils = require('./utils.js'),
	yUtils = require('yasgui-utils');

var root = module.exports = function(yasr){

	var options = $.extend(true, {}, root.defaults);
	var id = yasr.container.closest('[id]').attr('id');

	var chartWrapper = null;
	var editor = null;

	var initEditor = function(callback) {
		var google = require('google');
		editor = new google.visualization.ChartEditor();
		google.visualization.events.addListener(editor, 'ok', function(){
				var tmp;
				chartWrapper = editor.getChartWrapper();
				tmp = chartWrapper.getDataTable();
				chartWrapper.setDataTable(null);
				//ugly: need to parse json string to json obj again, as google chart does not provide access to object directly
				options.chartConfig = JSON.parse(chartWrapper.toJSON());
				//remove container ID though, for portability
				if (options.chartConfig.containerId) delete options.chartConfig['containerId'];
				yasr.store();
				chartWrapper.setDataTable(tmp);
				chartWrapper.setOption("width", options.width);
				chartWrapper.setOption("height", options.height);
				chartWrapper.draw();
				yasr.updateHeader();
			});
			if (callback) callback();
	};

	return {
		name: "Google Chart",
		hideFromSelection: false,
		priority: 7,
		options: options,
		getPersistentSettings: function() {
			return {
				chartConfig: options.chartConfig,
				motionChartState: options.motionChartState
			}
		},
		setPersistentSettings: function(persSettings) {
			if (persSettings['chartConfig']) options.chartConfig = persSettings['chartConfig'];
			if (persSettings['motionChartState']) options.motionChartState = persSettings['motionChartState'];
		},
		canHandleResults: function(yasr){
			var results, variables;
			return (results = yasr.results) != null && (variables = results.getVariables()) && variables.length > 0;
		},
		getDownloadInfo: function() {
			if (!yasr.results) return null;
			var svgEl = yasr.resultsContainer.find('svg');
			if (svgEl.length > 0) {
				return {
					getContent: function(){
						if (svgEl[0].outerHTML) {
							return svgEl[0].outerHTML;
						} else {
							//outerHTML not supported. use workaround
							return $('
').append(svgEl.clone()).html();
						}
					},
					filename: "queryResults.svg",
					contentType: "image/svg+xml",
					buttonTitle: "Download SVG Image"
				};
			}
			//ok, not a svg. is it a table?
			var $table = yasr.resultsContainer.find('.google-visualization-table-table');
			if ($table.length > 0) {
				return {
					getContent: function(){
						return $table.tableToCsv();
					},
					filename: "queryResults.csv",
					contentType: "text/csv",
					buttonTitle: "Download as CSV"
				};
			}
		},
		getEmbedHtml: function() {
			if (!yasr.results) return null;

			var svgEl = yasr.resultsContainer.find('svg')
				.clone()//create clone, as we'd like to remove height/width attributes
				.removeAttr('height').removeAttr('width')
				.css('height', '').css('width','');
			if (svgEl.length == 0) return null;

			var htmlString = svgEl[0].outerHTML;
			if (!htmlString) {
				//outerHTML not supported. use workaround
				htmlString = $('
').append(svgEl.clone()).html();
			}
			//wrap in div, so users can more easily tune width/height
			//don't use jquery, so we can easily influence indentation
			return '
\n' + htmlString + '\n
';
		},
		draw: function(){
			var doDraw = function () {
				//clear previous results (if any)
				yasr.resultsContainer.empty();
				var wrapperId = id + '_gchartWrapper';

				yasr.resultsContainer.append(
					$('<button>', {class: 'openGchartBtn yasr_btn'})
						.text('Chart Config')
						.click(function() {
							editor.openDialog(chartWrapper);
						})
				).append(
					$('
', {id: wrapperId, class: 'gchartWrapper'})
				);
				var dataTable = new google.visualization.DataTable();
				var jsonResults = yasr.results.getAsJson();

				jsonResults.head.vars.forEach(function(variable) {
					var type = 'string';
					try {
						type = utils.getGoogleTypeForBindings(jsonResults.results.bindings, variable);
					} catch(e) {
						if (e instanceof require('./exceptions.js').GoogleTypeException) {
							yasr.warn(e.toHtml())
						} else {
							throw e;
						}
					}
					dataTable.addColumn(type, variable);
				});
				var usedPrefixes = null;
				if (yasr.options.getUsedPrefixes) {
					usedPrefixes = (typeof yasr.options.getUsedPrefixes == "function"? yasr.options.getUsedPrefixes(yasr):  yasr.options.getUsedPrefixes);
				}
				jsonResults.results.bindings.forEach(function(binding) {
					var row = [];
					jsonResults.head.vars.forEach(function(variable, columnId) {
						row.push(utils.castGoogleType(binding[variable], usedPrefixes, dataTable.getColumnType(columnId)));
					})
					dataTable.addRow(row);
				});

				if (options.chartConfig && options.chartConfig.chartType) {
					options.chartConfig.containerId = wrapperId;
					chartWrapper = new google.visualization.ChartWrapper(options.chartConfig);
					if (chartWrapper.getChartType() === "MotionChart" && options.motionChartState) {
						chartWrapper.setOption("state", options.motionChartState);
						google.visualization.events.addListener(chartWrapper, 'ready', function(){
							var motionChart;
							motionChart = chartWrapper.getChart();
							google.visualization.events.addListener(motionChart, 'statechange', function(){
								options.motionChartState = motionChart.getState();
								yasr.store();
							});
						});
					}
					chartWrapper.setDataTable(dataTable);
				} else {
					chartWrapper = new google.visualization.ChartWrapper({
						chartType: 'Table',
						dataTable: dataTable,
						containerId: wrapperId
					});
				}
				chartWrapper.setOption("width", options.width);
				chartWrapper.setOption("height", options.height);
				chartWrapper.draw();
				google.visualization.events.addListener(chartWrapper, 'ready', yasr.updateHeader);
			}

			if (!require('google') || !require('google').visualization || !editor) {
				require('./gChartLoader.js')
					.on('done', function() {
						initEditor();
						doDraw();
					})
					.on('error', function() {
						//TODO: disable or something?
					})
					.googleLoad();
			} else {
				//everything (editor as well) is already initialized
				doDraw();
			}
		}
	};
};
root.defaults = {
	height: "100%",
	width: "100%",
	persistencyId: 'gchart',
	chartConfig: null,
	motionChartState: null
};

function deepEq$(x, y, type){
	var toString = {}.toString, hasOwnProperty = {}.hasOwnProperty,
	    has = function (obj, key) { return hasOwnProperty.call(obj, key); };
  var first = true;
  return eq(x, y, []);
  function eq(a, b, stack) {
    var className, length, size, result, alength, blength, r, key, ref, sizeB;
    if (a == null || b == null) { return a === b; }
    if (a.__placeholder__ || b.__placeholder__) { return true; }
    if (a === b) { return a !== 0 || 1 / a == 1 / b; }
    className = toString.call(a);
    if (toString.call(b) != className) { return false; }
    switch (className) {
      case '[object String]': return a == String(b);
      case '[object Number]':
        return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
      case '[object Date]':
      case '[object Boolean]':
        return +a == +b;
      case '[object RegExp]':
        return a.source == b.source &&
               a.global == b.global &&
               a.multiline == b.multiline &&
               a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != 'object' || typeof b != 'object') { return false; }
    length = stack.length;
    while (length--) { if (stack[length] == a) { return true; } }
    stack.push(a);
    size = 0;
    result = true;
    if (className == '[object Array]') {
      alength = a.length;
      blength = b.length;
      if (first) {
        switch (type) {
        case '===': result = alength === blength; break;
        case '<==': result = alength <= blength; break;
        case '<<=': result = alength < blength; break;
        }
        size = alength;
        first = false;
      } else {
        result = alength === blength;
        size = alength;
      }
      if (result) {
        while (size--) {
          if (!(result = size in a == size in b && eq(a[size], b[size], stack))){ break; }
        }
      }
    } else {
      if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) {
        return false;
      }
      for (key in a) {
        if (has(a, key)) {
          size++;
          if (!(result = has(b, key) && eq(a[key], b[key], stack))) { break; }
        }
      }
      if (result) {
        sizeB = 0;
        for (key in b) {
          if (has(b, key)) { ++sizeB; }
        }
        if (first) {
          if (type === '<<=') {
            result = size < sizeB;
          } else if (type === '<==') {
            result = size <= sizeB
          } else {
            result = size === sizeB;
          }
        } else {
          first = false;
          result = size === sizeB;
        }
      }
    }
    stack.pop();
    return result;
  }
}
<|endoftext|>


<commit_before>ZiggeoSdk = require("../index.js");
var app_token = process.argv[2];
var app_private = process.argv[3];

ZiggeoSdk.init (app_token, app_private);
var search_arguments = {
	limit: 50
}
ZiggeoSdk.EffectProfiles.index (search_arguments, function(effects){
	console.log(effects);
});
<commit_msg>change effectprofile get to do it's proper function (previously it's indexing)<commit_after>ZiggeoSdk = require("../index.js");
var app_token = process.argv[2];
var app_private = process.argv[3];
var effectprofile_token = process.argv[5];

ZiggeoSdk.init (app_token, app_private);
var search_arguments = {
	limit: 50
}
ZiggeoSdk.EffectProfiles.get (search_arguments, function(effects){
	console.log(effects);
});
<|endoftext|>


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

const yargs = require('yargs');

yargs
  .usage('react-power <cmd> [args]')
  .command(
    'dev',
    'Run in development environment.',
    () => {},
    argv => {
      require('../lib/dev');
    }
  )
  .command(
    'build',
    'Run in production environment.',
    yargs => yargs.option('watch', {
      alias: 'w',
      default: false
    }),
    argv => {
      process._argv = argv
      require('../lib/clean');
      require('../lib/build');
    }
  )
  .command(
    'clean',
    'Clean the work directory.',
    () => {},
    argv => {
      require('../lib/clean');
    }
  )
  .command(
    '*',
    'The default command.',
    () => {},
    argv => {
    console.log('Command not found. Run `react-power --help` for usage.')
  })
  .help().argv;
<commit_msg>refactor: bin entry<commit_after>#!/usr/bin/env node

const yargs = require('yargs')

yargs
  .usage('react-power <cmd> [args]')
  .command(
    'dev',
    'Run in development environment.',
    () => {},
    argv => {
      require('../lib/dev')
    }
  )
  .command(
    'build',
    'Run in production environment.',
    yargs =>
      yargs.option('watch', {
        alias: 'w',
        default: false
      }),
    argv => {
      process._argv = argv
      require('../lib/clean')
      require('../lib/build')
    }
  )
  .command(
    'clean',
    'Clean the work directory.',
    () => {},
    argv => {
      require('../lib/clean')
    }
  )
  .command(
    '*',
    'The default command.',
    () => {},
    argv => {
      console.log('Command not found. Run `react-power --help` for usage.')
    }
  )
  .help().argv
<|endoftext|>


<commit_before>/*
 * Copyright (c) Microsoft Open Technologies, Inc.  All rights reserved.
 * Microsoft Open Technologies would like to thank its contributors, a list
 * of whom are at http://rx.codeplex.com/wikipage?title=Contributors.
 *
 * 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 debugFactory from 'debug';
import { noop, Observable, throwError } from 'rxjs';
import { map } from 'rxjs/operators';

import { isGoodXHRStatus } from './';

const debug = debugFactory('fcc:ajax$');
const root = typeof window !== 'undefined' ? window : {};

// Gets the proper XMLHttpRequest for support for older IE
function getXMLHttpRequest() {
  if (root.XMLHttpRequest) {
    return new root.XMLHttpRequest();
  } else {
    var progId;
    try {
      var progIds = [
        'Msxml2.XMLHTTP',
        'Microsoft.XMLHTTP',
        'Msxml2.XMLHTTP.4.0'
      ];
      for (var i = 0; i < 3; i++) {
        try {
          progId = progIds[i];
          if (new root.ActiveXObject(progId)) {
            break;
          }
        } catch (e) {
          // purposely do nothing
          noop.noop(e);
        }
      }
      return new root.ActiveXObject(progId);
    } catch (e) {
      throw new Error('XMLHttpRequest is not supported by your browser');
    }
  }
}

// Get CORS support even for older IE
function getCORSRequest() {
  var xhr = new root.XMLHttpRequest();
  if ('withCredentials' in xhr) {
    return xhr;
  } else if (root.XDomainRequest) {
    return new root.XDomainRequest();
  } else {
    throw new Error('CORS is not supported by your browser');
  }
}

function parseXhrResponse(responseType, xhr) {
  switch (responseType) {
    case 'json': {
      if (isGoodXHRStatus(xhr.status)) {
        if ('response' in xhr) {
          return xhr.responseType
            ? xhr.response
            : JSON.parse(xhr.response || xhr.responseText || 'null');
        } else {
          return JSON.parse(xhr.responseText || 'null');
        }
      } else {
        return null;
      }
    }
    case 'xml':
      return xhr.responseXML;
    case 'text':
    default:
      return 'response' in xhr ? xhr.response : xhr.responseText;
  }
}

function normalizeAjaxSuccessEvent(e, xhr, settings) {
  return {
    response: parseXhrResponse(settings.responseType || xhr.responseType, xhr),
    status: xhr.status,
    responseType: xhr.responseType,
    xhr: xhr,
    originalEvent: e
  };
}

function createNormalizeAjaxErrorEvent(options) {
  let _body = {};
  let _endpoint = '';
  if (typeof options === 'string') {
    _endpoint = options;
  } else {
    _body = options.body;
    _endpoint = options.url;
  }
  return (e, xhr, type) => ({
    _body,
    _endpoint,
    type: type,
    status: xhr.status,
    xhr: xhr,
    originalEvent: e
  });
}
/*
 * Creates an observable for an Ajax request with either a settings object
 * with url, headers, etc or a string for a URL.
 *
 * @example
 *   source = Rx.DOM.ajax('/products');
 *   source = Rx.DOM.ajax( url: 'products', method: 'GET' });
 *
 * interface Options {
 *   url: String, // URL of the request
 *   body?: Object, // The body of the request
 *   method? = 'GET' : 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
 *   async? = true: Boolean, // Whether the request is async
 *   headers?: Object, // optional headers
 *   crossDomain?: true // if a cross domain request, else false
 * }
 *
 * ajax$(url?: String, options: Options) => Observable[XMLHttpRequest]
 */
export function ajax$(options) {
  var settings = {
    method: 'GET',
    crossDomain: false,
    async: true,
    headers: {},
    responseType: 'text',
    createXHR: function() {
      return this.crossDomain ? getCORSRequest() : getXMLHttpRequest();
    },
    normalizeError: createNormalizeAjaxErrorEvent(options),
    normalizeSuccess: normalizeAjaxSuccessEvent
  };

  if (typeof options === 'string') {
    settings.url = options;
  } else {
    for (var prop in options) {
      if (hasOwnProperty.call(options, prop)) {
        settings[prop] = options[prop];
      }
    }
  }
  const { normalizeError, normalizeSuccess } = settings;

  if (!settings.crossDomain && !settings.headers['X-Requested-With']) {
    settings.headers['X-Requested-With'] = 'XMLHttpRequest';
  }
  settings.hasContent = typeof settings.body !== 'undefined';

  return new Observable.create(function(observer) {
    var isDone = false;
    var xhr;

    const throwWithMeta = err => {
      err._body = options.body || {};
      err._endpoint = options.url;
      observer.error(err);
    };

    var processResponse = function(xhr, e) {
      var status = xhr.status === 1223 ? 204 : xhr.status;
      if ((status >= 200 && status <= 300) || status === 0 || status === '') {
        try {
          observer.next(normalizeSuccess(e, xhr, settings));
          observer.complete();
        } catch (err) {
          throwWithMeta(err);
        }
      } else {
        observer.error(normalizeError(e, xhr, 'error'));
      }
      isDone = true;
    };

    try {
      xhr = settings.createXHR();
    } catch (err) {
      throwWithMeta(err);
    }

    try {
      if (settings.user) {
        xhr.open(
          settings.method,
          settings.url,
          settings.async,
          settings.user,
          settings.password
        );
      } else {
        xhr.open(settings.method, settings.url, settings.async);
      }

      var headers = settings.headers;
      for (var header in headers) {
        if (hasOwnProperty.call(headers, header)) {
          xhr.setRequestHeader(header, headers[header]);
        }
      }

      if (!xhr.upload || (!('withCredentials' in xhr) && root.XDomainRequest)) {
        xhr.onload = function(e) {
          if (settings.progressObserver) {
            settings.progressObserver.next(e);
            settings.progressObserver.complete();
          }
          processResponse(xhr, e);
        };

        if (settings.progressObserver) {
          xhr.onprogress = function(e) {
            settings.progressObserver.next(e);
          };
        }

        xhr.onerror = function(e) {
          if (settings.progressObserver) {
            settings.progressObserver.error(e);
          }
          observer.error(normalizeError(e, xhr, 'error'));
          isDone = true;
        };

        xhr.onabort = function(e) {
          if (settings.progressObserver) {
            settings.progressObserver.error(e);
          }
          observer.error(normalizeError(e, xhr, 'abort'));
          isDone = true;
        };
      } else {
        xhr.onreadystatechange = function(e) {
          if (xhr.readyState === 4) {
            processResponse(xhr, e);
          }
        };
      }

      debug('ajax$ sending content', settings.hasContent && settings.body);
      xhr.send((settings.hasContent && settings.body) || null);
    } catch (err) {
      throwWithMeta(err);
    }

    return function() {
      if (!isDone && xhr.readyState !== 4) {
        xhr.abort();
      }
    };
  });
}

// Creates an observable sequence from an Ajax POST Request with the body.
// post$(url: String, body: Object) => Observable[Any]
export function post$(url, body) {
  try {
    body = JSON.stringify(body);
  } catch (e) {
    return throwError(e);
  }

  return ajax$({ url, body, method: 'POST' });
}

// postJSON$(url: String, body: Object) => Observable[Object]
export function postJSON$(url, body) {
  try {
    body = JSON.stringify(body);
  } catch (e) {
    return throwError(e);
  }

  return ajax$({
    url,
    body,
    method: 'POST',
    responseType: 'json',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json'
    },
    normalizeError: (e, xhr) => parseXhrResponse('json', xhr)
  });
}

// Creates an observable sequence from an Ajax GET Request with the body.
// get$(url: String) => Obserable[Any]
export function get$(url) {
  return ajax$({ url: url });
}

/**
 * Creates an observable sequence from JSON from an Ajax request
 *
 * @param {String} url The URL to GET
 * @returns {Observable} The observable sequence which contains the parsed JSON
 */
// getJSON$(url: String) => Observable[Object];
export function getJSON$(url) {
  return ajax$({
    url: url,
    responseType: 'json',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json'
    },
    normalizeError: (e, xhr) => parseXhrResponse('json', xhr)
  }).pipe(map(({ response }) => response));
}
<commit_msg>chore(client): remove unused ajax util lib<commit_after><|endoftext|>


<commit_before>/**
 * Telescope permissions
 * @namespace Users.can
 */
Users.can = {};

/**
 * Permissions checks.  Return true if all is well.
 * @param {Object} user - Meteor.user()
 */
Users.can.view = function (user) {
  if (Settings.get('requireViewInvite', false)) {

    if (Meteor.isClient) {
      // on client only, default to the current user
      user = (typeof user === 'undefined') ? Meteor.user() : user;
    }

    return (!!user && (Users.is.admin(user) || Users.is.invited(user)));
  }
  return true;
};

Users.can.viewById = function (userId) {
  // if an invite is required to view, run permission check, else return true
  if (Settings.get('requireViewInvite', false)) {
    return !!userId ? Users.can.view(Meteor.users.findOne(userId)) : false;
  }
  return true;
};

Users.can.viewPendingPosts = function (user) {
  user = (typeof user === 'undefined') ? Meteor.user() : user;
  return Users.is.admin(user);
};

Users.can.viewPendingPost = function (user, post) {
  return Users.is.owner(user, post) || Users.can.viewPendingPosts(user);
};

Users.can.viewRejectedPosts = function (user) {
  user = (typeof user === 'undefined') ? Meteor.user() : user;
  return Users.is.admin(user);
};

Users.can.viewRejectedPost = function (user, post) {
  return Users.is.owner(user, post) || Users.can.viewRejectedPosts(user);
};

Users.can.post = function (user) {
  user = (typeof user === 'undefined') ? Meteor.user() : user;

  if (!user) {
    return returnError ? "no_account" : false;
  } else if (Users.is.admin(user)) {
    return true;
  } else if (Settings.get('requirePostInvite')) {
    if (user.telescope.isInvited) {
      return true;
    } else {
      return false;
    }
  } else {
    return true;
  }
};

Users.can.comment = function (user, returnError) {
  return Users.can.post(user, returnError);
};

Users.can.vote = function (user, returnError) {
  return Users.can.post(user, returnError);
};

/**
 * Check if a user can edit a document
 * @param {Object} user - The user performing the action
 * @param {Object} document - The document being edited
 */
Users.can.edit = function (user, document) {
  user = (typeof user === 'undefined') ? Meteor.user() : user;

  if (!user || !document) {
    return false;
  }

  var adminCheck = Users.is.admin(user);
  var ownerCheck = Users.is.owner(user, document);

  return adminCheck || ownerCheck;
};

Users.can.editById = function (userId, document) {
  var user = Meteor.users.findOne(userId);
  return Users.can.edit(user, document);
};

/**
 * Check if a user can submit a field
 * @param {Object} user - The user performing the action
 * @param {Object} field - The field being edited or inserted
 */
Users.can.submitField = function (user, field) {

  if (!field.editableBy || !user) {
    return false;
  }

  var adminCheck = _.contains(field.editableBy, "admin") && Users.is.admin(user); // is the field editable by admins?
  var memberCheck = _.contains(field.editableBy, "member"); // is the field editable by regular users?

  return adminCheck || memberCheck;

};

/** @function
 * Check if a user can edit a field – for now, identical to Users.can.submitField
 * @param {Object} user - The user performing the action
 * @param {Object} field - The field being edited or inserted
 */
Users.can.editField = Users.can.submitField;

Users.can.currentUserEdit = function (item) {
  return Users.can.edit(Meteor.user(), item);
};

Users.can.invite = function (user) {
  return Users.is.invited(user) || Users.is.admin(user);
};
<commit_msg>restore missing returnError arg<commit_after>/**
 * Telescope permissions
 * @namespace Users.can
 */
Users.can = {};

/**
 * Permissions checks.  Return true if all is well.
 * @param {Object} user - Meteor.user()
 */
Users.can.view = function (user) {
  if (Settings.get('requireViewInvite', false)) {

    if (Meteor.isClient) {
      // on client only, default to the current user
      user = (typeof user === 'undefined') ? Meteor.user() : user;
    }

    return (!!user && (Users.is.admin(user) || Users.is.invited(user)));
  }
  return true;
};

Users.can.viewById = function (userId) {
  // if an invite is required to view, run permission check, else return true
  if (Settings.get('requireViewInvite', false)) {
    return !!userId ? Users.can.view(Meteor.users.findOne(userId)) : false;
  }
  return true;
};

Users.can.viewPendingPosts = function (user) {
  user = (typeof user === 'undefined') ? Meteor.user() : user;
  return Users.is.admin(user);
};

Users.can.viewPendingPost = function (user, post) {
  return Users.is.owner(user, post) || Users.can.viewPendingPosts(user);
};

Users.can.viewRejectedPosts = function (user) {
  user = (typeof user === 'undefined') ? Meteor.user() : user;
  return Users.is.admin(user);
};

Users.can.viewRejectedPost = function (user, post) {
  return Users.is.owner(user, post) || Users.can.viewRejectedPosts(user);
};

Users.can.post = function (user, returnError) {
  user = (typeof user === 'undefined') ? Meteor.user() : user;

  if (!user) {
    return returnError ? "no_account" : false;
  } else if (Users.is.admin(user)) {
    return true;
  } else if (Settings.get('requirePostInvite')) {
    if (user.telescope.isInvited) {
      return true;
    } else {
      return false;
    }
  } else {
    return true;
  }
};

Users.can.comment = function (user, returnError) {
  return Users.can.post(user, returnError);
};

Users.can.vote = function (user, returnError) {
  return Users.can.post(user, returnError);
};

/**
 * Check if a user can edit a document
 * @param {Object} user - The user performing the action
 * @param {Object} document - The document being edited
 */
Users.can.edit = function (user, document) {
  user = (typeof user === 'undefined') ? Meteor.user() : user;

  if (!user || !document) {
    return false;
  }

  var adminCheck = Users.is.admin(user);
  var ownerCheck = Users.is.owner(user, document);

  return adminCheck || ownerCheck;
};

Users.can.editById = function (userId, document) {
  var user = Meteor.users.findOne(userId);
  return Users.can.edit(user, document);
};

/**
 * Check if a user can submit a field
 * @param {Object} user - The user performing the action
 * @param {Object} field - The field being edited or inserted
 */
Users.can.submitField = function (user, field) {

  if (!field.editableBy || !user) {
    return false;
  }

  var adminCheck = _.contains(field.editableBy, "admin") && Users.is.admin(user); // is the field editable by admins?
  var memberCheck = _.contains(field.editableBy, "member"); // is the field editable by regular users?

  return adminCheck || memberCheck;

};

/** @function
 * Check if a user can edit a field – for now, identical to Users.can.submitField
 * @param {Object} user - The user performing the action
 * @param {Object} field - The field being edited or inserted
 */
Users.can.editField = Users.can.submitField;

Users.can.currentUserEdit = function (item) {
  return Users.can.edit(Meteor.user(), item);
};

Users.can.invite = function (user) {
  return Users.is.invited(user) || Users.is.admin(user);
};
<|endoftext|>


<commit_before>/* global Observable */

/**
 * Jasmine test specification for Observable-JS
 */
describe('Observable-JS', function(){
	'use strict';

	var clock = {
		count	: 0,
		tick	: function(){
			return ++this.count;
		}
	};

	it('Tests creating an observable object', function(){
		Observable.create(clock);
		expect(clock.subscribe).toBeDefined();
		expect(clock.unsubscribe).toBeDefined();
		expect(clock.signal).toBeDefined();
	});

	it('Tests subscribing to an observable object', function(){
		var count = 0, message = '';
		var listener = clock.subscribe('tick');
		listener.onNext = function(tick){
			count = tick.count;
		};
		listener.onError = function(error){
			message = error.message;
		};

		clock.signal(Observable.NEXT, 'tick', { count : clock.tick() });
		clock.signal(Observable.ERROR, 'tick', { message : 'Error!' });
		clock.signal(Observable.NEXT, 'tock', { message : 'Never Used'});
		expect(count).toEqual(clock.count);
		expect(message).toEqual('Error!');
	});

	it('Tests signaling using different streams', function(){
		var count = 0, message = '', complete = false;
		var	listener = clock.subscribe('tock', {
			onNext: function(tick){
				count = tick.count;
			}
		});
		listener.onError = function(error){
			message = error.message;
		};
		listener.onComplete = function(){
			complete = true;
		};

		clock.signal(Observable.NEXT, 'tock', { count : clock.tick() });
		clock.signal(Observable.ERROR, 'tock', { message : 'Error: Forgot how to count!' });
		clock.signal(Observable.COMPLETE, 'tock');

		expect(count).toEqual(clock.count);
		expect(message).toEqual('Error: Forgot how to count!');
		expect(complete).toBeTruthy();
	});

	it('Tests unsubscribing from an observer', function(){
		var count = 0;
		var listener = clock.subscribe('tick',{
			onNext: function(tick){
				count = tick.count;
			}
		});

		clock.unsubscribe(listener);
		clock.signal(Observable.NEXT, 'tick', { count : clock.tick() });
		expect(count).toBe(0);
	});

	it('Tests unsubscribing from an observer before subscribing', function(){
		expect(clock.unsubscribe({})).toBeFalsy();
		expect(clock.unsubscribe()).toBeFalsy();
		expect(clock.unsubscribe({ _signals: ['tick']})).toBeFalsy();
		expect(clock.unsubscribe({ _signals: ['none']})).toBeFalsy();
	});

	it('Tests expected errors from an observer', function(){
		var source = Observable.create({}, { data : {}});

		expect(function(){return source.subscribe('pass');}).not.toThrow();
		expect(function(){return source.subscribe(123);}).toThrow();

	});

	it('Tests target validation before signaling', function(){
		var source = Observable.create({});
		delete source._subs;
		expect(function(){return source.signal(Observable.NEXT, 'data');}).toThrow();
		delete source._signals;
		expect(function(){return source.signal(Observable.NEXT, 'data');}).toThrow();
	});

	it('Tests async signals', function(){
		var source = Observable.create({}, { data : {async : true}});
		var expected = [], actual = [];
		var signal = function(x){
			source.signal(Observable.NEXT, 'data', {value : x});
		};

		source.subscribe('data', {
			onNext : function(data){
				actual.push(data.value);
			}
		});

		for(var i = 0; i < 100; i++){
			expected.push(i);
			setTimeout(signal.bind(null, i), i);
		}

		// Wait at least 300ms before checking the output so that all async events
		// have completed
		setTimeout(function(){
			expect(actual).toEqual(expected);
		}, 300);
	});

});
<commit_msg>Added test case for register<commit_after>/* global Observable */

/**
 * Jasmine test specification for Observable-JS
 */
describe('Observable-JS', function(){
	'use strict';

	var clock = {
		count	: 0,
		tick	: function(){
			return ++this.count;
		}
	};

	it('Tests creating an observable object', function(){
		Observable.create(clock);
		expect(clock.subscribe).toBeDefined();
		expect(clock.unsubscribe).toBeDefined();
		expect(clock.signal).toBeDefined();
	});

	it('Tests subscribing to an observable object', function(){
		var count = 0, message = '';
		var listener = clock.subscribe('tick');
		listener.onNext = function(tick){
			count = tick.count;
		};
		listener.onError = function(error){
			message = error.message;
		};

		clock.signal(Observable.NEXT, 'tick', { count : clock.tick() });
		clock.signal(Observable.ERROR, 'tick', { message : 'Error!' });
		clock.signal(Observable.NEXT, 'tock', { message : 'Never Used'});
		expect(count).toEqual(clock.count);
		expect(message).toEqual('Error!');
	});

	it('Tests signaling using different streams', function(){
		var count = 0, message = '', complete = false;
		var	listener = clock.subscribe('tock', {
			onNext: function(tick){
				count = tick.count;
			}
		});
		listener.onError = function(error){
			message = error.message;
		};
		listener.onComplete = function(){
			complete = true;
		};

		clock.signal(Observable.NEXT, 'tock', { count : clock.tick() });
		clock.signal(Observable.ERROR, 'tock', { message : 'Error: Forgot how to count!' });
		clock.signal(Observable.COMPLETE, 'tock');

		expect(count).toEqual(clock.count);
		expect(message).toEqual('Error: Forgot how to count!');
		expect(complete).toBeTruthy();
	});

	it('Tests unsubscribing from an observer', function(){
		var count = 0;
		var listener = clock.subscribe('tick',{
			onNext: function(tick){
				count = tick.count;
			}
		});

		clock.unsubscribe(listener);
		clock.signal(Observable.NEXT, 'tick', { count : clock.tick() });
		expect(count).toBe(0);
	});

	it('Tests unsubscribing from an observer before subscribing', function(){
		expect(clock.unsubscribe({})).toBeFalsy();
		expect(clock.unsubscribe()).toBeFalsy();
		expect(clock.unsubscribe({ _signals: ['tick']})).toBeFalsy();
		expect(clock.unsubscribe({ _signals: ['none']})).toBeFalsy();
	});

	it('Tests expected errors from an observer', function(){
		var source = Observable.create({}, { data : {}});

		expect(function(){return source.subscribe('pass');}).not.toThrow();
		expect(function(){return source.subscribe(123);}).toThrow();

	});

	it('Tests target validation before signaling', function(){
		var source = Observable.create({});
		delete source._subs;
		expect(function(){return source.signal(Observable.NEXT, 'data');}).toThrow();
		delete source._signals;
		expect(function(){return source.signal(Observable.NEXT, 'data');}).toThrow();
	});

	it('Tests registering a new signal to an object', function(){
		var source = Observable.create({});
		var signal = source.register('data');
		signal.async = true;

		expect(source._signals.data.async).toBe(true);

		expect(function(){return source.register(123);}).toThrow();

		delete source._subs;
		expect(function(){return source.register('hello');}).toThrow();
		delete source._signals;
		expect(function(){return source.register('goodbye');}).toThrow();
	});

	it('Tests async signals', function(){
		var source = Observable.create({}, { data : {async : true}});
		var expected = [], actual = [];
		var signal = function(x){
			source.signal(Observable.NEXT, 'data', {value : x});
		};

		source.subscribe('data', {
			onNext : function(data){
				actual.push(data.value);
			}
		});

		for(var i = 0; i < 100; i++){
			expected.push(i);
			setTimeout(signal.bind(null, i), i);
		}

		// Wait at least 300ms before checking the output so that all async events
		// have completed
		setTimeout(function(){
			expect(actual).toEqual(expected);
		}, 300);
	});

});
<|endoftext|>


<commit_before>/* NODE MODULES */
var eventerface = require('eventerface')
    EventEmitter = require('events').EventEmitter,
    zoneProperties = require('./properties'),
    zoneEvents = require('./events'),
    servers = require('../servers');

/** MODULE INTERFACE
 *@method {function} create -
 */
module.exports = {
    create: create
};

/*----------------------------------------------------------------------------*/

/** Creates a zone object
 * @param {object} properties - The properties of the zone to be created
 * @returns {object} zone - The created zone object
 */
function create(properties) {
    var zoneNamespace = 'zone_' + properties.id,
        zone = Object.create({
            namespace: zoneNamespace
        }),
        apiNamespace = eventerface.create(),
        apiEmitter = apiNamespace.emitter(),
        localNamespace = eventerface.create(),
        zoneServers = servers.setup(zone);

    // Create event emitters in the same namespace to communicate with the module user
    Object.defineProperties(zone, {
        moduleapi: { value: apiNamespace.emitter() },
        on:     { value: apiEmitter.on },
        emit:   { value: apiEmitter.emit }
    });

    // Configure the JAMP server that will be used by the zone
    if (typeof properties.servers === 'object' && !properties.servers.jamp) {
        properties.servers.jamp = zoneServers.setup.jampServer();
    } else {
        properties.servers = {
            jamp: zoneServers.setup.jampServer()
        };
    }

    // Join the created zone namespace and define the properties of the zone object
    eventerface.find(zoneNamespace, function (zoneNamespace) {
        // Define the properties of the zone object and watch their changes with event listeners
        properties = zoneProperties.define(properties, zoneNamespace, localNamespace);
        Object.defineProperties(zone, properties);
        zoneEvents.watchProperties(zone, zoneNamespace, localNamespace.emitter());
        // Start the zone's servers and emit the 'ready' event
        zoneServers.start(function () {
            zone.moduleapi.emit('ready');
        });
    });

    return zone;
}
/*----------------------------------------------------------------------------*/<commit_msg>Cascaded the calls to start the jampAssets, web and webSocket servers<commit_after>/* NODE MODULES */
var eventerface = require('eventerface')
    EventEmitter = require('events').EventEmitter,
    zoneProperties = require('./properties'),
    zoneEvents = require('./events'),
    servers = require('../servers'),
    io = require('socket.io');

/** MODULE INTERFACE
 *@method {function} create -
 */
module.exports = {
    create: create
};

/*----------------------------------------------------------------------------*/

/** Creates a zone object
 * @param {object} properties - The properties of the zone to be created
 * @returns {object} zone - The created zone object
 */
function create(properties) {
    var zoneNamespace = 'zone_' + properties.id,
        zone = Object.create({
            namespace: zoneNamespace
        }),
        apiNamespace = eventerface.create(),
        apiEmitter = apiNamespace.emitter(),
        localNamespace = eventerface.create(),
        zoneServers = servers.setup(zone);

    // Create event emitters in the same namespace to communicate with the module user
    Object.defineProperties(zone, {
        moduleapi: { value: apiNamespace.emitter() },
        on:     { value: apiEmitter.on },
        emit:   { value: apiEmitter.emit }
    });

    // Configure the JAMP server that will be used by the zone
    if (typeof properties.servers === 'object' && !properties.servers.jamp) {
        properties.servers.jamp = zoneServers.setup.jampServer();
    } else {
        properties.servers = {
            jamp: zoneServers.setup.jampServer()
        };
    }

    // Join the created zone namespace and define the properties of the zone object
    eventerface.find(zoneNamespace, function (zoneNamespace) {
        // Define the properties of the zone object and watch their changes with event listeners
        properties = zoneProperties.define(properties, zoneNamespace, localNamespace);
        Object.defineProperties(zone, properties);
        zoneEvents.watchProperties(zone, zoneNamespace, localNamespace.emitter());
        // Start the zone's servers and emit the 'ready' event
        zoneServers.start.jampServer(function () {
            zoneServers.start.webServer(function () {
                zoneServers.start.webSockets(function () {
                    zone.moduleapi.emit('ready');
                });
            });
        });
    });

    return zone;
}
/*----------------------------------------------------------------------------*/<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | ilios calendar week', function(hooks) {
  setupRenderingTest(hooks);

  hooks.beforeEach(function() {
    this.actions = {};
    this.send = (actionName, ...args) => this.actions[actionName].apply(this, args);
  });

  test('it renders', async function(assert) {
    assert.expect(2);
    const date = new Date('2015-09-30T12:00:00');
    this.set('date', date);

    await render(hbs`<IliosCalendarWeek @date={{date}} />`);
    assert.equal(this.element.textContent.trim().search(/^Week of September/), 0);
    assert.equal(this.element.querySelectorAll('.event').length, 0);
  });

  test('clicking on a day header fires the correct events', async function(assert) {
    assert.expect(4);
    const date = new Date('2015-09-30T12:00:00');
    this.set('date', date);
    this.actions.changeDate = newDate => {
      assert.ok(newDate instanceof Date);
      assert.ok(newDate.toString().search(/Sun Sep 27/) === 0);
    };
    this.actions.changeView = newView => {
      assert.equal(newView, 'day');
    };

    await render(hbs`<IliosCalendarWeek
      @date={{date}}
      @changeDate={{action "changeDate"}}
      @changeView={{action "changeView"}}
    />`);

    const weekTitles = '.week-titles .cell';
    const sunday = `${weekTitles}:nth-of-type(2)`;

    assert.dom(sunday).hasClass('clickable');

    await click(sunday);
  });

  test('clicking on a day header does nothing when areDaysSelectable is false', async function(assert) {
    assert.expect(1);
    const date = new Date('2015-09-30T12:00:00');
    this.set('date', date);
    this.set('nothing', () => {
      assert.ok(false, 'this should never be called');
    });

    await render(hbs`<IliosCalendarWeek
      @date={{date}}
      @areDaysSelectable={{false}}
      @changeDate={{action nothing}}
      @changeView={{action nothing}}
    />`);

    const weekTitles = '.week-titles .cell';
    const sunday = `${weekTitles}:nth-of-type(2)`;

    assert.dom(sunday).hasNoClass('clickable');

    await click(sunday);
  });
});
<commit_msg>Fixup ilios-calendar-week test<commit_after>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { component as weeklyCalendarComponent } from 'ilios-common/page-objects/components/weekly-calendar';

module('Integration | Component | ilios calendar week', function(hooks) {
  setupRenderingTest(hooks);

  hooks.beforeEach(function() {
    this.actions = {};
    this.send = (actionName, ...args) => this.actions[actionName].apply(this, args);
  });

  test('it renders', async function(assert) {
    assert.expect(2);
    const date = new Date('2015-09-30T12:00:00');
    this.set('date', date);

    await render(hbs`<IliosCalendarWeek @date={{this.date}} />`);
    assert.dom().containsText('Week of September 27th 2015');
    assert.equal(weeklyCalendarComponent.events.length, 0);
  });

  test('clicking on a day header fires the correct events', async function(assert) {
    assert.expect(3);
    const date = new Date('2015-09-30T12:00:00');
    this.set('date', date);
    this.actions.changeDate = newDate => {
      assert.ok(newDate instanceof Date);
      assert.ok(newDate.toString().search(/Sun Sep 27/) === 0);
    };
    this.actions.changeView = newView => {
      assert.equal(newView, 'day');
    };

    await render(hbs`<IliosCalendarWeek
      @date={{this.date}}
      @changeDate={{action "changeDate"}}
      @changeView={{action "changeView"}}
    />`);
    weeklyCalendarComponent.dayHeadings[0].selectLongDay();
  });

  test('clicking on a day header does nothing when areDaysSelectable is false', async function(assert) {
    assert.expect(0);
    const date = new Date('2015-09-30T12:00:00');
    this.set('date', date);
    this.set('nothing', () => {
      assert.ok(false, 'this should never be called');
    });

    await render(hbs`<IliosCalendarWeek
      @date={{this.date}}
      @areDaysSelectable={{false}}
      @changeDate={{this.nothing}}
      @changeView={{this.nothing}}
    />`);
    await weeklyCalendarComponent.dayHeadings[0].selectLongDay();
  });
});
<|endoftext|>


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

var fs = require("fs");
var path = require("path");
var ncp = require("ncp");
var mkdirp = require("mkdirp");

var ALL_ARGS = process.argv.slice(1);
var TEMPLATE_DIR = path.join(
  __dirname,
  "..",
  "templates"
);

/**
 * generateComponent
 *
 * @param {string} name name of the new component to create
 * @returns {undefined}
 */
function generateComponent(name) {
  try {
    fs.statSync("./src/client/app/javascripts/components/");
  } catch (e) {
    console.log("The path ./src/client/app/javascripts/components/ does not exist.");
    return;
  }

  try {
    fs.statSync(`./src/client/app/component/${name}`);
    console.log(`The file ./src/client/app/component/${name} already exists.`);
    return;
  } catch (e) {}

  try {
    fs.statSync(`./src/client/app/javascripts/components/${/(.*)\/?.*$/.exec(name)[1]}`);
  } catch (e) {
    if (/\//.test(name)) {
      mkdirp(`./src/client/app/javascripts/components/${/(.*)\/.*$/.exec(name)[1]}`);
    }
  }

  console.log(`Generating component ${name}`);

  fs.readFile(path.join(
    TEMPLATE_DIR,
    "component.js"
  ), function (err, data) {
    fs.writeFileSync(
      `./src/client/app/javascripts/components/${name}.js`,
      data.toString().replace(/{{class_name}}/g, /([^\/]*)$/.exec(name)[1])
    );
  });
}

/**
 * generateProject
 *
 * @param {string} name name of the new project to create
 * @returns {undefined}
 */
function generateProject(name) {
  try {
    fs.statSync(`./${name}`);
    console.log(`${name} already exists or is not empty`);
    return;
  } catch (e) {
    fs.mkdirSync(name);
  }

  console.log(`Generating project ${name}`);

  fs.readFile(path.join(
    TEMPLATE_DIR,
    "project",
    "package.json"
  ), function (err, data) {
    ncp(path.join(
      TEMPLATE_DIR,
      "project"
    ), `./${name}`, function () {
      fs.writeFileSync(
        `./${name}/package.json`,
        data.toString().replace("{{project_name}}", name)
      );
    });
  });
}

/**
 * parser
 *
 * @param {array} args list of args passed into binary
 * @returns {undefined}
 */
function parser(args) {
  switch(args[1]) {
  case "project":
    generateProject(args[2]);
    break;
  case "component":
    generateComponent(args[2]);
    break;
  default:
    console.log("all the commands");
  }
}

parser(ALL_ARGS);
<commit_msg>feat(component): check package.json first<commit_after>#! /usr/bin/env node

var fs = require("fs");
var path = require("path");
var ncp = require("ncp");
var mkdirp = require("mkdirp");

var ALL_ARGS = process.argv.slice(1);
var TEMPLATE_DIR = path.join(
  __dirname,
  "..",
  "templates"
);

/**
 * generateComponent
 *
 * @param {string} name name of the new component to create
 * @returns {undefined}
 */
function generateComponent(name) {
  var BASE_PATH = "./";
  try {
    fs.statSync("./package.json");
    BASE_PATH += "src/client/app/javascripts/components/";
  } catch (e) {}

  try {
    fs.statSync(BASE_PATH);
  } catch (e) {
    console.log(`The path ${BASE_PATH} does not exist.`);
    return;
  }

  try {
    fs.statSync(`${BASE_PATH}${name}`);
    console.log(`The file ./src/client/app/component/${name} already exists.`);
    return;
  } catch (e) {}

  try {
    fs.statSync(`${BASE_PATH}${/(.*)\/?.*$/.exec(name)[1]}`);
  } catch (e) {
    if (/\//.test(name)) {
      mkdirp(`${BASE_PATH}${/(.*)\/.*$/.exec(name)[1]}`);
    }
  }

  console.log(`Generating component ${name}`);

  fs.readFile(path.join(
    TEMPLATE_DIR,
    "component.js"
  ), function (err, data) {
    fs.writeFileSync(
      `${BASE_PATH}${name}.js`,
      data.toString().replace(/{{class_name}}/g, /([^\/]*)$/.exec(name)[1])
    );
  });
}

/**
 * generateProject
 *
 * @param {string} name name of the new project to create
 * @returns {undefined}
 */
function generateProject(name) {
  try {
    fs.statSync(`./${name}`);
    console.log(`${name} already exists or is not empty`);
    return;
  } catch (e) {
    fs.mkdirSync(name);
  }

  console.log(`Generating project ${name}`);

  fs.readFile(path.join(
    TEMPLATE_DIR,
    "project",
    "package.json"
  ), function (err, data) {
    ncp(path.join(
      TEMPLATE_DIR,
      "project"
    ), `./${name}`, function () {
      fs.writeFileSync(
        `./${name}/package.json`,
        data.toString().replace("{{project_name}}", name)
      );
    });
  });
}

/**
 * parser
 *
 * @param {array} args list of args passed into binary
 * @returns {undefined}
 */
function parser(args) {
  switch(args[1]) {
  case "project":
    generateProject(args[2]);
    break;
  case "component":
    generateComponent(args[2]);
    break;
  default:
    console.log("all the commands");
  }
}

parser(ALL_ARGS);
<|endoftext|>


<commit_before>import CreatePerson from '../pages/createNewPerson.page'
import { expect } from 'chai'

const VALID_PERSON_PRINCIPAL = {
        lastName: 'Doe'
    }
const VALID_PERSON_ADVISOR = {
        lastName: 'Roe',
        firstName: 'Jane',
        emailAddress: 'test@NATO.INT'
    }

describe('Create new Person form page', () => {

    describe('When creating a Principle user', () => {
        it('Should save a principle with only a last name', () => {
            CreatePerson.openAsSuperUser()
            CreatePerson.form.waitForExist()
            CreatePerson.form.waitForVisible()
            CreatePerson.lastName.setValue(VALID_PERSON_PRINCIPAL.lastName)
            CreatePerson.submitForm()
            CreatePerson.waitForAlertSuccessToLoad()
            const alertMessage = CreatePerson.alertSuccess.getText()
            expect(alertMessage).to.equal('Person saved successfully')
        })
        it('Should not save a principle without a valid email address', () => {
            CreatePerson.openAsSuperUser()
            CreatePerson.form.waitForExist()
            CreatePerson.form.waitForVisible()
            CreatePerson.lastName.setValue(VALID_PERSON_PRINCIPAL.lastName)
            CreatePerson.emailAddress.setValue('notValidEmail@')
            CreatePerson.submitForm()
            const errorMessage = browser.element('input#emailAddress + span.help-block')
            errorMessage.waitForExist()
            errorMessage.waitForVisible()
            expect(errorMessage.getText()).to.equal('Valid email address is required')

            // perform submit form to prevent warning dialog
            CreatePerson.emailAddress.clearElement()
            CreatePerson.lastName.click()
            CreatePerson.submitForm()
            CreatePerson.waitForAlertSuccessToLoad()
            const alertMessage = CreatePerson.alertSuccess.getText()
            expect(alertMessage).to.equal('Person saved successfully')
        })
    })

    describe('When creating an Advisor user', () => {
        it('Should display a warning message specific for duplicate accounts', () => {
            // Only admin users can create an advisor user
            CreatePerson.openAsAdmin()
            CreatePerson.form.waitForExist()
            CreatePerson.form.waitForVisible()
            CreatePerson.roleAdvisorButton.waitForExist()
            CreatePerson.roleAdvisorButton.click()
            const warningMessage = browser.element('.alert.alert-warning')
            warningMessage.waitForExist()
            warningMessage.waitForVisible()
            expect(warningMessage.getText()).to.equal('Creating a NATO Member in ANET could result in duplicate accounts if this person logs in later. If you notice duplicate accounts, please contact an ANET administrator.')
        })
        it('Should save with a valid email address in uppercase', () => {
            CreatePerson.openAsAdmin()
            CreatePerson.form.waitForExist()
            CreatePerson.form.waitForVisible()
            CreatePerson.lastName.setValue(VALID_PERSON_ADVISOR.lastName)
            CreatePerson.firstName.setValue(VALID_PERSON_ADVISOR.firstName)
            CreatePerson.roleAdvisorButton.waitForExist()
            CreatePerson.roleAdvisorButton.click()
            CreatePerson.emailAddress.setValue(VALID_PERSON_ADVISOR.emailAddress)
            const errorMessage = browser.element('input#emailAddress + span.help-block')
            errorMessage.waitForVisible(1000, true) // element should *not* be visible!
            CreatePerson.rank.selectByValue(CreatePerson.getRandomOption(CreatePerson.rank))
            CreatePerson.gender.selectByValue(CreatePerson.getRandomOption(CreatePerson.gender))
            CreatePerson.country.selectByValue(CreatePerson.getRandomOption(CreatePerson.country))
            CreatePerson.submitForm()
            CreatePerson.waitForAlertSuccessToLoad()
            const alertMessage = CreatePerson.alertSuccess.getText()
            expect(alertMessage).to.equal('Person saved successfully')
        })
    })
})
<commit_msg>Prevent alert about leaving page in wdio test<commit_after>import CreatePerson from '../pages/createNewPerson.page'
import { expect } from 'chai'

const VALID_PERSON_PRINCIPAL = {
        lastName: 'Doe'
    }
const VALID_PERSON_ADVISOR = {
        lastName: 'Roe',
        firstName: 'Jane',
        emailAddress: 'test@NATO.INT'
    }

describe('Create new Person form page', () => {

    describe('When creating a Principle user', () => {
        it('Should save a principle with only a last name', () => {
            CreatePerson.openAsSuperUser()
            CreatePerson.form.waitForExist()
            CreatePerson.form.waitForVisible()
            CreatePerson.lastName.setValue(VALID_PERSON_PRINCIPAL.lastName)
            CreatePerson.submitForm()
            CreatePerson.waitForAlertSuccessToLoad()
            const alertMessage = CreatePerson.alertSuccess.getText()
            expect(alertMessage).to.equal('Person saved successfully')
        })
        it('Should not save a principle without a valid email address', () => {
            CreatePerson.openAsSuperUser()
            CreatePerson.form.waitForExist()
            CreatePerson.form.waitForVisible()
            CreatePerson.lastName.setValue(VALID_PERSON_PRINCIPAL.lastName)
            CreatePerson.emailAddress.setValue('notValidEmail@')
            CreatePerson.submitForm()
            const errorMessage = browser.element('input#emailAddress + span.help-block')
            errorMessage.waitForExist()
            errorMessage.waitForVisible()
            expect(errorMessage.getText()).to.equal('Valid email address is required')

            // perform submit form to prevent warning dialog
            CreatePerson.emailAddress.clearElement()
            CreatePerson.lastName.click()
            CreatePerson.submitForm()
            CreatePerson.waitForAlertSuccessToLoad()
            const alertMessage = CreatePerson.alertSuccess.getText()
            expect(alertMessage).to.equal('Person saved successfully')
        })
    })

    describe('When creating an Advisor user', () => {
        it('Should display a warning message specific for duplicate accounts', () => {
            // Only admin users can create an advisor user
            CreatePerson.openAsAdmin()
            CreatePerson.form.waitForExist()
            CreatePerson.form.waitForVisible()
            CreatePerson.roleAdvisorButton.waitForExist()
            CreatePerson.roleAdvisorButton.click()
            const warningMessage = browser.element('.alert.alert-warning')
            warningMessage.waitForExist()
            warningMessage.waitForVisible()
            expect(warningMessage.getText()).to.equal('Creating a NATO Member in ANET could result in duplicate accounts if this person logs in later. If you notice duplicate accounts, please contact an ANET administrator.')
        })
        it('Should save with a valid email address in uppercase', () => {
            // Continue on the same page to prevent "Are you sure you wish to navigate away from the page" warning
            CreatePerson.lastName.setValue(VALID_PERSON_ADVISOR.lastName)
            CreatePerson.firstName.setValue(VALID_PERSON_ADVISOR.firstName)
            CreatePerson.roleAdvisorButton.waitForExist()
            CreatePerson.roleAdvisorButton.click()
            CreatePerson.emailAddress.setValue(VALID_PERSON_ADVISOR.emailAddress)
            const errorMessage = browser.element('input#emailAddress + span.help-block')
            errorMessage.waitForVisible(1000, true) // element should *not* be visible!
            CreatePerson.rank.selectByValue(CreatePerson.getRandomOption(CreatePerson.rank))
            CreatePerson.gender.selectByValue(CreatePerson.getRandomOption(CreatePerson.gender))
            CreatePerson.country.selectByValue(CreatePerson.getRandomOption(CreatePerson.country))
            CreatePerson.submitForm()
            CreatePerson.waitForAlertSuccessToLoad()
            const alertMessage = CreatePerson.alertSuccess.getText()
            expect(alertMessage).to.equal('Person saved successfully')
        })
    })
})
<|endoftext|>


<commit_before>module.exports = {
  rules: {
    // Errors
    'trailing-comma': [true, {
      'multiline': 'never',
      'singleline': 'never'
    }],
    'variable-name': [true,
      'ban-keywords',
      'check-format',
      'allow-pascal-case',
      'allow-leading-underscore'
    ],
    'no-unused-variable': [true, 'React'],
    'import-name': [true, { 'react': 'React' }],

    // Warnings
    'max-line-length': {
      'severity': 'warn',
      'options': 200
    },

    // Excludes
    'member-access': false,
    'ordered-imports': [false],
    'object-literal-sort-keys': false,
    'member-ordering': [false],
    'interface-name': [false],
    'jsx-boolean-value': false
  }
}
<commit_msg>Update react rules.<commit_after>module.exports = {
  rules: {
    // Errors
    'trailing-comma': [true, {
      'multiline': 'never',
      'singleline': 'never'
    }],
    'variable-name': [true,
      'ban-keywords',
      'check-format',
      'allow-pascal-case',
      'allow-leading-underscore'
    ],
    'no-unused-variable': [true, 'React'],
    'import-name': [true, { 'react': 'React' }],

    // Warnings
    'max-line-length': {
      'severity': 'warn',
      'options': 200
    },

    // Excludes
    'member-access': false,
    'ordered-imports': [false],
    'object-literal-sort-keys': false,
    'member-ordering': [false],
    'interface-name': [false],

    // Excludes - React
    'jsx-boolean-value': false, // booleans are more concise
    'jsx-no-lambda': false  // consider using this
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node bin
var argv = require('minimist')(process.argv.slice(2));
var child_process = require('child_process');
var spawn = child_process.spawn
var path = require('path')

if (argv._[0] === 'help') {
    console.log("Usage:");
    logHelp()
    process.exit()
}
else if (argv._[0] === 'play')
{
    var port = process.env.PORT || argv.port

    console.log("------------------------------------------------------")
    console.log("Playing Konga!")
    console.log("------------------------------------------------------")
    console.log("")

    console.log(argv)

    var args = ["app.js","--prod"]
    if(port) args.push("--port=" + port)

    console.log(args)

    var cmd = spawn('node',
        args,
        {cwd : path.join(__dirname,".."), stdio: "inherit"});
    cmd.on('exit', function(code){
        console.log("Exiting",code);
    });
}
else if(argv._[0] === 'prepare') {

  console.log("Preparing database...")

  if(!process.env.DB_ADAPTER && !argv.adapter) {
    console.error("No db adapter defined. Set --adapter {mongo || mysql || postgres || sql-srv}")
    return process.exit(1);
  }

  if(!process.env.DB_URI && !argv.uri) {
    console.error("No db connection string is defined. Set --uri {db_connection_string}")
    return process.exit(1);
  }

  process.env.DB_ADAPTER = process.env.DB_ADAPTER || argv.adapter;
  process.env.DB_URI = process.env.DB_URI || argv.uri;

  require("../makedb")(function(err) {
    if(err) {
      process.exit();
    }

    var Sails = require('sails');
    Sails.lift({
      environment: 'development',
      port: process.env.PORT || argv.port || "1339",
      hooks: {
        grunt: false
      }
    }, function callback(error, sails) {

      if(error) {
        console.log("Failed to lift Sails:",error)
        return process.exit(1);
      }

      process.exit()

    });
  });

}
else
{
    console.log(argv)
    console.log("Unknown command. Try one of:");
    logHelp()
}

function logHelp() {
    console.log("==============================");
    console.log("konga play      | Start Konga.");
    console.log("==============================");
    process.exit()
}<commit_msg>Validate port arg<commit_after>#!/usr/bin/env node bin
var argv = require('minimist')(process.argv.slice(2));
var child_process = require('child_process');
var spawn = child_process.spawn
var path = require('path')
var _ = require('lodash');

if (argv._[0] === 'help') {
    console.log("Usage:");
    logHelp()
    process.exit()
}
else if (argv._[0] === 'play')
{
    var port = process.env.PORT || argv.port

    console.log("------------------------------------------------------")
    console.log("Playing Konga!")
    console.log("------------------------------------------------------")
    console.log("")

    console.log(argv)

    var args = ["app.js","--prod"]
    if(port) args.push("--port=" + port)

    console.log(args)

    var cmd = spawn('node',
        args,
        {cwd : path.join(__dirname,".."), stdio: "inherit"});
    cmd.on('exit', function(code){
        console.log("Exiting",code);
    });
}
else if(argv._[0] === 'prepare') {

  console.log("Preparing database...")

  if(!process.env.DB_ADAPTER && !argv.adapter) {
    console.error("No db adapter defined. Set --adapter {mongo || mysql || postgres || sql-srv}")
    return process.exit(1);
  }

  if(!process.env.DB_URI && !argv.uri) {
    console.error("No db connection string is defined. Set --uri {db_connection_string}")
    return process.exit(1);
  }

  process.env.DB_ADAPTER = process.env.DB_ADAPTER || argv.adapter;
  process.env.DB_URI = process.env.DB_URI || argv.uri;
  process.env.PORT = _.isString(argv.port) || _.isNumber(argv.port) ? argv.port : 1339;

  require("../makedb")(function(err) {
    if(err) {
      process.exit();
    }

    var Sails = require('sails');
    Sails.lift({
      environment: 'development',
      port: process.env.PORT,
      hooks: {
        grunt: false
      }
    }, function callback(error, sails) {

      if(error) {
        console.log("Failed to lift Sails:",error)
        return process.exit(1);
      }

      process.exit()

    });
  });

}
else
{
    console.log(argv)
    console.log("Unknown command. Try one of:");
    logHelp()
}

function logHelp() {
    console.log("==============================");
    console.log("konga play      | Start Konga.");
    console.log("==============================");
    process.exit()
}<|endoftext|>


<commit_before>/**
 * Created by tferguson on 05/03/2015.
 */

(function() {

    'use strict';

    angular.module('MeetingRoomInterface')
        .config(function ($routeProvider) {

            $routeProvider
                .when('/', {
                    templateUrl: 'charts/chart.html',
                    controller: 'MainCtrl'
                })
                .otherwise({
                    redirectTo: '/'
                });
        });
})();
<commit_msg>Removed app.routes<commit_after><|endoftext|>


<commit_before>/*
  Provides an object called `github` with useful functions for interacting with
  the GitHub API. Each function in `github` maps to one of GitHub's APIs, for
  example `github.user` maps to `/user:username` which can be used to return
  information about a user on GitHub. Each function requires the arguments
  necessary to create a valid url and must also be provided with a callback for
  both success and failure scenarios. The success callback takes the response as
  its first argument.

  Example usage:

    github.user("barischj", function(user) {
      console.log(user.email)
    }, function() {
      console.log("failed")
    });
*/

var get = function(url, onsuccess, onfail) {
  $.get(url, function(response) {
    onsuccess(response);
  }).fail(function() {
    onfail();
  });
};

//checks if a unix timestamp is within two others inclusively.
var withinTime = function(start_week, end_week, input_week){
    var isValid = false;
    if((start_week === NULL && end_week === NULL) || (start_week === NULL && input_week <= end_week ) || (start_week <= input_week && input_week <= end_week)){
        isValid = true;
    }
    return isValid;
};

var github = {
    // GET /users/:username
    user: function(username, onsuccess, onfail) {
        get("https://api.github.com/users/" + username, onsuccess, onfail);
    },
    // GET /repos/:owner/:repo/collaborators
    commits: function(owner, repo, onsuccess, onfail) {
        get("https://api.github.com/repos/" + owner + "/" + repo + "/commits", onsuccess, onfail);
    },
    // GET /repos/:owner/:repo/stats/contributors
    // start_week, end_week: week numbers given as a Unix timestamp https://en.wikipedia.org/wiki/Unix_time
    // start_week: if null indicated the beginning of time
    // end_week: if null specifies now
    //a valid week is considered to be one which begins before the end_week and after the start_week values
    collaborators: function(owner, repo, start_week, end_week, user, onsuccess, onfail) {
        var json = get("https://api.github.com/repos/" + owner + "/" + repo + "/stats/contributors", onsuccess, onfail);

        $.grep(json, function (value1) {  //http://api.jquery.com/jQuery.grep/ returns array of desired contributors -- if return value is true, element is retained, else it is deleted.
            var validContributor = true;
            if(user === NULL || value.author.login === user){     //check if desired contributor
                $.grep(value.weeks, function (value2){            //check if given week is within desired time frame
                    return withinTime(start_week, end_week, value2.w);
                });
            }
            else
                validContributor = false;
            return validContributor;
        });
    }
};

// Make available to `node` for unittesting.
module.exports = github;
<commit_msg>Working collaborators function<commit_after>/*
  Provides an object called `github` with useful functions for interacting with
  the GitHub API. Each function in `github` maps to one of GitHub's APIs, for
  example `github.user` maps to `/user:username` which can be used to return
  information about a user on GitHub. Each function requires the arguments
  necessary to create a valid url and must also be provided with a callback for
  both success and failure scenarios. The success callback takes the response as
  its first argument.

  Example usage:

    github.user("barischj", function(user) {
      console.log(user.email)
    }, function() {
      console.log("failed")
    });
*/

var get = function(url, onsuccess, onfail) {
    $.get(url, function (response) {
    onsuccess(response);
  }).fail(function() {
    onfail();
  });
};

//checks if a unix timestamp is within two others inclusively.
var withinTime = function(start_week, end_week, input_week){
    var isValid = false;
    if((start_week === null && end_week === null) || (start_week === null && input_week <= end_week ) || (start_week <= input_week && end_week === null) || (start_week <= input_week && input_week <= end_week)){
        isValid = true;
    }
    return isValid;
};

var github = {
    // GET /users/:username
    user: function(username, onsuccess, onfail) {
        get("https://api.github.com/users/" + username, onsuccess, onfail);
    },
    // GET /repos/:owner/:repo/collaborators
    commits: function(owner, repo, onsuccess, onfail) {
        get("https://api.github.com/repos/" + owner + "/" + repo + "/commits", onsuccess, onfail);
    },
    // GET /repos/:owner/:repo/stats/contributors
    // start_week, end_week: week numbers given as a Unix timestamp https://en.wikipedia.org/wiki/Unix_time
    // start_week: if null indicated the beginning of time
    // end_week: if null specifies now
    //a valid week is considered to be one which begins before the end_week and after the start_week values
    contributors: function (owner, repo, start_week, end_week, user, onsuccess, onfail) {
        get("https://api.github.com/repos/" + owner + "/" + repo + "/stats/contributors", function (response) {

            response = $.grep(response, function (collaborator, index) {                            //http://api.jquery.com/jQuery.grep/ returns array of desired contributors -- if return value is true, element is retained, else it is deleted.
                var validContributor = true;

                if (user === null || collaborator.author.login === user) {                          //filter desired contributors
                    response[index].weeks = $.grep(collaborator.weeks, function (week) {            //filter desired weeks from desired contributors
                        return withinTime(start_week, end_week, week.w);
                    });
                }
                else
                    validContributor = false;

                return validContributor;
            });
            onsuccess(response);
        }, onfail);

    }
};

// Make available to `node` for unittesting.
module.exports = github;
<|endoftext|>


<commit_before>function marketChartsService($timeout, $log, numbers) {
  'ngInject';

  const service = {};

  service.createDefaultOHLCConfig = createDefaultOHLCConfig;
  service.createOHLCInterval = createOHLCInterval;
  service.createOHLCSeries = createOHLCSeries;
  service.createOHLCVolumeSeries = createOHLCVolumeSeries;
  service.calcMovingAvg = calcMovingAvg;
  service.daysToAverages = daysToAverages;
  service.create5DaySMASeries = create5DaySMASeries;
  service.createDefaultPriceHistoryConfig = createDefaultPriceHistoryConfig;
  service.createAverageSeries = createAverageSeries;
  service.create20DaySMASeries = create20DaySMASeries;
  service.createUpperMovingBollingerBandSeries = createUpperMovingBollingerBandSeries;
  service.createLowerMovingBollingerBandSeries = createLowerMovingBollingerBandSeries;
  service.createUpperBollingerBandSeries = createUpperBollingerBandSeries;
  service.createLowerBollingerBandSeries = createLowerBollingerBandSeries;

  return service;

  function createDefaultOHLCConfig() {
    return {
      series: [],
      title: {
        text: 'OHLC'
      },
      options : {
        chart: {
          zoomType: 'x'
        },
        rangeSelector: {
          enabled: true
        },
        navigator: {
          enabled: true
        },
        scrollbar: {
          enabled: false
        },
        yAxis: [{
          labels: {
            align: 'right',
            x: -3
          },
          title: {
            text: 'ISK'
          },
          height: '60%',
          lineWidth: 2
        }, {
          labels: {
            align: 'right',
            x: -3
          },
          title: {
            text: 'Volume'
          },
          top: '65%',
          height: '35%',
          offset: 0,
          lineWidth: 2
        }]
      },
      useHighStocks: true,
      func: function(chart) {
        $timeout(function() {
          chart.reflow();
        }, 0);
      }
    }
  }

  function createDefaultPriceHistoryConfig() {
    return {
      series: [],
      options: {
        chart: {
          zoomType: 'x'
        },
        rangeSelector: {
          enabled: true
        },
        navigator: {
          enabled: true
        },
        scrollbar: {
          enabled: false
        },
        yAxis: {
          labels: {
            align: 'right',
            x: -3
          },
          title: {
            text: 'ISK'
          }
        },
        tooltip: {
          pointFormat: '{series.name}: {point.y} ISK
',
          valueDecimals: 2,
          split: true
        }
      },
      useHighStocks: true,
      func: function(chart) {
        $timeout(function() {
          chart.reflow();
        }, 0);
      }
    };
  }

  function createOHLCSeries(days) {
    return {
      type: 'candlestick',
      name: 'OHLC',
      tooltip: {
        valueDecimals: 1,
        valueSuffix: ' ISK',
      },
      data: days.map((day) => {
        return createOHLCInterval({
          open: day.open,
          close: day.close,
          high: day.max,
          low: day.min,
          time: day.time
        })
      }),
      dataGrouping: {
        units: [['day', 1]]
      }
    }
  }

  function createOHLCInterval(interval) {
    let {time, high, low, open, close} = interval;
    return [time, open, high, low, close];
  }

  function createOHLCVolumeSeries(days) {
    return {
      type: 'column',
      name: 'Average Volume',
      yAxis: 1,
      tooltip: {
        valueDecimals: 1
      },
      dataGrouping: {
        units: [
          ['day', 1]
        ]
      },
      data: days.map((day) => {
        return [day.time, day.avgVolume];
      })
    };
  }

  function create5DaySMASeries(days) {
    return createLineSeries(calcMovingAvg(daysToAverages(days), 5), '5 day moving average');
  }

  function create20DaySMASeries(days) {
    return createLineSeries(calcMovingAvg(daysToAverages(days), 20), '20 day moving average');
  }

  function createAverageSeries(days) {
    return createLineSeries(daysToAverages(days), 'average');
  }

  function createUpperBollingerBandSeries(days) {
    return createDashedLineSeries(daysToUpperStdDev(days), 'upper standard deviation');
  }

  function createLowerBollingerBandSeries(days) {
    return createDashedLineSeries(daysToLowerStdDev(days), 'lower standard deviation');
  }

  function createUpperMovingBollingerBandSeries(days, interval, bandMagnitude = 2) {
    let sma = calcMovingAvg(daysToAverages(days), interval);
    let stdDevInterval = calcMovingStdDev(daysToAverages(days), interval);
    let upperBand = calcUpperBollingerBand(sma, stdDevInterval, bandMagnitude);

    return createDashedLineSeries(upperBand, interval + ' day upper standard deviation average');
  }

  function createLowerMovingBollingerBandSeries(days, interval, bandMagnitude = 2) {
    let sma = calcMovingAvg(daysToAverages(days), interval);
    let stdDevInterval = calcMovingStdDev(daysToAverages(days), interval);
    let lowerBand = calcLowerBollingerBand(sma, stdDevInterval, bandMagnitude);

    return createDashedLineSeries(lowerBand, interval +' day lower standard deviation average');
  }

  function createLineSeries(data = [], name = '') {
    return {
      name: name,
      data: data,
      tooltip: {
        valueDecimals: 1
      }
    };
  }

  function createDashedLineSeries(data = [], name = '') {
    return {
      name: name,
      dashStyle: 'longdash',
      data: data,
      tooltip: {
        valueDecimals: 1
      }
    }
  }

  function calcUpperBollingerBand(sma, stdDevInterval, magnitude) {
    return sma.map((day, index) => {
      return {x: day.x, y: day.y + (stdDevInterval[index].y * magnitude)};
    });
  }

  function calcLowerBollingerBand(sma, stdDevInterval, magnitude) {
    return sma.map((day, index) => {
      return {x: day.x, y: day.y - (stdDevInterval[index].y * magnitude)};
    });
  }

  function daysToUpperStdDev(days) {
    return days.map(function(day) {
      return {x: day.time, y: day.stdDevBounds.upper};
    });
  }

  function daysToLowerStdDev(days) {
    return days.map(function(day) {
      return {x: day.time, y: day.stdDevBounds.lower};
    });
  }

  function daysToAverages(days) {
    return days.map(function(day) {
      return {x: day.time, y: day.avg};
    });
  }

  function calcMovingAvg(points, n) {
    return points.map(function (each, index, arr) {
      const fromIndex = index - n;
      let subSeq, sum;

      if(fromIndex >= 0) {
        // Splice the period from the array.
        subSeq = arr.slice(fromIndex, index);

        // Get sum
        sum = subSeq.reduce(function(a, b) {
          return a + b.y;
        }, 0);

        // Get average
        return {x: each.x, y: sum / n};
      }
      else {
        // Insufficient data to calculate average, return undefined for that interval.
        return {x: each.x, y: undefined};
      }
    });
  }

  function calcMovingStdDev(points, n) {
    return points.map((each, index, arr) => {
      const fromIndex = index -n;

      if(fromIndex >= 0) {
        // Splice the period from the array.
        let subSeq = arr.slice(fromIndex, index).map((point) => {
          return point.y;
        });

        // Get standard deviation
        const stdDev = numbers.statistic.standardDev(subSeq);

        // Return point standard deviation
        return {x: each.x, y: stdDev};
      }
      else {
        // Insufficient data to calculate standard deviation for that interval.
        return {x: each.x, y: undefined};
      }
    })
  }
}

export default {
  name: 'marketChartsService',
  fn: marketChartsService
}
<commit_msg>Renamed standard deviation to variance<commit_after>function marketChartsService($timeout, $log, numbers) {
  'ngInject';

  const service = {};

  service.createDefaultOHLCConfig = createDefaultOHLCConfig;
  service.createOHLCInterval = createOHLCInterval;
  service.createOHLCSeries = createOHLCSeries;
  service.createOHLCVolumeSeries = createOHLCVolumeSeries;
  service.calcMovingAvg = calcMovingAvg;
  service.daysToAverages = daysToAverages;
  service.create5DaySMASeries = create5DaySMASeries;
  service.createDefaultPriceHistoryConfig = createDefaultPriceHistoryConfig;
  service.createAverageSeries = createAverageSeries;
  service.create20DaySMASeries = create20DaySMASeries;
  service.createUpperMovingBollingerBandSeries = createUpperMovingBollingerBandSeries;
  service.createLowerMovingBollingerBandSeries = createLowerMovingBollingerBandSeries;
  service.createUpperBollingerBandSeries = createUpperBollingerBandSeries;
  service.createLowerBollingerBandSeries = createLowerBollingerBandSeries;

  return service;

  function createDefaultOHLCConfig() {
    return {
      series: [],
      title: {
        text: 'OHLC'
      },
      options : {
        chart: {
          zoomType: 'x'
        },
        rangeSelector: {
          enabled: true
        },
        navigator: {
          enabled: true
        },
        scrollbar: {
          enabled: false
        },
        yAxis: [{
          labels: {
            align: 'right',
            x: -3
          },
          title: {
            text: 'ISK'
          },
          height: '60%',
          lineWidth: 2
        }, {
          labels: {
            align: 'right',
            x: -3
          },
          title: {
            text: 'Volume'
          },
          top: '65%',
          height: '35%',
          offset: 0,
          lineWidth: 2
        }]
      },
      useHighStocks: true,
      func: function(chart) {
        $timeout(function() {
          chart.reflow();
        }, 0);
      }
    }
  }

  function createDefaultPriceHistoryConfig() {
    return {
      series: [],
      options: {
        chart: {
          zoomType: 'x'
        },
        rangeSelector: {
          enabled: true
        },
        navigator: {
          enabled: true
        },
        scrollbar: {
          enabled: false
        },
        yAxis: {
          labels: {
            align: 'right',
            x: -3
          },
          title: {
            text: 'ISK'
          }
        },
        tooltip: {
          pointFormat: '{series.name}: {point.y} ISK
',
          valueDecimals: 2,
          split: true
        }
      },
      useHighStocks: true,
      func: function(chart) {
        $timeout(function() {
          chart.reflow();
        }, 0);
      }
    };
  }

  function createOHLCSeries(days) {
    return {
      type: 'candlestick',
      name: 'OHLC',
      tooltip: {
        valueDecimals: 1,
        valueSuffix: ' ISK',
      },
      data: days.map((day) => {
        return createOHLCInterval({
          open: day.open,
          close: day.close,
          high: day.max,
          low: day.min,
          time: day.time
        })
      }),
      dataGrouping: {
        units: [['day', 1]]
      }
    }
  }

  function createOHLCInterval(interval) {
    let {time, high, low, open, close} = interval;
    return [time, open, high, low, close];
  }

  function createOHLCVolumeSeries(days) {
    return {
      type: 'column',
      name: 'Average Volume',
      yAxis: 1,
      tooltip: {
        valueDecimals: 1
      },
      dataGrouping: {
        units: [
          ['day', 1]
        ]
      },
      data: days.map((day) => {
        return [day.time, day.avgVolume];
      })
    };
  }

  function create5DaySMASeries(days) {
    return createLineSeries(calcMovingAvg(daysToAverages(days), 5), '5 day moving average');
  }

  function create20DaySMASeries(days) {
    return createLineSeries(calcMovingAvg(daysToAverages(days), 20), '20 day moving average');
  }

  function createAverageSeries(days) {
    return createLineSeries(daysToAverages(days), 'average');
  }

  function createUpperBollingerBandSeries(days) {
    return createDashedLineSeries(daysToUpperStdDev(days), 'upper variance');
  }

  function createLowerBollingerBandSeries(days) {
    return createDashedLineSeries(daysToLowerStdDev(days), 'lower variance');
  }

  function createUpperMovingBollingerBandSeries(days, interval, bandMagnitude = 2) {
    let sma = calcMovingAvg(daysToAverages(days), interval);
    let stdDevInterval = calcMovingStdDev(daysToAverages(days), interval);
    let upperBand = calcUpperBollingerBand(sma, stdDevInterval, bandMagnitude);

    return createDashedLineSeries(upperBand, interval + ' day upper standard deviation average');
  }

  function createLowerMovingBollingerBandSeries(days, interval, bandMagnitude = 2) {
    let sma = calcMovingAvg(daysToAverages(days), interval);
    let stdDevInterval = calcMovingStdDev(daysToAverages(days), interval);
    let lowerBand = calcLowerBollingerBand(sma, stdDevInterval, bandMagnitude);

    return createDashedLineSeries(lowerBand, interval +' day lower standard deviation average');
  }

  function createLineSeries(data = [], name = '') {
    return {
      name: name,
      data: data,
      tooltip: {
        valueDecimals: 1
      }
    };
  }

  function createDashedLineSeries(data = [], name = '') {
    return {
      name: name,
      dashStyle: 'longdash',
      data: data,
      tooltip: {
        valueDecimals: 1
      }
    }
  }

  function calcUpperBollingerBand(sma, stdDevInterval, magnitude) {
    return sma.map((day, index) => {
      return {x: day.x, y: day.y + (stdDevInterval[index].y * magnitude)};
    });
  }

  function calcLowerBollingerBand(sma, stdDevInterval, magnitude) {
    return sma.map((day, index) => {
      return {x: day.x, y: day.y - (stdDevInterval[index].y * magnitude)};
    });
  }

  function daysToUpperStdDev(days) {
    return days.map(function(day) {
      return {x: day.time, y: day.stdDevBounds.upper};
    });
  }

  function daysToLowerStdDev(days) {
    return days.map(function(day) {
      return {x: day.time, y: day.stdDevBounds.lower};
    });
  }

  function daysToAverages(days) {
    return days.map(function(day) {
      return {x: day.time, y: day.avg};
    });
  }

  function calcMovingAvg(points, n) {
    return points.map(function (each, index, arr) {
      const fromIndex = index - n;
      let subSeq, sum;

      if(fromIndex >= 0) {
        // Splice the period from the array.
        subSeq = arr.slice(fromIndex, index);

        // Get sum
        sum = subSeq.reduce(function(a, b) {
          return a + b.y;
        }, 0);

        // Get average
        return {x: each.x, y: sum / n};
      }
      else {
        // Insufficient data to calculate average, return undefined for that interval.
        return {x: each.x, y: undefined};
      }
    });
  }

  function calcMovingStdDev(points, n) {
    return points.map((each, index, arr) => {
      const fromIndex = index -n;

      if(fromIndex >= 0) {
        // Splice the period from the array.
        let subSeq = arr.slice(fromIndex, index).map((point) => {
          return point.y;
        });

        // Get standard deviation
        const stdDev = numbers.statistic.standardDev(subSeq);

        // Return point standard deviation
        return {x: each.x, y: stdDev};
      }
      else {
        // Insufficient data to calculate standard deviation for that interval.
        return {x: each.x, y: undefined};
      }
    })
  }
}

export default {
  name: 'marketChartsService',
  fn: marketChartsService
}
<|endoftext|>


<commit_before>/*
 *  A shim for running underscore tests.
 */

var skipErrors = true;

var module = function(name) {
    print('MODULE', name);
};

var test = function(name, func) {
    print('***', name);
    func();
};

var handleResult = function(bool, msg) {
    if (bool) {
        print('SUCCESS', msg);
    } else {
        if (skipErrors) {
            print('FAILURE', msg);
        } else {
            throw new Error('FAILURE: ' + msg);
        }
    }
}

var ok = function(bool, msg) {
    handleResult(bool, msg);
};

var equal = function(x, y, msg) {
    handleResult(x == y, msg);
};

var strictEqual = function(x, y, msg) {
    handleResult(x === y, msg);
};

var deepEqual = function(x, y, msg) {
    // FIXME: incorrect as key ordering matters, but close enough maybe?
    handleResult(Duktape.jsonxEnc(x) === Duktape.jsonxEnc(y), msg);
};

// These are needed to transform the $(document).ready(fn); notation into
// a synchronous call.

var document = {};

var $ = function(arg) {
    return $;
};
$.ready = function(cb) {
    // just call directly
    cb();
};

<commit_msg>some more underscore test shimming, many cases now run properly<commit_after>/*
 *  A shim for running underscore tests.
 *
 *  See: http://api.qunitjs.com/
 */

var skipErrors = true;

var module = function(name) {
    print('MODULE', name);
};

var assert_count;

var test = function(name, arg1, arg2) {
    var emsg;
    print('***', name);

    assert_count = 0;
    if (typeof(arg1) === 'function') {
        arg1();
    } else {
        // deprecated
        arg2();
        if (assert_count !== arg1) {
            emsg = 'TEST CASE FAILED: assert count mismatch (' + assert_count + ' vs ' + arg1 + ')';
            if (skipErrors) {
                print(emsg);
            } else {
                throw new Error(emsg);
            }
        }
    }
};

var asyncTest = function(name, arg1, arg2) {
    print('***', name, 'SKIPPED (asyncTest unimplemented)');
    return;

    assert_count = 0;
    if (typeof(arg1) === 'function') {
        throw new Error('unimplemented');
    } else {
        // deprecated
        throw new Error('unimplemented');
        if (assert_count !== arg1) {
            emsg = 'TEST CASE FAILED: assert count mismatch (' + assert_count + ' vs ' + arg1 + ')';
            if (skipErrors) {
                print(emsg);
            } else {
                throw new Error(emsg);
            }
        }
    }
}

var handleResult = function(bool, msg) {
    var emsg;

    if (bool) {
        print('SUCCESS', msg);
    } else {
        emsg = 'FAILURE ' + msg;
        if (skipErrors) {
            print(emsg);
        } else {
            throw new Error(emsg);
        }
    }
}

var ok = function(bool, msg) {
    assert_count++;
    handleResult(bool, msg);
};

var equal = function(x, y, msg) {
    assert_count++;
    handleResult(x == y, msg);
};

var notEqual = function(x, y, msg) {
    assert_count++;
    handleResult(x != y, msg);
};

var strictEqual = function(x, y, msg) {
    assert_count++;
    handleResult(x === y, msg);
};

var notStrictEqual = function(x, y, msg) {
    assert_count++;
    handleResult(x !== y, msg);
};

var deepEqual = function(x, y, msg) {
    // FIXME: incorrect as key ordering matters, but close enough maybe?
    assert_count++;
    handleResult(Duktape.jsonxEnc(x) === Duktape.jsonxEnc(y), msg);
};

var notDeepEqual = function(x, y, msg) {
    // FIXME: incorrect as key ordering matters, but close enough maybe?
    assert_count++;
    handleResult(Duktape.jsonxEnc(x) !== Duktape.jsonxEnc(y), msg);
};

var raises = function(fn, expect_err, msg) {
    var emsg;
    var err_name = expect_err.name;

    assert_count++;
    try {
        fn();
        emsg = 'FAILURE ' + msg + ' -- did not throw ' + err_name + ' as expected';
        if (skipErrors) {
            print(emsg);
        } else {
            throw new Error(emsg);
        }
    } catch (e) {
        if (err_name === e.name) {
            print('SUCCESS', msg);
        } else {
            emsg = 'FAILURE ' + msg + ' -- got unexpected error type: ' + e.name + ' (expected ' + err_name + ')';
            if (skipErrors) {
                print(emsg);
            } else {
                throw new Error(emsg);
            }
        }
    }
}

// Minimal jQuery fakery.  These are needed to transform the $(document).ready(fn);
// notation into a synchronous call, and to provide enough fake data and functions
// to satisfy the tests (while not breaking the test intent).

var doc_images = [];
var document = {
    images: doc_images
};
var iObject = {};

var $ = function(arg) {
    if (arg === document) {
        return $;
    }
    if (arg === '#map-test') {
        return {
            children: function() {
                return [ { id: 'id1' }, { id: 'id2' } ];
            }
        };
    }
    if (arg === doc_images) {
        return [ { id: 'chart_image' } ];
    }

    // This is a bit tricky, the test is more or less bypassed.
    // equal(_.size($('<div>').add('<span>').add('<span>')), 3, 'can compute the size of jQuery objects');

    if (arg === '<div>') {
        var fun_count = 1;
        var fun = function (add_arg) {
            fun_count++;
            if (fun_count == 3) {
                return { length: 3 };
            } else {
                return fun;
            }
        };
        fun.add = fun;
        return fun;
    }

    throw Error('unexpected call to $: ' + arg);
};
$.ready = function(cb) {
    // just call directly
    cb();
};

var jQuery = $;

<|endoftext|>