<commit_before>/**
 * Copyright 2005-2009 by Purdue Research Foundation, West Lafayette, IN 47906.
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License,
 * version 2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

//-----------------------------------------------------------
//  Ensure we have our namespace
//-----------------------------------------------------------
if (!HUB) {
	var HUB = {};
}

//----------------------------------------------------------
// Project Component JS
//----------------------------------------------------------
if (!jq) {
	var jq = $;
}

HUB.Projects = {
	jQuery: jq,

	initialize: function()
	{
		// Fix up users with no JS
		HUB.Projects.fixJS();

		// Activate boxed content
		HUB.Projects.launchBox();

		// Add confirms
		HUB.Projects.addConfirms();

		// Reviewers
		HUB.Projects.addFiltering();

		// Fade-out status message
		HUB.Projects.addMessageFade();
	},

	addFiltering: function()
	{
		var $ = this.jQuery;
		// Browse projects - filtering
		$(".filterby").each(function(i, item) {
			$(item).on('change', function(e) {
				if ($('#browseForm')) {
					$('#browseForm').submit();
				}
			});
		});
	},

	addMessageFade: function()
	{
		var $ = this.jQuery;

		if ($("#status-msg").length > 0)
		{
			var keyupTimer = setTimeout((function()
			{
				if (!$("#status-msg").hasClass('ajax-loading') && $('#status-msg').html().trim() != '')
				{
					$("#status-msg").animate({opacity:0.0}, 2000, function() {
					    $('#status-msg').html('');
					});
				}
			}), 4000);
		}
	},

	addConfirms: function()
	{
		var $ = this.jQuery;
		// Confirm delete
		$('#suspend').on('click', function(e)
		{
			e.preventDefault();
			HUB.Projects.addConfirm($('#suspend'),
			'Are you sure you want to suspend this project?',
			'Yes, suspend', 'No, do not suspend');
		});

		// Confirm delete
		$('#delproject').on('click', function(e)
		{
			e.preventDefault();
			HUB.Projects.addConfirm($('#delproject'),
			'Are you sure you want to delete this project?
This is a permanent action and cannot be undone.',
			'Yes, delete', 'No, do not delete');
		});

		// Confirm revert
		$('#confirm-revert').on('click', function(e)
			{
				e.preventDefault();
				HUB.Projects.addConfirm($('#confirm-revert'),
				'Are you sure you want to revert this project to draft mode?',
				'Yes, revert', 'No, keep as pending');
		});
	},

	// Refresh counts of project activities and resources
	refreshCount: function(what)
	{
		var $ = this.jQuery;
		if ($('#projectid')) {
			var url = 'index.php?option=com_projects&task=showcount&no_html=1&pid=' + $('#projectid').val();

			if (what=='publications' && $('#c-publications') && $('#c-publications-num')) {
				$.get(url + '&what=publication', {}, function(data) {
					$('#c-publications-num').html(data);
				});
			}
			if (what=='files' && $('#c-files') && $('#c-files-num')) {
				$.get(url + '&what=files', {}, function(data) {
					$('#c-files-num').html(data);
				});
			}
			if (what=='team' && $('#c-team') && $('#c-team-num')) {
				$.get(url + '&what=team', {}, function(data) {
					$('#c-team-num').html(data);
				});
			}
			if (what=='todo' && $('#c-todo') && $('#c-todo-num')) {
				$.get(url + '&what=todo', {}, function(data) {
					$('#c-todo-num').html(data);
				});
			}
			if (what=='newactivity' && $('#c-new') && $('#c-new-num')) {
				$.get(url + '&what=newactivity', {}, function(data) {
					$('#c-new-num').html(data);
				});
			}
		}
	},

	// Launch SqueezeBox with Ajax actions
	launchBox: function()
	{
		var $ = this.jQuery;
		var bWidth 	= 600;
		var bHeight = 500;
		var css 	= 'sbp-window';
		var cBtn	= 1;

		$('.showinbox').each(function(i, item) {
			// Clean up
			$(item).off('click');

			var href = $(item).attr('href');
			if (href.search('&no_html=1') == -1) {
				href = href + '&no_html=1';
			}
			if (href.search('&ajax=1') == -1) {
				href = href + '&ajax=1';
			}
			$(item).attr('href', href);

			// TEX compiler view
			if ($(item).hasClass('tex-menu'))
			{
				bWidth = 800;
			}

			// Open box on click
			$(item).on('click', function(e) {
				e.preventDefault();

				// New publication process: fileselector
				if ($(this).hasClass('item-add'))
				{
					bWidth = 700;
				}
				if ($(this).hasClass('nox'))
				{
					cBtn = 0;
				}

				if (!$(this).hasClass('inactive')) {
					// Modal box for actions
					$.fancybox(this,{
						type: 'ajax',
						width: bWidth,
						height: 'auto',
						autoSize: false,
						fitToView: false,
						wrapCSS: css,
						closeBtn: cBtn,
						afterShow: function() {
							if ($('#cancel-action')) {
								$('#cancel-action').on('click', function(e) {
									$.fancybox.close();
								});
							}

							// Publication process
							if ($('#ajax-selections') && $('#section')) {
								if (HUB.ProjectPublications) {
									var replacement = '';
									if ($('#section').val() == 'gallery' || $('#section').val() == 'content') {
										replacement = 'clone-';
									} else {
										replacement = 'clone-author::';
									}
									var selections = HUB.ProjectPublications.gatherSelections(replacement);
									$('#ajax-selections').val(selections);
								}
							}
							// Reviewers
							HUB.Projects.resetApproval();
						}
					});
				}
			});
		});
	},

	resetApproval: function()
	{
		var $ = this.jQuery;
		if ($('#grant_approval') && $('#rejected')) {
			$('#grant_approval').on('keyup', function(e) {
				if ($('#grant_approval').val() != '') {
					$('#rejected').attr('checked', 'checked');
				}
			});
			$('#rejected').on('click', function(e) {
				if ($('#rejected').attr('checked') != 'undefined' && $('#rejected').attr('checked') == 'checked') {
					$('#grant_approval').val('');
				}
			});
		}
	},

	setCounter: function(el, numel)
	{
		var $ = this.jQuery;
		var maxchars = 250,
			current_length = $(el).val().length,
			remaining_chars = maxchars-current_length;

		if (remaining_chars < 0) {
			remaining_chars = 0;
		}

		if ($(numel).length) {
			if (remaining_chars <= 10) {
				$(numel).css('color', '#ff0000').html(remaining_chars + ' chars remaining');
			} else {
				$(numel).css('color', '#999999').html('');
			}
		}

		if (remaining_chars == 0) {
			$(el).val($(el).val().substr(0, maxchars));
		}
	},

	cleanupText: function(text)
	{
		// Clean up entered value
		var cleaned = text.toLowerCase()
						  .replace('_', '')
						  .replace('-', '')
						  .replace(' ', '')
						  .replace(/[|&;$%@"<>()+,#!?.~*^=-_]/g, '');
		return cleaned;
	},

	fixJS: function()
	{
		var $ = this.jQuery;
		var js_off = $(".nojs"),
			js_on = $(".js");

		// Hide all no-js messages
		if (js_off.length)
		{
			js_off.each(function(i, item) {
				$(item).css('display', 'none');
			});
		}

		// Show all js-only options
		if (js_on.length)
		{
			js_on.each(function(i, item) {
				$(item).removeClass('js');
			});
		}
	},

	addConfirm: function (link, question, yesanswer, noanswer)
	{
		var $ = this.jQuery;
		if ($('#confirm-box')) {
			$('#confirm-box').remove();
		}

		var href = $(link).attr('href');

		// Add confirmation
		var ancestor = $(link).parent().parent();
		$(ancestor).after('
' +
			'
' + question + '
' +
			'
' +
				'' + yesanswer + '' +
				'' + noanswer + '' +
			'
' +
		'
');

		$('#confirm-box-cancel').on('click', function(e){
			e.preventDefault();
			$('#confirm-box').remove();
		});

		// Move close to item
		var coord = $($(link).parent()).position();

		$('html, body').animate({
			scrollTop: $(link).offset().top
		}, 2000);

		$('#confirm-box').css('left', coord.left).css('top', coord.top + 200);
	},

	loadingIma: function(txt)
	{
		var html = '' +
			'' +
			' ' +
			' ' +
			'  ';

		if (txt)
		{
			html = html + txt;
		}

		html = html +
			'' +
		'';

		return html;
	},

	setStatusMessage: function (txt, loading)
	{
		var $ = this.jQuery;

		var log = $('#status-msg').empty();

		if (loading == 1)
		{
			$('#status-msg').addClass('ajax-loading');

			if (!txt)
			{
				txt = 'Please wait while we are performing your request...';
			}

			var html = HUB.Projects.loadingIma(txt);
		}
		else
		{
			var html = txt;
		}

		// Add element
		if (txt)
		{
			$('#status-msg').html(html);
			$('#status-msg').css({'opacity':100});
		}
		else
		{
			$('#status-msg').css('opacity', 0);
			return;
		}
	},

	getArrayIndex: function (obj, arr)
	{
		if (!Array.indexOf)
		{
			// Fix for indexOf in IE browsers
			for (var i = 0, j = arr.length; i < j; i++)
			{
			   if (arr[i] === obj) { return i; }
			}
			return -1;
		}
		else
		{
			return arr.indexOf(obj);
		}
	}
}

jQuery(document).ready(function($){
	HUB.Projects.initialize();
});<commit_msg>[COM_PROJECTS] remove annoying scroll when clicking to confirm delete<commit_after>/**
 * Copyright 2005-2009 by Purdue Research Foundation, West Lafayette, IN 47906.
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License,
 * version 2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

//-----------------------------------------------------------
//  Ensure we have our namespace
//-----------------------------------------------------------
if (!HUB) {
	var HUB = {};
}

//----------------------------------------------------------
// Project Component JS
//----------------------------------------------------------
if (!jq) {
	var jq = $;
}

HUB.Projects = {
	jQuery: jq,

	initialize: function()
	{
		// Fix up users with no JS
		HUB.Projects.fixJS();

		// Activate boxed content
		HUB.Projects.launchBox();

		// Add confirms
		HUB.Projects.addConfirms();

		// Reviewers
		HUB.Projects.addFiltering();

		// Fade-out status message
		HUB.Projects.addMessageFade();
	},

	addFiltering: function()
	{
		var $ = this.jQuery;
		// Browse projects - filtering
		$(".filterby").each(function(i, item) {
			$(item).on('change', function(e) {
				if ($('#browseForm')) {
					$('#browseForm').submit();
				}
			});
		});
	},

	addMessageFade: function()
	{
		var $ = this.jQuery;

		if ($("#status-msg").length > 0)
		{
			var keyupTimer = setTimeout((function()
			{
				if (!$("#status-msg").hasClass('ajax-loading') && $('#status-msg').html().trim() != '')
				{
					$("#status-msg").animate({opacity:0.0}, 2000, function() {
					    $('#status-msg').html('');
					});
				}
			}), 4000);
		}
	},

	addConfirms: function()
	{
		var $ = this.jQuery;
		// Confirm delete
		$('#suspend').on('click', function(e)
		{
			e.preventDefault();
			HUB.Projects.addConfirm($('#suspend'),
			'Are you sure you want to suspend this project?',
			'Yes, suspend', 'No, do not suspend');
		});

		// Confirm delete
		$('#delproject').on('click', function(e)
		{
			e.preventDefault();
			HUB.Projects.addConfirm($('#delproject'),
			'Are you sure you want to delete this project?
This is a permanent action and cannot be undone.',
			'Yes, delete', 'No, do not delete');
		});

		// Confirm revert
		$('#confirm-revert').on('click', function(e)
			{
				e.preventDefault();
				HUB.Projects.addConfirm($('#confirm-revert'),
				'Are you sure you want to revert this project to draft mode?',
				'Yes, revert', 'No, keep as pending');
		});
	},

	// Refresh counts of project activities and resources
	refreshCount: function(what)
	{
		var $ = this.jQuery;
		if ($('#projectid')) {
			var url = 'index.php?option=com_projects&task=showcount&no_html=1&pid=' + $('#projectid').val();

			if (what=='publications' && $('#c-publications') && $('#c-publications-num')) {
				$.get(url + '&what=publication', {}, function(data) {
					$('#c-publications-num').html(data);
				});
			}
			if (what=='files' && $('#c-files') && $('#c-files-num')) {
				$.get(url + '&what=files', {}, function(data) {
					$('#c-files-num').html(data);
				});
			}
			if (what=='team' && $('#c-team') && $('#c-team-num')) {
				$.get(url + '&what=team', {}, function(data) {
					$('#c-team-num').html(data);
				});
			}
			if (what=='todo' && $('#c-todo') && $('#c-todo-num')) {
				$.get(url + '&what=todo', {}, function(data) {
					$('#c-todo-num').html(data);
				});
			}
			if (what=='newactivity' && $('#c-new') && $('#c-new-num')) {
				$.get(url + '&what=newactivity', {}, function(data) {
					$('#c-new-num').html(data);
				});
			}
		}
	},

	// Launch SqueezeBox with Ajax actions
	launchBox: function()
	{
		var $ = this.jQuery;
		var bWidth 	= 600;
		var bHeight = 500;
		var css 	= 'sbp-window';
		var cBtn	= 1;

		$('.showinbox').each(function(i, item) {
			// Clean up
			$(item).off('click');

			var href = $(item).attr('href');
			if (href.search('&no_html=1') == -1) {
				href = href + '&no_html=1';
			}
			if (href.search('&ajax=1') == -1) {
				href = href + '&ajax=1';
			}
			$(item).attr('href', href);

			// TEX compiler view
			if ($(item).hasClass('tex-menu'))
			{
				bWidth = 800;
			}

			// Open box on click
			$(item).on('click', function(e) {
				e.preventDefault();

				// New publication process: fileselector
				if ($(this).hasClass('item-add'))
				{
					bWidth = 700;
				}
				if ($(this).hasClass('nox'))
				{
					cBtn = 0;
				}

				if (!$(this).hasClass('inactive')) {
					// Modal box for actions
					$.fancybox(this,{
						type: 'ajax',
						width: bWidth,
						height: 'auto',
						autoSize: false,
						fitToView: false,
						wrapCSS: css,
						closeBtn: cBtn,
						afterShow: function() {
							if ($('#cancel-action')) {
								$('#cancel-action').on('click', function(e) {
									$.fancybox.close();
								});
							}

							// Publication process
							if ($('#ajax-selections') && $('#section')) {
								if (HUB.ProjectPublications) {
									var replacement = '';
									if ($('#section').val() == 'gallery' || $('#section').val() == 'content') {
										replacement = 'clone-';
									} else {
										replacement = 'clone-author::';
									}
									var selections = HUB.ProjectPublications.gatherSelections(replacement);
									$('#ajax-selections').val(selections);
								}
							}
							// Reviewers
							HUB.Projects.resetApproval();
						}
					});
				}
			});
		});
	},

	resetApproval: function()
	{
		var $ = this.jQuery;
		if ($('#grant_approval') && $('#rejected')) {
			$('#grant_approval').on('keyup', function(e) {
				if ($('#grant_approval').val() != '') {
					$('#rejected').attr('checked', 'checked');
				}
			});
			$('#rejected').on('click', function(e) {
				if ($('#rejected').attr('checked') != 'undefined' && $('#rejected').attr('checked') == 'checked') {
					$('#grant_approval').val('');
				}
			});
		}
	},

	setCounter: function(el, numel)
	{
		var $ = this.jQuery;
		var maxchars = 250,
			current_length = $(el).val().length,
			remaining_chars = maxchars-current_length;

		if (remaining_chars < 0) {
			remaining_chars = 0;
		}

		if ($(numel).length) {
			if (remaining_chars <= 10) {
				$(numel).css('color', '#ff0000').html(remaining_chars + ' chars remaining');
			} else {
				$(numel).css('color', '#999999').html('');
			}
		}

		if (remaining_chars == 0) {
			$(el).val($(el).val().substr(0, maxchars));
		}
	},

	cleanupText: function(text)
	{
		// Clean up entered value
		var cleaned = text.toLowerCase()
						  .replace('_', '')
						  .replace('-', '')
						  .replace(' ', '')
						  .replace(/[|&;$%@"<>()+,#!?.~*^=-_]/g, '');
		return cleaned;
	},

	fixJS: function()
	{
		var $ = this.jQuery;
		var js_off = $(".nojs"),
			js_on = $(".js");

		// Hide all no-js messages
		if (js_off.length)
		{
			js_off.each(function(i, item) {
				$(item).css('display', 'none');
			});
		}

		// Show all js-only options
		if (js_on.length)
		{
			js_on.each(function(i, item) {
				$(item).removeClass('js');
			});
		}
	},

	addConfirm: function (link, question, yesanswer, noanswer)
	{
		var $ = this.jQuery;
		if ($('#confirm-box')) {
			$('#confirm-box').remove();
		}

		var href = $(link).attr('href');

		// Add confirmation
		var ancestor = $(link).parent().parent();
		$(ancestor).after('
' +
			'
' + question + '
' +
			'
' +
				'' + yesanswer + '' +
				'' + noanswer + '' +
			'
' +
		'
');

		$('#confirm-box-cancel').on('click', function(e){
			e.preventDefault();
			$('#confirm-box').remove();
		});

		// Move close to item
		var coord = $($(link).parent()).position();

		/*
		$('html, body').animate({
			scrollTop: $(link).offset().top
		}, 2000); */

		$('#confirm-box').css('left', coord.left).css('top', coord.top + 200);
	},

	loadingIma: function(txt)
	{
		var html = '' +
			'' +
			' ' +
			' ' +
			'  ';

		if (txt)
		{
			html = html + txt;
		}

		html = html +
			'' +
		'';

		return html;
	},

	setStatusMessage: function (txt, loading)
	{
		var $ = this.jQuery;

		var log = $('#status-msg').empty();

		if (loading == 1)
		{
			$('#status-msg').addClass('ajax-loading');

			if (!txt)
			{
				txt = 'Please wait while we are performing your request...';
			}

			var html = HUB.Projects.loadingIma(txt);
		}
		else
		{
			var html = txt;
		}

		// Add element
		if (txt)
		{
			$('#status-msg').html(html);
			$('#status-msg').css({'opacity':100});
		}
		else
		{
			$('#status-msg').css('opacity', 0);
			return;
		}
	},

	getArrayIndex: function (obj, arr)
	{
		if (!Array.indexOf)
		{
			// Fix for indexOf in IE browsers
			for (var i = 0, j = arr.length; i < j; i++)
			{
			   if (arr[i] === obj) { return i; }
			}
			return -1;
		}
		else
		{
			return arr.indexOf(obj);
		}
	}
}

jQuery(document).ready(function($){
	HUB.Projects.initialize();
});<|endoftext|>


<commit_before>Ext.define('GeoExt.tree.LayerNode', {
    extend: 'Ext.AbstractPlugin',
    mixins: ['Ext.util.Observable'],
    alias: 'plugin.gx_layer',

    /**
     * The layer that the layer node will be bound to.
     * @cfg {OpenLayers.Layer} layer
     */

    /**
     * If provided, nodes will be rendered with a radio button instead of a
     * checkbox. All layers represented by nodes with the same checkedGroup are
     * considered mutually exclusive - only one can be visible at a time.
     * @cfg {String} checkedGroup
     */

    /**
     * If the node was configured with a text, we consider the text fixed and
     * won't update it when the layer's name changes.
     * @cfg {Boolean} fixedText
     */

    /**
     *  @private
     */
    init: function(target) {
        target.raw.checked = "";
        target.raw.layer = this.layer;
        target.raw.checkedGroup = this.checkedGroup;
        target.raw.fixedText = !!target.raw.text;

        target.raw.leaf = target.raw.leaf || !target.raw.children;

        if(!target.raw.iconCls && !target.raw.children) {
            target.raw.iconCls = "gx-tree-layer-icon";
        }

        if (target.raw.text) {
            this.fixedText = true;
        }
    }

});<commit_msg>Setting checkedGroup<commit_after>Ext.define('GeoExt.tree.LayerNode', {
    extend: 'Ext.AbstractPlugin',
    mixins: ['Ext.util.Observable'],
    alias: 'plugin.gx_layer',

    /**
     * The layer that the layer node will be bound to.
     * @cfg {OpenLayers.Layer} layer
     */

    /**
     * If provided, nodes will be rendered with a radio button instead of a
     * checkbox. All layers represented by nodes with the same checkedGroup are
     * considered mutually exclusive - only one can be visible at a time.
     * @cfg {String} checkedGroup
     */

    /**
     * If the node was configured with a text, we consider the text fixed and
     * won't update it when the layer's name changes.
     * @cfg {Boolean} fixedText
     */

    /**
     *  @private
     */
    init: function(target) {
        target.raw.checked = "";
        target.raw.layer = this.layer;
        target.raw.checkedGroup = this.checkedGroup === undefined ?
            this.layer.isBaseLayer ? "gx_baselayer" : "" :
            "";
        target.raw.fixedText = !!target.raw.text;

        target.raw.leaf = target.raw.leaf || !target.raw.children;

        if(!target.raw.iconCls && !target.raw.children) {
            target.raw.iconCls = "gx-tree-layer-icon";
        }

        if (target.raw.text) {
            this.fixedText = true;
        }
    }

});<|endoftext|>


<commit_before>#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import util from 'util';
import repl from 'repl';
import minimist from 'minimist';
import 'source-map-support/register';
import Log from '@gasbuddy/configured-pino';
import Service from './Service';
import Server from './Server';
import { syntheticRequest } from './util';

const HISTORY_FILE = '.node_repl_history.log';

const argv = minimist(process.argv.slice(2), {
  boolean: ['built', 'repl', 'nobind', 'babel', 'nosubs'],
});

if (argv.nosubs) {
  // A little helper for a common issue which is wanting to run a service
  // without any queue processing
  process.env.DISABLE_RABBITMQ_SUBSCRIPTIONS = 'true';
}

if (argv.repl) {
  // REPL shouldn't buffer logs
  process.env.NO_LOG_BUFFERING = 'true';
}

let ServiceClass = Service;

if (argv.module) {
  // eslint-disable-next-line global-require, import/no-dynamic-require
  const serviceModule = require(argv.module);
  if (argv.className && serviceModule[argv.className]) {
    ServiceClass = serviceModule[argv.className];
  } else {
    ServiceClass = serviceModule;
  }
}

const prettyPrint = !process.env.NO_PRETTY_LOGS
  || ((process.env.NODE_ENV || 'development') === 'development');
const BaseLogger = new Log({}, {
  prettyPrint,
  useLevelLabels: true,
  meta: { },
});
const logger = BaseLogger.start();

const ServerClass = ServiceClass.Server || Server;

// eslint-disable-next-line import/no-dynamic-require
const pkg = require(path.join(process.cwd(), 'package.json'));
const name = pkg.name.replace(/^@[^/]+\//, '');

// ES6 native promises are kinda slow, missing convenience methods,
// and don't get long stack traces (mainly used in tests). This decision has
// to be made early, thus we make it here in our opinionated launcher
global.Promise = require('bluebird');

// More opinion... Your src should be in src pre-transpile and build after
let dirname = path.join(process.cwd(), 'src');

if (!argv.babel && (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging' || argv.built)) {
  dirname = path.join(process.cwd(), 'build');
} else {
  // eslint-disable-next-line global-require
  require('@babel/register')();
}

try {
  const env = fs.readFileSync(path.join(process.cwd(), '.env'), 'utf8');
  if (env) {
    for (const envVar of env.split('\n')) {
      const match = envVar.match(/(?:\S+\s+)?\s*([^=]+)\s*=(.*)\s*/);
      if (match) {
        if (!process.env[match[1]]) {
          logger.info(`Read ${match[1]} environment variable from .env`);
          const [, key, value] = match;
          process.env[key] = value;
        }
      }
    }
  }
} catch (error) {
  // Nothing to do
}

logger.info(`Starting ${name} from ${dirname}`);

let service;
let server;

process.on('unhandledRejection', (err) => {
  try {
    if (service && service.wrapError) {
      logger.error('Unhandled Rejection', service.wrapError(err));
    } else {
      logger.error('Unhandled Rejection', JSON.stringify(err));
    }
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error('Unhandled Rejection', JSON.stringify(err));
  }
});

if (argv.nobind) {
  service = new ServiceClass(name);
  service.configure(dirname).catch((err) => {
    logger.error('Configuration failed', service.wrapError(err));
  }).then(() => {
    // Done with this disconnected logger
    BaseLogger.stop();
  });
} else {
  // Done with this disconnected logger
  BaseLogger.stop();
  server = new ServerClass(name);
  ({ service } = server);

  server
    .create(dirname)
    .catch(() => {
      if (!argv.repl) {
        process.exit(-1);
      }
    });
}

if (argv.repl) {
  let promiseCounter = 1;
  let displayedHistoryError = false;
  const rl = repl.start({
    prompt: '> ',
    writer(v) {
      try {
        fs.appendFileSync(HISTORY_FILE, rl.lines.join('\n'));
      } catch (e) {
        if (!displayedHistoryError) {
          displayedHistoryError = true;
          // eslint-disable-next-line no-console
          console.error('History could not be saved', e);
        }
      }
      if (v && typeof v.then === 'function' && typeof v.catch === 'function') {
        const me = promiseCounter;
        promiseCounter += 1;
        v
          .then((r) => {
            // eslint-disable-next-line no-console
            console.log(`\nPromise #${me} returns`, util.inspect(r));
            rl.context['$'] = r;
          })
          // eslint-disable-next-line no-console
          .catch(e => console.error(`\nPromise #${me} error`, util.inspect(e)));
        return `{ Returned Promise #${me} }`;
      }
      return util.inspect(v);
    },
  });
  try {
    // load command history from a file
    fs.readFileSync(HISTORY_FILE, 'utf8')
      .split('\n')
      .reverse()
      .filter(line => line.trim())
      .forEach(line => rl.history.push(line));
  } catch (e) {
    if (e.code !== 'ENOENT') {
      // eslint-disable-next-line no-console
      console.error('History unavailable', e);
    }
  }
  rl.on('exit', () => {
    service.destroy();
  });

  service.on('configured', () => {
    // Build a synthetic req to make calls easier
    const correlationid = argv.correlationid || `${service.name}-repl-${Date.now()}`;
    const req = syntheticRequest(service, correlationid);
    rl.context.req = req;
  });

  rl.context.server = server;
  rl.context.service = service;
  rl.context.repl = rl;
}
<commit_msg>Oops, lint<commit_after>#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import util from 'util';
import repl from 'repl';
import minimist from 'minimist';
import 'source-map-support/register';
import Log from '@gasbuddy/configured-pino';
import Service from './Service';
import Server from './Server';
import { syntheticRequest } from './util';

const HISTORY_FILE = '.node_repl_history.log';

const argv = minimist(process.argv.slice(2), {
  boolean: ['built', 'repl', 'nobind', 'babel', 'nosubs'],
});

if (argv.nosubs) {
  // A little helper for a common issue which is wanting to run a service
  // without any queue processing
  process.env.DISABLE_RABBITMQ_SUBSCRIPTIONS = 'true';
}

if (argv.repl) {
  // REPL shouldn't buffer logs
  process.env.NO_LOG_BUFFERING = 'true';
}

let ServiceClass = Service;

if (argv.module) {
  // eslint-disable-next-line global-require, import/no-dynamic-require
  const serviceModule = require(argv.module);
  if (argv.className && serviceModule[argv.className]) {
    ServiceClass = serviceModule[argv.className];
  } else {
    ServiceClass = serviceModule;
  }
}

const prettyPrint = !process.env.NO_PRETTY_LOGS
  || ((process.env.NODE_ENV || 'development') === 'development');
const BaseLogger = new Log({}, {
  prettyPrint,
  useLevelLabels: true,
  meta: { },
});
const logger = BaseLogger.start();

const ServerClass = ServiceClass.Server || Server;

// eslint-disable-next-line import/no-dynamic-require
const pkg = require(path.join(process.cwd(), 'package.json'));
const name = pkg.name.replace(/^@[^/]+\//, '');

// ES6 native promises are kinda slow, missing convenience methods,
// and don't get long stack traces (mainly used in tests). This decision has
// to be made early, thus we make it here in our opinionated launcher
global.Promise = require('bluebird');

// More opinion... Your src should be in src pre-transpile and build after
let dirname = path.join(process.cwd(), 'src');

if (!argv.babel && (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging' || argv.built)) {
  dirname = path.join(process.cwd(), 'build');
} else {
  // eslint-disable-next-line global-require
  require('@babel/register')();
}

try {
  const env = fs.readFileSync(path.join(process.cwd(), '.env'), 'utf8');
  if (env) {
    for (const envVar of env.split('\n')) {
      const match = envVar.match(/(?:\S+\s+)?\s*([^=]+)\s*=(.*)\s*/);
      if (match) {
        if (!process.env[match[1]]) {
          logger.info(`Read ${match[1]} environment variable from .env`);
          const [, key, value] = match;
          process.env[key] = value;
        }
      }
    }
  }
} catch (error) {
  // Nothing to do
}

logger.info(`Starting ${name} from ${dirname}`);

let service;
let server;

process.on('unhandledRejection', (err) => {
  try {
    if (service && service.wrapError) {
      logger.error('Unhandled Rejection', service.wrapError(err));
    } else {
      logger.error('Unhandled Rejection', JSON.stringify(err));
    }
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error('Unhandled Rejection', JSON.stringify(err));
  }
});

if (argv.nobind) {
  service = new ServiceClass(name);
  service.configure(dirname).catch((err) => {
    logger.error('Configuration failed', service.wrapError(err));
  }).then(() => {
    // Done with this disconnected logger
    BaseLogger.stop();
  });
} else {
  // Done with this disconnected logger
  BaseLogger.stop();
  server = new ServerClass(name);
  ({ service } = server);

  server
    .create(dirname)
    .catch(() => {
      if (!argv.repl) {
        process.exit(-1);
      }
    });
}

if (argv.repl) {
  let promiseCounter = 1;
  let displayedHistoryError = false;
  const rl = repl.start({
    prompt: '> ',
    writer(v) {
      try {
        fs.appendFileSync(HISTORY_FILE, rl.lines.join('\n'));
      } catch (e) {
        if (!displayedHistoryError) {
          displayedHistoryError = true;
          // eslint-disable-next-line no-console
          console.error('History could not be saved', e);
        }
      }
      if (v && typeof v.then === 'function' && typeof v.catch === 'function') {
        const me = promiseCounter;
        promiseCounter += 1;
        v
          .then((r) => {
            // eslint-disable-next-line no-console
            console.log(`\nPromise #${me} returns`, util.inspect(r));
            rl.context.$ = r;
          })
          // eslint-disable-next-line no-console
          .catch(e => console.error(`\nPromise #${me} error`, util.inspect(e)));
        return `{ Returned Promise #${me} }`;
      }
      return util.inspect(v);
    },
  });
  try {
    // load command history from a file
    fs.readFileSync(HISTORY_FILE, 'utf8')
      .split('\n')
      .reverse()
      .filter(line => line.trim())
      .forEach(line => rl.history.push(line));
  } catch (e) {
    if (e.code !== 'ENOENT') {
      // eslint-disable-next-line no-console
      console.error('History unavailable', e);
    }
  }
  rl.on('exit', () => {
    service.destroy();
  });

  service.on('configured', () => {
    // Build a synthetic req to make calls easier
    const correlationid = argv.correlationid || `${service.name}-repl-${Date.now()}`;
    const req = syntheticRequest(service, correlationid);
    rl.context.req = req;
  });

  rl.context.server = server;
  rl.context.service = service;
  rl.context.repl = rl;
}
<|endoftext|>


<commit_before>

var app = angular.module('restApp',[])

app.controller('applicationController',['$scope',function($scope) {
    $scope.mapOptions = {
      center: {
         lat: 40.7903,
         lng: -73.9597
      },
      zoom: 10
    };

    $scope.map = new google.maps.Map(document.getElementById('map-canvas'),$scope.mapOptions);
    $scope.markers = [];
    $scope.koverseIsReady = KoverseApplication.EVENT_READY;
    $scope.dataCollection = null;

    // Koverse.addEventListener($scope.koverseIsReady, function() {
      // console.log("[Koverse] Ready1.");
      // Koverse.getDataCollectionByName('violators',function(dataCollectionResponse) {
      //   $scope.dataCollection = dataCollectionResponse.dataCollection;
      // });
    // });

    Koverse.addEventListener($scope.koverseIsReady, function() {
      console.log("[Koverse] Ready2.");

      Koverse.getDataCollectionByName('georestaurants',function(dataCollectionResponse) {
        $scope.dataCollection = dataCollectionResponse.dataCollection;
        Koverse.performQuery("{$any: *}",[$scope.dataCollection.id],function(response) {
          $scope.records = response.records;
          _.each($scope.records,function(record) {
            var fields = record.fields;
            var latLng = new google.maps.LatLng(fields.Latitude,fields.Longitude)
            var marker = new google.maps.Marker({
              'position': latLng
            });
            console.log("[Koverse] Will push marker.");
            $scope.markers.push(marker);
          });
          $scope.mc = new MarkerClusterer($scope.map,$scope.markers);
        },200,0,false);
      });

    });

    Koverse.addEventListener($scope.koverseIsReady, function() {
      console.log("[Koverse] Ready3.");
      $scope.mc = new MarkerClusterer($scope.map,$scope.markers);
    });

    $scope.mc = new MarkerClusterer($scope.map,$scope.markers);
    google.maps.event.addDomListener(window, 'load');

    $scope.debug = function() {
      debugger;
    };
}]);

<commit_msg>Will add click event.<commit_after>

var app = angular.module('restApp',[])

app.controller('applicationController',['$scope',function($scope) {
    $scope.mapOptions = {
      center: {
         lat: 40.7903,
         lng: -73.9597
      },
      zoom: 10
    };

    $scope.map = new google.maps.Map(document.getElementById('map-canvas'),$scope.mapOptions);
    $scope.markers = [];
    $scope.koverseIsReady = KoverseApplication.EVENT_READY;
    $scope.dataCollection = null;

    // Koverse.addEventListener($scope.koverseIsReady, function() {
      // console.log("[Koverse] Ready1.");
      // Koverse.getDataCollectionByName('violators',function(dataCollectionResponse) {
      //   $scope.dataCollection = dataCollectionResponse.dataCollection;
      // });
    // });

    Koverse.addEventListener($scope.koverseIsReady, function() {
      console.log("[Koverse] Ready2.");

      Koverse.getDataCollectionByName('georestaurants',function(dataCollectionResponse) {
        $scope.dataCollection = dataCollectionResponse.dataCollection;
        Koverse.performQuery("{$any: *}",[$scope.dataCollection.id],function(response) {
          $scope.records = response.records;
          _.each($scope.records,function(record) {
            var fields = record.fields;
            var camis = fields.CAMIS.toString();
            var latLng = new google.maps.LatLng(fields.Latitude,fields.Longitude)
            var marker = new google.maps.Marker({
              'position': latLng,
              title: camis
            });

            google.maps.event.addListener(marker, 'click', function() {
               alert("foo");
             });

            $scope.markers.push(marker);
          });
          $scope.mc = new MarkerClusterer($scope.map,$scope.markers);
        },200,0,false);
      });

    });

    Koverse.addEventListener($scope.koverseIsReady, function() {
      console.log("[Koverse] Ready3.");
      $scope.mc = new MarkerClusterer($scope.map,$scope.markers);
    });

    $scope.mc = new MarkerClusterer($scope.map,$scope.markers);
    google.maps.event.addDomListener(window, 'load');

    $scope.debug = function() {
      debugger;
    };
}]);

<|endoftext|>


<commit_before>// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
(function() {
  'use strict';

  const NUMBER_FIXED_COLUMNS = 3;

  Polymer({
    is: 'gr-change-list',

    /**
     * Fired when next page key shortcut was pressed.
     *
     * @event next-page
     */

    /**
     * Fired when previous page key shortcut was pressed.
     *
     * @event previous-page
     */

    hostAttributes: {
      tabindex: 0,
    },

    properties: {
      /**
       * The logged-in user's account, or an empty object if no user is logged
       * in.
       */
      account: {
        type: Object,
        value() { return {}; },
      },
      /**
       * An array of ChangeInfo objects to render.
       * https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-info
       */
      changes: {
        type: Array,
        observer: '_changesChanged',
      },
      /**
       * ChangeInfo objects grouped into arrays. The sections and changes
       * properties should not be used together.
       *
       * @type {!Array<{
       *   sectionName: string,
       *   query: string,
       *   results: !Array<!Object>
       * }>}
       */
      sections: {
        type: Array,
        value() { return []; },
      },
      labelNames: {
        type: Array,
        computed: '_computeLabelNames(sections)',
      },
      selectedIndex: {
        type: Number,
        notify: true,
      },
      showNumber: Boolean, // No default value to prevent flickering.
      showStar: {
        type: Boolean,
        value: false,
      },
      showReviewedState: {
        type: Boolean,
        value: false,
      },
      keyEventTarget: {
        type: Object,
        value() { return document.body; },
      },
      changeTableColumns: Array,
      visibleChangeTableColumns: Array,
    },

    behaviors: [
      Gerrit.BaseUrlBehavior,
      Gerrit.ChangeTableBehavior,
      Gerrit.KeyboardShortcutBehavior,
      Gerrit.RESTClientBehavior,
      Gerrit.URLEncodingBehavior,
    ],

    keyBindings: {
      'j': '_handleJKey',
      'k': '_handleKKey',
      'n ]': '_handleNKey',
      'o': '_handleOKey',
      'p [': '_handlePKey',
      'shift+r': '_handleRKey',
      's': '_handleSKey',
    },

    listeners: {
      keydown: '_scopedKeydownHandler',
    },

    /**
     * Iron-a11y-keys-behavior catches keyboard events globally. Some keyboard
     * events must be scoped to a component level (e.g. `enter`) in order to not
     * override native browser functionality.
     *
     * Context: Issue 7294
     */
    _scopedKeydownHandler(e) {
      if (e.keyCode === 13) {
        // Enter.
        this._handleOKey(e);
      }
    },

    attached() {
      this._loadPreferences();
    },

    _lowerCase(column) {
      return column.toLowerCase();
    },

    _loadPreferences() {
      return this._getLoggedIn().then(loggedIn => {
        this.changeTableColumns = this.columnNames;

        if (!loggedIn) {
          this.showNumber = false;
          this.visibleChangeTableColumns = this.columnNames;
          return;
        }
        return this._getPreferences().then(preferences => {
          this.showNumber = !!(preferences &&
              preferences.legacycid_in_change_table);
          this.visibleChangeTableColumns = preferences.change_table.length > 0 ?
              preferences.change_table : this.columnNames;
        });
      });
    },

    _getLoggedIn() {
      return this.$.restAPI.getLoggedIn();
    },

    _getPreferences() {
      return this.$.restAPI.getPreferences();
    },

    _computeColspan(changeTableColumns, labelNames) {
      return changeTableColumns.length + labelNames.length +
          NUMBER_FIXED_COLUMNS;
    },

    _computeLabelNames(sections) {
      if (!sections) { return []; }
      let labels = [];
      const nonExistingLabel = function(item) {
        return !labels.includes(item);
      };
      for (const section of sections) {
        if (!section.results) { continue; }
        for (const change of section.results) {
          if (!change.labels) { continue; }
          const currentLabels = Object.keys(change.labels);
          labels = labels.concat(currentLabels.filter(nonExistingLabel));
        }
      }
      return labels.sort();
    },

    _computeLabelShortcut(labelName) {
      return labelName.split('-').reduce((a, i) => {
        return a + i[0].toUpperCase();
      }, '');
    },

    _changesChanged(changes) {
      this.sections = changes ? [{results: changes}] : [];
    },

    _sectionHref(query) {
      return `${this.getBaseUrl()}/q/${this.encodeURL(query, true)}`;
    },

    /**
     * Maps an index local to a particular section to the absolute index
     * across all the changes on the page.
     *
     * @param sectionIndex {number} index of section
     * @param localIndex {number} index of row within section
     * @return {number} absolute index of row in the aggregate dashboard
     */
    _computeItemAbsoluteIndex(sectionIndex, localIndex) {
      let idx = 0;
      for (let i = 0; i < sectionIndex; i++) {
        idx += this.sections[i].results.length;
      }
      return idx + localIndex;
    },

    _computeItemSelected(sectionIndex, index, selectedIndex) {
      const idx = this._computeItemAbsoluteIndex(sectionIndex, index);
      return idx == selectedIndex;
    },

    _computeItemNeedsReview(account, change, showReviewedState) {
      return showReviewedState && !change.reviewed &&
          this.changeIsOpen(change.status) &&
          account._account_id != change.owner._account_id;
    },

    _computeItemAssigned(account, change) {
      if (!change.assignee) { return false; }
      return account._account_id === change.assignee._account_id;
    },

    _handleJKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      // Compute absolute index of item that would come after final item.
      const len = this._computeItemAbsoluteIndex(this.sections.length, 0);
      if (this.selectedIndex === len - 1) { return; }
      this.selectedIndex += 1;
    },

    _handleKKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      if (this.selectedIndex === 0) { return; }
      this.selectedIndex -= 1;
    },

    _handleOKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      Gerrit.Nav.navigateToChange(this._changeForIndex(this.selectedIndex));
    },

    _handleNKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e) && !this.isModifierPressed(e, 'shiftKey')) {
        return;
      }

      e.preventDefault();
      this.fire('next-page');
    },

    _handlePKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e) && !this.isModifierPressed(e, 'shiftKey')) {
        return;
      }

      e.preventDefault();
      this.fire('previous-page');
    },

    _handleRKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      window.location.reload();
    },

    _handleSKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      this._toggleStarForIndex(this.selectedIndex);
    },

    _toggleStarForIndex(index) {
      const changeEls = this._getListItems();
      if (index >= changeEls.length || !changeEls[index]) {
        return;
      }

      const changeEl = changeEls[index];
      const change = changeEl.change;
      const newVal = !change.starred;
      changeEl.set('change.starred', newVal);
      this.$.restAPI.saveChangeStarred(change._number, newVal);
    },

    _changeForIndex(index) {
      const changeEls = this._getListItems();
      if (index < changeEls.length && changeEls[index]) {
        return changeEls[index].change;
      }
      return null;
    },

    _getListItems() {
      return Polymer.dom(this.root).querySelectorAll('gr-change-list-item');
    },
  });
})();
<commit_msg>PG: fix warnings flagged by closure compiler<commit_after>// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
(function() {
  'use strict';

  const NUMBER_FIXED_COLUMNS = 3;

  Polymer({
    is: 'gr-change-list',

    /**
     * Fired when next page key shortcut was pressed.
     *
     * @event next-page
     */

    /**
     * Fired when previous page key shortcut was pressed.
     *
     * @event previous-page
     */

    hostAttributes: {
      tabindex: 0,
    },

    properties: {
      /**
       * The logged-in user's account, or an empty object if no user is logged
       * in.
       */
      account: {
        type: Object,
        value() { return {}; },
      },
      /**
       * An array of ChangeInfo objects to render.
       * https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-info
       */
      changes: {
        type: Array,
        observer: '_changesChanged',
      },
      /**
       * ChangeInfo objects grouped into arrays. The sections and changes
       * properties should not be used together.
       *
       * @type {!Array<{
       *   sectionName: string,
       *   query: string,
       *   results: !Array<!Object>
       * }>}
       */
      sections: {
        type: Array,
        value() { return []; },
      },
      labelNames: {
        type: Array,
        computed: '_computeLabelNames(sections)',
      },
      selectedIndex: {
        type: Number,
        notify: true,
      },
      showNumber: Boolean, // No default value to prevent flickering.
      showStar: {
        type: Boolean,
        value: false,
      },
      showReviewedState: {
        type: Boolean,
        value: false,
      },
      keyEventTarget: {
        type: Object,
        value() { return document.body; },
      },
      changeTableColumns: Array,
      visibleChangeTableColumns: Array,
    },

    behaviors: [
      Gerrit.BaseUrlBehavior,
      Gerrit.ChangeTableBehavior,
      Gerrit.KeyboardShortcutBehavior,
      Gerrit.RESTClientBehavior,
      Gerrit.URLEncodingBehavior,
    ],

    keyBindings: {
      'j': '_handleJKey',
      'k': '_handleKKey',
      'n ]': '_handleNKey',
      'o': '_handleOKey',
      'p [': '_handlePKey',
      'shift+r': '_handleRKey',
      's': '_handleSKey',
    },

    listeners: {
      keydown: '_scopedKeydownHandler',
    },

    /**
     * Iron-a11y-keys-behavior catches keyboard events globally. Some keyboard
     * events must be scoped to a component level (e.g. `enter`) in order to not
     * override native browser functionality.
     *
     * Context: Issue 7294
     */
    _scopedKeydownHandler(e) {
      if (e.keyCode === 13) {
        // Enter.
        this._handleOKey(e);
      }
    },

    attached() {
      this._loadPreferences();
    },

    _lowerCase(column) {
      return column.toLowerCase();
    },

    _loadPreferences() {
      return this._getLoggedIn().then(loggedIn => {
        this.changeTableColumns = this.columnNames;

        if (!loggedIn) {
          this.showNumber = false;
          this.visibleChangeTableColumns = this.columnNames;
          return;
        }
        return this._getPreferences().then(preferences => {
          this.showNumber = !!(preferences &&
              preferences.legacycid_in_change_table);
          this.visibleChangeTableColumns = preferences.change_table.length > 0 ?
              preferences.change_table : this.columnNames;
        });
      });
    },

    _getLoggedIn() {
      return this.$.restAPI.getLoggedIn();
    },

    _getPreferences() {
      return this.$.restAPI.getPreferences();
    },

    _computeColspan(changeTableColumns, labelNames) {
      return changeTableColumns.length + labelNames.length +
          NUMBER_FIXED_COLUMNS;
    },

    _computeLabelNames(sections) {
      if (!sections) { return []; }
      let labels = [];
      const nonExistingLabel = function(item) {
        return !labels.includes(item);
      };
      for (const section of sections) {
        if (!section.results) { continue; }
        for (const change of section.results) {
          if (!change.labels) { continue; }
          const currentLabels = Object.keys(change.labels);
          labels = labels.concat(currentLabels.filter(nonExistingLabel));
        }
      }
      return labels.sort();
    },

    _computeLabelShortcut(labelName) {
      return labelName.split('-').reduce((a, i) => {
        return a + i[0].toUpperCase();
      }, '');
    },

    _changesChanged(changes) {
      this.sections = changes ? [{results: changes}] : [];
    },

    _sectionHref(query) {
      return `${this.getBaseUrl()}/q/${this.encodeURL(query, true)}`;
    },

    /**
     * Maps an index local to a particular section to the absolute index
     * across all the changes on the page.
     *
     * @param {number} sectionIndex index of section
     * @param {number} localIndex index of row within section
     * @return {number} absolute index of row in the aggregate dashboard
     */
    _computeItemAbsoluteIndex(sectionIndex, localIndex) {
      let idx = 0;
      for (let i = 0; i < sectionIndex; i++) {
        idx += this.sections[i].results.length;
      }
      return idx + localIndex;
    },

    _computeItemSelected(sectionIndex, index, selectedIndex) {
      const idx = this._computeItemAbsoluteIndex(sectionIndex, index);
      return idx == selectedIndex;
    },

    _computeItemNeedsReview(account, change, showReviewedState) {
      return showReviewedState && !change.reviewed &&
          this.changeIsOpen(change.status) &&
          account._account_id != change.owner._account_id;
    },

    _computeItemAssigned(account, change) {
      if (!change.assignee) { return false; }
      return account._account_id === change.assignee._account_id;
    },

    _handleJKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      // Compute absolute index of item that would come after final item.
      const len = this._computeItemAbsoluteIndex(this.sections.length, 0);
      if (this.selectedIndex === len - 1) { return; }
      this.selectedIndex += 1;
    },

    _handleKKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      if (this.selectedIndex === 0) { return; }
      this.selectedIndex -= 1;
    },

    _handleOKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      Gerrit.Nav.navigateToChange(this._changeForIndex(this.selectedIndex));
    },

    _handleNKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e) && !this.isModifierPressed(e, 'shiftKey')) {
        return;
      }

      e.preventDefault();
      this.fire('next-page');
    },

    _handlePKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e) && !this.isModifierPressed(e, 'shiftKey')) {
        return;
      }

      e.preventDefault();
      this.fire('previous-page');
    },

    _handleRKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      window.location.reload();
    },

    _handleSKey(e) {
      if (this.shouldSuppressKeyboardShortcut(e) ||
          this.modifierPressed(e)) { return; }

      e.preventDefault();
      this._toggleStarForIndex(this.selectedIndex);
    },

    _toggleStarForIndex(index) {
      const changeEls = this._getListItems();
      if (index >= changeEls.length || !changeEls[index]) {
        return;
      }

      const changeEl = changeEls[index];
      const change = changeEl.change;
      const newVal = !change.starred;
      changeEl.set('change.starred', newVal);
      this.$.restAPI.saveChangeStarred(change._number, newVal);
    },

    _changeForIndex(index) {
      const changeEls = this._getListItems();
      if (index < changeEls.length && changeEls[index]) {
        return changeEls[index].change;
      }
      return null;
    },

    _getListItems() {
      return Polymer.dom(this.root).querySelectorAll('gr-change-list-item');
    },
  });
})();
<|endoftext|>


<commit_before>/**
 * The EvalSystem set of functions (keeps the namespace clean and tidy) -AZ
 * DEPENDS on jQuery 1.2 to operate
 * @author Antranig Basman
 * @author Aaron Zeckoski (aaronz@vt.edu)
 */
var EvalSystem = function() {
  function $it(elementID) {
    return document.getElementById(elementID);
  }

  /**
   * Because JQuery uses this sort of CSS based selector system, if you have
   * wacky characters in your tag ID (such as RSF Colons) you have to escape
   * them. At the moment this just escapes the colons, should probably have a
   * fuller (or automatic) jquery escaping mechanism.
   */
  function escIdForJquery(value) {
    return value != null ? "#" + value.replace(/:/g, "\\:") : null;
  }

  /**
   * Creates an adhoc group delete function for a specific link,
   * this expects to be called by an event handler
   */
  function makeAdhocDeleteFunction(deleteLink, adhocArea) {
	  return function(event) {
		  var url = deleteLink.attr("href");
		  $.ajax({
			  url: url,
			  type: "DELETE",
			  dataType: "text",
			  cache: false,
			  success: function(data, msg) {
				  adhocArea.fadeOut(500, function() {
					  adhocArea.hide(0);
					  adhocArea.remove();
				  });
			  },
			  error: function(request, msg, errorThrown) {
				  var status = request.status;
				  // 404 just means it does not exist which is ok
				  if (status != "404") {
					  alert( "Failure: " + status + " :" + msg + " :" + errorThrown + " :" + XMLHttpRequest );
				  }
			  }
		  });
		  return false;
	  };
  }

  return {

    /**
     *  A little bit of javascript to validate the Eval Assign Page. At the
     *  moment this is only for making sure users have selected at least one
     *  group or hierarchy node or something.
     *
     * @errorDivId A Div with an already translated message we can light up.
     * @submitButtonId The button that is doing the submitting.
     */
    initEvalAssignValidation: function(formId, errorDivId, submitButtonId) {
        var form = $(escIdForJquery(formId));
        var errorDiv = $(escIdForJquery(errorDivId));
        var submitButton = $(escIdForJquery(submitButtonId));

        // Boolean to store whether the form should submit based on validation.
        var passes = false;

        form.submit(function() {
            if (!passes) {
                errorDiv.show();
                RSF.getDOMModifyFirer().fireEvent();
            }
            return passes;
        });

        var onAssignClick = function(event) {
            passes = false;
            var n = $(".evalgroupselect:checked").length;
            if (n > 0) {
                passes=true;
            }
        }

        submitButton.click( function(event) { onAssignClick(event) } );
    },

    /**
     * Handle the setup of all adhoc group delete handlers
     */
    initEvalAssignAdhocDelete: function(adhocAreaIds) {
    	// get all adhoc areas (these will be hidden when the group is deleted)
    	for (var i = 0; i < adhocAreaIds.length; i++) {
    		var adhocAreaId = adhocAreaIds[i];
    		var adhocArea = $(escIdForJquery(adhocAreaId));
    		var deleteLink = $(escIdForJquery(adhocAreaId + "deleteGroupLink"));
    		if (adhocArea.length > 0 && !(adhocArea[0] === document)
    				&& deleteLink.length > 0 && !(deleteLink[0] === document)) {
    			deleteLink.show(0); // only show the links which actually could be found
    			var onAdhocDeleteClick = makeAdhocDeleteFunction(deleteLink, adhocArea);
    			deleteLink.click( onAdhocDeleteClick );
    		} else {
    			// failed to find the id given, nothing really to do here
    			//alert("Failed to find adhoc elements: " + adhocAreaId + " :" + adhocArea + " :" + deleteLink);
    		}
    	}
    },

    initEvalReportView: function (allCommentsId, allTextResponsesId) {
        // for now this is just enabling toggling of comments and responses
        // see the makeToggle method for description of arguments
        if (allCommentsId.length > 0) {
            $(escIdForJquery(allCommentsId)).show();
            EvalSystem.makeToggle(allCommentsId + "Show", allCommentsId + "Hide", null, "showcomments", false);
        }
        if (allTextResponsesId.length > 0) {
            $(escIdForJquery(allTextResponsesId)).show();
            EvalSystem.makeToggle(allTextResponsesId + "Show", allTextResponsesId + "Hide", null, "showtextresponses", false);
        }
    },

    /**
     * Adds a limitation of numbers only to an input box (inputId),
     * displays the numbers only warning in the message area (msgId)
     */
    addNumericOnly: function(inputId, msgId) {
    	var inputBox = $(escIdForJquery(inputId));
        var msgSpan = $(escIdForJquery(msgId));
        inputBox.keypress(function (e) {
        	//if the letter is not digit then display error and don't type anything
        	if( e.which!=13 && e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
        		//display error message
        		msgSpan.html("Numbers Only").show().fadeOut(3000);
        		return false;
        	}
        });
    },

    /**
     * This will hide an area (or a set areas that match the toggleClass)
     * when the element with hideId is clicked (it will also be hidden),
     * it will show the area(s) and the hideId element when the element with showId is clicked,
     * and also hide the showId element
     * showId: the id of the element that triggers the show when clicked
     * hideId: the id of the element that triggers the hide when clicked
     * areaId: the id of area (div probably) to show/hide, set null if not used
     * toggleClass: a classname such that all elements with this class will be shown/hidden, set null if not used
     * initialHide: if true then start things hidden, else start things shown (default if unspecified)
     */
    makeToggle: function (showId, hideId, areaId, toggleClass, initialHide) {
        var showButton = $(escIdForJquery(showId));
        var hideButton = $(escIdForJquery(hideId));
        var area = $(escIdForJquery(areaId));
        var toggles = $(toggleClass == null ? null : "." + toggleClass);

        var togglearea = showButton.parent().parent();

        showButton.show();

        hideButton.show();
        showButton.parent().next().wrap("");

        var showAction = function(event) {
            showButton.hide();
            hideButton.show();
            area.show("normal");
            toggles.show("normal");
            RSF.getDOMModifyFirer().fireEvent();
        }

        var hideAction = function(event) {
            showButton.show();
            hideButton.hide();
            area.hide("normal");
            toggles.hide("normal");
            RSF.getDOMModifyFirer().fireEvent();
        }

        if (initialHide) {
            hideAction();
        } else {
            showAction();
        }

        var toggle = function(event) {
        	showButton.toggle();
        	hideButton.toggle();
        	area.toggle("normal");
        	toggles.toggle("normal");
        	RSF.getDOMModifyFirer().fireEvent();
        }

        togglearea.click( function (event) { toggle(event) } );

        /*showButton.click( function (event) { showAction(event) });
        hideButton.click( function (event) { hideAction(event) });*/
    },

    // this just makes it easier to add in more stuff later -AZ
    initEvalSettings: function (areaId, selectId, selectValue, reminderId) {
        // see the toggleAndDisableSetReminder method for description of arguments
        EvalSystem.toggleAndDisableSetReminder(areaId, selectId, selectValue, reminderId);
    },

    /**
     * This will hide and disable the setReminder option area
     * and force the setting to 0 reminders on the evaluation settings page
     * when the anonymous auth option is selected OR reveal the option area
     * areaId: the id of area (div probably) to show/hide
     * selectId: the id of the select that triggers the show/hide
     * selectValue: the value of the select that causes the hide action (other cause show)
     * reminderId: the id of the form control to set when hide action happens
     */
    toggleAndDisableSetReminder: function (areaId, selectId, selectValue, reminderId) {
        var area = $("#"+areaId); //document.getElementById(areaId);
        var select = $("#"+selectId); //document.getElementById(selectId);
        var reminder = $("#"+reminderId); //document.getElementById(reminderId);

        var changeAction = function(event) {
            var selectedValue = event.target.value;
            if (selectedValue == selectValue) {
                // values are the same so we need to hide things
                // only take action if needed so we are not resetting the field constantly
                if ( area.is(':visible') ) {
                    // area is currently visible so hide it
                    area.hide("normal");
                    // force reminder to the no reminders setting of 0
                    reminder.val('0');
                }
            } else {
                // set to one of the non-hiding options
                if ( area.is(':hidden') ) {
                    // area is currently hidden so reveal it
                    area.show("slow");
                }
            }
        }
        // add the event for onchange to trigger the changeAction method and cause it to fire immediately
        select.change( function(event) { changeAction(event) }).change();
    },

    getRelativeID: function (baseid, targetid) {
      colpos = baseid.lastIndexOf(':');
      return baseid.substring(0, colpos + 1) + targetid;
    },

   // See http://www.pageresource.com/jscript/jdropbox.htm for general approach
    operateSelectLink: function(linkid, localselectid) {
      var selectid = EvalSystem.getRelativeID(linkid, localselectid);
      var selection = $it(selectid);
      var url = selection.options[selection.selectedIndex].value;
      jQuery.facebox({ ajax: url });
    },

    decorateReorderSelects: function(namebase, count) {
      var buttonid = namebase + "hiddenBtn";
      var button = $it(buttonid);
      for (var i = 0; i < count; ++ i) {
        var selectid = namebase + "item-row:"+i+":item-select-selection";
        var selection = $it(selectid);
        selection.onchange = function() {
        	button.click();
       };
      }
    }

  }
}();<commit_msg>Validated and updated the JS based on JSLint recommendations<commit_after>/**
 * The EvalSystem set of functions (keeps the namespace clean and tidy) -AZ
 * DEPENDS on jQuery 1.2 to operate
 * @author Aaron Zeckoski (aaronz@vt.edu)
 * @author Antranig Basman - dropbox methods at end
 */
var EvalSystem = function() {
	var $ = $ || function() { throw "JQuery undefined"; };
	var RSF = RSF || function() { throw "RSF JS undefined"; };
	function $it(elementID) {
		return document.getElementById(elementID);
	}

	/**
	 * Because JQuery uses this sort of CSS based selector system, if you have
	 * wacky characters in your tag ID (such as RSF Colons) you have to escape
	 * them. At the moment this just escapes the colons, should probably have a
	 * fuller (or automatic) jquery escaping mechanism.
	 */
	function escIdForJquery(value) {
		var escaped = (value !== null ? "#" + value.replace(/:/g, "\\:") : null);
		escaped = (escaped === "#" ? null : escaped);
		return escaped;
	}

	/**
	 * Creates an adhoc group delete function for a specific link,
	 * this expects to be called by an event handler
	 */
	function makeAdhocDeleteFunction(deleteLink, adhocArea) {
		return function(event) {
			var url = deleteLink.attr("href");
			$.ajax({
				url: url,
				type: "DELETE",
				dataType: "text",
				cache: false,
				success: function(data, msg) {
				adhocArea.fadeOut(500, function() {
					adhocArea.hide(0);
					adhocArea.remove();
				});
			},
			error: function(request, msg, errorThrown) {
				var status = request.status;
				// 404 just means it does not exist which is ok
				if (status !== "404") {
					alert( "Failure: " + status + " :" + msg + " :" + errorThrown + " :" + XMLHttpRequest );
				}
			}
			});
			return false;
		};
	}

	return {

		/**
		 *  A little bit of javascript to validate the Eval Assign Page. At the
		 *  moment this is only for making sure users have selected at least one
		 *  group or hierarchy node or something.
		 *
		 * @errorDivId A Div with an already translated message we can light up.
		 * @submitButtonId The button that is doing the submitting.
		 */
		initEvalAssignValidation: function(formId, errorDivId, submitButtonId) {
			var form = $(escIdForJquery(formId));
			var errorDiv = $(escIdForJquery(errorDivId));
			var submitButton = $(escIdForJquery(submitButtonId));

			// Boolean to store whether the form should submit based on validation.
			var passes = false;

			form.submit(function() {
				if (!passes) {
					errorDiv.show();
					RSF.getDOMModifyFirer().fireEvent();
				}
				return passes;
			});

			var onAssignClick = function(event) {
				passes = false;
				var n = $(".evalgroupselect:checked").length;
				if (n > 0) {
					passes=true;
				}
			};

			submitButton.click( function(event) { onAssignClick(event); } );
		},

		/**
		 * Handle the setup of all adhoc group delete handlers
		 */
		initEvalAssignAdhocDelete: function(adhocAreaIds) {
			// get all adhoc areas (these will be hidden when the group is deleted)
			for (var i = 0; i < adhocAreaIds.length; i++) {
				var adhocAreaId = adhocAreaIds[i];
				var adhocArea = $(escIdForJquery(adhocAreaId));
				var deleteLink = $(escIdForJquery(adhocAreaId + "deleteGroupLink"));
				if (adhocArea.length > 0 && deleteLink.length > 0) {
					deleteLink.show(0); // only show the links which actually could be found
					var onAdhocDeleteClick = makeAdhocDeleteFunction(deleteLink, adhocArea);
					deleteLink.click( onAdhocDeleteClick );
				} else {
					// failed to find the id given, nothing really to do here
					//alert("Failed to find adhoc elements: " + adhocAreaId + " :" + adhocArea + " :" + deleteLink);
				}
			}
		},

		initEvalReportView: function (allCommentsId, allTextResponsesId) {
			// for now this is just enabling toggling of comments and responses
			// see the makeToggle method for description of arguments
			if (allCommentsId.length > 0) {
				$(escIdForJquery(allCommentsId)).show();
				EvalSystem.makeToggle(allCommentsId + "Show", allCommentsId + "Hide", null, "showcomments", false);
			}
			if (allTextResponsesId.length > 0) {
				$(escIdForJquery(allTextResponsesId)).show();
				EvalSystem.makeToggle(allTextResponsesId + "Show", allTextResponsesId + "Hide", null, "showtextresponses", false);
			}
		},

		/**
		 * Adds a limitation of numbers only to an input box (inputId),
		 * displays the numbers only warning in the message area (msgId)
		 */
		addNumericOnly: function(inputId, msgId) {
			var inputBox = $(escIdForJquery(inputId));
			var msgSpan = $(escIdForJquery(msgId));
			inputBox.keypress(function (e) {
				//if the letter is not digit then display error and don't type anything
				if( e.which !== 13 && e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
					//display error message
					msgSpan.html("Numbers Only").show().fadeOut(3000);
					return false;
				}
			});
		},

		/**
		 * This will hide an area (or a set areas that match the toggleClass)
		 * when the element with hideId is clicked (it will also be hidden),
		 * it will show the area(s) and the hideId element when the element with showId is clicked,
		 * and also hide the showId element
		 * showId: the id of the element that triggers the show when clicked
		 * hideId: the id of the element that triggers the hide when clicked
		 * areaId: the id of area (div probably) to show/hide, set null if not used
		 * toggleClass: a classname such that all elements with this class will be shown/hidden, set null if not used
		 * initialHide: if true then start things hidden, else start things shown (default if unspecified)
		 */
		makeToggle: function (showId, hideId, areaId, toggleClass, initialHide) {
			var showButton = $(escIdForJquery(showId));
			var hideButton = $(escIdForJquery(hideId));
			var area = $(escIdForJquery(areaId));
			var toggles = $(toggleClass === null ? null : "." + toggleClass);

			var togglearea = showButton.parent().parent();

			showButton.show();

			hideButton.show();
			showButton.parent().next().wrap("");

			var showAction = function(event) {
				showButton.hide();
				hideButton.show();
				area.show("normal");
				toggles.show("normal");
				RSF.getDOMModifyFirer().fireEvent();
			};

			var hideAction = function(event) {
				showButton.show();
				hideButton.hide();
				area.hide("normal");
				toggles.hide("normal");
				RSF.getDOMModifyFirer().fireEvent();
			};

			if (initialHide) {
				hideAction();
			} else {
				showAction();
			}

			var toggle = function(event) {
				showButton.toggle();
				hideButton.toggle();
				area.toggle("normal");
				toggles.toggle("normal");
				RSF.getDOMModifyFirer().fireEvent();
			};

			togglearea.click( function (event) { toggle(event); } );

			/*showButton.click( function (event) { showAction(event) });
	        hideButton.click( function (event) { hideAction(event) });*/
		},

		// this just makes it easier to add in more stuff later -AZ
		initEvalSettings: function (areaId, selectId, selectValue, reminderId) {
			// see the toggleAndDisableSetReminder method for description of arguments
			EvalSystem.toggleAndDisableSetReminder(areaId, selectId, selectValue, reminderId);
		},

		/**
		 * This will hide and disable the setReminder option area
		 * and force the setting to 0 reminders on the evaluation settings page
		 * when the anonymous auth option is selected OR reveal the option area
		 * areaId: the id of area (div probably) to show/hide
		 * selectId: the id of the select that triggers the show/hide
		 * selectValue: the value of the select that causes the hide action (other cause show)
		 * reminderId: the id of the form control to set when hide action happens
		 */
		toggleAndDisableSetReminder: function (areaId, selectId, selectValue, reminderId) {
			var area = $("#"+areaId); //document.getElementById(areaId);
			var select = $("#"+selectId); //document.getElementById(selectId);
			var reminder = $("#"+reminderId); //document.getElementById(reminderId);

			var changeAction = function(event) {
				var selectedValue = event.target.value;
				if (selectedValue === selectValue) {
					// values are the same so we need to hide things
					// only take action if needed so we are not resetting the field constantly
					if ( area.is(':visible') ) {
						// area is currently visible so hide it
						area.hide("normal");
						// force reminder to the no reminders setting of 0
						reminder.val('0');
					}
				} else {
					// set to one of the non-hiding options
					if ( area.is(':hidden') ) {
						// area is currently hidden so reveal it
						area.show("slow");
					}
				}
			};
			// add the event for onchange to trigger the changeAction method and cause it to fire immediately
			select.change( function(event) { changeAction(event); }).change();
		},

		getRelativeID: function (baseid, targetid) {
			var colpos = baseid.lastIndexOf(':');
			return baseid.substring(0, colpos + 1) + targetid;
		},

		// See http://www.pageresource.com/jscript/jdropbox.htm for general approach
		operateSelectLink: function(linkid, localselectid) {
			var selectid = EvalSystem.getRelativeID(linkid, localselectid);
			var selection = $it(selectid);
			var url = selection.options[selection.selectedIndex].value;
			$.facebox({ ajax: url });
		},

		decorateReorderSelects: function(namebase, count) {
			var makeButtonClick = function(b) {
				return function() {
					b.click();
				};
			};
			var buttonid = namebase + "hiddenBtn";
			var button = $it(buttonid);
			for (var i = 0; i < count; ++ i) {
				var selectid = namebase + "item-row:"+i+":item-select-selection";
				var selection = $it(selectid);
				selection.onchange = makeButtonClick(button);
			}
		}

	};
}();<|endoftext|>


<commit_before>angular.module('racer.js', [], function ($provide) {
	function extendObject(from, to) {
		if (from === to) return to;

		if (from.constructor === Array && to.constructor === Array) {
			for (var i = 0; i < from.length; ++i) {
				to[i] = extendObject(from[i], to[i]);
			}
			to.splice(from.length, to.length);

			return to;
		} else if (from.constructor === Object && to && to.constructor === Object) {
			for (var key in to) {
				if (typeof from[key] === 'undefined') {
					delete to[key];
				}
			}

			for (var key in from) {
				to[key] = extendObject(from[key], to[key]);
			}

			return to;
		} else {
			return from;
		}
	}

	var setImmediate = window && window.setImmediate ? window.setImmediate : function (fn) {
		setTimeout(fn, 0);
	};

	var racer = require('racer');

	$provide.factory('racer', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope) {
		$http.get('/model').success(function (data) {
			racer.init(data);
		});

		var def = $q.defer();
		racer.ready(function (model) {
			var paths = {};

			var oldGet = model.get;
			model.get = function (path) {
				if (!paths[path]) {
					paths[path] = oldGet.call(model, path);

					model.on('all', path ? path + '**' : '**', function () {
						var newData = oldGet.call(model, path);
						paths[path] = extendObject(newData, paths[path]);
						setImmediate($rootScope.$apply.bind($rootScope));
					});
				}

				return paths[path];
			};

			def.resolve(model);
			$rootScope.$apply();
		});

		return def.promise;
	}]);
});<commit_msg>Add a missing condition<commit_after>angular.module('racer.js', [], function ($provide) {
	function extendObject(from, to) {
		if (from === to) return to;

		if (from.constructor === Array && to && to.constructor === Array) {
			for (var i = 0; i < from.length; ++i) {
				to[i] = extendObject(from[i], to[i]);
			}
			to.splice(from.length, to.length);

			return to;
		} else if (from.constructor === Object && to && to.constructor === Object) {
			for (var key in to) {
				if (typeof from[key] === 'undefined') {
					delete to[key];
				}
			}

			for (var key in from) {
				to[key] = extendObject(from[key], to[key]);
			}

			return to;
		} else {
			return from;
		}
	}

	var setImmediate = window && window.setImmediate ? window.setImmediate : function (fn) {
		setTimeout(fn, 0);
	};

	var racer = require('racer');

	$provide.factory('racer', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope) {
		$http.get('/model').success(function (data) {
			racer.init(data);
		});

		var def = $q.defer();
		racer.ready(function (model) {
			var paths = {};

			var oldGet = model.get;
			model.get = function (path) {
				if (!paths[path]) {
					paths[path] = oldGet.call(model, path);

					model.on('all', path ? path + '**' : '**', function () {
						var newData = oldGet.call(model, path);
						paths[path] = extendObject(newData, paths[path]);
						setImmediate($rootScope.$apply.bind($rootScope));
					});
				}

				return paths[path];
			};

			def.resolve(model);
			$rootScope.$apply();
		});

		return def.promise;
	}]);
});<|endoftext|>


<commit_before>$(function(e) {
    //$('#typeahead').typeahead({"source": ['aaas']});
$('#input').typeahead([
    {
        name: 'Test',
        local: [ "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Nine" ],
        header: '
Test
'
    }
]);
});

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

<commit_msg>Search typeahead<commit_after>$(function(e) {
$('#input').typeahead([
    {
        name: 'Test',
        local: [ "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Nine" ],
        header: '
Test
'
    }
]);
});

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

<|endoftext|>


<commit_before>
const fs = require('fs-extra');
const path = require('path');
const Sqlite3 = require('better-sqlite3');

// load configuration variables
const config = require( 'pelias-config' ).generate(require('../schema')).imports.whosonfirst;
const sqliteFiles = config.sqlite_files;

// ensure sqlite_files array is specified in config
if( !Array.isArray( config.sqlite_files ) || !config.sqlite_files.length ){
  console.error('you must specify the imports.whosonfirst.sqlite_files array in your pelias.json');
  process.exit(1);
}

// ensure required directory structure exists
const metaDir = path.join(config.datapath, 'meta');
const dataDir = path.join(config.datapath, 'data');
fs.ensureDirSync(metaDir);
fs.ensureDirSync(dataDir);

// sql statements
const sql = {
  data: `SELECT id, body FROM geojson
  WHERE id IN (
    SELECT id
    FROM ancestors
    WHERE id = @wofid
    OR ancestor_id = @wofid
    GROUP BY id
    ORDER BY id ASC
  );`,
  meta: `SELECT * FROM spr
  WHERE id IN (
    SELECT id
    FROM ancestors
    WHERE id = @wofid
    OR ancestor_id = @wofid
    GROUP BY id
    ORDER BY id ASC
  );`
};

// open one write stream per metadata file
// note: important for to ensure meta files are written correctly
// with only one header per import run
const metafiles = new MetaDataFiles();

// extract from a single db file
function extract( dbpath ){
  let targetWofId = config.importPlace;

  // connect to sql db
  let db = new Sqlite3( dbpath, { readonly: true } );

  // extract all data to disk
  for( let row of db.prepare(sql.data).iterate({ wofid: targetWofId }) ){
    writeJson( row );
  }

  // write meta data to disk
  for( let row of db.prepare(sql.meta).iterate({ wofid: targetWofId }) ){
    metafiles.write( row );
  }

  // close connection
  db.close();
}

// extract from all database files
config.sqlite_files.forEach(file => { extract( file.filename ); });

// ----------------------------------------------------------------------------

// write json to disk
function writeJson( row ){
  let targetDir = path.join(dataDir, wofIdToPath(row.id).join(path.sep));
  fs.ensureDir(targetDir, (error) => {
    if( error ){ console.error(`error making directory ${targetDir}`); }
    fs.writeFileSync( path.join(targetDir, `${row.id}.geojson`), row.body, 'utf8' );
  });
}

// convert wofid integer to array of path components
function wofIdToPath( id ){
  let strId = id.toString();
  let parts = [];
  while( strId.length ){
    let part = strId.substr(0, 3);
    parts.push(part);
    strId = strId.substr(3);
  }
  return parts;
}

// handler for all metatdata streams
function MetaDataFiles(){
  let streams = {};
  this.write = function( row ){
    let keys = Object.keys(row);

    // first time writing to this meta file
    if( !streams.hasOwnProperty( row.placetype ) ){

      // create write stream
      streams[row.placetype] = fs.createWriteStream(
        path.join( metaDir, `${row.placetype}.csv` )
      );

      // write csv header
      streams[row.placetype].write( keys.join(',') + '\n' );
    }

    // write csv row
    streams[row.placetype].write( keys.map(key => {
      // quote fields containing comma or newline
      if( /[,\n]/.test( row[key] ) ) {
        return '"' + row[key] + '"';
      }
      return row[key];
    }).join(',') + '\n' );
  };
}
<commit_msg>improved csv encoding<commit_after>
const fs = require('fs-extra');
const path = require('path');
const Sqlite3 = require('better-sqlite3');

// load configuration variables
const config = require( 'pelias-config' ).generate(require('../schema')).imports.whosonfirst;
const sqliteFiles = config.sqlite_files;

// ensure sqlite_files array is specified in config
if( !Array.isArray( config.sqlite_files ) || !config.sqlite_files.length ){
  console.error('you must specify the imports.whosonfirst.sqlite_files array in your pelias.json');
  process.exit(1);
}

// ensure required directory structure exists
const metaDir = path.join(config.datapath, 'meta');
const dataDir = path.join(config.datapath, 'data');
fs.ensureDirSync(metaDir);
fs.ensureDirSync(dataDir);

// sql statements
const sql = {
  data: `SELECT id, body FROM geojson
  WHERE id IN (
    SELECT id
    FROM ancestors
    WHERE id = @wofid
    OR ancestor_id = @wofid
    GROUP BY id
    ORDER BY id ASC
  );`,
  meta: `SELECT * FROM spr
  WHERE id IN (
    SELECT id
    FROM ancestors
    WHERE id = @wofid
    OR ancestor_id = @wofid
    GROUP BY id
    ORDER BY id ASC
  );`
};

// open one write stream per metadata file
// note: important for to ensure meta files are written correctly
// with only one header per import run
const metafiles = new MetaDataFiles();

// extract from a single db file
function extract( dbpath ){
  let targetWofId = config.importPlace;

  // connect to sql db
  let db = new Sqlite3( dbpath, { readonly: true } );

  // extract all data to disk
  for( let row of db.prepare(sql.data).iterate({ wofid: targetWofId }) ){
    writeJson( row );
  }

  // write meta data to disk
  for( let row of db.prepare(sql.meta).iterate({ wofid: targetWofId }) ){
    metafiles.write( row );
  }

  // close connection
  db.close();
}

// extract from all database files
config.sqlite_files.forEach(file => { extract( file.filename ); });

// ----------------------------------------------------------------------------

// write json to disk
function writeJson( row ){
  let targetDir = path.join(dataDir, wofIdToPath(row.id).join(path.sep));
  fs.ensureDir(targetDir, (error) => {
    if( error ){ console.error(`error making directory ${targetDir}`); }
    fs.writeFileSync( path.join(targetDir, `${row.id}.geojson`), row.body, 'utf8' );
  });
}

// convert wofid integer to array of path components
function wofIdToPath( id ){
  let strId = id.toString();
  let parts = [];
  while( strId.length ){
    let part = strId.substr(0, 3);
    parts.push(part);
    strId = strId.substr(3);
  }
  return parts;
}

// handler for all metatdata streams
function MetaDataFiles(){
  let streams = {};
  this.write = function( row ){
    let keys = Object.keys(row);

    // first time writing to this meta file
    if( !streams.hasOwnProperty( row.placetype ) ){

      // create write stream
      streams[row.placetype] = fs.createWriteStream(
        path.join( metaDir, `${row.placetype}.csv` )
      );

      // write csv header
      streams[row.placetype].write( keys.join(',') + '\n' );
    }

    // write csv row
    streams[row.placetype].write( keys.map(key => {
      // quote fields containing comma or newline, escape internal quotes
      // https://gist.github.com/getify/3667624
      if( /[,\n]/.test( row[key] ) ) {
        return '"' + row[key].replace(/\\([\s\S])|(")/g,'\\$1$2') + '"';
      }
      return row[key];
    }).join(',') + '\n' );
  };
}
<|endoftext|>


<commit_before>// Silently create raptor namespace
if(typeof raptor === 'undefined') {
	var raptor = {};
}

raptor.pack = (function() {

	var nodeStorage = {};
	var fragmentStorage = {};

	var util = {

		/**
		 * Creates Element and adds to storage or clones existing
		 *
		 * @param {String} tag
		 */
		newElement : function(tag) {
			if (!nodeStorage[tag]) nodeStorage[tag] = document.createElement(tag);
			return nodeStorage[tag].cloneNode(true);
		},

		/**
		 * Adds text to element
		 *
		 * - auto-detects HTML Entities and uses innerHTML
		 *
		 * @param {HTMLElement} el
		 * @param {String} string
		 */
		insertText : function(el, text) {
			if (/\&\S+;/.test(text)) el.innerHTML += text;
			else el.appendChild(document.createTextNode(text));
		},

		/**
		 * Tests for data type by constructor name
		 *
		 * @param {Array} types
		 * @param {Array|Boolean|Date|Math|Number|String|RegExp|Object|HTMLElement} data
		 */
		type : function(types, data) {
			var match = false;
			for (var i = 0; i < types.length; i++) {
				switch(types[i]) {
					case 'Object':
						if (typeof data === 'object' && data.length == undefined && data != null) match = true;
						break;
					case 'HTMLElement':
						if (data.tagName) match = true;
						break;
					default:
						if (data.constructor && data.constructor.toString().indexOf(types[i]) !== -1) match = true;
				}
				if (match) return true;
			}
			return false;
		}
	}

	return {

		/**
		 * Creates DOMElements
		 *
		 * - Contents can contain array of strings, numbers, or other DOMElements created by this method
		 * - Fragment is the name of the fragment to append the birthed DOMElement to
		 *
		 * @param {String} tag
		 * @param {Object} attrs
		 * @param {String|Number|Array|HTMLElement} contents
		 * @param {String} fragment (optional)
		 */
		birth : function(tag, attrs, contents, fragment) {

			// creates new element, or clones existing
			var el = util.newElement(tag);

			// set attributes
			if (attrs == '') attrs = {};
			for (var attr in attrs) {

				if (attr == 'style') {

					var styles = attrs[attr];
					for (var prop in styles) {
						el.style[prop] = styles[prop];
					}
				}
				else {
					if (el[attr]) el[attr] = attrs[attr];
					else el.setAttribute(attr, attrs[attr]);
				}
			}

			// parse content
			if (util.type(['String', 'Number'], contents)) {
				util.insertText(el, contents);
			}
			else if (util.type(['Array'], contents)){
				for (var i = 0; i < contents.length; i++) {
					if (util.type(['String', 'Number'], contents[i])) {
						util.insertText(el, contents[i], true);
					}
					else if (util.type(['Function'], contents[i])) {
						contents[i](el);
					}
					else {
						el.appendChild(contents[i]);
					}
				}
			}
			else if (util.type(['Function'], contents)) contents(el);

			// if fragment referenced, create and/or add to existing
			if (fragment) {
				if (!fragmentStorage[fragment]) fragmentStorage[fragment] = document.createDocumentFragment();
				fragmentStorage[fragment].appendChild(el);
			}

			return el;
		},

		/**
		 * Returns stored documentFragment clone
		 *
		 * @param {String} name
		 */
		nursery : function(name) {
			return fragmentStorage[name].cloneNode(true);
		}
	}
})();<commit_msg>allow string passed for testing type<commit_after>// Silently create raptor namespace
if(typeof raptor === 'undefined') {
	var raptor = {};
}

raptor.pack = (function() {

	var nodeStorage = {};
	var fragmentStorage = {};

	var util = {

		/**
		 * Creates Element and adds to storage or clones existing
		 *
		 * @param {String} tag
		 */
		newElement : function(tag) {
			if (!nodeStorage[tag]) nodeStorage[tag] = document.createElement(tag);
			return nodeStorage[tag].cloneNode(true);
		},

		/**
		 * Adds text to element
		 *
		 * - auto-detects HTML Entities and uses innerHTML
		 *
		 * @param {HTMLElement} el
		 * @param {String} string
		 */
		insertText : function(el, text) {
			if (/\&\S+;/.test(text)) el.innerHTML += text;
			else el.appendChild(document.createTextNode(text));
		},

		/**
		 * Tests for data type by constructor name
		 *
		 * @param {Array} types
		 * @param {Array|Boolean|Date|Math|Number|String|RegExp|Object|HTMLElement} data
		 */
		type : function(types, data) {

			var match = false;

			var test = function(type) {
				switch(type) {
					case 'Object':
						if (typeof data === 'object' && data.length == undefined && data != null) match = true;
						break;
					case 'HTMLElement':
						if (data.tagName) match = true;
						break;
					default:
						if (data.constructor && data.constructor.toString().indexOf(type) !== -1) match = true;
				}
			}

			if (typeof types === 'string') test(types);
			else {
				for (var i = 0; i < types.length; i++) {
					test(types[i]);
					if (match) break;
				}
			}
			return (match) ? true : false;
		}
	}

	return {

		/**
		 * Creates DOMElements
		 *
		 * - Contents can contain array of strings, numbers, or other DOMElements created by this method
		 * - Fragment is the name of the fragment to append the birthed DOMElement to
		 *
		 * @param {String} tag
		 * @param {Object} attrs
		 * @param {String|Number|Array|HTMLElement} contents
		 * @param {String} fragment (optional)
		 */
		birth : function(tag, attrs, contents, fragment) {

			// creates new element, or clones existing
			var el = util.newElement(tag);

			// set attributes
			if (attrs == '') attrs = {};
			for (var attr in attrs) {

				if (attr == 'style') {

					var styles = attrs[attr];
					for (var prop in styles) {
						el.style[prop] = styles[prop];
					}
				}
				else {
					if (el[attr]) el[attr] = attrs[attr];
					else el.setAttribute(attr, attrs[attr]);
				}
			}

			// parse content
			if (util.type(['String', 'Number'], contents)) {
				util.insertText(el, contents);
			}
			else if (util.type(['Array'], contents)){
				for (var i = 0; i < contents.length; i++) {
					if (util.type(['String', 'Number'], contents[i])) {
						util.insertText(el, contents[i], true);
					}
					else if (util.type(['Function'], contents[i])) {
						contents[i](el);
					}
					else {
						el.appendChild(contents[i]);
					}
				}
			}
			else if (util.type(['Function'], contents)) contents(el);

			// if fragment referenced, create and/or add to existing
			if (fragment) {
				if (!fragmentStorage[fragment]) fragmentStorage[fragment] = document.createDocumentFragment();
				fragmentStorage[fragment].appendChild(el);
			}

			return el;
		},

		/**
		 * Returns stored documentFragment clone
		 *
		 * @param {String} name
		 */
		nursery : function(name) {
			return fragmentStorage[name].cloneNode(true);
		}
	}
})();<|endoftext|>