<commit_before>/**
 * @license
 * Copyright 2014 Google Inc. 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.
 */

/**
 * @fileoverview Provides the UI elements to generate a new PGP key.
 */

goog.provide('e2e.ext.ui.panels.GenerateKey');

goog.require('e2e.ext.constants.CssClass');
goog.require('e2e.ext.keyserver');
goog.require('e2e.ext.ui.templates.panels.generatekey');
goog.require('e2e.ext.utils.text');
goog.require('goog.array');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.ui.Component');
goog.require('goog.ui.KeyboardShortcutHandler');
goog.require('soy');

goog.scope(function() {
var constants = e2e.ext.constants;
var panels = e2e.ext.ui.panels;
var templates = e2e.ext.ui.templates.panels.generatekey;
var utils = e2e.ext.utils;

/**
 * Constructor for the UI component that provides the form to generate new PGP
 * keys.
 * @param {!function(...)} callback The callback to invoke when a new PGP key is
 *     to be generated.
 * @param {boolean=} opt_hideTitle Optional. A flag to control the display of
 *     the section title. If true, the section title will not be displayed.
 *     Defaults to false.
 * @param {string=} opt_actionBtnTitle Optional. The title for the action
 *     button. Uses extension defaults if not specified.
 * @constructor
 * @extends {goog.ui.Component}
 */
panels.GenerateKey = function(callback, opt_hideTitle, opt_actionBtnTitle) {
  goog.base(this);

  /**
   * The callback to invoke when a new PGP key is to be generated.
   * @type {!function(...)}
   * @private
   */
  this.callback_ = callback;

  /**
   * The keyserver client component associated with this panel.
   * @type {!e2e.ext.keyserver.Client}
   * @private
   */
  this.keyserverClient_ =
      new e2e.ext.keyserver.Client('https://us-mg999.mail.yahoo.com');

  /**
   * The title for the generate key section. If empty, it will not be displayed.
   * @type {string}
   * @private
   */
  this.sectionTitle_ = Boolean(opt_hideTitle) ?
      '' : chrome.i18n.getMessage('genKeyTitle');

  /**
   * The title for the action button.
   * @type {string}
   * @private
   */
  this.actionButtonTitle_ =
      opt_actionBtnTitle || chrome.i18n.getMessage('genKeyGenerateButtonLabel');
};
goog.inherits(panels.GenerateKey, goog.ui.Component);

/** @override */
panels.GenerateKey.prototype.createDom = function() {
  goog.base(this, 'createDom');
  this.decorateInternal(this.getElement());
};

/** @override */
panels.GenerateKey.prototype.decorateInternal = function(elem) {
  goog.base(this, 'decorateInternal', elem);

  soy.renderElement(elem, templates.generateKeyForm, {
    sectionTitle: this.sectionTitle_,
    emailLabel: chrome.i18n.getMessage('genKeyEmailLabel'),
    commentsLabel: chrome.i18n.getMessage('genKeyCommentsLabel'),
    actionButtonTitle: this.actionButtonTitle_
  });
};

/** @override */
panels.GenerateKey.prototype.enterDocument = function() {
  goog.base(this, 'enterDocument');

  var keyboardHandler = new goog.ui.KeyboardShortcutHandler(
      this.getElementByClass(constants.CssClass.EMAIL));
  keyboardHandler.registerShortcut('enter', goog.events.KeyCodes.ENTER);
  this.getHandler().
      listen(
          this.getElementByClass(constants.CssClass.ACTION),
          goog.events.EventType.CLICK,
          this.generate_).
      listen(
          keyboardHandler,
          goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_TRIGGERED,
          this.generate_);
};

/**
 * Generates a new PGP key using the information provided by the user.
 * @private
 */
panels.GenerateKey.prototype.generate_ = function() {
  this.clearFailure_();
  var name = '';
  var email = this.getElementByClass(constants.CssClass.EMAIL).value;
  var comments = '';

  // TODO(radi): Add a mechanism to allow the user to adjust this.
  var expDate = Math.floor(new Date('9999/12/31').getTime() / 1e3);

  this.callback_(this, name, email, comments, expDate);
};

/**
 * Resets the key generation form.
 */
panels.GenerateKey.prototype.reset = function() {
  this.clearFailure_();
  var inputs = this.getElement().querySelectorAll('input');
  goog.array.forEach(inputs, function(input) {
    input.value = '';
  });
};

/**
 * Sends an OpenPGP public key(s) to the keyserver.
 * @param {!e2e.openpgp.Keys} keys
 * @param {function(string)} callback
 * @param {e2e.openpgp.ContextImpl} ctx
 */
panels.GenerateKey.prototype.sendKeys = function(keys, callback, ctx) {
  goog.array.forEach(keys, goog.bind(function(key) {
    if (!key.key.secret) {
      var email = utils.text.extractValidYahooEmail(key.uids[0]);
      if (email) {
        try {
          this.keyserverClient_.sendKey(email, key.serialized, goog.bind(
              function(response) {
                this.keyserverClient_.cacheKeyData(response);
                callback(response);
                window.alert('successfully registered key: ' +
                             response);
              }, this),
              goog.bind(function() {
                // The key wasn't sent to the server, so delete it for now.
                // TODO: Separate key generation and import to keyring.
                if (ctx !== null) {
                  ctx.deleteKey(key.uids[0]);
                }
                this.displayFailure_(
                    new e2e.ext.keyserver.AuthError('Please login to your ' +
                        'corpmail account before generating a new key!'));
              }, this));
        } catch (e) {
          console.log('got key send failure in generate key', email);
          this.displayFailure_(e);
        }
      }
    }
  }, this));
};

/**
 * Displays error message.
 * @param {Error} error The error to display.
 * @private
 */
panels.GenerateKey.prototype.displayFailure_ = function(error) {
  var errorDiv = this.getElement().getElementsByClassName(
      constants.CssClass.ERROR)[0];
  if (error) {
    var errorMsg = goog.isDef(error.messageId) ?
        chrome.i18n.getMessage(error.messageId) : error.message;
    utils.errorHandler(error);
    errorDiv.textContent = errorMsg;
  } else {
    errorDiv.textContent = '';
  }
};

/**
 * Clears error messages.
 * @private
 */
panels.GenerateKey.prototype.clearFailure_ = function() {
  this.displayFailure_(null);
};

});  // goog.scope
<commit_msg>Put errorDiv existence check back into generatekey panel<commit_after>/**
 * @license
 * Copyright 2014 Google Inc. 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.
 */

/**
 * @fileoverview Provides the UI elements to generate a new PGP key.
 */

goog.provide('e2e.ext.ui.panels.GenerateKey');

goog.require('e2e.ext.constants.CssClass');
goog.require('e2e.ext.keyserver');
goog.require('e2e.ext.ui.templates.panels.generatekey');
goog.require('e2e.ext.utils.text');
goog.require('goog.array');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.ui.Component');
goog.require('goog.ui.KeyboardShortcutHandler');
goog.require('soy');

goog.scope(function() {
var constants = e2e.ext.constants;
var panels = e2e.ext.ui.panels;
var templates = e2e.ext.ui.templates.panels.generatekey;
var utils = e2e.ext.utils;

/**
 * Constructor for the UI component that provides the form to generate new PGP
 * keys.
 * @param {!function(...)} callback The callback to invoke when a new PGP key is
 *     to be generated.
 * @param {boolean=} opt_hideTitle Optional. A flag to control the display of
 *     the section title. If true, the section title will not be displayed.
 *     Defaults to false.
 * @param {string=} opt_actionBtnTitle Optional. The title for the action
 *     button. Uses extension defaults if not specified.
 * @constructor
 * @extends {goog.ui.Component}
 */
panels.GenerateKey = function(callback, opt_hideTitle, opt_actionBtnTitle) {
  goog.base(this);

  /**
   * The callback to invoke when a new PGP key is to be generated.
   * @type {!function(...)}
   * @private
   */
  this.callback_ = callback;

  /**
   * The keyserver client component associated with this panel.
   * @type {!e2e.ext.keyserver.Client}
   * @private
   */
  this.keyserverClient_ =
      new e2e.ext.keyserver.Client('https://us-mg999.mail.yahoo.com');

  /**
   * The title for the generate key section. If empty, it will not be displayed.
   * @type {string}
   * @private
   */
  this.sectionTitle_ = Boolean(opt_hideTitle) ?
      '' : chrome.i18n.getMessage('genKeyTitle');

  /**
   * The title for the action button.
   * @type {string}
   * @private
   */
  this.actionButtonTitle_ =
      opt_actionBtnTitle || chrome.i18n.getMessage('genKeyGenerateButtonLabel');
};
goog.inherits(panels.GenerateKey, goog.ui.Component);

/** @override */
panels.GenerateKey.prototype.createDom = function() {
  goog.base(this, 'createDom');
  this.decorateInternal(this.getElement());
};

/** @override */
panels.GenerateKey.prototype.decorateInternal = function(elem) {
  goog.base(this, 'decorateInternal', elem);

  soy.renderElement(elem, templates.generateKeyForm, {
    sectionTitle: this.sectionTitle_,
    emailLabel: chrome.i18n.getMessage('genKeyEmailLabel'),
    commentsLabel: chrome.i18n.getMessage('genKeyCommentsLabel'),
    actionButtonTitle: this.actionButtonTitle_
  });
};

/** @override */
panels.GenerateKey.prototype.enterDocument = function() {
  goog.base(this, 'enterDocument');

  var keyboardHandler = new goog.ui.KeyboardShortcutHandler(
      this.getElementByClass(constants.CssClass.EMAIL));
  keyboardHandler.registerShortcut('enter', goog.events.KeyCodes.ENTER);
  this.getHandler().
      listen(
          this.getElementByClass(constants.CssClass.ACTION),
          goog.events.EventType.CLICK,
          this.generate_).
      listen(
          keyboardHandler,
          goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_TRIGGERED,
          this.generate_);
};

/**
 * Generates a new PGP key using the information provided by the user.
 * @private
 */
panels.GenerateKey.prototype.generate_ = function() {
  this.clearFailure_();
  var name = '';
  var email = this.getElementByClass(constants.CssClass.EMAIL).value;
  var comments = '';

  // TODO(radi): Add a mechanism to allow the user to adjust this.
  var expDate = Math.floor(new Date('9999/12/31').getTime() / 1e3);

  this.callback_(this, name, email, comments, expDate);
};

/**
 * Resets the key generation form.
 */
panels.GenerateKey.prototype.reset = function() {
  this.clearFailure_();
  var inputs = this.getElement().querySelectorAll('input');
  goog.array.forEach(inputs, function(input) {
    input.value = '';
  });
};

/**
 * Sends an OpenPGP public key(s) to the keyserver.
 * @param {!e2e.openpgp.Keys} keys
 * @param {function(string)} callback
 * @param {e2e.openpgp.ContextImpl} ctx
 */
panels.GenerateKey.prototype.sendKeys = function(keys, callback, ctx) {
  goog.array.forEach(keys, goog.bind(function(key) {
    if (!key.key.secret) {
      var email = utils.text.extractValidYahooEmail(key.uids[0]);
      if (email) {
        try {
          this.keyserverClient_.sendKey(email, key.serialized, goog.bind(
              function(response) {
                this.keyserverClient_.cacheKeyData(response);
                callback(response);
                window.alert('successfully registered key: ' +
                             response);
              }, this),
              goog.bind(function() {
                // The key wasn't sent to the server, so delete it for now.
                // TODO: Separate key generation and import to keyring.
                if (ctx !== null) {
                  ctx.deleteKey(key.uids[0]);
                }
                this.displayFailure_(
                    new e2e.ext.keyserver.AuthError('Please login to your ' +
                        'corpmail account before generating a new key!'));
              }, this));
        } catch (e) {
          console.log('got key send failure in generate key', email);
          this.displayFailure_(e);
        }
      }
    }
  }, this));
};

/**
 * Displays error message.
 * @param {Error} error The error to display.
 * @private
 */
panels.GenerateKey.prototype.displayFailure_ = function(error) {
  var errorDiv = this.getElement().getElementsByClassName(
      constants.CssClass.ERROR)[0];
  if (error) {
    var errorMsg = goog.isDef(error.messageId) ?
        chrome.i18n.getMessage(error.messageId) : error.message;
    utils.errorHandler(error);
    if (errorDiv) {
      errorDiv.textContent = errorMsg;
    } else {
      // The errorDiv might be destroyed by the time displayFailure_ fires
      window.alert('Error: ' + errorMsg);
    }
  } else if (errorDiv) {
    errorDiv.textContent = '';
  }
};

/**
 * Clears error messages.
 * @private
 */
panels.GenerateKey.prototype.clearFailure_ = function() {
  this.displayFailure_(null);
};

});  // goog.scope
<|endoftext|>


<commit_before>/* global jasmine, describe, it, beforeEach, expect, StateLog, window */

describe('Test array functionality', () => {

  it("check if exception gets thrown for null value", () => {
    expect(() => {
      new StateLog(null);
    }).toThrow(new TypeError('Given value is not referencable'));
  });

  it("check if exception gets thrown for undefined value", () => {
    expect(() => {
      new StateLog(undefined);
    }).toThrow(new TypeError('Given value is not referencable'));
  });

  it("check if exception gets thrown for number value", () => {
    expect(() => {
      new StateLog(42);
    }).toThrow(new TypeError('Given value is not referencable'));
  });

  it("check if exception gets thrown for string value", () => {
    expect(() => {
      new StateLog("foo");
    }).toThrow(new TypeError('Given value is not referencable'));
  });

  it("check if exception gets thrown for boolean value", () => {
    expect(() => {
      new StateLog(true);
    }).toThrow(new TypeError('Given value is not referencable'));
  });
});<commit_msg>[test] removed unneeded globals<commit_after>/* global describe, it, expect, StateLog */

describe('Test array functionality', () => {

  it("check if exception gets thrown for null value", () => {
    expect(() => {
      new StateLog(null);
    }).toThrow(new TypeError('Given value is not referencable'));
  });

  it("check if exception gets thrown for undefined value", () => {
    expect(() => {
      new StateLog(undefined);
    }).toThrow(new TypeError('Given value is not referencable'));
  });

  it("check if exception gets thrown for number value", () => {
    expect(() => {
      new StateLog(42);
    }).toThrow(new TypeError('Given value is not referencable'));
  });

  it("check if exception gets thrown for string value", () => {
    expect(() => {
      new StateLog("foo");
    }).toThrow(new TypeError('Given value is not referencable'));
  });

  it("check if exception gets thrown for boolean value", () => {
    expect(() => {
      new StateLog(true);
    }).toThrow(new TypeError('Given value is not referencable'));
  });
});
<|endoftext|>


<commit_before>import EmberRouter from '@ember/routing/router';
import config from './config/environment';
import googlePageview from './mixins/google-pageview';
import RouterScroll from 'ember-router-scroll';

const Router = EmberRouter.extend(googlePageview, RouterScroll, {
    location: config.locationType,
    rootURL: config.rootURL
});

Router.map(function() {
  this.route('logout');
  this.route('login');
  this.route('github_login');
  this.route('github_authorize', { path: '/authorize/github' });
  this.route('crates');
  this.route('crate', { path: '/crates/:crate_id' }, function() {
      this.route('download');
      this.route('versions');
      this.route('version', { path: '/:version_num' });

      this.route('reverse_dependencies');

      // Well-known routes
      this.route('docs');
      this.route('repo');
  });
  this.route('me', function() {
    this.route('crates');
    this.route('following');
    this.route('pending-invites');
  });
  this.route('user', { path: '/users/:user_id' });
  this.route('install');
  this.route('search');
  this.route('dashboard');
  this.route('keywords');
  this.route('keyword', { path: '/keywords/:keyword_id' }, function() {
      this.route('index', { path: '/' });
  });
  this.route('categories');
  this.route('category', { path: '/categories/:category_id' }, function() {
      this.route('index', { path: '/' });
  });
  this.route('category_slugs');
  this.route('catchAll', { path: '*path' });
  this.route('team', { path: '/teams/:team_id' });
  this.route('policies');
});

export default Router;
<commit_msg>fix router tabbing errors<commit_after>import EmberRouter from '@ember/routing/router';
import config from './config/environment';
import googlePageview from './mixins/google-pageview';
import RouterScroll from 'ember-router-scroll';

const Router = EmberRouter.extend(googlePageview, RouterScroll, {
    location: config.locationType,
    rootURL: config.rootURL
});

Router.map(function() {
    this.route('logout');
    this.route('login');
    this.route('github_login');
    this.route('github_authorize', { path: '/authorize/github' });
    this.route('crates');
    this.route('crate', { path: '/crates/:crate_id' }, function() {
        this.route('download');
        this.route('versions');
        this.route('version', { path: '/:version_num' });

        this.route('reverse_dependencies');

        // Well-known routes
        this.route('docs');
        this.route('repo');
    });
    this.route('me', function() {
        this.route('crates');
        this.route('following');
        this.route('pending-invites');
    });
    this.route('user', { path: '/users/:user_id' });
    this.route('install');
    this.route('search');
    this.route('dashboard');
    this.route('keywords');
    this.route('keyword', { path: '/keywords/:keyword_id' }, function() {
        this.route('index', { path: '/' });
    });
    this.route('categories');
    this.route('category', { path: '/categories/:category_id' }, function() {
        this.route('index', { path: '/' });
    });
    this.route('category_slugs');
    this.route('catchAll', { path: '*path' });
    this.route('team', { path: '/teams/:team_id' });
    this.route('policies');
});

export default Router;
<|endoftext|>


<commit_before>// Returns fragment that emits direct data for specified object
// Optional filtering of some records is possible via `options.filter`

'use strict';

var ensureCallable = require('es5-ext/object/valid-callable')
  , ensureString   = require('es5-ext/object/validate-stringifiable-value')
  , escape         = require('es5-ext/reg-exp/escape')
  , memoize        = require('memoizee')
  , Fragment       = require('data-fragment')
  , anyIdToStorage = require('../utils/any-id-to-storage')

  , driver = require('mano').dbDriver;

var getKeyPathFilter = function (keyPath) {
	var matches = RegExp.prototype.test.bind(new RegExp('^[a-z0-9][a-z0-9A-Z]*/' +
		escape(keyPath) + '(?:/.+|$)'));
	return function (data) { return matches(data.id); };
};

module.exports = memoize(function (storageName) {
	var storage;
	if (storageName) storage = driver.getStorage(storageName);
	return memoize(function (ownerId/*, options*/) {
		var fragment, options = Object(arguments[1]), filter, index, customFilter, keyPathFilter
		  , promise, setupListener;

		ownerId = ensureString(ownerId);
		if (options.filter != null) customFilter = ensureCallable(options.filter);
		index = ownerId.indexOf('/');
		if (index !== -1) {
			keyPathFilter = getKeyPathFilter(ownerId.slice(index + 1));
			ownerId = ownerId.slice(0, index);
		}
		if (keyPathFilter) {
			if (customFilter) {
				filter = function (data) { return keyPathFilter(data) && customFilter(data); };
			} else {
				filter = keyPathFilter;
			}
		} else if (customFilter) {
			filter = customFilter;
		}
		fragment = new Fragment();
		setupListener = function (storage) {
			storage.on('owner:' + ownerId, function (event) {
				if (event.type !== 'direct') return;
				if (!filter || filter(event)) fragment.update(event.id, event.data);
			});
		};
		if (storage) {
			promise = storage.getObject(ownerId);
			setupListener(storage);
		} else {
			promise = anyIdToStorage(ownerId)(function (storage) {
				setupListener(storage);
				return storage.getObject(ownerId);
			});
		}
		fragment.promise = promise(function (data) {
			data.forEach(function (data) {
				if (!filter || filter(data)) fragment.update(data.id, data.data);
			});
		});
		return fragment;
	}, { primitive: true });
}, { primitive: true, resolvers: [function (storageName) {
	if (storageName == null) return '';
	return ensureString(storageName);
}] });
<commit_msg>Improve error handling<commit_after>// Returns fragment that emits direct data for specified object
// Optional filtering of some records is possible via `options.filter`

'use strict';

var ensureCallable = require('es5-ext/object/valid-callable')
  , ensureString   = require('es5-ext/object/validate-stringifiable-value')
  , escape         = require('es5-ext/reg-exp/escape')
  , memoize        = require('memoizee')
  , Fragment       = require('data-fragment')
  , anyIdToStorage = require('../utils/any-id-to-storage')

  , stringify = JSON.stringify
  , driver = require('mano').dbDriver;

var getKeyPathFilter = function (keyPath) {
	var matches = RegExp.prototype.test.bind(new RegExp('^[a-z0-9][a-z0-9A-Z]*/' +
		escape(keyPath) + '(?:/.+|$)'));
	return function (data) { return matches(data.id); };
};

module.exports = memoize(function (storageName) {
	var storage;
	if (storageName) storage = driver.getStorage(storageName);
	return memoize(function (ownerId/*, options*/) {
		var fragment, options = Object(arguments[1]), filter, index, customFilter, keyPathFilter
		  , promise, setupListener;

		ownerId = ensureString(ownerId);
		if (options.filter != null) customFilter = ensureCallable(options.filter);
		index = ownerId.indexOf('/');
		if (index !== -1) {
			keyPathFilter = getKeyPathFilter(ownerId.slice(index + 1));
			ownerId = ownerId.slice(0, index);
		}
		if (keyPathFilter) {
			if (customFilter) {
				filter = function (data) { return keyPathFilter(data) && customFilter(data); };
			} else {
				filter = keyPathFilter;
			}
		} else if (customFilter) {
			filter = customFilter;
		}
		fragment = new Fragment();
		setupListener = function (storage) {
			storage.on('owner:' + ownerId, function (event) {
				if (event.type !== 'direct') return;
				if (!filter || filter(event)) fragment.update(event.id, event.data);
			});
		};
		if (storage) {
			promise = storage.getObject(ownerId);
			setupListener(storage);
		} else {
			promise = anyIdToStorage(ownerId)(function (storage) {
				if (!storage) throw new Error("Object " + stringify(ownerId) + " not found in database");
				setupListener(storage);
				return storage.getObject(ownerId);
			});
		}
		fragment.promise = promise(function (data) {
			data.forEach(function (data) {
				if (!filter || filter(data)) fragment.update(data.id, data.data);
			});
		});
		return fragment;
	}, { primitive: true });
}, { primitive: true, resolvers: [function (storageName) {
	if (storageName == null) return '';
	return ensureString(storageName);
}] });
<|endoftext|>


<commit_before>function(doc) {
    "use strict";
    if (doc.name.toLowerCase().indexOf("speech") !== -1) {
        var key = doc.uid ? doc.uid : doc.source + ":" + doc.sid;
        emit(key, doc);
    }
}<commit_msg>Opened up the map function as we are no longer testing poorly performing reduce functions.<commit_after>function(doc) {
    "use strict";
    var key = doc.uid ? doc.uid : doc.source + ":" + doc.sid;
    emit(key, doc);
}<|endoftext|>


<commit_before>(function(){
  'use strict';

  var paths = {
    tmp: '.gulptmp/',
    dest: 'cla_frontend/assets/',
    src: 'cla_frontend/assets-src/',
    icons: [],
    images: [],
    fonts: [],
    styles: [],
    ng_partials: [],
    vendor_static: [],
    scripts: {},
  };

  // styles
  paths.styles.push(paths.src + 'stylesheets/**/*.scss');
  // icons
  paths.icons.push(paths.src + 'fonts/svg-icons/*.svg');
  // fonts
  paths.fonts.push(paths.src + 'fonts/*.{eot,svg,ttf,woff}');
  paths.fonts.push(paths.tmp + 'fonts/*.{eot,svg,ttf,woff}');
  // images
  paths.images.push(paths.src + 'images/**/*');
  // partials
  paths.ng_partials.push(paths.src + 'javascripts/app/partials/**/*.html');
  // vendor scripts
  paths.vendor_static.push(paths.src + 'javascripts/vendor/**/*');
  paths.vendor_static.push(paths.src + 'vendor/fullcalendar/fullcalendar.min.js');
  paths.vendor_static.push(paths.src + 'vendor/raven-js/dist/raven.min.js');
  // ignore certain vendor scripts from the copy
  paths.vendor_static.push('!' + paths.src + 'javascripts/vendor/diff-match-patch/');
  paths.vendor_static.push('!' + paths.src + 'javascripts/vendor/diff-match-patch/**');
  paths.vendor_static.push('!' + paths.src + 'javascripts/vendor/ui-bootstrap-custom-tpls-1.3.3.js');
  // scripts
  paths.scripts = {
    vendor: [
      paths.src + 'vendor/lodash/dist/lodash.js',
      paths.src + 'vendor/jquery/jquery.js',
      paths.src + 'vendor/select2/select2.js',
      // angular specific
      paths.src + 'vendor/angular/angular.js',
      paths.src + 'vendor/angular-sanitize/angular-sanitize.js',
      paths.src + 'vendor/angular-messages/angular-messages.js',
      paths.src + 'vendor/angular-animate/angular-animate.js',
      paths.src + 'vendor/angular-sticky/dist/angular-sticky.js',
      paths.src + 'vendor/angular-resource/angular-resource.js',
      paths.src + 'vendor/angular-ui-router/release/angular-ui-router.js',
      paths.src + 'vendor/ui-router-extras/release/ct-ui-router-extras.js',
      paths.src + 'vendor/angular-ui-select2/src/select2.js',
      paths.src + 'vendor/angular-i18n/angular-locale_en-gb.js',
      paths.src + 'vendor/moment/moment.js',
      paths.src + 'vendor/moment-timezone/builds/moment-timezone-with-data-2010-2020.js',
      paths.src + 'vendor/angular-moment/angular-moment.js',
      paths.src + 'vendor/angular-blocks/dist/angular-blocks.js',
      paths.src + 'vendor/rome/dist/rome.standalone.js', // datepicker
      paths.src + 'javascripts/vendor/ui-bootstrap-custom-tpls-1.3.3.js',
      paths.src + 'vendor/angular-xeditable/dist/js/xeditable.js',
      paths.src + 'vendor/conduitjs/lib/conduit.js',
      paths.src + 'vendor/postal.js/lib/postal.js',
      paths.src + 'vendor/angular-loading-bar/build/loading-bar.js',
      paths.src + 'vendor/socket.io-client/dist/socket.io.js',
      paths.src + 'vendor/angular-socket-io/socket.js',
      paths.src + 'vendor/angulartics/src/angulartics.js',
      paths.src + 'vendor/angulartics/src/angulartics-ga.js',
      paths.src + 'vendor/angular-hotkeys/build/hotkeys.js',
      paths.src + 'vendor/ng-text-truncate/ng-text-truncate.js',
      paths.src + 'vendor/angular-local-storage/dist/angular-local-storage.js',
      paths.src + 'vendor/angularUtils/src/directives/pagination/dirPagination.js',
      paths.src + 'vendor/ng-idle/angular-idle.js',
      paths.src + 'javascripts/vendor/diff-match-patch/angular-diff-match-patch.js',
      paths.src + 'javascripts/vendor/diff-match-patch/google-diff-match-patch.js',
      paths.src + 'vendor/papaparse/papaparse.js', // csv upload
      paths.src + 'vendor/FileSaver/FileSaver.js' // csv upload
    ],
    app: [
      paths.src + 'javascripts/app/js/app.js',
      paths.tmp + 'javascripts/app/partials/**/*', // dynamically generated by gulp task (ng-templates)
      paths.src + 'javascripts/app/js/**/*.js',
      paths.tmp + 'javascripts/app/js/constants.js', // dynamically generated by gulp task (ng-constants)
      paths.src + 'javascripts/modules/**/*.js'
    ]
  };

  module.exports = paths;
})();
<commit_msg>Correctly reference new file location after package upgrade<commit_after>(function(){
  'use strict';

  var paths = {
    tmp: '.gulptmp/',
    dest: 'cla_frontend/assets/',
    src: 'cla_frontend/assets-src/',
    icons: [],
    images: [],
    fonts: [],
    styles: [],
    ng_partials: [],
    vendor_static: [],
    scripts: {},
  };

  // styles
  paths.styles.push(paths.src + 'stylesheets/**/*.scss');
  // icons
  paths.icons.push(paths.src + 'fonts/svg-icons/*.svg');
  // fonts
  paths.fonts.push(paths.src + 'fonts/*.{eot,svg,ttf,woff}');
  paths.fonts.push(paths.tmp + 'fonts/*.{eot,svg,ttf,woff}');
  // images
  paths.images.push(paths.src + 'images/**/*');
  // partials
  paths.ng_partials.push(paths.src + 'javascripts/app/partials/**/*.html');
  // vendor scripts
  paths.vendor_static.push(paths.src + 'javascripts/vendor/**/*');
  paths.vendor_static.push(paths.src + 'vendor/fullcalendar/fullcalendar.min.js');
  paths.vendor_static.push(paths.src + 'vendor/raven-js/dist/raven.min.js');
  // ignore certain vendor scripts from the copy
  paths.vendor_static.push('!' + paths.src + 'javascripts/vendor/diff-match-patch/');
  paths.vendor_static.push('!' + paths.src + 'javascripts/vendor/diff-match-patch/**');
  paths.vendor_static.push('!' + paths.src + 'javascripts/vendor/ui-bootstrap-custom-tpls-1.3.3.js');
  // scripts
  paths.scripts = {
    vendor: [
      paths.src + 'vendor/lodash/dist/lodash.js',
      paths.src + 'vendor/jquery/jquery.js',
      paths.src + 'vendor/select2/select2.js',
      // angular specific
      paths.src + 'vendor/angular/angular.js',
      paths.src + 'vendor/angular-sanitize/angular-sanitize.js',
      paths.src + 'vendor/angular-messages/angular-messages.js',
      paths.src + 'vendor/angular-animate/angular-animate.js',
      paths.src + 'vendor/angular-sticky/dist/angular-sticky.js',
      paths.src + 'vendor/angular-resource/angular-resource.js',
      paths.src + 'vendor/angular-ui-router/release/angular-ui-router.js',
      paths.src + 'vendor/ui-router-extras/release/ct-ui-router-extras.js',
      paths.src + 'vendor/angular-ui-select2/src/select2.js',
      paths.src + 'vendor/angular-i18n/angular-locale_en-gb.js',
      paths.src + 'vendor/moment/moment.js',
      paths.src + 'vendor/moment-timezone/builds/moment-timezone-with-data-2010-2020.js',
      paths.src + 'vendor/angular-moment/angular-moment.js',
      paths.src + 'vendor/angular-blocks/dist/angular-blocks.js',
      paths.src + 'vendor/rome/dist/rome.standalone.js', // datepicker
      paths.src + 'javascripts/vendor/ui-bootstrap-custom-tpls-1.3.3.js',
      paths.src + 'vendor/angular-xeditable/dist/js/xeditable.js',
      paths.src + 'vendor/conduitjs/lib/conduit.js',
      paths.src + 'vendor/postal.js/lib/postal.js',
      paths.src + 'vendor/angular-loading-bar/build/loading-bar.js',
      paths.src + 'vendor/socket.io-client/dist/socket.io.js',
      paths.src + 'vendor/angular-socket-io/socket.js',
      paths.src + 'vendor/angulartics/src/angulartics.js',
      paths.src + 'vendor/angulartics-google-analytics/lib/angulartics-ga.js',
      paths.src + 'vendor/angular-hotkeys/build/hotkeys.js',
      paths.src + 'vendor/ng-text-truncate/ng-text-truncate.js',
      paths.src + 'vendor/angular-local-storage/dist/angular-local-storage.js',
      paths.src + 'vendor/angularUtils/src/directives/pagination/dirPagination.js',
      paths.src + 'vendor/ng-idle/angular-idle.js',
      paths.src + 'javascripts/vendor/diff-match-patch/angular-diff-match-patch.js',
      paths.src + 'javascripts/vendor/diff-match-patch/google-diff-match-patch.js',
      paths.src + 'vendor/papaparse/papaparse.js', // csv upload
      paths.src + 'vendor/FileSaver/FileSaver.js' // csv upload
    ],
    app: [
      paths.src + 'javascripts/app/js/app.js',
      paths.tmp + 'javascripts/app/partials/**/*', // dynamically generated by gulp task (ng-templates)
      paths.src + 'javascripts/app/js/**/*.js',
      paths.tmp + 'javascripts/app/js/constants.js', // dynamically generated by gulp task (ng-constants)
      paths.src + 'javascripts/modules/**/*.js'
    ]
  };

  module.exports = paths;
})();
<|endoftext|>


<commit_before>import React from 'react';
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';

const birthdays = {
  3: ['Mirko', 'Gianni'],
  8: ['Elena'],
  9: ['Irene'],
  12: ['Paolo', 'Giorgia'],
  18: ['Claudia'],
  22: ['Maria', 'Luigi'],
  25: ['Simone'],
  26: ['Marta'],
};

function renderDay(day) {
  const date = day.getDate();
  const dateStyle = {
    position: 'absolute',
    color: 'lightgray',
    bottom: 0,
    right: 0,
    fontSize: 20,
  };
  const birthdayStyle = { fontSize: '0.8em', textAlign: 'left' };
  const cellStyle = {
    height: 50,
    width: 60,
    position: 'relative',
  };
  return (

{date}

      {birthdaysDate[] &&
        birthdaysDate[].map((name, i) => (

            🎁 {name}

        ))}

  );
}

export default function Example() {
  return (
    <DayPicker
      canChangeMonth={false}
      className="Birthdays"
      renderDay={renderDay}
    />
  );
}
<commit_msg>Fix example<commit_after>import React from 'react';
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';

const birthdays = {
  3: ['Mirko', 'Gianni'],
  8: ['Elena'],
  9: ['Irene'],
  12: ['Paolo', 'Giorgia'],
  18: ['Claudia'],
  22: ['Maria', 'Luigi'],
  25: ['Simone'],
  26: ['Marta'],
};

function renderDay(day) {
  const date = day.getDate();
  const dateStyle = {
    position: 'absolute',
    color: 'lightgray',
    bottom: 0,
    right: 0,
    fontSize: 20,
  };
  const birthdayStyle = { fontSize: '0.8em', textAlign: 'left' };
  const cellStyle = {
    height: 50,
    width: 60,
    position: 'relative',
  };
  return (

{date}

      {birthdays[date] &&
        birthdays[date].map((name, i) => (

            🎁 {name}

        ))}

  );
}

export default function Example() {
  return (
    <DayPicker
      canChangeMonth={false}
      className="Birthdays"
      renderDay={renderDay}
    />
  );
}
<|endoftext|>


<commit_before>function setupTopBar() {
    getElement('start').value = 0
    var i = 0;
    for (var test in testFunctions) {
        i++
    }
    getElement('end').value = i-1
    getElement('count').textContent = i-1
}

function runTests() {
    addTests(getElement('start').value, getElement('end').value)
}

function doCanvas(canvasTD, testFunction) {
    var canvas = CANVAS({'width':200, 'height':200});
    replaceChildNodes(canvasTD, canvas);
    if (canvas.getContext) {
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0,0,200,200);
        try{
            testFunction(ctx);
        }
        catch (e) {
            log(""+e);
        }
    }
}

function doTest(canvasTD, svgTD, functionArea, svgSrcArea, buttonXML, include_canvas) {
    var target, svg;
    var testFunction = eval(functionArea.value);
    if (type=='svg') {
        target = new SVGKit(200, 200);
        svg = target;
    }
    else if (type=='canvas') {
        if (!isUndefinedOrNull(include_canvas) && include_canvas==true)
            doCanvas(canvasTD, testFunction)
        target = new SVGCanvas(200, 200);
        svg = target.svg;
    }
    else if (type=='plot') {
        target = new SVGPlot(200, 200);
        svg = target.svg;
    }
    var setSVGSrc = function (svg, textarea) {
        replaceChildNodes(textarea, svg.toXML());
    }
    svg.whenReady( partial(testFunction, target) );
    svg.whenReady( partial(setSVGSrc, svg, svgSrcArea) );  // Comment out for IE
    addToCallStack(buttonXML, 'onclick', partial(setSVGSrc, svg, svgSrcArea) );
    replaceChildNodes(svgTD, svg.htmlElement);
}

function addTests(start, end) {
    log("getting table");
    var tbody = getElement('tests');
    replaceChildNodes(tbody)
    var i = 0;
    var buttonDoIt, buttonXML;
    for (var test in testFunctions) {
        if (i>=start && i<=end) {
            log("doing test number ", i, "name ", test);
            var code = (''+testFunctions[test]+'\n').replace(/ +/g, " ");
            var functionArea, svgSrcArea, button, svgTD, button;
            var canvasTD = null
            var tr = TR(null, TD(null, ""+i+": "+test, BR(null), IMG({'src':'canvas_tests_images/'+test+'.png'}) ) );
            var include_canvas = (type=='canvas')
            if (include_canvas)
                appendChildNodes(tr, canvasTD=TD({width:210}) )
            appendChildNodes(tr,
                              TD(null, functionArea=TEXTAREA({'rows':"14", 'cols':"40", 'wrap':"off"}, code),
                                       BR(null),
                                       buttonDoIt=INPUT({type:"button", value:"Do It"}),
                                       " ",
                                       buttonXML=INPUT({type:"button", value:"Update XML"}) ),
                              svgTD=TD({width:210}),
                              TD(null,
                                FORM( { name:'form_'+test, method:'post', action:"http://brainflux.org/cgi-bin/convert_svg.py"},
                                   svgSrcArea=TEXTAREA({rows:"14", cols:"60", wrap:"off", name:'source'} ,"SVG Source"),
                                   BR(null),
                                   buttonSVG=INPUT({type:"submit", name:"type", value:"svg"}), " ",
                                   buttonPDF=INPUT({type:"submit", name:"type", value:"pdf"}), " ",
                                   buttonPNG=INPUT({type:"submit", name:"type", value:"png"}), " ",
                                   buttonJPEG=INPUT({type:"submit", name:"type", value:"jpg"}) )
                                )
                        );
            appendChildNodes(tbody, tr);
            addToCallStack(buttonDoIt, 'onclick', partial(doTest,canvasTD, svgTD, functionArea, svgSrcArea, buttonXML, include_canvas) );
            doTest(canvasTD, svgTD, functionArea, svgSrcArea, buttonXML, include_canvas);
        }
        i++;
    }
}

type = 'svg'  // Can be overriden by other files.
addLoadEvent(setupTopBar)
addLoadEvent(partial(addTests, 0, 0))
<commit_msg>Conversions now open in a new window. target="_blank" is a deprecated feature, but very useful since you can't right click on the submit button to choose if you want to open it in a new window, and going back is SLOW<commit_after>converter_url = 'http://brainflux.org/cgi-bin/convert_svg.py'

function setupTopBar() {
    getElement('start').value = 0
    var i = 0;
    for (var test in testFunctions) {
        i++
    }
    getElement('end').value = i-1
    getElement('count').textContent = i-1
}

function runTests() {
    addTests(getElement('start').value, getElement('end').value)
}

function doCanvas(canvasTD, testFunction) {
    var canvas = CANVAS({'width':200, 'height':200});
    replaceChildNodes(canvasTD, canvas);
    if (canvas.getContext) {
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0,0,200,200);
        try{
            testFunction(ctx);
        }
        catch (e) {
            log(""+e);
        }
    }
}

function doTest(canvasTD, svgTD, functionArea, svgSrcArea, buttonXML, include_canvas) {
    var target, svg;
    var testFunction = eval(functionArea.value);
    if (type=='svg') {
        target = new SVGKit(200, 200);
        svg = target;
    }
    else if (type=='canvas') {
        if (!isUndefinedOrNull(include_canvas) && include_canvas==true)
            doCanvas(canvasTD, testFunction)
        target = new SVGCanvas(200, 200);
        svg = target.svg;
    }
    else if (type=='plot') {
        target = new SVGPlot(200, 200);
        svg = target.svg;
    }
    var setSVGSrc = function (svg, textarea) {
        replaceChildNodes(textarea, svg.toXML());
    }
    svg.whenReady( partial(testFunction, target) );
    svg.whenReady( partial(setSVGSrc, svg, svgSrcArea) );  // Comment out for IE
    addToCallStack(buttonXML, 'onclick', partial(setSVGSrc, svg, svgSrcArea) );
    replaceChildNodes(svgTD, svg.htmlElement);
}

function addTests(start, end) {
    log("getting table");
    var tbody = getElement('tests');
    replaceChildNodes(tbody)
    var i = 0;
    var buttonDoIt, buttonXML;
    for (var test in testFunctions) {
        if (i>=start && i<=end) {
            log("doing test number ", i, "name ", test);
            var code = (''+testFunctions[test]+'\n').replace(/ +/g, " ");
            var functionArea, svgSrcArea, button, svgTD, button, form;
            var canvasTD = null
            var tr = TR(null, TD(null, ""+i+": "+test, BR(null), IMG({'src':'canvas_tests_images/'+test+'.png'}) ) );
            var include_canvas = (type=='canvas')
            if (include_canvas)
                appendChildNodes(tr, canvasTD=TD({width:210}) )
            var types = ['svg', 'pdf', 'png', 'jpg']
            appendChildNodes(tr,
                              TD(null, functionArea=TEXTAREA({'rows':"14", 'cols':"40", 'wrap':"off", id:test+'_code'}, code),
                                       BR(null),
                                       buttonDoIt=INPUT({type:"button", value:"Do It"}),
                                       " ",
                                       buttonXML=INPUT({type:"button", value:"Update XML"}) ),
                              svgTD=TD({width:210}),
                              TD(null,
                                // Form will open result in new window.
                                // target="_blank" is a deprecated feature, but very useful since you can't right click
                                // on the submit button to choose if you want to open it in a new window, and going back is SLOW
                                form=FORM( { name:'form_'+test, method:'post', action:converter_url, id:test+'_form', target:"_blank"},
                                   svgSrcArea=TEXTAREA({rows:"14", cols:"60", wrap:"off", name:'source', id:test+'_src'} ,"SVG Source"),
                                   BR(null) // Buttons get added below.
                                )
                              )
                        );
            appendChildNodes(tbody, tr);
            var make_input = function(type) {
                var button=INPUT({type:"submit", name:"type", value:type, id:test+'_'+type})
                //addToCallStack(button, 'onclick', partial(convert, test, type))  // Doesn't work to external site
                return SPAN(null, button, " ")  // Put a space after each button
            }
            appendChildNodes(form, map(make_input, types))
            appendChildNodes(form, '(opens in new window)')
            addToCallStack(buttonDoIt, 'onclick', partial(doTest,canvasTD, svgTD, functionArea, svgSrcArea, buttonXML, include_canvas) );
            doTest(canvasTD, svgTD, functionArea, svgSrcArea, buttonXML, include_canvas);
        }
        i++;
    }
}

/*
// For security reasons, browsers won't let JavaScript get the converted file - it must be opened in a new window.
function convert(name, type) {
    var src = name+'_src'
    var contents = formContents(name+'_form')
    //var s = queryString(contents)
    var d = doXHR(converter_url, {method: 'POST', queryString: contents})
    var got_converted = function(response) {
        log(repr(response))
    }
    var failed_converted = function(response) {
        log("failed: "+repr(response))
    }
    d.addCallbacks(got_converted, failed_converted)
}
*/

type = 'svg'  // Can be overriden by other files.
addLoadEvent(setupTopBar)
addLoadEvent(partial(addTests, 0, 0))
<|endoftext|>


<commit_before>var S = require('string');
var _ = require('lodash');
var OptionsList = require('../lib/OptionsList');

describe('Options List', function() {
  it('Should return full options when no form name is passed', function(done) {
    // Test Object.
    var optList = new OptionsList();
    var genderChoices = optList.getFormChoices('gender');
    var genderChoicesControl = { any: 'Cualquier', male: 'Hombre', female: 'Mujer', other_gender: 'Otro' };
    genderChoices.should.eql(genderChoicesControl);

    // Test Array.
    var ageChoices = optList.getFormChoices('age');
    var ageChoicesControl = ['Cualquier', '16-25', '26-40', '41-64', '65+'];
    var ageChoicesControl = _.zipObject(_.keys(ageChoicesControl), ageChoicesControl);
    ageChoices.should.eql(ageChoicesControl);
    return done();
  });

  it('Should return filtered options when fundMeWizard form name is passed', function(done) {
    // Test Object.
    var optList = new OptionsList('fundMeWizard');
    var genderChoices = optList.getFormChoices('gender');
    var genderChoicesControl = { any: 'Ambos - si propietarios de ambos géneros', male: 'Hombre', female: 'Mujer'};
    genderChoices.should.eql(genderChoicesControl);

    // Test Array.
    var ageChoices = optList.getFormChoices('age');
    var ageChoicesControl = ['Cualquier', '16-25', '26-40', '41-64', '65+'];
    var ageChoicesControl = _.zipObject(_.keys(ageChoicesControl), ageChoicesControl);
    // Delete to simulate override.
    delete ageChoicesControl['0'];
    ageChoices.should.eql(ageChoicesControl);
    return done();
  });
});
<commit_msg>Fixing a test<commit_after>var S = require('string');
var _ = require('lodash');
var OptionsList = require('../lib/OptionsList');

describe('Options List', function() {
  it('Should return full options when no form name is passed', function(done) {
    // Test Object.
    var optList = new OptionsList();
    var genderChoices = optList.getFormChoices('gender');
    var genderChoicesControl = { any: 'Cualquier', male: 'Hombre', female: 'Mujer', other_gender: 'Otro' };
    genderChoices.should.eql(genderChoicesControl);

    // Test Array.
    var ageChoices = optList.getFormChoices('age');
    var ageChoicesControl = ['Cualquier', '16-25', '26-40', '41-64', '65+'];
    var ageChoicesControl = _.zipObject(_.keys(ageChoicesControl), ageChoicesControl);
    ageChoices.should.eql(ageChoicesControl);
    return done();
  });

  it('Should return filtered options when fundMeWizard form name is passed', function(done) {
    // Test Object.
    var optList = new OptionsList('fundMeWizard');
    var genderChoices = optList.getFormChoices('gender');
    var genderChoicesControl = { any: 'Ambos - si hubieran propietarios de ambos sexos', male: 'Hombre', female: 'Mujer'};
    genderChoices.should.eql(genderChoicesControl);

    // Test Array.
    var ageChoices = optList.getFormChoices('age');
    var ageChoicesControl = ['Cualquier', '16-25', '26-40', '41-64', '65+'];
    var ageChoicesControl = _.zipObject(_.keys(ageChoicesControl), ageChoicesControl);
    // Delete to simulate override.
    delete ageChoicesControl['0'];
    ageChoices.should.eql(ageChoicesControl);
    return done();
  });
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
  "use strict";

  // External dependencies.
  var Backbone = require("backbone");
  require("hammerjs");
  require("jqueryhammer");

  //views
  var MainView = require("views/MainView");
  var mainView;

  var PrepareView = require("views/PrepareView");
  var prepareView;

  var StartView = require("views/StartView");
  var startView;

  // Defining the application router.
  module.exports = Backbone.Router.extend({
    initialize: function() {
        mainView = new MainView();
        prepareView = new PrepareView();
        startView = new StartView();
    },
    routes: {
      "": "index",
      "download":"download",
      "*action":"index"
    },

    index: function() {
      require(["image!app/img/fox.png",
               "image!app/img/logofox.png",
               "image!app/img/window.png",
               "image!app/img/windowtop.png",
               "image!app/img/about-1.png",
               "image!app/img/about-2.png",
               "image!app/img/about-3.png",
               "image!app/img/about-4.png",
               "image!app/img/phone.png",
               "image!app/img/download.png",
               "image!app/img/arrowup.png",
               "image!app/img/bg.png",
               "image!app/img/intro.png"],function(fox,logofox,window,windowtop,about1,about2,about3,about4,phone,download,arrow,bg,intro){
          startView.render();
      });

    },
    download: function() {
        if ( startView.isRendered ) {

        } else {

        }
    }
  });
});
<commit_msg>download router<commit_after>define(function(require, exports, module) {
  "use strict";

  // External dependencies.
  var Backbone = require("backbone");
  require("hammerjs");
  require("jqueryhammer");

  //views
  var MainView = require("views/MainView");
  var mainView;

  var PrepareView = require("views/PrepareView");
  var prepareView;

  var StartView = require("views/StartView");
  var startView;

  // Defining the application router.
  module.exports = Backbone.Router.extend({
    initialize: function() {
        mainView = new MainView();
        prepareView = new PrepareView();
        startView = new StartView();
    },
    routes: {
      "": "index",
      "download":"download",
      "*action":"index"
    },

    index: function() {
      require(["image!app/img/fox.png",
               "image!app/img/logofox.png",
               "image!app/img/window.png",
               "image!app/img/windowtop.png",
               "image!app/img/about-1.png",
               "image!app/img/about-2.png",
               "image!app/img/about-3.png",
               "image!app/img/about-4.png",
               "image!app/img/phone.png",
               "image!app/img/download.png",
               "image!app/img/arrowup.png",
               "image!app/img/bg.png",
               "image!app/img/intro.png"],function(fox,logofox,window,windowtop,about1,about2,about3,about4,phone,download,arrow,bg,intro){
          startView.render();
      });

    },
    download: function() {
        window.location.href="https://itunes.apple.com/us/app/mi-misecret/id880007797?ls=1&mt=8";
    }
  });
});
<|endoftext|>


<commit_before>module("Date parse");

/*
 * Test the supported date formats
 * 2010
 * 2010-02
 * 2010-02-18
 * 2010-02-18T07:44Z
 * 1997-07-16T19:20+01:00
 * 1997-07-16T19:20:30+01:00
 * 1269331220896 */

test("Date format: YYYY", function(){
    var date = sakai.api.Util.parseSakaiDate("2010");
    equals(date.getFullYear(), "2010", "The year is correct");
});

test("Date format: YYYY-MM", function(){
    var date = sakai.api.Util.parseSakaiDate("2010-11");
    equals(date.getFullYear(), "2010", "The year is correct");
    equals(date.getMonth(), "10", "The month is correct");
});

test("Date format: YYYY-MM-DD", function(){
    var date = sakai.api.Util.parseSakaiDate("2010-11-19");
    equals(date.getFullYear(), "2010", "The year is correct");
    equals(date.getMonth(), "10", "The month is correct");
    equals(date.getDate(), "19", "The day is correct");
});

test("Date format: YYYY-MM-DDThh:mmTZD", function(){
    var date = sakai.api.Util.parseSakaiDate("1997-07-16T19:20+01:00");
    equals(date.getFullYear(), "1997", "The year is correct");
    equals(date.getMonth(), "6", "The month is correct");
    equals(date.getDate(), "16", "The day is correct");
    equals(date.getHours(), "19", "The hour is correct");
    equals(date.getMinutes(), "20", "The minutes are correct");
});

test("Date format: YYYY-MM-DDThh:mm:ssTZD", function(){
    var date = sakai.api.Util.parseSakaiDate("1997-07-16T19:20:30+01:00");
    equals(date.getFullYear(), "1997", "The year is correct");
    equals(date.getMonth(), "6", "The month is correct");
    equals(date.getDate(), "16", "The day is correct");
    equals(date.getHours(), "19", "The hour is correct");
    equals(date.getMinutes(), "20", "The minutes are correct");
    equals(date.getSeconds(), "30", "The seconds are correct");
});

test("Date format: 1269331220896 (milliseconds)", function(){
    var date = sakai.api.Util.parseSakaiDate(1269331220896);
    equals(date.getFullYear(), "2010", "The year is correct");
    equals(date.getMonth(), "2", "The month is correct");
    equals(date.getDate(), "23", "The day is correct");
    equals(date.getHours(), "8", "The hour is correct");
    equals(date.getMinutes(), "0", "The minutes are correct");
    equals(date.getSeconds(), "20", "The seconds are correct");
});

module("Date create");

test("Date format: 1269331220896 (milliseconds)", function(){
    var dateEquals = new Date();
    var date = sakai.api.Util.createSakaiDate(dateEquals, 6);

    equals(dateEquals.getTime(), date, "Test without date offset is correct");

    date = sakai.api.Util.createSakaiDate(dateEquals, 6, "+01:00");
    equals(dateEquals.getTime()+1000*60*60, date, "Test with date offset is correct");
});

test("Date format: YYYY-MM-DDThh:mm:ssTZD", function(){
    var dateEquals = new Date();
    var date = sakai.api.Util.createSakaiDate(dateEquals);

    equals(dateEquals.getFullYear(), date.substr(0,4), "The year is correct");
    equals(dateEquals.getMonth() + 1, date.substr(5,2), "The month is correct");
    var hours = dateEquals.getHours();
    var day = dateEquals.getDate();
    if(hours === 0){
        hours = 24;
        day--
    }
    equals(day, date.substr(8,2), "The day is correct");
    equals(hours - 1, date.substr(11,2), "The hour is correct");
    equals(dateEquals.getMinutes(), date.substr(14,2), "The minutes are correct");
    equals(dateEquals.getSeconds(), date.substr(17,2), "The seconds are correct");
});<commit_msg>SAKIII-382 - fixed the failing of the QUnit tests in ie7/8<commit_after>module("Date parse");

/*
 * Test the supported date formats
 * 2010
 * 2010-02
 * 2010-02-18
 * 2010-02-18T07:44Z
 * 1997-07-16T19:20+01:00
 * 1997-07-16T19:20:30+01:00
 * 1269331220896 */

test("Date format: YYYY", function(){
    var date = sakai.api.Util.parseSakaiDate("2010");
    equals(date.getUTCFullYear(), "2010", "The year is correct");
});

test("Date format: YYYY-MM", function(){
    var date = sakai.api.Util.parseSakaiDate("2010-11");
    equals(date.getUTCFullYear(), "2010", "The year is correct");
    equals(date.getUTCMonth(), "10", "The month is correct");
});

test("Date format: YYYY-MM-DD", function(){
    var date = sakai.api.Util.parseSakaiDate("2010-11-19");
    equals(date.getUTCFullYear(), "2010", "The year is correct");
    equals(date.getUTCMonth(), "10", "The month is correct");
    equals(date.getUTCDate(), "19", "The day is correct");
});

test("Date format: YYYY-MM-DDThh:mmTZD", function(){
    var date = sakai.api.Util.parseSakaiDate("1997-07-16T19:20+01:00");
    equals(date.getUTCFullYear(), "1997", "The year is correct");
    equals(date.getUTCMonth(), "6", "The month is correct");
    equals(date.getUTCDate(), "16", "The day is correct");
    equals(date.getUTCHours()+1, "19", "The hour is correct");
    equals(date.getUTCMinutes(), "20", "The minutes are correct");
});

test("Date format: YYYY-MM-DDThh:mm:ssTZD", function(){
    var date = sakai.api.Util.parseSakaiDate("1997-07-16T19:20:30+01:00");
    equals(date.getUTCFullYear(), "1997", "The year is correct");
    equals(date.getUTCMonth(), "6", "The month is correct");
    equals(date.getUTCDate(), "16", "The day is correct");
    equals(date.getUTCHours()+1, "19", "The hour is correct");
    equals(date.getUTCMinutes(), "20", "The minutes are correct");
    equals(date.getUTCSeconds(), "30", "The seconds are correct");
});

test("Date format: 1269331220896 (milliseconds)", function(){
    var date = sakai.api.Util.parseSakaiDate(1269331220896);
    equals(date.getUTCFullYear(), "2010", "The year is correct");
    equals(date.getUTCMonth(), "2", "The month is correct");
    equals(date.getUTCDate(), "23", "The day is correct");
    equals(date.getUTCHours(), "8", "The hour is correct");
    equals(date.getUTCMinutes(), "0", "The minutes are correct");
    equals(date.getUTCSeconds(), "20", "The seconds are correct");
});

module("Date create");

test("Date format: 1269331220896 (milliseconds)", function(){
    var dateEquals = new Date();
    var date = sakai.api.Util.createSakaiDate(dateEquals, 6);

    equals(dateEquals.getTime(), date, "Test without date offset is correct");

    date = sakai.api.Util.createSakaiDate(dateEquals, 6, "+01:00");
    equals(dateEquals.getTime()+1000*60*60, date, "Test with date offset is correct");
});

test("Date format: YYYY-MM-DDThh:mm:ssTZD", function(){
    var dateEquals = new Date();
    var date = sakai.api.Util.createSakaiDate(dateEquals);

    equals(dateEquals.getUTCFullYear(), date.substr(0,4), "The year is correct");
    equals(dateEquals.getUTCMonth() + 1, date.substr(5,2), "The month is correct");
    equals(dateEquals.getUTCDate(), date.substr(8,2) , "The day is correct");
    equals(dateEquals.getUTCHours(), date.substr(11,2) , "The hour is correct");
    equals(dateEquals.getUTCMinutes(), date.substr(14,2), "The minutes are correct");
    equals(dateEquals.getUTCSeconds(), date.substr(17,2), "The seconds are correct");
});<|endoftext|>


<commit_before>// Invoked by: CloudFormation
// Returns: A `Data` object to a pre-signed URL
//
// Used as part of an ECS service custom resource, which allows for the
// DesiredSize of a service to be persisted across CloudFormation deploys.
// The name of the a cluster and service is passed in as part of the event data,
// and a query is made to the ECS API to get the current value, which is then
// returned and made available to other CloudFormation resources.

const https = require('https');
const url = require('url');
const AWS = require('aws-sdk');

const ecs = new AWS.ECS();

const REQUEST_TYPE_DELETE = 'Delete';

const STATUS_SUCCESS = 'SUCCESS';
// const STATUS_FAILED = 'FAILED';

const HTTP_PUT = 'PUT';

const RESPONSE_DATA_KEY_DESIRED_COUNT = 'DesiredCount';

// Send response to the pre-signed S3 URL
function sendResponse(event, context, responseStatus, responseData) {
    const crResponse = {
        Status: responseStatus,
        Reason: `CloudWatch Logs: ${context.logStreamName}`,
        PhysicalResourceId: context.logStreamName,
        StackId: event.StackId,
        RequestId: event.RequestId,
        LogicalResourceId: event.LogicalResourceId,
        Data: responseData,
    };

    const responseBody = JSON.stringify(crResponse);

    const parsedUrl = url.parse(event.ResponseURL);
    const options = {
        hostname: parsedUrl.hostname,
        port: 443,
        path: parsedUrl.path,
        method: HTTP_PUT,
        headers: {
            'content-type': '',
            'content-length': responseBody.length,
        },
    };

    const request = https.request(options, () => {
        context.done();
    });

    request.on('error', (error) => {
        console.log(`sendResponse Error: ${error}`);
        // Tell AWS Lambda that the function execution is done
        context.done();
    });

    // write data to request body
    request.write(responseBody);
    request.end();
}

exports.handler = (event, context) => {
    // For Delete requests, immediately send a SUCCESS response.
    if (event.RequestType === REQUEST_TYPE_DELETE) {
        sendResponse(event, context, STATUS_SUCCESS);
        return;
    }

    ecs.describeServices({
        cluster: event.ResourceProperties.ClusterName,
        services: [event.ResourceProperties.ServiceName],
    }, (err, data) => {
        if (err) {
            const defaultCount = process.env.DEFAULT_DESIRED_COUNT;
            const responseData = {
                [RESPONSE_DATA_KEY_DESIRED_COUNT]: defaultCount,
            };

            sendResponse(event, context, STATUS_SUCCESS, responseData);
        } else {
            const service = data.services[0];

            const responseData = {
                [RESPONSE_DATA_KEY_DESIRED_COUNT]: service.desiredCount,
            };

            sendResponse(event, context, STATUS_SUCCESS, responseData);
        }
    });
};

<commit_msg>Add a default default desired count<commit_after>// Invoked by: CloudFormation
// Returns: A `Data` object to a pre-signed URL
//
// Used as part of an ECS service custom resource, which allows for the
// DesiredSize of a service to be persisted across CloudFormation deploys.
// The name of the a cluster and service is passed in as part of the event data,
// and a query is made to the ECS API to get the current value, which is then
// returned and made available to other CloudFormation resources.

const https = require('https');
const url = require('url');
const AWS = require('aws-sdk');

const ecs = new AWS.ECS();

const REQUEST_TYPE_DELETE = 'Delete';

const STATUS_SUCCESS = 'SUCCESS';
// const STATUS_FAILED = 'FAILED';

const HTTP_PUT = 'PUT';

const RESPONSE_DATA_KEY_DESIRED_COUNT = 'DesiredCount';

// Send response to the pre-signed S3 URL
function sendResponse(event, context, responseStatus, responseData) {
    const crResponse = {
        Status: responseStatus,
        Reason: `CloudWatch Logs: ${context.logStreamName}`,
        PhysicalResourceId: context.logStreamName,
        StackId: event.StackId,
        RequestId: event.RequestId,
        LogicalResourceId: event.LogicalResourceId,
        Data: responseData,
    };

    const responseBody = JSON.stringify(crResponse);

    const parsedUrl = url.parse(event.ResponseURL);
    const options = {
        hostname: parsedUrl.hostname,
        port: 443,
        path: parsedUrl.path,
        method: HTTP_PUT,
        headers: {
            'content-type': '',
            'content-length': responseBody.length,
        },
    };

    const request = https.request(options, () => {
        context.done();
    });

    request.on('error', (error) => {
        console.log(`sendResponse Error: ${error}`);
        // Tell AWS Lambda that the function execution is done
        context.done();
    });

    // write data to request body
    request.write(responseBody);
    request.end();
}

exports.handler = (event, context) => {
    // For Delete requests, immediately send a SUCCESS response.
    if (event.RequestType === REQUEST_TYPE_DELETE) {
        sendResponse(event, context, STATUS_SUCCESS);
        return;
    }

    ecs.describeServices({
        cluster: event.ResourceProperties.ClusterName,
        services: [event.ResourceProperties.ServiceName],
    }, (err, data) => {
        if (err) {
            const defaultCount = process.env.DEFAULT_DESIRED_COUNT || 10;
            const responseData = {
                [RESPONSE_DATA_KEY_DESIRED_COUNT]: defaultCount,
            };

            sendResponse(event, context, STATUS_SUCCESS, responseData);
        } else {
            const service = data.services[0];

            const responseData = {
                [RESPONSE_DATA_KEY_DESIRED_COUNT]: service.desiredCount,
            };

            sendResponse(event, context, STATUS_SUCCESS, responseData);
        }
    });
};

<|endoftext|>


<commit_before>'use strict';

$(function () {
  var TTEXT_MIME_TYPE = 'application/x-thrift; protocol=TTEXT';

  var specification = {};
  var navTemplate = Handlebars.compile($('#nav-template').html());
  var functionTemplate = Handlebars.compile($('#function-template').html());
  var classTemplate = Handlebars.compile($('#class-template').html());

  var functionContainer = $('#function');
  var classContainer = $('#class');

  var previousFragmentPath = null;

  $.getJSON('specification.json', function (data) {
    specification = data;

    renderNav();
    $(window).trigger('hashchange');
  });

  $(window).on('hashchange', function () {
    render(URI(window.location.href));
  });

  function render(uri) {
    var fragmentUri = uri.fragment(true);
    var path = fragmentUri.pathname();

    if (path == previousFragmentPath) {
      // Path hasn't changed so don't re-render (probably just updated link
      // for sharing debug requests).
      return;
    }
    previousFragmentPath = path;

    resetClasses();

    var hashSplit = path.split('/');
    var prefix = hashSplit[0];

    var mapping = {
      'function': function (serviceName, functionName) {
        renderFunction(serviceName, functionName);
      },

      'class': function (className) {
        renderClass(className);
      }
    };

    if (mapping[prefix]) {
      mapping[prefix].apply(this, hashSplit.slice(1));
    } else {
      renderHome();
    }
  }

  function resetClasses() {
    $('li.active').removeClass('active');
    $('.main .content').addClass('hidden');
    $('.collapse.in').collapse('hide');
  }

  function renderNav() {
    $('.sidebar').html(navTemplate({specification: specification}));
  }

  function renderHome() {
    $('#home').removeClass('hidden');
  }

  function renderFunction(serviceName, functionName) {
    var serviceInfo = specification.services[serviceName];
    if (serviceInfo == undefined) {
      return;
    }
    var functionInfo = serviceInfo.functions[functionName];
    if (functionInfo == undefined) {
      return;
    }

    processService(serviceInfo);
    processFunction(functionInfo);

    makeActive('li#nav-' + serviceName + '.' + functionName);

    functionContainer.html(functionTemplate({
      'serviceName': serviceName,
      'serviceSimpleName': serviceInfo.simpleName,
      'serviceEndpoints': serviceInfo.endpoints,
      'serviceDebugPath': serviceInfo.debugPath,
      'function': functionInfo
    }));

    var debugText = functionContainer.find('.debug-textarea').val(functionInfo.sampleJsonRequest);
    var debugResponse = functionContainer.find('.debug-response code');

    var submitDebugRequest = function () {
      var args;
      try {
        args = JSON.parse(debugText.val());
      } catch (e) {
        debugResponse.text("Failed to parse a JSON object, please check your request:\n" + e);
        return false;
      }
      var request = {
        method: functionInfo.name,
        type: 'CALL',
        args: args
      };
      $.ajax({
        type: 'POST',
        url: serviceInfo.debugPath,
        data: JSON.stringify(request),
        contentType: TTEXT_MIME_TYPE,
        success: function (response) {
          debugResponse.text(response);
          hljs.highlightBlock(debugResponse.get(0));
          var uri = URI(window.location.href);
          var fragment = uri.fragment(true);
          fragment.setQuery('req', debugText.val());
          window.location.href = uri.toString();
        },
        error: function (jqXHR, textStatus, errorThrown) {
          debugResponse.text(errorThrown);
        }
      });
      return false;
    };
    functionContainer.find('.debug-submit').on('click', submitDebugRequest);

    functionContainer.removeClass('hidden');

    var fragment = URI(window.location.href).fragment(true);
    var fragmentParams = fragment.query(true);
    if (fragmentParams.req) {
      debugText.val(fragmentParams.req);
      submitDebugRequest();
    }
  }

  function processService(serviceInfo) {
    var endpoints = serviceInfo.endpoints;
    for (var idx = 0; idx < endpoints.length; idx++) {
      processPath(serviceInfo, endpoints[idx]);
    }
  }

  function processPath(serviceInfo, pathInfo) {
    var availableMimeTypes = pathInfo.availableMimeTypes;
    for (var idx = 0; idx < availableMimeTypes.length; idx++) {
      var mimeType = availableMimeTypes[idx];
      if (mimeType === TTEXT_MIME_TYPE && serviceInfo.debugPath == undefined) {
        serviceInfo.debugPath = pathInfo.path;
      }
      if (mimeType === pathInfo.defaultMimeType) {
        availableMimeTypes[idx] = '' + mimeType + '';
      }
    }
  }

  function processFunction(functionInfo) {
    var parameters = functionInfo.parameters;
    for (var idx = 0; idx < parameters.length; idx++) {
      processType(parameters[idx].type);
    }

    processType(functionInfo.returnType);

    var exceptions = functionInfo.exceptions;
    for (var idx = 0; idx < exceptions.length; idx++) {
      processType(exceptions[idx]);
    }
  }

  function processType(type) {
    type.typeStr = escapeTag(type.type)
        .replace(new RegExp('(?:\\w+\\.)+\\w+', 'g'),
                 function (className) {
                   var classInfo = specification.classes[className];
                   if (!classInfo) {
                     return className;
                   }

                   return '' +
                          classInfo.simpleName + '';
                 });
  }

  function escapeTag(value) {
    return value.replace(/</g, '<').replace(/>/g, '>');
  }

  function makeActive(selector) {
    $(escapeSelector(selector)).addClass('active');
  }

  function escapeSelector(value) {
    return value.replace(/\./g, '\\.');
  }

  function renderClass(className) {
    var classInfo = specification.classes[className];
    if (classInfo == undefined) {
      return;
    }

    var fields = classInfo.fields;
    for (var idx = 0; idx < fields.length; idx++) {
      processType(fields[idx].type);
    }

    makeActive('li#nav-' + className);
    classContainer.html(classTemplate({'class': classInfo}));
    classContainer.removeClass('hidden');
  }
});
<commit_msg>Fix the broken links for classes in DocService<commit_after>'use strict';

$(function () {
  var TTEXT_MIME_TYPE = 'application/x-thrift; protocol=TTEXT';

  var specification = {};
  var navTemplate = Handlebars.compile($('#nav-template').html());
  var functionTemplate = Handlebars.compile($('#function-template').html());
  var classTemplate = Handlebars.compile($('#class-template').html());

  var functionContainer = $('#function');
  var classContainer = $('#class');

  var previousFragmentPath = null;

  $.getJSON('specification.json', function (data) {
    specification = data;

    renderNav();
    $(window).trigger('hashchange');
  });

  $(window).on('hashchange', function () {
    render(URI(window.location.href));
  });

  function render(uri) {
    var fragmentUri = uri.fragment(true);
    var path = fragmentUri.pathname();

    if (path == previousFragmentPath) {
      // Path hasn't changed so don't re-render (probably just updated link
      // for sharing debug requests).
      return;
    }
    previousFragmentPath = path;

    resetClasses();

    var hashSplit = path.split('/');
    var prefix = hashSplit[0];

    var mapping = {
      'function': function (serviceName, functionName) {
        renderFunction(serviceName, functionName);
      },

      'class': function (className) {
        renderClass(className);
      }
    };

    if (mapping[prefix]) {
      mapping[prefix].apply(this, hashSplit.slice(1));
    } else {
      renderHome();
    }
  }

  function resetClasses() {
    $('li.active').removeClass('active');
    $('.main .content').addClass('hidden');
    $('.collapse.in').collapse('hide');
  }

  function renderNav() {
    $('.sidebar').html(navTemplate({specification: specification}));
  }

  function renderHome() {
    $('#home').removeClass('hidden');
  }

  function renderFunction(serviceName, functionName) {
    var serviceInfo = specification.services[serviceName];
    if (serviceInfo == undefined) {
      return;
    }
    var functionInfo = serviceInfo.functions[functionName];
    if (functionInfo == undefined) {
      return;
    }

    processService(serviceInfo);
    processFunction(functionInfo);

    makeActive('li#nav-' + serviceName + '.' + functionName);

    functionContainer.html(functionTemplate({
      'serviceName': serviceName,
      'serviceSimpleName': serviceInfo.simpleName,
      'serviceEndpoints': serviceInfo.endpoints,
      'serviceDebugPath': serviceInfo.debugPath,
      'function': functionInfo
    }));

    var debugText = functionContainer.find('.debug-textarea').val(functionInfo.sampleJsonRequest);
    var debugResponse = functionContainer.find('.debug-response code');

    var submitDebugRequest = function () {
      var args;
      try {
        args = JSON.parse(debugText.val());
      } catch (e) {
        debugResponse.text("Failed to parse a JSON object, please check your request:\n" + e);
        return false;
      }
      var request = {
        method: functionInfo.name,
        type: 'CALL',
        args: args
      };
      $.ajax({
        type: 'POST',
        url: serviceInfo.debugPath,
        data: JSON.stringify(request),
        contentType: TTEXT_MIME_TYPE,
        success: function (response) {
          debugResponse.text(response);
          hljs.highlightBlock(debugResponse.get(0));
          var uri = URI(window.location.href);
          var fragment = uri.fragment(true);
          fragment.setQuery('req', debugText.val());
          window.location.href = uri.toString();
        },
        error: function (jqXHR, textStatus, errorThrown) {
          debugResponse.text(errorThrown);
        }
      });
      return false;
    };
    functionContainer.find('.debug-submit').on('click', submitDebugRequest);

    functionContainer.removeClass('hidden');

    var fragment = URI(window.location.href).fragment(true);
    var fragmentParams = fragment.query(true);
    if (fragmentParams.req) {
      debugText.val(fragmentParams.req);
      submitDebugRequest();
    }
  }

  function processService(serviceInfo) {
    var endpoints = serviceInfo.endpoints;
    for (var idx = 0; idx < endpoints.length; idx++) {
      processPath(serviceInfo, endpoints[idx]);
    }
  }

  function processPath(serviceInfo, pathInfo) {
    var availableMimeTypes = pathInfo.availableMimeTypes;
    for (var idx = 0; idx < availableMimeTypes.length; idx++) {
      var mimeType = availableMimeTypes[idx];
      if (mimeType === TTEXT_MIME_TYPE && serviceInfo.debugPath == undefined) {
        serviceInfo.debugPath = pathInfo.path;
      }
      if (mimeType === pathInfo.defaultMimeType) {
        availableMimeTypes[idx] = '' + mimeType + '';
      }
    }
  }

  function processFunction(functionInfo) {
    var parameters = functionInfo.parameters;
    for (var idx = 0; idx < parameters.length; idx++) {
      processType(parameters[idx].type);
    }

    processType(functionInfo.returnType);

    var exceptions = functionInfo.exceptions;
    for (var idx = 0; idx < exceptions.length; idx++) {
      processType(exceptions[idx]);
    }
  }

  function processType(type) {
    type.typeStr = escapeTag(type.type)
        .replace(new RegExp('(?:\\w+\\.)+\\w+', 'g'),
                 function (className) {
                   var classInfo = specification.classes[className];
                   if (!classInfo) {
                     return className;
                   }

                   return '' +
                          classInfo.simpleName + '';
                 });
  }

  function escapeTag(value) {
    return value.replace(/</g, '<').replace(/>/g, '>');
  }

  function makeActive(selector) {
    $(escapeSelector(selector)).addClass('active');
  }

  function escapeSelector(value) {
    return value.replace(/\./g, '\\.');
  }

  function renderClass(className) {
    var classInfo = specification.classes[className];
    if (classInfo == undefined) {
      return;
    }

    var fields = classInfo.fields;
    for (var idx = 0; idx < fields.length; idx++) {
      processType(fields[idx].type);
    }

    makeActive('li#nav-' + className);
    classContainer.html(classTemplate({'class': classInfo}));
    classContainer.removeClass('hidden');
  }
});
<|endoftext|>