<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;

var errors = require('./errors');

function TChannelRequest(channel, options) {
    options = options || {};
    if (options.streamed) {
        throw new Error('streaming request federation not supported');
    }
    var self = this;
    EventEmitter.call(self);
    self.channel = channel;
    self.logger = self.channel.logger;
    self.random = self.channel.random;
    self.timers = self.channel.timers;

    self.options = options;
    self.triedRemoteAddrs = {};
    self.outReqs = [];
    self.timeout = self.options.timeout || TChannelRequest.defaultTimeout;
    self.limit = self.options.retryLimit || TChannelRequest.defaultRetryLimit;
    self.start = 0;
    self.end = 0;
    self.elapsed = 0;
    self.resendSanity = 0;

    self.service = options.service || '';
    self.headers = self.options.headers || {}; // so that as-foo can punch req.headers.X
    self.options.headers = self.headers; // for passing to peer.request(opts) later

    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.err = null;
    self.res = null;
    self.on('error', self.onError);
    self.on('response', self.onResponse);
}

inherits(TChannelRequest, EventEmitter);

TChannelRequest.defaultRetryLimit = 5;
TChannelRequest.defaultTimeout = 5000;

TChannelRequest.prototype.type = 'tchannel.request';

TChannelRequest.prototype.onError = function onError(err) {
    var self = this;
    if (!self.end) self.end = self.timers.now();
    self.err = err;
};

TChannelRequest.prototype.onResponse = function onResponse(res) {
    var self = this;
    if (!self.end) self.end = self.timers.now();
    self.res = res;
};

TChannelRequest.prototype.hookupStreamCallback = function hookupCallback(callback) {
    throw new Error('not implemented');
};

TChannelRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    if (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;

    self.on('error', onError);
    self.on('response', onResponse);

    function onError(err) {
        if (called) return;
        called = true;
        callback(err, null, null, null);
    }

    function onResponse(res) {
        if (called) return;
        called = true;
        withArg23(res, callback);
    }

    return self;
};

TChannelRequest.prototype.choosePeer = function choosePeer() {
    var self = this;
    return self.channel.peers.choosePeer(self, self.options);
};

TChannelRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    self.arg1 = arg1;
    self.arg2 = arg2;
    self.arg3 = arg3;
    if (callback) {
        self.hookupCallback(callback);
    }
    self.start = self.timers.now();
    self.resendSanity = self.limit + 1;
    self.resend();
};

TChannelRequest.prototype.resend = function resend() {
    var self = this;

    if (self.checkTimeout()) return;

    var peer = self.choosePeer();
    if (!peer) {
        if (self.outReqs.length) {
            var lastReq = self.outReqs[self.outReqs.length - 1];
            if (lastReq.err) self.emit('error', lastReq.err);
            else self.emit('response', lastReq.res);
        } else {
            self.emit('error', errors.NoPeerAvailable());
        }
        return;
    }

    if (self.checkTimeout()) return;

    var opts = {};
    var keys = Object.keys(self.options);
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        opts[key] = self.options[key];
    }
    var outReq = peer.request(opts);
    self.outReqs.push(outReq);

    self.triedRemoteAddrs[outReq.remoteAddr] = (self.triedRemoteAddrs[outReq.remoteAddr] || 0) + 1;
    outReq.on('response', onResponse);
    outReq.on('error', onError);
    outReq.send(self.arg1, self.arg2, self.arg3);

    function onError(err) {
        if (self.checkTimeout(err)) return;
        if (self.shouldRetry(err)) {
            deferResend();
        } else {
            self.emit('error', err);
        }
    }

    function onResponse(res) {
        withArg23(res, function onArg23(err, res, arg2, arg3) {
            if (self.checkTimeout(err, res)) return;
            if (self.shouldRetry(err, res, arg2, arg3)) {
                deferResend();
            } else if (err) {
                self.emit('error', err);
            } else {
                self.emit('response', res);
            }
        });
    }

    function deferResend() {
        if (--self.resendSanity <= 0) {
            throw new Error('TChannelRequest out of resend sanity');
        } else {
            process.nextTick(doResend);
        }
    }

    function doResend() {
        self.resend();
    }
};

TChannelRequest.prototype.checkTimeout = function checkTimeout(err, res) {
    var self = this;
    var now = self.timers.now();
    self.elapsed = now - self.start;
    if (self.elapsed < self.timeout) return false;
    if (err) {
        if (!self.err) {
            self.emit('error', err);
        }
    } else if (res) {
        if (!self.err && !self.res) {
            self.emit('response', res);
        }
    } else if (!self.err) {
        self.emit('error', errors.TimeoutError({
            start: self.start,
            elapsed: self.elapsed,
            timeout: self.timeout
        }));
    }
    return true;
};

TChannelRequest.prototype.shouldRetry = function shouldRetry(err, res, arg2, arg3) {
    var self = this;

    if (self.outReqs.length >= self.limit) {
        return false;
    }

    if (err) {
        switch (err.type) {
            case 'tchannel.bad-request':
            case 'tchannel.canceled':
                return false;

            case 'tchannel.socket':
            case 'tchannel.timeout':
            case 'tchannel.busy':
            case 'tchannel.declined':
            case 'tchannel.unexpected':
            case 'tchannel.protocol':
                return true;

            default:
                self.logger.error('unknown error type in request retry', {
                    error: err
                });
                return true;
        }
    }

    if (!res.ok && self.options.shouldApplicationRetry) {
        return self.options.shouldApplicationRetry(self, res, arg2, arg3);
    }

    return false;
};

module.exports = TChannelRequest;

function withArg23(res, callback) {
    if (!res.streamed) {
        callback(null, res, res.arg2, res.arg3);
        return;
    }
    parallel({
        arg2: res.arg2.onValueReady,
        arg3: res.arg3.onValueReady
    }, compatCall);
    function compatCall(err, args) {
        callback(err, res, args.arg2, args.arg3);
    }
}
<commit_msg>TChannelRequest: correct timeout passing to time remaining<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;

var errors = require('./errors');

function TChannelRequest(channel, options) {
    options = options || {};
    if (options.streamed) {
        throw new Error('streaming request federation not supported');
    }
    var self = this;
    EventEmitter.call(self);
    self.channel = channel;
    self.logger = self.channel.logger;
    self.random = self.channel.random;
    self.timers = self.channel.timers;

    self.options = options;
    self.triedRemoteAddrs = {};
    self.outReqs = [];
    self.timeout = self.options.timeout || TChannelRequest.defaultTimeout;
    self.limit = self.options.retryLimit || TChannelRequest.defaultRetryLimit;
    self.start = 0;
    self.end = 0;
    self.elapsed = 0;
    self.resendSanity = 0;

    self.service = options.service || '';
    self.headers = self.options.headers || {}; // so that as-foo can punch req.headers.X
    self.options.headers = self.headers; // for passing to peer.request(opts) later

    self.arg1 = null;
    self.arg2 = null;
    self.arg3 = null;

    self.err = null;
    self.res = null;
    self.on('error', self.onError);
    self.on('response', self.onResponse);
}

inherits(TChannelRequest, EventEmitter);

TChannelRequest.defaultRetryLimit = 5;
TChannelRequest.defaultTimeout = 5000;

TChannelRequest.prototype.type = 'tchannel.request';

TChannelRequest.prototype.onError = function onError(err) {
    var self = this;
    if (!self.end) self.end = self.timers.now();
    self.err = err;
};

TChannelRequest.prototype.onResponse = function onResponse(res) {
    var self = this;
    if (!self.end) self.end = self.timers.now();
    self.res = res;
};

TChannelRequest.prototype.hookupStreamCallback = function hookupCallback(callback) {
    throw new Error('not implemented');
};

TChannelRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    if (callback.canStream) {
        return self.hookupStreamCallback(callback);
    }
    var called = false;

    self.on('error', onError);
    self.on('response', onResponse);

    function onError(err) {
        if (called) return;
        called = true;
        callback(err, null, null, null);
    }

    function onResponse(res) {
        if (called) return;
        called = true;
        withArg23(res, callback);
    }

    return self;
};

TChannelRequest.prototype.choosePeer = function choosePeer() {
    var self = this;
    return self.channel.peers.choosePeer(self, self.options);
};

TChannelRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    self.arg1 = arg1;
    self.arg2 = arg2;
    self.arg3 = arg3;
    if (callback) {
        self.hookupCallback(callback);
    }
    self.start = self.timers.now();
    self.resendSanity = self.limit + 1;
    self.resend();
};

TChannelRequest.prototype.resend = function resend() {
    var self = this;

    if (self.checkTimeout()) return;

    var peer = self.choosePeer();
    if (!peer) {
        if (self.outReqs.length) {
            var lastReq = self.outReqs[self.outReqs.length - 1];
            if (lastReq.err) self.emit('error', lastReq.err);
            else self.emit('response', lastReq.res);
        } else {
            self.emit('error', errors.NoPeerAvailable());
        }
        return;
    }

    if (self.checkTimeout()) return;

    var opts = {};
    var keys = Object.keys(self.options);
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        opts[key] = self.options[key];
    }
    opts.timeout = self.timeout - self.elapsed;
    var outReq = peer.request(opts);
    self.outReqs.push(outReq);

    self.triedRemoteAddrs[outReq.remoteAddr] = (self.triedRemoteAddrs[outReq.remoteAddr] || 0) + 1;
    outReq.on('response', onResponse);
    outReq.on('error', onError);
    outReq.send(self.arg1, self.arg2, self.arg3);

    function onError(err) {
        if (self.checkTimeout(err)) return;
        if (self.shouldRetry(err)) {
            deferResend();
        } else {
            self.emit('error', err);
        }
    }

    function onResponse(res) {
        withArg23(res, function onArg23(err, res, arg2, arg3) {
            if (self.checkTimeout(err, res)) return;
            if (self.shouldRetry(err, res, arg2, arg3)) {
                deferResend();
            } else if (err) {
                self.emit('error', err);
            } else {
                self.emit('response', res);
            }
        });
    }

    function deferResend() {
        if (--self.resendSanity <= 0) {
            throw new Error('TChannelRequest out of resend sanity');
        } else {
            process.nextTick(doResend);
        }
    }

    function doResend() {
        self.resend();
    }
};

TChannelRequest.prototype.checkTimeout = function checkTimeout(err, res) {
    var self = this;
    var now = self.timers.now();
    self.elapsed = now - self.start;
    if (self.elapsed < self.timeout) return false;
    if (err) {
        if (!self.err) {
            self.emit('error', err);
        }
    } else if (res) {
        if (!self.err && !self.res) {
            self.emit('response', res);
        }
    } else if (!self.err) {
        self.emit('error', errors.TimeoutError({
            start: self.start,
            elapsed: self.elapsed,
            timeout: self.timeout
        }));
    }
    return true;
};

TChannelRequest.prototype.shouldRetry = function shouldRetry(err, res, arg2, arg3) {
    var self = this;

    if (self.outReqs.length >= self.limit) {
        return false;
    }

    if (err) {
        switch (err.type) {
            case 'tchannel.bad-request':
            case 'tchannel.canceled':
                return false;

            case 'tchannel.socket':
            case 'tchannel.timeout':
            case 'tchannel.busy':
            case 'tchannel.declined':
            case 'tchannel.unexpected':
            case 'tchannel.protocol':
                return true;

            default:
                self.logger.error('unknown error type in request retry', {
                    error: err
                });
                return true;
        }
    }

    if (!res.ok && self.options.shouldApplicationRetry) {
        return self.options.shouldApplicationRetry(self, res, arg2, arg3);
    }

    return false;
};

module.exports = TChannelRequest;

function withArg23(res, callback) {
    if (!res.streamed) {
        callback(null, res, res.arg2, res.arg3);
        return;
    }
    parallel({
        arg2: res.arg2.onValueReady,
        arg3: res.arg3.onValueReady
    }, compatCall);
    function compatCall(err, args) {
        callback(err, res, args.arg2, args.arg3);
    }
}
<|endoftext|>


<commit_before>export default {
  props: {
    form: Object,
    field: Object,
    model: Object,
    to: Object
  },
  methods: {
    // Core access function
    _getEl (obj, path, defaultVal = undefined) {
      /**
       * Gets values from objects and sets defaults by relative path
       * Used to bind elements from Formly config object to a tag attribute
       * @example
       * // returns 1
       * _getEl({a: {b: {c: 1}}}, 'a/b/c')
       * @example
       * // returns null
       * _getEl({a: {b: {c: 1}}}, 'a/b/x', null)
       */
      let value = defaultVal
      path.split('/').forEach((elem, i, arr) => {
        if (obj.hasOwnProperty(elem)) {
          if (++i === arr.length) {
            value = obj[elem]
          } else {
            obj = obj[elem]
          }
        }
      })
      return value
    },
    // Shortcuts
    getFormEl (path, defaultVal = undefined) {
      return this._getEl(this.form[this.field.key], path, defaultVal)
    },
    getModelEl () {
      return this.model[this.field.key]
    },
    getFieldEl (path, defaultVal = undefined) {
      return this._getEl(this.field, path, defaultVal)
    },
    handleEvent (eventPath) {
      const eventHandler = this.getFieldEl(eventPath)
      if (typeof eventHandler === 'function') {
        eventHandler()
      }
    }
  },
  watch: {
    form () {
      /**
       * Force update DOM for a field when it's form changes
       * This is required because tag attributes of the field
       * which bind from Formly config object are not reactive
       */
      this.$forceUpdate()
    }
  }
}
<commit_msg>Add new shortcuts for BaseFormlyMixin<commit_after>export default {
  props: {
    form: Object,
    field: Object,
    model: Object,
    to: Object
  },
  methods: {
    // Core access function
    _getValue (obj, path, defaultVal = undefined) {
      /**
       * Gets values from objects and sets defaults by relative path
       * Used to bind elements from Formly config object to a tag attribute
       * @example
       * // returns 1
       * _getValue({a: {b: {c: 1}}}, 'a/b/c')
       * @example
       * // returns null
       * _getValue({a: {b: {c: 1}}}, 'a/b/x', null)
       */
      let value = defaultVal
      path.split('/').forEach((elem, i, arr) => {
        if (obj.hasOwnProperty(elem)) {
          if (++i === arr.length) {
            value = obj[elem]
          } else {
            obj = obj[elem]
          }
        }
      })
      return value
    },
    // Shortcuts
    getFormValueOf (path, defaultVal = undefined) {
      return this._getValue(this.form[this.field.key], path, defaultVal)
    },
    getModelValueOf () {
      return this.model[this.field.key]
    },
    getFieldValueOf (path, defaultVal = undefined) {
      return this._getValue(this.field, path, defaultVal)
    },
    getToValueOf (path, defaultVal = undefined) {
      return this._getValue(this.to, path, defaultVal)
    },
    handleEvent (eventPath) {
      const eventHandler = this.getFieldValueOf(eventPath)
      if (typeof eventHandler === 'function') {
        eventHandler()
      }
    }
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var localStrings = new LocalStrings();

/**
 * Window onload handler, sets up the page.
 */
function load() {
  $('cancel-button').addEventListener('click', function(e) {
    window.close();
  });

  chrome.send('getPrinters');
};

/**
 * Fill the printer list drop down.
 */
function setPrinters(printers) {
  if (printers.length > 0) {
    for (var i = 0; i < printers.length; ++i) {
      var option = document.createElement('option');
      option.textContent = printers[i];
      $('printer-list').add(option);
    }
  } else {
    var option = document.createElement('option');
    option.textContent = localStrings.getString('no-printer');
    $('printer-list').add(option);
    $('printer-list').disabled = true;
    $('print-button').disabled = true;
  }
}

window.addEventListener('DOMContentLoaded', load);

<commit_msg>Add in a missing change from r67143 for print preview options.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var localStrings = new LocalStrings();

/**
 * Window onload handler, sets up the page.
 */
function load() {
  $('cancel-button').addEventListener('click', function(e) {
    window.close();
  });

  chrome.send('getPrinters');
};

/**
 * Fill the printer list drop down.
 */
function setPrinters(printers) {
  if (printers.length > 0) {
    for (var i = 0; i < printers.length; ++i) {
      var option = document.createElement('option');
      option.textContent = printers[i];
      $('printer-list').add(option);
    }
  } else {
    var option = document.createElement('option');
    option.textContent = localStrings.getString('noPrinter');
    $('printer-list').add(option);
    $('printer-list').disabled = true;
    $('print-button').disabled = true;
  }
}

window.addEventListener('DOMContentLoaded', load);

<|endoftext|>


<commit_before>$.widget('boom.tagAutocompleter', {

	onSelect : null,

	selectedTags : [],

	type : null,

	_create : function() {
		var self = this;

		this.element.parents().find('.b-dialog').css('overflow', 'visible');

		this.type = this.options.type == 'asset' || this.options.type == 1? 1 : 2;
		this.onSelect = this.options.onSelect;

		this.element.autocomplete({
			delay: 200, // Time to wait after keypress before making the AJAX call.
			source : function(request, response) {
				self._autocompleteSource(request, response);
			},
			focus : function(event, ui) {
				event.preventDefault();

				self.element.val(ui.item.label);
			},
			select : function(event, ui) {
				event.preventDefault();

				self.element.val('');
				self._tagSelected(ui.item.label, ui.item.value);
			}
		})
		.on('keypress', function(e) {
			// Add a tag when the enter key is pressed.
			// This allows us to add a tag which doesn't already exist.
			if (e.which == 13) {
				self._tagSelected(self.element.val(), -1);
				self.element.val('');
			}
		});
	},

	_autocompleteSource : function(request, response) {
		$.ajax({
			url: '/cms/autocomplete/tags',
			dataType: 'json',
			data: {
				text : this.element.val(),
				type : this.type,
				tags : this.selectedTags
			}
		})
		.done(function(data) {
			var suggestions = [], name;

			for (name in data) {
				suggestions.push({
					label : name,
					value : data[name]
				});
			}

			response(suggestions);
		});
	},

	setSelectedTags : function(tags) {
		this.selectedTags = tags;
	},

	_tagSelected : function(name, id) {
		this._trigger('complete', null, {name : name, id : id});
	}
});<commit_msg>Bugfix: close autocomplete widget when enter key is pressed in tagAutocompleter<commit_after>$.widget('boom.tagAutocompleter', {

	onSelect : null,

	selectedTags : [],

	type : null,

	_create : function() {
		var self = this;

		this.element.parents().find('.b-dialog').css('overflow', 'visible');

		this.type = this.options.type == 'asset' || this.options.type == 1? 1 : 2;
		this.onSelect = this.options.onSelect;

		this.element.autocomplete({
			delay: 200, // Time to wait after keypress before making the AJAX call.
			source : function(request, response) {
				self._autocompleteSource(request, response);
			},
			focus : function(event, ui) {
				event.preventDefault();

				self.element.val(ui.item.label);
			},
			select : function(event, ui) {
				event.preventDefault();

				self.element.val('');
				self._tagSelected(ui.item.label, ui.item.value);
			}
		})
		.on('keypress', function(e) {
			// Add a tag when the enter key is pressed.
			// This allows us to add a tag which doesn't already exist.
			if (e.which == 13) {
				self._tagSelected(self.element.val(), -1);
				self.element.val('');
				self.element.autocomplete('close');
			}
		});
	},

	_autocompleteSource : function(request, response) {
		$.ajax({
			url: '/cms/autocomplete/tags',
			dataType: 'json',
			data: {
				text : this.element.val(),
				type : this.type,
				tags : this.selectedTags
			}
		})
		.done(function(data) {
			var suggestions = [], name;

			for (name in data) {
				suggestions.push({
					label : name,
					value : data[name]
				});
			}

			response(suggestions);
		});
	},

	setSelectedTags : function(tags) {
		this.selectedTags = tags;
	},

	_tagSelected : function(name, id) {
		this._trigger('complete', null, {name : name, id : id});
	}
});<|endoftext|>


<commit_before>// ==UserScript==
// @name         GitHub Utils
// @description  Something will go here...
// @version      0.10.0
// @updateURL    https://github.com/dracco1993/GitHubUtils/raw/master/githubutils.user.js
// @downloadURL  https://github.com/dracco1993/GitHubUtils/raw/master/githubutils.user.js
// @author       @dracco1993
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js
// @match        http://*.github.com/*
// @match        https://*.github.com/*
// @grant        none
// ==/UserScript==

/* jshint esversion: 6 */
/* eslint-env jquery   */

// global variables
var username;
var urlMatcher = /\/pulls/;
var isLoadingPages = false;
var nextPageUrl;
var isDarkMode;

(function() {
  "use strict";
  if (Array.isArray(window.location.pathname.match(urlMatcher))) {
    init();
  }

  document.addEventListener("pjax:end", function() {
    if (Array.isArray(window.location.pathname.match(urlMatcher))) {
      init();
    }
  });
})();

function init() {
  setTheme();
  setupNeverEndingGithub();
  setUsername();
  colorizeMeCaptain();
}

function setUsername() {
  username = $(".user-profile-link .css-truncate-target").text();
}

function setTheme() {
  var colorMode = $("html").data().colorMode;
  var systemIsDarkTheme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

  isDarkMode = (colorMode == "dark") || (colorMode == "auto" && systemIsDarkTheme == true);
}

function colorizeMeCaptain() {
  $(".Box-row:not(.ghu-styled)").each(function(k, v) {
    var links = $(v).find("div.flex-auto > a");
    var temp, repo;
    if (links[0].href.match(/\/pull/)) {
      temp = links[0];
    } else {
      temp = links[1];
      repo = links[0].text
        .replace(/\r?\n|\r/g, "")
        .trim()
        .split("/")
        .join("_");
    }
    $.ajax({
      url: temp.href,
      success: function(result) {
        var temp = $("<div/>")
          .html(result)
          .contents();
        getComments(temp, repo);
      }
    });
  });
}

function setupNeverEndingGithub() {
  addNeverEndingStyles();
  setNextPageURL($(document));

  $(window).scroll(function() {
    if ($(window).scrollTop() + $(window).height() === $(document).height()) {
      if (!isLoadingPages && nextPageUrl) {
        loadNextPage();
      }
    }
  });
}

function loadNextPage() {
  isLoadingPages = true;

  $.ajax({
    url: nextPageUrl,
    success: function(result) {
      var temp = $("<div/>")
        .html(result)
        .contents();
      displayNextPage(temp);
    },
    always: function() {
      isLoadingPages = false;
    }
  });
}

function displayNextPage(source) {
  // Actually add the new loaded content into the current container
  $("div.js-navigation-container").append(
    source.find("[id^=issue_]:not([id$=_link])")
  );
  colorizeMeCaptain();
  setNextPageURL(source);
  isLoadingPages = false;
}

function setNextPageURL(source) {
  var nextPageButton = source.find(".pagination .next_page");
  if (nextPageButton.length > 0) {
    nextPageUrl = nextPageButton[0].href;
  }
}

function getComments(source, repo) {
  var content = source.find(".js-comment-container");
  var prNumber = source
    .find(".gh-header-number")
    .first()
    .text()
    .slice(1);
  var prDescription = content.slice(0, 1);
  var newComment = content.slice(-1, 1);
  var comments = content.slice(1, content.length - 1);
  var timelineComments = source.find(
    ".js-discussion .timeline-comment-wrapper"
  );
  var location = $("#issue_" + prNumber)[0];
  if (location === undefined) {
    location = $("#issue_" + prNumber + "_" + repo);
  }

  $(location).addClass("ghu-styled");
  redify(location);

  if (comments.length > 0) {
    var lastComment = getLastComment(comments);
    var lastUserComment = getLastComment(comments, username);
    //var src = $(lastComment).find('.timeline-comment-avatar')[0].src;
    //addIcon(location, src, lastComment, prNumber);
    if (typeof lastUserComment !== "undefined") {
      greenify(location);
    }
  } else {
    yellowify(location);
  }

  if (timelineComments.length > 0) {
    var lastUserCodeComment = getLastComment(timelineComments, username);
    if (typeof lastUserCodeComment !== "undefined") {
      greenify(location);
    }
  }

  // Set the theme
  themify(location);
}

function addIcon(location, source, content, prNumber) {
  var temp = $(location).find(".lh-condensed")[0];
  var href = $(content).find("a[href^='#issuecomment']")[0];
  href = $(href).attr("href");
  var url = window.location.href.replace(/(pulls.*)/g, "");
  var link = $("<a>", {
    href: url + "pull/" + prNumber + href
  });
  var image = link.append(
    $("<img>", {
      src: source,
      width: 44
    })
  );
  $(temp).append(image);
}

function getLastComment(comments, tempuser) {
  if (typeof tempuser !== "undefined") {
    // Username passed
    var lastComment;
    $.each(comments, function(i, comment) {
      var image = $(comment).find("img");
      if (
        image.length > 0 &&
        $(comment)
          .find("img")[0]
          .alt.slice(1) === tempuser
      ) {
        lastComment = comment;
      }
    });
    return lastComment;
  } else {
    // No username passed
    return comments[comments.length - 1];
  }
}

function setStyle(location, style) {
  // Called with something like:
  //  setStyle(location, {
  //    'background-color': '#FFEC94'
  //  });
  $(location).css(style);
}

function redify(location) {
  clearColors(location);
  $(location).addClass("ghu-red");
}

function yellowify(location) {
  clearColors(location);
  $(location).addClass("ghu-yellow");
}

function greenify(location) {
  clearColors(location);
  $(location).addClass("ghu-green");
}

function themify(location) {
  clearTheme(location);

  if (isDarkMode) {
    $(location).addClass("ghu-dark");
  } else {
    $(location).addClass("ghu-light");
  }
}

function clearColors(location) {
  $(location).removeClass("ghu-red ghu-yellow ghu-green");
}

function clearTheme(location) {
  $(location).removeClass("ghu-light ghu-dark");
}

function addNeverEndingStyles() {
  var neverEndingStyles = `
    .ghu-styled {
    }

    .ghu-red.ghu-light {
      background-color: #FFEC94 !important;
    }

    .ghu-yellow.ghu-light {
      background-color: #FFAEAE !important;
    }a

    .ghu-green.ghu-light {
      background-color: #B0E57C !important;
    }

    .ghu-red.ghu-dark {
      background-color: #570000 !important;
    }

    .ghu-yellow.ghu-dark {
      background-color: #804a00 !important;
    }

    .ghu-green.ghu-dark {
      background-color: #002900 !important;
    }
  `;
  addGlobalStyle(neverEndingStyles);
}

function addGlobalStyle(css) {
  var head = document.getElementsByTagName("head")[0];
  if (!head) {
    return;
  }
  var style = document.createElement("style");
  style.type = "text/css";
  style.innerHTML = css;
  head.appendChild(style);
}

function hideUserDeletedCommentDivs() {
  $(".discussion-item-comment_deleted").hide();
}
<commit_msg>CC fix<commit_after>// ==UserScript==
// @name         GitHub Utils
// @description  Something will go here...
// @version      0.10.0
// @updateURL    https://github.com/dracco1993/GitHubUtils/raw/master/githubutils.user.js
// @downloadURL  https://github.com/dracco1993/GitHubUtils/raw/master/githubutils.user.js
// @author       @dracco1993
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js
// @match        http://*.github.com/*
// @match        https://*.github.com/*
// @grant        none
// ==/UserScript==

/* jshint esversion: 6 */
/* eslint-env jquery   */

// global variables
var username;
var urlMatcher = /\/pulls/;
var isLoadingPages = false;
var nextPageUrl;
var isDarkMode;

(function() {
  "use strict";
  if (Array.isArray(window.location.pathname.match(urlMatcher))) {
    init();
  }

  document.addEventListener("pjax:end", function() {
    if (Array.isArray(window.location.pathname.match(urlMatcher))) {
      init();
    }
  });
})();

function init() {
  setTheme();
  setupNeverEndingGithub();
  setUsername();
  colorizeMeCaptain();
}

function setUsername() {
  username = $(".user-profile-link .css-truncate-target").text();
}

function setTheme() {
  var colorMode = $("html").data().colorMode;
  var systemIsDarkTheme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

  isDarkMode = (colorMode === "dark") || (colorMode === "auto" && systemIsDarkTheme === true);
}

function colorizeMeCaptain() {
  $(".Box-row:not(.ghu-styled)").each(function(k, v) {
    var links = $(v).find("div.flex-auto > a");
    var temp, repo;
    if (links[0].href.match(/\/pull/)) {
      temp = links[0];
    } else {
      temp = links[1];
      repo = links[0].text
        .replace(/\r?\n|\r/g, "")
        .trim()
        .split("/")
        .join("_");
    }
    $.ajax({
      url: temp.href,
      success: function(result) {
        var temp = $("<div/>")
          .html(result)
          .contents();
        getComments(temp, repo);
      }
    });
  });
}

function setupNeverEndingGithub() {
  addNeverEndingStyles();
  setNextPageURL($(document));

  $(window).scroll(function() {
    if ($(window).scrollTop() + $(window).height() === $(document).height()) {
      if (!isLoadingPages && nextPageUrl) {
        loadNextPage();
      }
    }
  });
}

function loadNextPage() {
  isLoadingPages = true;

  $.ajax({
    url: nextPageUrl,
    success: function(result) {
      var temp = $("<div/>")
        .html(result)
        .contents();
      displayNextPage(temp);
    },
    always: function() {
      isLoadingPages = false;
    }
  });
}

function displayNextPage(source) {
  // Actually add the new loaded content into the current container
  $("div.js-navigation-container").append(
    source.find("[id^=issue_]:not([id$=_link])")
  );
  colorizeMeCaptain();
  setNextPageURL(source);
  isLoadingPages = false;
}

function setNextPageURL(source) {
  var nextPageButton = source.find(".pagination .next_page");
  if (nextPageButton.length > 0) {
    nextPageUrl = nextPageButton[0].href;
  }
}

function getComments(source, repo) {
  var content = source.find(".js-comment-container");
  var prNumber = source
    .find(".gh-header-number")
    .first()
    .text()
    .slice(1);
  var prDescription = content.slice(0, 1);
  var newComment = content.slice(-1, 1);
  var comments = content.slice(1, content.length - 1);
  var timelineComments = source.find(
    ".js-discussion .timeline-comment-wrapper"
  );
  var location = $("#issue_" + prNumber)[0];
  if (location === undefined) {
    location = $("#issue_" + prNumber + "_" + repo);
  }

  $(location).addClass("ghu-styled");
  redify(location);

  if (comments.length > 0) {
    var lastComment = getLastComment(comments);
    var lastUserComment = getLastComment(comments, username);
    //var src = $(lastComment).find('.timeline-comment-avatar')[0].src;
    //addIcon(location, src, lastComment, prNumber);
    if (typeof lastUserComment !== "undefined") {
      greenify(location);
    }
  } else {
    yellowify(location);
  }

  if (timelineComments.length > 0) {
    var lastUserCodeComment = getLastComment(timelineComments, username);
    if (typeof lastUserCodeComment !== "undefined") {
      greenify(location);
    }
  }

  // Set the theme
  themify(location);
}

function addIcon(location, source, content, prNumber) {
  var temp = $(location).find(".lh-condensed")[0];
  var href = $(content).find("a[href^='#issuecomment']")[0];
  href = $(href).attr("href");
  var url = window.location.href.replace(/(pulls.*)/g, "");
  var link = $("<a>", {
    href: url + "pull/" + prNumber + href
  });
  var image = link.append(
    $("<img>", {
      src: source,
      width: 44
    })
  );
  $(temp).append(image);
}

function getLastComment(comments, tempuser) {
  if (typeof tempuser !== "undefined") {
    // Username passed
    var lastComment;
    $.each(comments, function(i, comment) {
      var image = $(comment).find("img");
      if (
        image.length > 0 &&
        $(comment)
          .find("img")[0]
          .alt.slice(1) === tempuser
      ) {
        lastComment = comment;
      }
    });
    return lastComment;
  } else {
    // No username passed
    return comments[comments.length - 1];
  }
}

function setStyle(location, style) {
  // Called with something like:
  //  setStyle(location, {
  //    'background-color': '#FFEC94'
  //  });
  $(location).css(style);
}

function redify(location) {
  clearColors(location);
  $(location).addClass("ghu-red");
}

function yellowify(location) {
  clearColors(location);
  $(location).addClass("ghu-yellow");
}

function greenify(location) {
  clearColors(location);
  $(location).addClass("ghu-green");
}

function themify(location) {
  clearTheme(location);

  if (isDarkMode) {
    $(location).addClass("ghu-dark");
  } else {
    $(location).addClass("ghu-light");
  }
}

function clearColors(location) {
  $(location).removeClass("ghu-red ghu-yellow ghu-green");
}

function clearTheme(location) {
  $(location).removeClass("ghu-light ghu-dark");
}

function addNeverEndingStyles() {
  var neverEndingStyles = `
    .ghu-styled {
    }

    .ghu-red.ghu-light {
      background-color: #FFEC94 !important;
    }

    .ghu-yellow.ghu-light {
      background-color: #FFAEAE !important;
    }a

    .ghu-green.ghu-light {
      background-color: #B0E57C !important;
    }

    .ghu-red.ghu-dark {
      background-color: #570000 !important;
    }

    .ghu-yellow.ghu-dark {
      background-color: #804a00 !important;
    }

    .ghu-green.ghu-dark {
      background-color: #002900 !important;
    }
  `;
  addGlobalStyle(neverEndingStyles);
}

function addGlobalStyle(css) {
  var head = document.getElementsByTagName("head")[0];
  if (!head) {
    return;
  }
  var style = document.createElement("style");
  style.type = "text/css";
  style.innerHTML = css;
  head.appendChild(style);
}

function hideUserDeletedCommentDivs() {
  $(".discussion-item-comment_deleted").hide();
}
<|endoftext|>


<commit_before>function createDataObj(buffer, headers) {
    return {
        headers: headers || "html"
      , buffer: buffer
    };
}

var ToBuffer = module.exports = function (data) {

    if (data === undefined) {
        return createDataObj(new Buffer(0));
    }

    if (typeof data === 'string') {
        return createDataObj(new Buffer(data));
    }

    if (data instanceof Buffer) {
        return createDataObj(data);
    }

    if (data instanceof Error) {
        data = createDataObj(data.toString());
    }

    try {
        data = JSON.stringify(data);
        createDataObj(data, "application/json; charset=utf-8");
    } catch (err) {
        return createDataObj(new Buffer(0));
    }

    if (data === undefined) {
        return createDataObj(new Buffer(0));
    }

    return createDataObj(new Buffer(data));
};
<commit_msg>Stringify and return json content<commit_after>function createDataObj(buffer, headers) {
    return {
        headers: headers || "html"
      , buffer: buffer
    };
}

var ToBuffer = module.exports = function (data) {

    if (data === undefined) {
        return createDataObj(new Buffer(0));
    }

    if (typeof data === 'string') {
        return createDataObj(new Buffer(data));
    }

    if (data instanceof Buffer) {
        return createDataObj(data);
    }

    if (data instanceof Error) {
        data = createDataObj(data.toString());
    }

    try {
        data = JSON.stringify(data, null, 2);
        return createDataObj(data, "application/json; charset=utf-8");
    } catch (err) {
        return createDataObj(new Buffer(0));
    }

    if (data === undefined) {
        return createDataObj(new Buffer(0));
    }

    return createDataObj(new Buffer(data));
};
<|endoftext|>


<commit_before>"use strict";

require('../core/setup');

var _ = require('lodash'),
    $ = require('jquery'),
    assert = require('chai').assert,
    Marionette = require('../../shim/backbone.marionette'),
    coreModels = require('../core/models'),
    coreUtils = require('../core/utils'),
    settings = require('../core/settings'),
    coreUnits = require('../core/units'),
    models = require('./models'),
    views = require('./views'),
    mocks = require('./mocks'),
    App = require('../app'),
    testUtils = require('../core/testUtils');

var sandboxId = 'sandbox',
    sandboxSelector = '#' + sandboxId,
    SandboxRegion = Marionette.Region.extend({
        el: sandboxSelector
    });

function renderPtSrcAndWQTableRowValue(n) {
    if (n && !_.isNaN(n)) {
        return Number(n.toFixed(3)).toLocaleString('en',
            { minimumFractionDigits: 3 });
    } else {
        return coreUtils.noData;
    }
}

describe('Analyze', function() {
    before(function() {
        if ($(sandboxSelector).length === 0) {
            $('<div>', {id: sandboxId}).appendTo('body');
        }

        settings.set('unit_scheme', coreUnits.UNIT_SCHEME.METRIC);
    });

    beforeEach(function() {

    });

    afterEach(function() {
        $(sandboxSelector).remove();
        $('<div>', {id: sandboxId}).appendTo('body');
        testUtils.resetApp(App);
    });

    after(function() {
        $(sandboxSelector).remove();
    });

    describe('Views', function() {
        describe('AnalysisResultView', function() {
            _.each(['land', 'soil', 'animals', 'pointsource', 'catchment_water_quality'], testAnalysisType);
        });
    });
});

function testAnalysisType(type) {
    it('tests ' + type + ' analysis renders as expected', function(done) {
        var sandbox = new SandboxRegion(),
            result = new models.LayerModel(_.find(mocks.results, { name: type })),
            resultView = new views.AnalyzeResultViews[type]({
                model: result
            });

        resultView.listenTo(resultView, 'show', function() {
            var expectedTableHeaders = tableHeaders[type],
                expectedTableRows = tableRows(type, result),
                actualTableHeaders = _.compact($('table thead th').map(function() {
                    if ($(this).hasClass('hidden-analyze-table-column')) {
                        return null;
                    }
                    return $(this).text().trim();
                }).toArray()),
                actualTableRows = _.compact($('table tbody td').map(function() {
                    if ($(this).hasClass('hidden-analyze-table-column')) {
                        return null;
                    }
                    return $(this).text().trim();
                }).toArray());

            assert.deepEqual(expectedTableHeaders, actualTableHeaders);
            assert.deepEqual(expectedTableRows, actualTableRows);

            done();
        });

        sandbox.show(resultView);
    });
}

function landTableFormatter(categories) {
    var collection = new coreModels.LandUseCensusCollection(categories);

    return collection.map(function(category) {
        var name = category.get('type'),
            areaKm2 = category.get('area') / coreUnits.METRIC.AREA_XL.factor,
            coverage = category.get('coverage') * 100;

        return [name, areaKm2.toFixed(2), coverage.toFixed(1)];
    });
}

function soilTableFormatter(categories) {
    var collection = new coreModels.SoilCensusCollection(categories);

    return collection.map(function(category) {
        var name = category.get('type'),
            areaKm2 = category.get('area') / coreUnits.METRIC.AREA_XL.factor,
            coverage = category.get('coverage') * 100;

        return [name, areaKm2.toFixed(2), coverage.toFixed(1)];
    });
}

function animalTableFormatter(categories) {
    var collection = new coreModels.AnimalCensusCollection(categories);

    return collection.map(function(category) {
        var name = category.get('type'),
            aeu = category.get('aeu').toLocaleString();

        return [name, aeu];
    });
}

function pointsourceTableFormatter(categories) {
    var collection = new coreModels.PointSourceCensusCollection(categories);

    return collection.map(function(category) {
        var code = category.get('npdes_id'),
            city = coreUtils.toTitleCase(category.get('city')),
            discharge = renderPtSrcAndWQTableRowValue(
                category.get('mgd') / coreUnits.METRIC.VOLUMETRICFLOWRATE.factor
            ),
            tn_load = renderPtSrcAndWQTableRowValue(category.get('kgn_yr')),
            tp_load = renderPtSrcAndWQTableRowValue(category.get('kgp_yr'));

        return [code, city, discharge, tn_load, tp_load];
    });
}

function catchmentWaterQualityTableFormatter(categories) {
    var collection = new coreModels.CatchmentWaterQualityCensusCollection(categories);
    return collection.map(function(category) {
        var nord = category.get('nord').toString(),
            areaha = renderPtSrcAndWQTableRowValue(category.get('areaha')),
            tn_tot_kgy = renderPtSrcAndWQTableRowValue(
                category.get('tn_tot_kgy')),
            tp_tot_kgy = renderPtSrcAndWQTableRowValue(
                category.get('tp_tot_kgy')),
            tss_tot_kg = renderPtSrcAndWQTableRowValue(
                category.get('tss_tot_kg')),
            tn_yr_avg_ = renderPtSrcAndWQTableRowValue(category.get('tn_yr_avg_')),
            tp_yr_avg_ = renderPtSrcAndWQTableRowValue(category.get('tp_yr_avg_')),
            tss_concmg = renderPtSrcAndWQTableRowValue(category.get('tss_concmg'));

        return [nord, areaha, tn_tot_kgy, tp_tot_kgy, tss_tot_kg, tn_yr_avg_,
            tp_yr_avg_, tss_concmg];
    });
}

var dataFormatters = {
    land: landTableFormatter,
    soil: soilTableFormatter,
    animals: animalTableFormatter,
    pointsource: pointsourceTableFormatter,
    catchment_water_quality: catchmentWaterQualityTableFormatter,
};

var tableHeaders = {
    land: ['Type', 'Area (km²)', 'Coverage (%)'],
    soil: ['Type', 'Area (km²)', 'Coverage (%)'],
    animals: ['Animal', 'Count'],
    pointsource: ['NPDES Code', 'City', 'Discharge (m³/d)', 'TN Load (kg/a)', 'TP Load (kg/a)'],
    catchment_water_quality: ['Id', 'Area (ha)', 'Total N (kg/ha)', 'Total P (kg/ha)',
        'Total SS (kg/ha)', 'Avg TN (mg/l)', 'Avg TP (mg/l)', 'Avg TSS (mg/l)'],
};

function tableRows(type, result) {
    var formatter = dataFormatters[type];

    return _.flatten(formatter(result.get('categories')));
}
<commit_msg>Update tests<commit_after>"use strict";

require('../core/setup');

var _ = require('lodash'),
    $ = require('jquery'),
    assert = require('chai').assert,
    Marionette = require('../../shim/backbone.marionette'),
    coreModels = require('../core/models'),
    coreUtils = require('../core/utils'),
    settings = require('../core/settings'),
    coreUnits = require('../core/units'),
    models = require('./models'),
    views = require('./views'),
    mocks = require('./mocks'),
    App = require('../app'),
    testUtils = require('../core/testUtils');

var sandboxId = 'sandbox',
    sandboxSelector = '#' + sandboxId,
    SandboxRegion = Marionette.Region.extend({
        el: sandboxSelector
    });

function renderPtSrcAndWQTableRowValue(n) {
    if (n && !_.isNaN(n)) {
        return Number(n.toFixed(3)).toLocaleString('en',
            { minimumFractionDigits: 3 });
    } else {
        return coreUtils.noData;
    }
}

describe('Analyze', function() {
    before(function() {
        if ($(sandboxSelector).length === 0) {
            $('<div>', {id: sandboxId}).appendTo('body');
        }

        settings.set('unit_scheme', coreUnits.UNIT_SCHEME.METRIC);
    });

    beforeEach(function() {

    });

    afterEach(function() {
        $(sandboxSelector).remove();
        $('<div>', {id: sandboxId}).appendTo('body');
        testUtils.resetApp(App);
    });

    after(function() {
        $(sandboxSelector).remove();
    });

    describe('Views', function() {
        describe('AnalysisResultView', function() {
            _.each(['land', 'soil', 'animals', 'pointsource', 'catchment_water_quality'], testAnalysisType);
        });
    });
});

function testAnalysisType(type) {
    it('tests ' + type + ' analysis renders as expected', function(done) {
        var sandbox = new SandboxRegion(),
            result = new models.LayerModel(_.find(mocks.results, { name: type })),
            resultView = new views.AnalyzeResultViews[type]({
                model: result
            });

        resultView.listenTo(resultView, 'show', function() {
            var expectedTableHeaders = tableHeaders[type],
                expectedTableRows = tableRows(type, result),
                actualTableHeaders = _.compact($('table thead th').map(function() {
                    if ($(this).hasClass('hidden-analyze-table-column')) {
                        return null;
                    }
                    return $(this).text().trim();
                }).toArray()),
                actualTableRows = _.compact($('table tbody td').map(function() {
                    if ($(this).hasClass('hidden-analyze-table-column')) {
                        return null;
                    }
                    return $(this).text().trim();
                }).toArray());

            assert.deepEqual(expectedTableHeaders, actualTableHeaders);
            assert.deepEqual(expectedTableRows, actualTableRows);

            done();
        });

        sandbox.show(resultView);
    });
}

function landTableFormatter(categories) {
    var collection = new coreModels.LandUseCensusCollection(categories);

    return collection.map(function(category) {
        var name = category.get('type'),
            areaKm2 = category.get('area') / coreUnits.METRIC.AREA_XL.factor,
            coverage = category.get('coverage') * 100;

        return [name, areaKm2.toFixed(2), coverage.toFixed(1)];
    });
}

function soilTableFormatter(categories) {
    var collection = new coreModels.SoilCensusCollection(categories);

    return collection.map(function(category) {
        var name = category.get('type'),
            areaKm2 = category.get('area') / coreUnits.METRIC.AREA_XL.factor,
            coverage = category.get('coverage') * 100;

        return [name, areaKm2.toFixed(2), coverage.toFixed(1)];
    });
}

function animalTableFormatter(categories) {
    var collection = new coreModels.AnimalCensusCollection(categories);

    return collection.map(function(category) {
        var name = category.get('type'),
            aeu = category.get('aeu').toLocaleString();

        return [name, aeu];
    });
}

function pointsourceTableFormatter(categories) {
    var collection = new coreModels.PointSourceCensusCollection(categories);

    return collection.map(function(category) {
        var code = category.get('npdes_id'),
            city = coreUtils.toTitleCase(category.get('city')),
            discharge = renderPtSrcAndWQTableRowValue(
                category.get('mgd') / coreUnits.METRIC.VOLUMETRICFLOWRATE.factor
            ),
            tn_load = renderPtSrcAndWQTableRowValue(category.get('kgn_yr')),
            tp_load = renderPtSrcAndWQTableRowValue(category.get('kgp_yr'));

        return [code, city, discharge, tn_load, tp_load];
    });
}

function catchmentWaterQualityTableFormatter(categories) {
    var collection = new coreModels.CatchmentWaterQualityCensusCollection(categories);
    return collection.map(function(category) {
        var nord = category.get('nord').toString(),
            areaha = renderPtSrcAndWQTableRowValue(category.get('areaha')),
            tn_tot_kgy = renderPtSrcAndWQTableRowValue(
                category.get('tn_tot_kgy')),
            tp_tot_kgy = renderPtSrcAndWQTableRowValue(
                category.get('tp_tot_kgy')),
            tss_tot_kg = renderPtSrcAndWQTableRowValue(
                category.get('tss_tot_kg')),
            tn_yr_avg_ = renderPtSrcAndWQTableRowValue(category.get('tn_yr_avg_')),
            tp_yr_avg_ = renderPtSrcAndWQTableRowValue(category.get('tp_yr_avg_')),
            tss_concmg = renderPtSrcAndWQTableRowValue(category.get('tss_concmg'));

        return [nord, areaha, tn_tot_kgy, tp_tot_kgy, tss_tot_kg, tn_yr_avg_,
            tp_yr_avg_, tss_concmg];
    });
}

var dataFormatters = {
    land: landTableFormatter,
    soil: soilTableFormatter,
    animals: animalTableFormatter,
    pointsource: pointsourceTableFormatter,
    catchment_water_quality: catchmentWaterQualityTableFormatter,
};

var tableHeaders = {
    land: ['Type', 'Area (km²)', 'Coverage (%)'],
    soil: ['Type', 'Area (km²)', 'Coverage (%)'],
    animals: ['Animal', 'Count'],
    pointsource: ['NPDES Code', 'City', 'Discharge (m³/d)', 'TN Load (kg/yr)', 'TP Load (kg/yr)'],
    catchment_water_quality: ['Id', 'Area (ha)', 'Total N (kg/ha)', 'Total P (kg/ha)',
        'Total SS (kg/ha)', 'Avg TN (mg/l)', 'Avg TP (mg/l)', 'Avg TSS (mg/l)'],
};

function tableRows(type, result) {
    var formatter = dataFormatters[type];

    return _.flatten(formatter(result.get('categories')));
}
<|endoftext|>


<commit_before>module.exports = function( Release, files, complete ) {

	var
		fs = require( "fs" ),
		shell = require( "shelljs" ),
		pkg = require( Release.dir.repo + "/package.json" ),
		distRemote = Release.remote

			// For local and github dists
			.replace( /jquery(\.git|$)/, "jquery-dist$1" ),

		// These files are included with the distribution
		extras = [
			"src",
			"LICENSE.txt",
			"AUTHORS.txt",
			"package.json"
		];

	/**
	 * Clone the distribution repo
	 */
	function clone() {
		Release.chdir( Release.dir.base );
		Release.dir.dist = Release.dir.base + "/dist";

		console.log( "Using distribution repo: ", distRemote );
		Release.exec( "git clone " + distRemote + " " + Release.dir.dist,
			"Error cloning repo." );

		// Distribution always works on master
		Release.chdir( Release.dir.dist );
		Release.exec( "git checkout master", "Error checking out branch." );
		console.log();
	}

	/**
	 * Generate bower file for jquery-dist
	 */
	function generateBower() {
		return JSON.stringify( {
			name: pkg.name,
			main: pkg.main,
			license: "MIT",
			ignore: [
				"package.json"
			],
			keywords: pkg.keywords
		}, null, 2 );
	}

	/**
	 * Copy necessary files over to the dist repo
	 */
	function copy() {

		// Copy dist files
		var distFolder = Release.dir.dist + "/dist";
		shell.mkdir( "-p", distFolder );
		files.forEach( function( file ) {
			shell.cp( "-f", Release.dir.repo + "/" + file, distFolder );
		} );

		// Copy other files
		extras.forEach( function( file ) {
			shell.cp( "-rf", Release.dir.repo + "/" + file, Release.dir.dist );
		} );

		// Write generated bower file
		fs.writeFileSync( Release.dir.dist + "/bower.json", generateBower() );

		console.log( "Adding files to dist..." );
		Release.exec( "git add .", "Error adding files." );
		Release.exec(
			"git commit -m 'Release " + Release.newVersion + "'",
			"Error committing files."
		);
		console.log();

		console.log( "Tagging release on dist..." );
		Release.exec( "git tag " + Release.newVersion,
			"Error tagging " + Release.newVersion + " on dist repo." );
		Release.tagTime = Release.exec( "git log -1 --format='%ad'",
			"Error getting tag timestamp." ).trim();
	}

	/**
	 * Push files to dist repo
	 */
	function push() {
		Release.chdir( Release.dir.dist );

		console.log( "Pushing release to dist repo..." );
		Release.exec( "git push " + distRemote + " master --tags",
			"Error pushing master and tags to git repo." );

		// Set repo for npm publish
		Release.dir.origRepo = Release.dir.repo;
		Release.dir.repo = Release.dir.dist;
	}

	Release.walk( [
		Release._section( "Copy files to distribution repo" ),
		clone,
		copy,
		Release.confirmReview,

		Release._section( "Pushing files to distribution repo" ),
		push
	], complete );
};
<commit_msg>Release: include external/sizzle in releases<commit_after>module.exports = function( Release, files, complete ) {

	var
		fs = require( "fs" ),
		shell = require( "shelljs" ),
		pkg = require( Release.dir.repo + "/package.json" ),
		distRemote = Release.remote

			// For local and github dists
			.replace( /jquery(\.git|$)/, "jquery-dist$1" ),

		// These files are included with the distribution
		extras = [
			"src",
			"external/sizzle",
			"LICENSE.txt",
			"AUTHORS.txt",
			"package.json"
		];

	/**
	 * Clone the distribution repo
	 */
	function clone() {
		Release.chdir( Release.dir.base );
		Release.dir.dist = Release.dir.base + "/dist";

		console.log( "Using distribution repo: ", distRemote );
		Release.exec( "git clone " + distRemote + " " + Release.dir.dist,
			"Error cloning repo." );

		// Distribution always works on master
		Release.chdir( Release.dir.dist );
		Release.exec( "git checkout master", "Error checking out branch." );
		console.log();
	}

	/**
	 * Generate bower file for jquery-dist
	 */
	function generateBower() {
		return JSON.stringify( {
			name: pkg.name,
			main: pkg.main,
			license: "MIT",
			ignore: [
				"package.json"
			],
			keywords: pkg.keywords
		}, null, 2 );
	}

	/**
	 * Copy necessary files over to the dist repo
	 */
	function copy() {

		// Copy dist files
		var distFolder = Release.dir.dist + "/dist";
		shell.mkdir( "-p", distFolder );
		files.forEach( function( file ) {
			shell.cp( "-f", Release.dir.repo + "/" + file, distFolder );
		} );

		// Copy other files
		extras.forEach( function( file ) {
			shell.cp( "-rf", Release.dir.repo + "/" + file, Release.dir.dist );
		} );

		// Write generated bower file
		fs.writeFileSync( Release.dir.dist + "/bower.json", generateBower() );

		console.log( "Adding files to dist..." );
		Release.exec( "git add .", "Error adding files." );
		Release.exec(
			"git commit -m 'Release " + Release.newVersion + "'",
			"Error committing files."
		);
		console.log();

		console.log( "Tagging release on dist..." );
		Release.exec( "git tag " + Release.newVersion,
			"Error tagging " + Release.newVersion + " on dist repo." );
		Release.tagTime = Release.exec( "git log -1 --format='%ad'",
			"Error getting tag timestamp." ).trim();
	}

	/**
	 * Push files to dist repo
	 */
	function push() {
		Release.chdir( Release.dir.dist );

		console.log( "Pushing release to dist repo..." );
		Release.exec( "git push " + distRemote + " master --tags",
			"Error pushing master and tags to git repo." );

		// Set repo for npm publish
		Release.dir.origRepo = Release.dir.repo;
		Release.dir.repo = Release.dir.dist;
	}

	Release.walk( [
		Release._section( "Copy files to distribution repo" ),
		clone,
		copy,
		Release.confirmReview,

		Release._section( "Pushing files to distribution repo" ),
		push
	], complete );
};
<|endoftext|>


<commit_before>require(['prefetchManifest']);

(function() {
    if (z.capabilities.mobile) {
        z.body.addClass('mobile');
    }
    if (z.capabilities.tablet) {
        z.body.addClass('tablet');
    }
    if (z.capabilities.desktop) {
        z.body.addClass('desktop');
    }

    // Reviewer tool search.
    initAdvancedMobileSearch();
    initMobileMenus();
    initClearSearch();

    initRegionalQueue();
    initAdditionalReviewQueue();

    initMoreAppInfo();

    if ($('.theme-search').length) {
        initSearch(true);
    } else {
        initSearch();
    }

    if ($('.comm-dashboard-switch').length) {
        require(['reviewersCommbadge']);
    }
})();

function initClearSearch() {
    var $clear = $('.clear-queue-search'),
        $appQueue = $('.search-toggle'),
        $search = $('.queue-search'),
        $searchIsland = $('#search-island');

    $clear.click(_pd(function() {
        $appQueue.show();
        $('#id_q').val('');
        $clear.hide();
        $searchIsland.hide();
    }));
}

function initSearch(isTheme) {
    var search_results = getTemplate($('#queue-search-template'));
    var no_results = getTemplate($('#queue-search-empty-template'));

    var $clear = $('.clear-queue-search'),
        $appQueue = $('.search-toggle'),
        $search = $('.queue-search'),
        $searchIsland = $('#search-island');

    if ($search.length) {
        // An underscore template for more advanced rendering.
        var search_result_row = _.template($('#queue-search-row-template').html());

        var apiUrl = $search.data('api-url');
        var review_url = $search.data('review-url');
        var statuses = $searchIsland.data('statuses');

        $search.on('submit', 'form', _pd(function() {
            var $form = $(this);
            $.get(apiUrl, $form.serialize()).done(function(data) {
                // Hide app queue.
                $appQueue.hide();
                $clear.show();
                // Show results.
                if (data.meta.total_count === 0) {
                    $searchIsland.html(no_results({})).show();
                } else {
                    var results = [];
                    $.each(data.objects, function(i, item) {
                        if (isTheme) {
                            item = buildThemeResultRow(item, review_url,
                                                       statuses);
                        } else {
                            item = buildAppResultRow(item, review_url,
                                                     statuses);
                        }
                        results.push(search_result_row(item));
                    });
                    $searchIsland.html(
                        search_results({rows: results.join('')})).show();
                }
            });
        }));
    }
}

function buildAppResultRow(app, review_url, statuses) {
    var flags = [];
    app.review_url = review_url.replace('__slug__', app.slug);
    app.status = statuses[app.status];
    if (app.latest_version.status) {
        app.status += format(' | {0}', statuses[app.latest_version.status]);
    }
    if (app.is_packaged) {
        flags.push({suffix: 'packaged-app', title: gettext('Packaged App')});
    }
    if (app.latest_version) {
        if (app.latest_version.is_privileged) {
            flags.push({suffix: 'privileged-app', title: gettext('Privileged App')});
        }
        if (app.latest_version.has_info_request) {
            flags.push({suffix: 'info', title: gettext('More Information Requested')});
        }
        if (app.latest_version.has_editor_comment) {
            flags.push({suffix: 'editor', title: gettext('Contains Editor Comment')});
        }
    }
    if (app.premium_type == 'premium-inapp' || app.premium_type == 'premium') {
        flags.push({suffix: 'premium', title: gettext('Premium App')});
    }
    if (app.is_escalated) {
        flags.push({suffix: 'escalated', title: gettext('Escalated')});
    }
    app.flags = flags;

    if (app.price === null) {
        app.price = gettext('Free');
    }

    return app;
}

function buildThemeResultRow(theme, review_url, statuses) {
    // Add some extra pretty attrs for the template.
    theme.name = theme.name[0];

    // Rather resolve URLs in backend, infer from slug.
    theme.review_url = review_url.replace(
        '__slug__', theme.slug);
    theme.status = statuses[theme.status];
    return theme;
}

function initMobileMenus() {
    // Nav action menu overlays for queues and logs.
    var $logTabOverlay = $('#log-tab-overlay');
    var $queueTabOverlay = $('#queue-tab-overlay');
    $('.trigger-queues').click(function(e) {
        if (z.capabilities.mobile || z.capabilities.tablet) {
            e.preventDefault();
            $queueTabOverlay.show();
        }
    });
    $('.trigger-logs').click(_pd(function() {
        if (z.capabilities.mobile || z.capabilities.tablet) {
            $logTabOverlay.show();
        }
    }));
    $('.nav-action-menu button').click(_pd(function() {
        // Turn buttons into links on nav tab overlays.
        var $button = $(this);
        if ($button.data('url') == '#cancel') {
            $queueTabOverlay.hide();
            $logTabOverlay.hide();
        } else {
            window.location.href = $button.data('url');
        }
    }));
}

function initAdvancedMobileSearch() {
    // Value selectors for mobile advanced search.
    $('.value-select-field').click(function() {
        $(this).next('div[role="dialog"]').show();
    });
    $('div[role="dialog"] .cancel').click(_pd(function() {
        $(this).closest('div[role="dialog"]').hide();
    }));

    var $advSearch = $('.advanced-search.desktop');
    $('.advanced-search li[role="option"] input').change(
        syncPrettyMobileForm).each(function(i, input) {
            /* Since Gaia form doesn't use selects, browser does not populate
               our Gaia form after submitting with GET params. We sync data
               between the populated hidden desktop advanced search form to our
               mobile Gaia form. */
            var $input = $(input);
            var val = $input.attr('value');
            if (val) {
                /* If input checked/selected in the desktop form, check/select
                   it in our Gaia form. */
                var nameSelect = '[name="' + $input.attr('name') + '"]';
                var $inputs = $(nameSelect + ' option[value="' + val + '"]:selected',
                                $advSearch);
                $inputs = $inputs.add(
                    $('input[value="' + val + '"]:checked' + nameSelect,
                      $advSearch));
                if ($inputs.length) {
                    $input.prop('checked', true);
                }
            }
        });
    syncPrettyMobileForm();
}

function syncPrettyMobileForm() {
    /* The pretty mobile visible form does not contain actual form elements.
       Value selector form elements are hidden and contained within overlays.
       When we check a value our form in the overlay, we sync the pretty
       representation of the form. */

    // Value selector is the name of the Gaia mobile radio/checkbox form.
    var $valSelectFields = $('.value-select-field');

    $valSelectFields.each(function(index, valSelectField) {
        var $valSelectField = $(valSelectField);
        var name = $valSelectField.data('field');

        var valStrs = [];
        var $checkedInputs = $('li[role="option"] input[name="' + name + '"]:checked');
        $checkedInputs.each(function(index, input) {
            // Build pretty string.
            valStrs.push($(input).next('span').text().trim());
        });

        // Sync new selected value to our span in the pretty form.
        var firstPrettyVal = $('li[role="option"]:first-child span',
            $valSelectField.next('div[role="dialog"]')).text();
        $('.' + name + '.selected-val span').text(
            valStrs.length ? valStrs.join() :
            $('.multi-val', $valSelectField).length ? gettext('Any') :
                                                      firstPrettyVal);
    });
}

function initRegionalQueue() {
    if (!$('.regional-queue').length) {
        return;
    }

    // POST to the API to approve/reject an app in a regional queue.
    z.doc.on('click', '.approve, .reject', _pd(function(e) {
        var $this = $(this);
        var $tr = $this.closest('tr');
        var $buttons = $tr.find('.button');
        var url = $tr.data('actionUrl');
        var appName = $tr.find('.app-name').text();
        var fmt = {app: appName};
        var approved = $this.data('action') == 'approve' ? '1' : '';

        $buttons.addClass('disabled');

        $.post(url, {'approve': approved}).success(function() {
            var msg;
            var classes;
            if (approved) {
                msg = format(gettext('Approved app: {app}'), fmt);
                classes = 'good';
            } else {
                msg = format(gettext('Rejected app: {app}'), fmt);
                classes = 'bad';
            }
            require('notification')({message: msg, timeout: 1000, classes: classes});
            $tr.hide();
        }).error(function() {
            var msg = approved ? format(gettext('Error approving app: {app}'), fmt) :
                                 format(gettext('Error rejecting app: {app}'), fmt);
            require('notification')({message: msg, timeout: 1000});
            $buttons.removeClass('disabled');
        });
    }));
}

function initAdditionalReviewQueue() {
    /* Setup the pass/fail buttons for the additional review queue. */
    if (!$('.additional-review-queue').length) {
        return;
    }

    z.doc.on('click', '.approve, .reject', _pd(function(e) {
        var $this = $(this);
        var $container = $this.closest('tr');
        var $buttons = $container.find('.button');
        var $tr = $($container.data('addon-selector'));
        var url = $tr.data('actionUrl');
        var appName = $tr.find('.app-name').text();
        var fmt = {app: appName};
        var passed = $this.data('action') == 'approve';
        var $comment = $container.find('[name="comment"]');
        var comment = $comment.val();
        var msgTimeout = 3000;

        if (!passed && comment.length === 0) {
            $comment.addClass('error');
        } else {
            $buttons.addClass('disabled');

            $.ajax({
                type: 'patch',
                url: url,
                data: JSON.stringify({'passed': passed, 'comment': comment}),
                contentType: 'application/json',
            }).done(function() {
                var msg;
                var classes;
                if (passed) {
                    msg = format(gettext('Approved app: {app}'), fmt);
                    classes = 'good';
                } else {
                    msg = format(gettext('Rejected app: {app}'), fmt);
                    classes = 'bad';
                }
                require('notification')({message: msg, timeout: msgTimeout, classes: classes});
                $tr.hide();
                $container.hide();
            }).fail(function() {
                var msg = passed ? format(gettext('Error passing app: {app}'), fmt) :
                                format(gettext('Error failing app: {app}'), fmt);
                require('notification')({message: msg, timeout: msgTimeout});
                $buttons.removeClass('disabled');
            });
        }
    }));
}

function initMoreAppInfo() {
    var $appinfo = $('.more-app-info');
    var $show_more = $('.more-app-info-show');
    var $show_less = $('.less-app-info-show');

    // Initial state.
    $appinfo.hide();

    // Click events.
    $show_more.click(_pd(function() {
        $show_more.hide();
        $appinfo.show();
    }));

    $show_less.click(_pd(function() {
        $appinfo.hide();
        $show_more.show();
    }));
}
<commit_msg>Don't assume null price is Free (bug 1005904)<commit_after>require(['prefetchManifest']);

(function() {
    if (z.capabilities.mobile) {
        z.body.addClass('mobile');
    }
    if (z.capabilities.tablet) {
        z.body.addClass('tablet');
    }
    if (z.capabilities.desktop) {
        z.body.addClass('desktop');
    }

    // Reviewer tool search.
    initAdvancedMobileSearch();
    initMobileMenus();
    initClearSearch();

    initRegionalQueue();
    initAdditionalReviewQueue();

    initMoreAppInfo();

    initSearch();

    if ($('.comm-dashboard-switch').length) {
        require(['reviewersCommbadge']);
    }
})();

function initClearSearch() {
    var $clear = $('.clear-queue-search'),
        $appQueue = $('.search-toggle'),
        $search = $('.queue-search'),
        $searchIsland = $('#search-island');

    $clear.click(_pd(function() {
        $appQueue.show();
        $('#id_q').val('');
        $clear.hide();
        $searchIsland.hide();
    }));
}

function initSearch() {
    var search_results = getTemplate($('#queue-search-template'));
    var no_results = getTemplate($('#queue-search-empty-template'));

    var $clear = $('.clear-queue-search'),
        $appQueue = $('.search-toggle'),
        $search = $('.queue-search'),
        $searchIsland = $('#search-island');

    if ($search.length) {
        // An underscore template for more advanced rendering.
        var search_result_row = _.template($('#queue-search-row-template').html());

        var apiUrl = $search.data('api-url');
        var review_url = $search.data('review-url');
        var statuses = $searchIsland.data('statuses');

        $search.on('submit', 'form', _pd(function() {
            var $form = $(this);
            $.get(apiUrl, $form.serialize()).done(function(data) {
                // Hide app queue.
                $appQueue.hide();
                $clear.show();
                // Show results.
                if (data.meta.total_count === 0) {
                    $searchIsland.html(no_results({})).show();
                } else {
                    var results = [];
                    $.each(data.objects, function(i, item) {
                        item = buildAppResultRow(item, review_url, statuses);
                        results.push(search_result_row(item));
                    });
                    $searchIsland.html(
                        search_results({rows: results.join('')})).show();
                }
            });
        }));
    }
}

function buildAppResultRow(app, review_url, statuses) {
    var flags = [];
    app.review_url = review_url.replace('__slug__', app.slug);
    app.status = statuses[app.status];
    if (app.latest_version.status) {
        app.status += format(' | {0}', statuses[app.latest_version.status]);
    }
    if (app.is_packaged) {
        flags.push({suffix: 'packaged-app', title: gettext('Packaged App')});
    }
    if (app.latest_version) {
        if (app.latest_version.is_privileged) {
            flags.push({suffix: 'privileged-app', title: gettext('Privileged App')});
        }
        if (app.latest_version.has_info_request) {
            flags.push({suffix: 'info', title: gettext('More Information Requested')});
        }
        if (app.latest_version.has_editor_comment) {
            flags.push({suffix: 'editor', title: gettext('Contains Editor Comment')});
        }
    }
    if (app.premium_type == 'premium-inapp' || app.premium_type == 'premium') {
        flags.push({suffix: 'premium', title: gettext('Premium App')});
    }
    if (app.is_escalated) {
        flags.push({suffix: 'escalated', title: gettext('Escalated')});
    }
    app.flags = flags;

    if (app.price === null) {
        app.price = 'null';
    }

    return app;
}

function initMobileMenus() {
    // Nav action menu overlays for queues and logs.
    var $logTabOverlay = $('#log-tab-overlay');
    var $queueTabOverlay = $('#queue-tab-overlay');
    $('.trigger-queues').click(function(e) {
        if (z.capabilities.mobile || z.capabilities.tablet) {
            e.preventDefault();
            $queueTabOverlay.show();
        }
    });
    $('.trigger-logs').click(_pd(function() {
        if (z.capabilities.mobile || z.capabilities.tablet) {
            $logTabOverlay.show();
        }
    }));
    $('.nav-action-menu button').click(_pd(function() {
        // Turn buttons into links on nav tab overlays.
        var $button = $(this);
        if ($button.data('url') == '#cancel') {
            $queueTabOverlay.hide();
            $logTabOverlay.hide();
        } else {
            window.location.href = $button.data('url');
        }
    }));
}

function initAdvancedMobileSearch() {
    // Value selectors for mobile advanced search.
    $('.value-select-field').click(function() {
        $(this).next('div[role="dialog"]').show();
    });
    $('div[role="dialog"] .cancel').click(_pd(function() {
        $(this).closest('div[role="dialog"]').hide();
    }));

    var $advSearch = $('.advanced-search.desktop');
    $('.advanced-search li[role="option"] input').change(
        syncPrettyMobileForm).each(function(i, input) {
            /* Since Gaia form doesn't use selects, browser does not populate
               our Gaia form after submitting with GET params. We sync data
               between the populated hidden desktop advanced search form to our
               mobile Gaia form. */
            var $input = $(input);
            var val = $input.attr('value');
            if (val) {
                /* If input checked/selected in the desktop form, check/select
                   it in our Gaia form. */
                var nameSelect = '[name="' + $input.attr('name') + '"]';
                var $inputs = $(nameSelect + ' option[value="' + val + '"]:selected',
                                $advSearch);
                $inputs = $inputs.add(
                    $('input[value="' + val + '"]:checked' + nameSelect,
                      $advSearch));
                if ($inputs.length) {
                    $input.prop('checked', true);
                }
            }
        });
    syncPrettyMobileForm();
}

function syncPrettyMobileForm() {
    /* The pretty mobile visible form does not contain actual form elements.
       Value selector form elements are hidden and contained within overlays.
       When we check a value our form in the overlay, we sync the pretty
       representation of the form. */

    // Value selector is the name of the Gaia mobile radio/checkbox form.
    var $valSelectFields = $('.value-select-field');

    $valSelectFields.each(function(index, valSelectField) {
        var $valSelectField = $(valSelectField);
        var name = $valSelectField.data('field');

        var valStrs = [];
        var $checkedInputs = $('li[role="option"] input[name="' + name + '"]:checked');
        $checkedInputs.each(function(index, input) {
            // Build pretty string.
            valStrs.push($(input).next('span').text().trim());
        });

        // Sync new selected value to our span in the pretty form.
        var firstPrettyVal = $('li[role="option"]:first-child span',
            $valSelectField.next('div[role="dialog"]')).text();
        $('.' + name + '.selected-val span').text(
            valStrs.length ? valStrs.join() :
            $('.multi-val', $valSelectField).length ? gettext('Any') :
                                                      firstPrettyVal);
    });
}

function initRegionalQueue() {
    if (!$('.regional-queue').length) {
        return;
    }

    // POST to the API to approve/reject an app in a regional queue.
    z.doc.on('click', '.approve, .reject', _pd(function(e) {
        var $this = $(this);
        var $tr = $this.closest('tr');
        var $buttons = $tr.find('.button');
        var url = $tr.data('actionUrl');
        var appName = $tr.find('.app-name').text();
        var fmt = {app: appName};
        var approved = $this.data('action') == 'approve' ? '1' : '';

        $buttons.addClass('disabled');

        $.post(url, {'approve': approved}).success(function() {
            var msg;
            var classes;
            if (approved) {
                msg = format(gettext('Approved app: {app}'), fmt);
                classes = 'good';
            } else {
                msg = format(gettext('Rejected app: {app}'), fmt);
                classes = 'bad';
            }
            require('notification')({message: msg, timeout: 1000, classes: classes});
            $tr.hide();
        }).error(function() {
            var msg = approved ? format(gettext('Error approving app: {app}'), fmt) :
                                 format(gettext('Error rejecting app: {app}'), fmt);
            require('notification')({message: msg, timeout: 1000});
            $buttons.removeClass('disabled');
        });
    }));
}

function initAdditionalReviewQueue() {
    /* Setup the pass/fail buttons for the additional review queue. */
    if (!$('.additional-review-queue').length) {
        return;
    }

    z.doc.on('click', '.approve, .reject', _pd(function(e) {
        var $this = $(this);
        var $container = $this.closest('tr');
        var $buttons = $container.find('.button');
        var $tr = $($container.data('addon-selector'));
        var url = $tr.data('actionUrl');
        var appName = $tr.find('.app-name').text();
        var fmt = {app: appName};
        var passed = $this.data('action') == 'approve';
        var $comment = $container.find('[name="comment"]');
        var comment = $comment.val();
        var msgTimeout = 3000;

        if (!passed && comment.length === 0) {
            $comment.addClass('error');
        } else {
            $buttons.addClass('disabled');

            $.ajax({
                type: 'patch',
                url: url,
                data: JSON.stringify({'passed': passed, 'comment': comment}),
                contentType: 'application/json',
            }).done(function() {
                var msg;
                var classes;
                if (passed) {
                    msg = format(gettext('Approved app: {app}'), fmt);
                    classes = 'good';
                } else {
                    msg = format(gettext('Rejected app: {app}'), fmt);
                    classes = 'bad';
                }
                require('notification')({message: msg, timeout: msgTimeout, classes: classes});
                $tr.hide();
                $container.hide();
            }).fail(function() {
                var msg = passed ? format(gettext('Error passing app: {app}'), fmt) :
                                format(gettext('Error failing app: {app}'), fmt);
                require('notification')({message: msg, timeout: msgTimeout});
                $buttons.removeClass('disabled');
            });
        }
    }));
}

function initMoreAppInfo() {
    var $appinfo = $('.more-app-info');
    var $show_more = $('.more-app-info-show');
    var $show_less = $('.less-app-info-show');

    // Initial state.
    $appinfo.hide();

    // Click events.
    $show_more.click(_pd(function() {
        $show_more.hide();
        $appinfo.show();
    }));

    $show_less.click(_pd(function() {
        $appinfo.hide();
        $show_more.show();
    }));
}
<|endoftext|>


<commit_before>/**
 * Copyright 2016 IBM Corp. All Rights Reserved.
 *
 * 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.
 */

'use strict';

// conversation variables
var conversation_result, is_wating = false, methods = {
	chatbot: function () {
		var $chatInput = $('.chat-window--message-input'),
		$jsonPanel = $('#json-panel .base--textarea'),
		$loading = $('.loader');
		//$mic = $('.ui-button-microphone');

		$chatInput.keyup(function(event){
			if(event.keyCode === 13) {
				var inputText = $(this).val();
				converse(inputText);
			}
		});

		/**
		 * Convert response context to car command
		 */
		/**var contextToCommand = function(conversation_result){
			var direction = '';
			var entities = conversation_result.entities;
			var intents = conversation_result.intents;
			for(var index in intents){
				var intent = intents[index];
				if(intent.confidence > 0.7 && intent.intent === 'move'){
					for(var key in entities){
						var entity = entities[key];
						if(entity.entity === 'direction') {
							switch(entity.value) {
							case 'right':
								direction = 'd';
								break;
							case 'forward':
								direction = 'w';
								break;
							case 'backward':
								direction = 's';
								break;
							case 'left':
								direction = 'a';
								break;
							}
							break;
						}
					}
					break;
				}
			}
			return direction;
		};
*/
		/**
		 * Synthesize
		 */
		/**		var synthesize = function(val) {
			var audio = new Audio();
			audio.src = 'Synthesize?text=' + val;
			audio.play();
		};
*/
		/**
		 * Perform conversation
		 */
		var converse = function(userText) {
			if (is_wating) {
				return;
			}
			is_wating = true;
		    $loading.show();
		    // $chatInput.hide();

		    // check if the user typed text or not
		    if (typeof(userText) !== undefined && $.trim(userText) !== '')
		      submitMessage(userText);

		    // build the conversation parameters
		    var params = { message : userText };

		    if (conversation_result) {
		    	params.context = JSON.stringify(conversation_result.context);
		    }

		    $.ajax({
		    	url:'Talk',
		    	method: 'POST',
		    	data: params
		    }).done(function onSucess(response) {
		    	is_wating = false;
		    	conversation_result = JSON.parse(response);

		        $chatInput.val(''); // clear the text input

		        $jsonPanel.html(JSON.stringify(conversation_result, null, 2));

		        var texts = conversation_result.output ? conversation_result.output.text : [];
		        if(texts.length == 0){
		        	talk('WATSON', 'Sorry, I did not understand what you just said.');
		        	return;
		        }
		        var response = texts.join('
'); // <br/> is

		        $chatInput.show();
		        $chatInput[0].focus();

		        //synthesize(response);

		        talk('WATSON', response); // show

		        //var command = contextToCommand(conversation_result);
		        //onSendingCommand(command);
		      })
		      .fail(function onError(error) {
		        talk('WATSON', error.responseJSON ? error.responseJSON.error : error.statusText);
		        is_wating = false;
		      })
		      .always(function always(){
		        $loading.hide();
		        scrollChatToBottom();
		        $chatInput.focus();
		      });
		};

		/**
		 * Scroll with animation
		 */
		var scrollChatToBottom = function() {
			var element = $('.chat-box--pane');
			element.animate({
				scrollTop: element[0].scrollHeight
			}, 420);
		};

		/**
		 * Scroll to input
		 */
		var scrollToInput = function() {
			var element = $('.chat-window--message-input');
			$('body, html').animate({
				scrollTop: (element.offset().top - window.innerHeight + element[0].offsetHeight) + 20 + 'px'
			});
		};

		/**
		 * Generate HTML to chat
		 */
		var talk = function(origin, text, format) {
			if(!format){
				format = 'html';
			}
			var $chatBox = $('.chat-box--item_' + origin).first().clone();
			var $loading = $('.loader');
			if(format == 'text')
				$chatBox.find('p').html($('
').html(text).text());
			else
				$chatBox.find('p').html($('
').html(text).html());

			$chatBox.insertBefore($loading);
			setTimeout(function() {
				$chatBox.removeClass('chat-box--item_HIDDEN');
			}, 100);
		};

		/**
		 * Send message to the service
		 */
		var submitMessage = function(text) {
			talk('YOU', text);
			scrollChatToBottom();
			clearInput();
		};

		/**
		 * Clear contents in the input
		 */
		var clearInput = function() {
			$('.chat-window--message-input').val('');
		};

		/**
		 * Tab switching
		 */
		$('.tab-panels--tab').click(function(e){
			e.preventDefault();
			var self = $(this);
			var inputGroup = self.closest('.tab-panels');
			var idName = null;
			inputGroup.find('.active').removeClass('active');
			self.addClass('active');
			idName = self.attr('href');
			$(idName).addClass('active');
		});

		/**
		 * Speech recognition UI
		 */
		/**		var changeUIState = function(isSpeaking) {
			if (isSpeaking) {
				$loading.show();
				$mic.addClass('active');
				$mic.val('Speaking...');
			} else {
				$loading.hide();
				$mic.removeClass('active');
				$mic.val('Speak');
			}
		};*/

		/**
		 * Inovking Speech recognition
		 */
		/**var recognize = function(token) {
			return WatsonSpeech.SpeechToText.recognizeMicrophone({
				token : token,
				objectMode : true
			});
		};
*/
		/**
		 * Obtain token of Speech services
		 */
		/**var initToken = function(val) {
			return $.ajax({
				url : 'Token',
				data : {
					category : val
				}
			});
		};
*/
		var isSpeaking = false, stream = null, ttsToken = '', sttToken = '';

		/**$mic.on('click', function(evt){
			if(isSpeaking && stream){
				stream.stop();
				isSpeaking = false;
				changeUIState(isSpeaking);
			}
			else {
				if(isSpeaking){
					return;
				}

				stream = recognize(sttToken);
				isSpeaking = true;
				changeUIState(isSpeaking);

				stream.on('data', function(data) {
					console.log('data:');
					console.log(data);
					var transcript = data.alternatives[0].transcript;
					$('.ui-transcription').html('
'+transcript+'
');

					if(data.hasOwnProperty('final') && data['final']){
						isSpeaking = false;
						changeUIState(isSpeaking);
						stream.stop();
						converse(transcript);
						$('.ui-transcription').text('');
					}
				});
				stream.on('error', function(err) {
					console.log(err);
					isSpeaking = false;
					changeUIState(isSpeaking);
				});
				stream.on('close', function(err) {
					console.log(err);
					isSpeaking = false;
					changeUIState(isSpeaking);
				});
				stream.on('connection-close', function(err) {
					console.log(err);
					isSpeaking = false;
					changeUIState(isSpeaking);
				});
			}
		});

		initToken('stt').then(function(t) {
			sttToken = t;
			converse('Hi Watson');
			var userAgent = window.navigator.userAgent.toLowerCase();
			if(userAgent.indexOf('chrome') != -1 || userAgent.indexOf('firefox') != -1){
				$mic.show();
			}
		});
		*/
		converse('Hi Watson');
		scrollToInput();

		// car control
		/**		var socket = io.connect(carServiceHost);

		socket.on("message", function (data) {
			console.log("socket data: " + data);
		});

		var onSendingCommand = function(command){
			if(command === '') {
				return;
			}
			console.log(command);
			socket.emit("String", command);
		};
		var keyToCommand = function(key){
			var direction = '';
			switch(key){

			case 'ArrowUp':
				direction = 'w';
				break;

			case 'ArrowLeft':
				direction = 'a';
				break;

			case 'ArrowDown':
				direction = 's';
				break;

			case 'ArrowRight':
				direction = 'd';
				break;
			}
			return direction;
		};

		var keys = $('.car-controller a');
		keys.on('click', function(evt){
			var command = $(this).attr('ref');
			// call Socket-IO
			onSendingCommand(command);
		});

		$(document).on('keyup', function(evt){
			var command = keyToCommand(evt.key);
			onSendingCommand(command);
			keys.removeClass('active');
		});
		$(document).on('keydown', function(evt){
			var command = keyToCommand(evt.key);
			if(command === ''){
				return;
			}
			keys.parent().find('[ref='+command+']').addClass('active');
		});
		*/
	}
};

$(document).ready(methods.chatbot);
<commit_msg>Update talk-to-watson.js<commit_after>/**
 * Copyright 2016 IBM Corp. All Rights Reserved.
 *
 * 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.
 */

'use strict';

// conversation variables
var conversation_result, is_wating = false, methods = {
	chatbot: function () {
		var $chatInput = $('.chat-window--message-input'),
		//$jsonPanel = $('#json-panel .base--textarea'),
		$loading = $('.loader');

		$chatInput.keyup(function(event){
			if(event.keyCode === 13) {
				var inputText = $(this).val();
				converse(inputText);
			}
		});

		var converse = function(userText) {
			if (is_wating) {
				return;
			}
			is_wating = true;
		    $loading.show();
		    // $chatInput.hide();

		    // check if the user typed text or not
		    if (typeof(userText) !== undefined && $.trim(userText) !== '')
		      submitMessage(userText);

		    // build the conversation parameters
		    var params = { message : userText };

		    if (conversation_result) {
		    	params.context = JSON.stringify(conversation_result.context);
		    }

		    $.ajax({
		    	url:'Talk',
		    	method: 'POST',
		    	data: params
		    }).done(function onSucess(response) {
		    	is_wating = false;
		    	conversation_result = JSON.parse(response);

		        $chatInput.val(''); // clear the text input

		        //$jsonPanel.html(JSON.stringify(conversation_result, null, 2));

		        var texts = conversation_result.output ? conversation_result.output.text : [];
		        if(texts.length == 0){
		        	talk('WATSON', 'Sorry, I did not understand what you just said.');
		        	return;
		        }
		        var response = texts.join('
'); // <br/> is

		        $chatInput.show();
		        $chatInput[0].focus();

		        //synthesize(response);

		        talk('WATSON', response); // show

		        //var command = contextToCommand(conversation_result);
		        //onSendingCommand(command);
		      })
		      .fail(function onError(error) {
		        talk('WATSON', error.responseJSON ? error.responseJSON.error : error.statusText);
		        is_wating = false;
		      })
		      .always(function always(){
		        $loading.hide();
		        scrollChatToBottom();
		        $chatInput.focus();
		      });
		};

		/**
		 * Scroll with animation
		 */
		var scrollChatToBottom = function() {
			var element = $('.chat-box--pane');
			element.animate({
				scrollTop: element[0].scrollHeight
			}, 420);
		};

		/**
		 * Scroll to input
		 */
		var scrollToInput = function() {
			var element = $('.chat-window--message-input');
			$('body, html').animate({
				scrollTop: (element.offset().top - window.innerHeight + element[0].offsetHeight) + 20 + 'px'
			});
		};

		/**
		 * Generate HTML to chat
		 */
		var talk = function(origin, text, format) {
			if(!format){
				format = 'html';
			}
			var $chatBox = $('.chat-box--item_' + origin).first().clone();
			var $loading = $('.loader');
			if(format == 'text')
				$chatBox.find('p').html($('
').html(text).text());
			else
				$chatBox.find('p').html($('
').html(text).html());

			$chatBox.insertBefore($loading);
			setTimeout(function() {
				$chatBox.removeClass('chat-box--item_HIDDEN');
			}, 100);
		};

		/**
		 * Send message to the service
		 */
		var submitMessage = function(text) {
			talk('YOU', text);
			scrollChatToBottom();
			clearInput();
		};

		/**
		 * Clear contents in the input
		 */
		var clearInput = function() {
			$('.chat-window--message-input').val('');
		};

		/**
		 * Tab switching
		 */
		$('.tab-panels--tab').click(function(e){
			e.preventDefault();
			var self = $(this);
			var inputGroup = self.closest('.tab-panels');
			var idName = null;
			inputGroup.find('.active').removeClass('active');
			self.addClass('active');
			idName = self.attr('href');
			$(idName).addClass('active');
		});

		var isSpeaking = false, stream = null, ttsToken = '', sttToken = '';

		converse('Hi Watson');
		scrollToInput();

	}
};

$(document).ready(methods.chatbot);
<|endoftext|>


<commit_before>// 'use strict';

// var Transform = module.exports = exports = {};

// // Transforms colorPalette's values for r, g, b
// module.exports.Transform = function Transform(paletteInfo) {
//   var g, b, r = 0;
//   for (var i = 1; i < 257; i += 4) {
//     g = Math.floor((parseInt(paletteInfo[i])) * (0.50));
//     paletteInfo[i] = g;
//     b = Math.floor((parseInt(paletteInfo[i + 1])) * (0.88));
//     paletteInfo[i + 1] = b;
//     r = Math.floor((parseInt(paletteInfo[i + 2])) * (0.05));
//     paletteInfo[i + 2] = r;
//   }
//   var newColorString = paletteInfo.toString();
//   // console.log(newColorString);
//   return newColorString;
//   // return paletteInfo;
//   // console.log(g, b, r);
// };

<commit_msg>deleting transform. js replaced by color-map.js<commit_after><|endoftext|>