<commit_before>/** @jsx React.DOM */

define(
  [
    'react',
    'actions/VersionActions'
  ],
  function (React, VersionActions) {

    var LoginLink = React.createClass({
      render: function () {
        return (

            Login

        );
      }
    });

    var LogoutLink = React.createClass({

      onShowVersion: function(e){
        e.preventDefault();
        VersionActions.showVersion();
      },

      render: function () {
        return (

            jchansen

                Version

                Sign out

        );
      }
    });

    var Header = React.createClass({

      render: function () {

        var profile = this.props.profile;
        var loginLogoutDropdown = profile ? LogoutLink({username: profile.get('username')}) : LoginLink();

        return (

                <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                  Toggle navigation

                </button>

                  Atmosphere: iPlant Cloud Services

                  {loginLogoutDropdown}

        );

      }
    });

    return Header;

  });
<commit_msg>bug fix: display correct username in header<commit_after>/** @jsx React.DOM */

define(
  [
    'react',
    'backbone',
    'actions/VersionActions'
  ],
  function (React, Backbone, VersionActions) {

    var LoginLink = React.createClass({
      render: function () {
        return (

            Login

        );
      }
    });

    var LogoutLink = React.createClass({

      propTypes: {
        username: React.PropTypes.string.isRequired
      },

      onShowVersion: function(e){
        e.preventDefault();
        VersionActions.showVersion();
      },

      render: function () {
        return (

              {this.props.username}

                Version

                Sign out

        );
      }
    });

    var Header = React.createClass({

      propTypes: {
        profile: React.PropTypes.instanceOf(Backbone.Model).isRequired
      },

      render: function () {

        var profile = this.props.profile;
        var loginLogoutDropdown = profile ? LogoutLink({username: profile.get('username')}) : LoginLink();

        return (

                <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                  Toggle navigation

                </button>

                  Atmosphere: iPlant Cloud Services

                  {loginLogoutDropdown}

        );

      }
    });

    return Header;

  });
<|endoftext|>


<commit_before>import { extend, last, random } from 'lodash';
import S from '../../helpers/string';
import { observable, computed, action } from 'mobx';
import ResponseValidation from '../../models/response_validation';
import Raven from '../../models/app/raven';

export
class ResponseValidationUX {

  @observable initialResponse;
  @observable retriedResponse;
  @observable messages;
  @observable messageIndex;
  @observable results = [];

  constructor({ step, messages, taskUX, validator = new ResponseValidation() }) {
    this.step = step;
    this.step.spy.response_validation = {};
    this.step.response_validation = {};
    this.validator = validator;
    this.messages = messages;
    this.taskUX = taskUX;
    this.initialResponse = step.free_response;
    this.messageIndex = random(0, messages.length - 1);
  }

  @computed get nudge() {
    return this.messages[this.messageIndex];
  }

  @computed get canRevert() {
    return Boolean(
      this.step.isOpenEndedExercise &&
        this.step.can_be_updated &&
        this.step.last_completed_at &&
        (!this.course.currentRole.isTeacher)
    );
  }

  @action.bound setResponse(ev) {
    if (this.taskUX.isReadOnly) {
      ev.preventDefault();
      return;
    }
    const { target: { value } } = ev;
    if (this.isDisplayingNudge) {
      this.retriedResponse = value;
    } else {
      this.initialResponse = value;
    }
  }

  @computed get response() {
    return this.isDisplayingNudge ? this.retriedResponse : this.initialResponse;
  }

  @computed get responseWords() {
    return S.countWords(this.response);
  }

  @computed get course() {
    return this.taskUX.course;
  }

  @action.bound async onSave() {
    if (!this.taskUX.canUpdateCurrentStep) {
      this.step.beginRecordingAnswer({ free_response: this.initialResponse });
      this.taskUX.onFreeResponseComplete(this.step);
      return;
    }
    const result = await this.validate();

    if (this.validator.isUIEnabled) {
      this.advanceUI(result);
    } else {
      this.step.beginRecordingAnswer({ free_response: result.response });
    }
    this.results.push(result);
    this.step.response_validation = { attempts: this.results };
  }

  @action async validate() {
    // Nudges are only displayed on the first attempt, only save the message if it was shown.
    const nudge = this.validator.isUIEnabled && S.isEmpty(this.results) ? this.nudge.title : null;
    const submitted = this.response;
    try {
      const reply = await this.validator.validate({
        uid: this.step.uid,
        response: submitted,
      });
      const validation = extend({}, reply.data, {
        timestamp: (new Date()).toISOString(),
        response: submitted, nudge,
      });
      this.step.spy.response_validation = validation;
      return validation;
    } catch (err) {
      Raven.captureException(err);
      return {
        valid: true,
        exception: err.toString(),
        response: submitted,
        timestamp: (new Date()).toISOString(),
        nudge,
      };
    }
  }

  @action.bound cancelWRQResubmit() {
    this.results = [];
    this.initialResponse = this.step.free_response;
  }

  @action advanceUI(result) {
    if (result.valid || this.isDisplayingNudge) {
      this.step.beginRecordingAnswer({ free_response: result.response });
      this.taskUX.onFreeResponseComplete(this.step);
    } else {
      this.retriedResponse = this.initialResponse;
    }
  }

  @action.bound submitOriginalResponse(ev) {
    ev && ev.preventDefault();
    this.step.beginRecordingAnswer({ free_response: this.initialResponse });
    this.taskUX.onFreeResponseComplete(this.step);
  }

  @computed get textHasChanged() {
    return this.step.free_response !== this.initialResponse;
  }

  @computed get submitBtnLabel() {
    if (!this.taskUX.canUpdateCurrentStep){
      return 'Next';
    }
    return this.isDisplayingNudge ? 'Re-submit' : 'Submit';
  }

  @computed get displayNudgeError() {
    return Boolean(
      this.isDisplayingNudge && this.initialResponse === this.retriedResponse
    );
  }

  @computed get isSubmitDisabled() {
    return Boolean(
      this.taskUX.isLocked || this.displayNudgeError || S.isEmpty(this.response),
    );
  }

  @computed get isDisplayingNudge() {
    return Boolean(
      this.validator.isUIEnabled &&
        this.results.length && !last(this.results).valid
    );
  }

  @computed get lastSubmitted() {
    return this.step.free_response && this.step.last_completed_at;
  }

}
<commit_msg>show resubmit label button if there is a response for a wrm question<commit_after>import { extend, last, random } from 'lodash';
import S from '../../helpers/string';
import { observable, computed, action } from 'mobx';
import ResponseValidation from '../../models/response_validation';
import Raven from '../../models/app/raven';

export
class ResponseValidationUX {

  @observable initialResponse;
  @observable retriedResponse;
  @observable messages;
  @observable messageIndex;
  @observable results = [];

  constructor({ step, messages, taskUX, validator = new ResponseValidation() }) {
    this.step = step;
    this.step.spy.response_validation = {};
    this.step.response_validation = {};
    this.validator = validator;
    this.messages = messages;
    this.taskUX = taskUX;
    this.initialResponse = step.free_response;
    this.messageIndex = random(0, messages.length - 1);
  }

  @computed get nudge() {
    return this.messages[this.messageIndex];
  }

  @computed get canRevert() {
    return Boolean(
      this.step.isOpenEndedExercise &&
        this.step.can_be_updated &&
        this.step.last_completed_at &&
        (!this.course.currentRole.isTeacher)
    );
  }

  @action.bound setResponse(ev) {
    if (this.taskUX.isReadOnly) {
      ev.preventDefault();
      return;
    }
    const { target: { value } } = ev;
    if (this.isDisplayingNudge) {
      this.retriedResponse = value;
    } else {
      this.initialResponse = value;
    }
  }

  @computed get response() {
    return this.isDisplayingNudge ? this.retriedResponse : this.initialResponse;
  }

  @computed get responseWords() {
    return S.countWords(this.response);
  }

  @computed get course() {
    return this.taskUX.course;
  }

  @action.bound async onSave() {
    if (!this.taskUX.canUpdateCurrentStep) {
      this.step.beginRecordingAnswer({ free_response: this.initialResponse });
      this.taskUX.onFreeResponseComplete(this.step);
      return;
    }
    const result = await this.validate();

    if (this.validator.isUIEnabled) {
      this.advanceUI(result);
    } else {
      this.step.beginRecordingAnswer({ free_response: result.response });
    }
    this.results.push(result);
    this.step.response_validation = { attempts: this.results };
  }

  @action async validate() {
    // Nudges are only displayed on the first attempt, only save the message if it was shown.
    const nudge = this.validator.isUIEnabled && S.isEmpty(this.results) ? this.nudge.title : null;
    const submitted = this.response;
    try {
      const reply = await this.validator.validate({
        uid: this.step.uid,
        response: submitted,
      });
      const validation = extend({}, reply.data, {
        timestamp: (new Date()).toISOString(),
        response: submitted, nudge,
      });
      this.step.spy.response_validation = validation;
      return validation;
    } catch (err) {
      Raven.captureException(err);
      return {
        valid: true,
        exception: err.toString(),
        response: submitted,
        timestamp: (new Date()).toISOString(),
        nudge,
      };
    }
  }

  @action.bound cancelWRQResubmit() {
    this.results = [];
    this.initialResponse = this.step.free_response;
  }

  @action advanceUI(result) {
    if (result.valid || this.isDisplayingNudge) {
      this.step.beginRecordingAnswer({ free_response: result.response });
      this.taskUX.onFreeResponseComplete(this.step);
    } else {
      this.retriedResponse = this.initialResponse;
    }
  }

  @action.bound submitOriginalResponse(ev) {
    ev && ev.preventDefault();
    this.step.beginRecordingAnswer({ free_response: this.initialResponse });
    this.taskUX.onFreeResponseComplete(this.step);
  }

  @computed get textHasChanged() {
    return this.step.free_response !== this.initialResponse;
  }

  @computed get submitBtnLabel() {
    if (!this.taskUX.canUpdateCurrentStep){
      return 'Next';
    }
    return this.step.free_response ? 'Re-submit' : 'Submit';
  }

  @computed get displayNudgeError() {
    return Boolean(
      this.isDisplayingNudge && this.initialResponse === this.retriedResponse
    );
  }

  @computed get isSubmitDisabled() {
    return Boolean(
      this.taskUX.isLocked || this.displayNudgeError || S.isEmpty(this.response),
    );
  }

  @computed get isDisplayingNudge() {
    return Boolean(
      this.validator.isUIEnabled &&
        this.results.length && !last(this.results).valid
    );
  }

  @computed get lastSubmitted() {
    return this.step.free_response && this.step.last_completed_at;
  }

}
<|endoftext|>


<commit_before>define([ "jquery", "message-bus", "module", //
"./accordion-group", "./alerts", "./buttons", "./checkbox", "./choice", //
"./commons", "./confirm-dialog", "./dialog", "./divstack", //
"./dropdown-buttons", "./form-collector", "./input", "./loading", "./radio", //
"./slider", "./sliding-div", "./table", "./text-area", "sortable", "tipsy" ],//
function($, bus, module, //
accordionGroup, alerts, buttons, checkbox, choice, //
commons, confirmDialog, dialog, divstack,//
dropdownButtons, formCollector, input, loading, radio, //
slider, slidingDiv, table, textArea, Sortable) {
  var TOOLTIP_ATTR = "geoladris-ui-tooltip";
  var TOOLTIP_GRAVITIES = {
    "left" : "e",
    "right" : "w",
    "top" : "s",
    "bottom" : "n",
    "top-left" : "se",
    "top-right" : "sw",
    "bottom-left" : "ne",
    "bottom-right" : "nw"
  };

  bus.listen("ui-show", function(e, id) {
    document.getElementById(id).style.display = "";
  });

  bus.listen("ui-hide", function(e, id) {
    document.getElementById(id).style.display = "none";
  });

  bus.listen("ui-toggle", function(e, id) {
    var e = document.getElementById(id);
    e.style.display = e.style.display == "none" ? "" : "none";
  });

  bus.listen("ui-open-url", function(e, msg) {
    window.open(msg.url, msg.target);
  });

  bus.listen("modules-loaded", function() {
    bus.send("ui-loaded");
  });

  return {
    create : function(type, props) {
      // Do not create if already exists
      var e = document.getElementById(props.id);
      if (e) {
        return e;
      }

      switch (type) {
      case "accordion-group":
        e = accordionGroup(props);
        break;
      case "autocomplete":
        e = autocomplete(props);
        break;
      case "button":
        e = buttons(props);
        break;
      case "checkbox":
        e = checkbox(props);
        break;
      case "choice":
        e = choice(props);
        break;
      case "confirm-dialog":
        e = confirmDialog(props);
        break;
      case "dialog":
        e = dialog(props);
        break;
      case "divstack":
        e = divstack(props);
        break;
      case "dropdown-button":
        e = dropdownButtons(props);
        break;
      case "input":
        e = input(props);
        break;
      case "radio":
        e = radio(props);
        break;
      case "slider":
        e = slider(props);
        break;
      case "sliding-div":
        e = slidingDiv(props);
        break;
      case "table-ext":
        e = table(props);
        break;
      case "text-area":
        e = textArea(props);
        break;
      default:
        e = commons.getOrCreateElem(type, props);
        break;
      }

      if (e) {
        bus.send("ui:created", e);
      }
      return e;
    },
    tooltip : function(elem, props) {
      if (typeof elem == "string") {
        elem = document.getElementById(elem);
      }

      elem.setAttribute(TOOLTIP_ATTR, props.text);
      var jelem = $(elem);
      jelem.tipsy({
        trigger : "manual",
        title : TOOLTIP_ATTR,
        html : true,
        opacity : 1,
        gravity : TOOLTIP_GRAVITIES[props.location] || $.fn.tipsy.autoNS
      });
      jelem.tipsy("show");

      return jelem.data("tipsy").$tip[0];
    },
    sortable : function(elem) {
      if (typeof elem == "string") {
        elem = document.getElementById(elem);
      }

      Sortable.create(elem, {
        onSort : function() {
          var event = document.createEvent('Event');
          event.initEvent('change', true, true);
          elem.dispatchEvent(event);
        }
      });
    }
  }
});
<commit_msg>Add element and indexes to sortable change event<commit_after>define([ "jquery", "message-bus", "module", //
"./accordion-group", "./alerts", "./buttons", "./checkbox", "./choice", //
"./commons", "./confirm-dialog", "./dialog", "./divstack", //
"./dropdown-buttons", "./form-collector", "./input", "./loading", "./radio", //
"./slider", "./sliding-div", "./table", "./text-area", "sortable", "tipsy" ],//
function($, bus, module, //
accordionGroup, alerts, buttons, checkbox, choice, //
commons, confirmDialog, dialog, divstack,//
dropdownButtons, formCollector, input, loading, radio, //
slider, slidingDiv, table, textArea, Sortable) {
  var TOOLTIP_ATTR = "geoladris-ui-tooltip";
  var TOOLTIP_GRAVITIES = {
    "left" : "e",
    "right" : "w",
    "top" : "s",
    "bottom" : "n",
    "top-left" : "se",
    "top-right" : "sw",
    "bottom-left" : "ne",
    "bottom-right" : "nw"
  };

  bus.listen("ui-show", function(e, id) {
    document.getElementById(id).style.display = "";
  });

  bus.listen("ui-hide", function(e, id) {
    document.getElementById(id).style.display = "none";
  });

  bus.listen("ui-toggle", function(e, id) {
    var e = document.getElementById(id);
    e.style.display = e.style.display == "none" ? "" : "none";
  });

  bus.listen("ui-open-url", function(e, msg) {
    window.open(msg.url, msg.target);
  });

  bus.listen("modules-loaded", function() {
    bus.send("ui-loaded");
  });

  return {
    create : function(type, props) {
      // Do not create if already exists
      var e = document.getElementById(props.id);
      if (e) {
        return e;
      }

      switch (type) {
      case "accordion-group":
        e = accordionGroup(props);
        break;
      case "autocomplete":
        e = autocomplete(props);
        break;
      case "button":
        e = buttons(props);
        break;
      case "checkbox":
        e = checkbox(props);
        break;
      case "choice":
        e = choice(props);
        break;
      case "confirm-dialog":
        e = confirmDialog(props);
        break;
      case "dialog":
        e = dialog(props);
        break;
      case "divstack":
        e = divstack(props);
        break;
      case "dropdown-button":
        e = dropdownButtons(props);
        break;
      case "input":
        e = input(props);
        break;
      case "radio":
        e = radio(props);
        break;
      case "slider":
        e = slider(props);
        break;
      case "sliding-div":
        e = slidingDiv(props);
        break;
      case "table-ext":
        e = table(props);
        break;
      case "text-area":
        e = textArea(props);
        break;
      default:
        e = commons.getOrCreateElem(type, props);
        break;
      }

      if (e) {
        bus.send("ui:created", e);
      }
      return e;
    },
    tooltip : function(elem, props) {
      if (typeof elem == "string") {
        elem = document.getElementById(elem);
      }

      elem.setAttribute(TOOLTIP_ATTR, props.text);
      var jelem = $(elem);
      jelem.tipsy({
        trigger : "manual",
        title : TOOLTIP_ATTR,
        html : true,
        opacity : 1,
        gravity : TOOLTIP_GRAVITIES[props.location] || $.fn.tipsy.autoNS
      });
      jelem.tipsy("show");

      return jelem.data("tipsy").$tip[0];
    },
    sortable : function(elem) {
      if (typeof elem == "string") {
        elem = document.getElementById(elem);
      }

      Sortable.create(elem, {
        onSort : function(e) {
          elem.dispatchEvent(new CustomEvent("change", {
            detail : {
              item : e.item,
              newIndex : e.newIndex,
              oldIndex : e.oldIndex
            }
          }));
        }
      });
    }
  }
});
<|endoftext|>


<commit_before>/** Renders table of a FormEntitiesTable object
 * @param document {object} - document object, usually DOM
 * @param options {object} -
 * {
 *  addButtonLabel {string} - default "Add new"
 *  append {object} - domjs object to append after table
 *  customize {function} - customization callback
 *  master {object} - by default section's master object
 *  prepend {object} - domjs object to prepend before table
 *  url {string} - url used by the form (note: url is used to build action attribute for the form)
 * }
 * @returns {array} - array of constructed domjs elements
 */

'use strict';

var _                   = require('mano').i18n.bind('View: Binding: Sections')
  , d                   = require('d')
  , db                  = require('mano').db
  , resolvePropertyPath = require('dbjs/_setup/utils/resolve-property-path')
  , generateId          = require('time-uuid')
  , loc                 = require('mano/lib/client/location')
  , ns                  = require('mano').domjs.ns
  , progressRules       = require('../components/progress-rules')
  , normalizeOptions    = require('es5-ext/object/normalize-options');

require('./form-section-base');

module.exports = Object.defineProperty(db.FormEntitiesTable.prototype, 'toDOMFieldset',
	d(function (document/*, options */) {
		var self = this, options, url, customizeData, resolvent, tableData, resolved, getAddUrl,
			collectionType, addButton, isMapMode;
		options = normalizeOptions(arguments[1]);
		customizeData = { master: options.master || this.master };
		url = options.url || ns.url;
		resolvent = this.getFormResolvent(options);
		resolved = resolvePropertyPath(customizeData.master, this.propertyName);
		tableData = resolved.value;
		if (tableData instanceof db.NestedMap) {
			isMapMode = true;
			tableData = tableData.ordered;
			collectionType = resolved.value.getDescriptor('ordered').type;
			getAddUrl = function () {
				return url(self.baseUrl, 'p' + generateId());
			};
		} else {
			collectionType = resolved.descriptor.type;
			getAddUrl = function () {
				return url(self.baseUrl + '-add');
			};
		}
		customizeData.arrayResult = [
			options.prepend,
			resolvent.formResolvent ? ns.form({
				action: url(self.baseUrl + '-resolvent'),
				class: 'form-elements',
				autoSubmit: true,
				method: 'post'
			}, resolvent.formResolvent, ns.p({ class: 'submit' },
				ns.input({ type: 'submit', value: _("Submit") }))) : undefined,
			progressRules(this),
			ns.div({ class: 'entities-overview-table-wrapper', id: resolvent.affectedSectionId },
				ns.table(
					{ class: ns._if(ns.not(ns.eq(tableData._size, 0)),
						'entities-overview-table',
						'entities-overview-table entities-overview-table-empty') },
					ns.thead(
						ns.tr(ns.list(this.entities, function (entity) {
							return ns.th({ class: [ns._if(entity._desktopOnly, 'desktop-only',
								ns._if(entity._mobileOnly, 'mobile-only')), entity.htmlClass] },
									or(entity._label, resolvePropertyPath(
									collectionType.prototype,
									entity.propertyName
								).descriptor.label));
						}), ns.th(),
							ns.th({ class: 'actions' }))
					),
					ns.tbody({ onEmpty: ns.tr(ns.td({ colspan: this.entities.size + 2 },
								this.onEmptyMessage)
						) },
						tableData,
						function (entityObject) {
							var editUrl, deleteUrl, status;
							if (isMapMode) {
								editUrl = url(self.baseUrl, entityObject.key);
								deleteUrl = url(self.baseUrl, entityObject.key, 'delete');
							} else {
								editUrl = url(self.baseUrl, entityObject.__id__);
								deleteUrl = url(self.baseUrl, entityObject.__id__, 'delete');
							}
							if (self.sectionProperty === 'dataForms') {
								status = entityObject.dataForms._progress;
							} else {
								status = resolvePropertyPath(entityObject,
										self.sectionProperty + 'Status').observable;
							}
							return ns.tr(ns.list(self.entities, function (entity) {
								var resolved = resolvePropertyPath(entityObject, entity.propertyName)
								  , htmlClass = [ns._if(entity._desktopOnly, 'desktop-only',
										ns._if(entity._mobileOnly, 'mobile-only')), entity.htmlClass]
								  , isObject = (typeof resolved.value === 'object') && resolved.value
										&& resolved.value.__id__;

								if (db.File && isObject && (resolved.value instanceof db.File)) {
									return td({ class: htmlClass }, _if(resolved.value._url,
											a({ href: resolved.value._url, target: '_blank' }, _("See picture"))));
								}
								return ns.td({ class: htmlClass },
										ns.a({ href: editUrl },
											resolved.observable));
							}),
								ns.td({ class: [ns._if(ns.eq(status, 1),
									'completed'), 'entities-overview-table-status-cell'] },
									ns.span({ class: 'status-complete' }, "✓"),
									ns.span({ class: 'hint-optional hint-optional-left status-incomplete',
											'data-hint': _("Some required fields are not filled") },
										"!")),
								ns.td({ class: 'actions  entities-overview-table-actions-cell' },
									ns.a({ class: 'actions-edit',
											href: editUrl },
										ns.span({ class: 'fa fa-edit' }, _("Edit"))),
									ns.postButton({ buttonClass: 'actions-delete',
										action: deleteUrl,
										value: ns.span({ class: 'fa fa-trash-o' },
											_("Delete")) })));
						}),
					this.generateFooter &&
						ns.tfoot(this.generateFooter(
							resolvePropertyPath(customizeData.master, this.propertyName).value
						))
				),
				options.append,
				resolvent.legacyScript,
				ns.p({ class: 'entities-overview-table-buttons' },
					customizeData.addButton = addButton = ns.a(
						{ class: 'button-regular', href: getAddUrl() },
						options.addButtonLabel || _("Add ${ entityLabel }",
							{ entityLabel: collectionType.prototype.label })
					)))
		];
		if (isMapMode) {
			loc.on('change', function (ev) {
				if (loc.pathname !== addButton.pathname) return;
				addButton.href = getAddUrl();
			});
		}
		if (typeof options.customize === 'function') {
			options.customize.call(this, customizeData);
		}

		return customizeData.arrayResult;
	}));
<commit_msg>Do not handle resolvent with legacy script<commit_after>/** Renders table of a FormEntitiesTable object
	* @param document {object} - document object, usually DOM
	* @param options {object} -
	* {
	*  addButtonLabel {string} - default "Add new"
	*  append {object} - domjs object to append after table
	*  customize {function} - customization callback
	*  master {object} - by default section's master object
	*  prepend {object} - domjs object to prepend before table
	*  url {string} - url used by the form (note: url is used to build action attribute for the form)
	* }
	* @returns {array} - array of constructed domjs elements
*/

'use strict';

var _                   = require('mano').i18n.bind('View: Binding: Sections')
  , d                   = require('d')
  , db                  = require('mano').db
  , resolvePropertyPath = require('dbjs/_setup/utils/resolve-property-path')
  , generateId          = require('time-uuid')
  , loc                 = require('mano/lib/client/location')
  , ns                  = require('mano').domjs.ns
  , progressRules       = require('../components/progress-rules')
  , normalizeOptions    = require('es5-ext/object/normalize-options');

require('./form-section-base');

module.exports = Object.defineProperty(db.FormEntitiesTable.prototype, 'toDOMFieldset',
	d(function (document/*, options */) {
		var self = this, options, url, customizeData, resolvent, tableData, resolved, getAddUrl
		  , collectionType, addButton, isMapMode;
		options = normalizeOptions(arguments[1]);
		customizeData = { master: options.master || this.master };
		url = options.url || ns.url;
		resolvent = this.getFormResolvent(options);
		resolved = resolvePropertyPath(customizeData.master, this.propertyName);
		tableData = resolved.value;
		if (tableData instanceof db.NestedMap) {
			isMapMode = true;
			tableData = tableData.ordered;
			collectionType = resolved.value.getDescriptor('ordered').type;
			getAddUrl = function () {
				return url(self.baseUrl, 'p' + generateId());
			};
		} else {
			collectionType = resolved.descriptor.type;
			getAddUrl = function () {
				return url(self.baseUrl + '-add');
			};
		}
		customizeData.arrayResult = [
			options.prepend,
			resolvent.formResolvent
				? ns.form({
					action: url(self.baseUrl + '-resolvent'),
					class: 'form-elements',
					autoSubmit: true,
					method: 'post'
				}, resolvent.formResolvent, ns.p({
					class: ['submit', _if(not(eqSloppy(this.getResolventObservable(), null)), 'completed')]
				}, ns.input({ type: 'submit', value: _("Submit") })))
				: undefined,
			_if(!this.resolventProperty || not(this._isUnresolved), div(
				{ class: 'blocks-container' },
				progressRules(this),
				ns.div({ class: 'entities-overview-table-wrapper', id: resolvent.affectedSectionId },
					ns.table(
						{ class: ns._if(ns.not(ns.eq(tableData._size, 0)),
							'entities-overview-table',
							'entities-overview-table entities-overview-table-empty') },
						ns.thead(
							ns.tr(ns.list(this.entities, function (entity) {
								return ns.th({ class: [ns._if(entity._desktopOnly, 'desktop-only',
									ns._if(entity._mobileOnly, 'mobile-only')), entity.htmlClass] },
									or(entity._label, resolvePropertyPath(
										collectionType.prototype,
										entity.propertyName
									).descriptor.label));
							}), ns.th(),
								ns.th({ class: 'actions' }))
						),
						ns.tbody({
							onEmpty: ns.tr(ns.td({ colspan: this.entities.size + 2 }, this.onEmptyMessage))
						}, tableData, function (entityObject) {
							var editUrl, deleteUrl, status;
							if (isMapMode) {
								editUrl = url(self.baseUrl, entityObject.key);
								deleteUrl = url(self.baseUrl, entityObject.key, 'delete');
							} else {
								editUrl = url(self.baseUrl, entityObject.__id__);
								deleteUrl = url(self.baseUrl, entityObject.__id__, 'delete');
							}
							if (self.sectionProperty === 'dataForms') {
								status = entityObject.dataForms._progress;
							} else {
								status = resolvePropertyPath(entityObject,
									self.sectionProperty + 'Status').observable;
							}
							return ns.tr(ns.list(self.entities, function (entity) {
								var resolved = resolvePropertyPath(entityObject, entity.propertyName)
								  , htmlClass = [ns._if(entity._desktopOnly, 'desktop-only',
										ns._if(entity._mobileOnly, 'mobile-only')), entity.htmlClass]
								  , isObject = (typeof resolved.value === 'object') && resolved.value
									&& resolved.value.__id__;

								if (db.File && isObject && (resolved.value instanceof db.File)) {
									return td({ class: htmlClass }, _if(resolved.value._url,
										a({ href: resolved.value._url, target: '_blank' }, _("See picture"))));
								}
								return ns.td({ class: htmlClass },
									ns.a({ href: editUrl },
										resolved.observable));
							}),
								ns.td({ class: [ns._if(ns.eq(status, 1),
									'completed'), 'entities-overview-table-status-cell'] },
									ns.span({ class: 'status-complete' }, "✓"),
									ns.span({ class: 'hint-optional hint-optional-left status-incomplete',
										'data-hint': _("Some required fields are not filled") },
										"!")),
								ns.td({ class: 'actions  entities-overview-table-actions-cell' },
									ns.a({ class: 'actions-edit',
										href: editUrl },
										ns.span({ class: 'fa fa-edit' }, _("Edit"))),
									ns.postButton({ buttonClass: 'actions-delete',
										action: deleteUrl,
										value: ns.span({ class: 'fa fa-trash-o' },
											_("Delete")) })));
						}),
						this.generateFooter &&
							ns.tfoot(this.generateFooter(
								resolvePropertyPath(customizeData.master, this.propertyName).value
							))
					),
					options.append,
					ns.p({ class: 'entities-overview-table-buttons' },
						customizeData.addButton = addButton = ns.a(
							{ class: 'button-regular', href: getAddUrl() },
							options.addButtonLabel || _("Add ${ entityLabel }",
								{ entityLabel: collectionType.prototype.label })
						)))
			))
		];
		if (isMapMode) {
			loc.on('change', function (ev) {
				if (loc.pathname !== addButton.pathname) return;
				addButton.href = getAddUrl();
			});
		}
		if (typeof options.customize === 'function') {
			options.customize.call(this, customizeData);
		}

		return customizeData.arrayResult;
	}));
<|endoftext|>


<commit_before>require([
	'lib/V',
	'goo/renderer/Material',
	'goo/renderer/shaders/ShaderLib',
	'goo/shapes/Box',
	'goo/math/Vector3',
	'goo/math/Quaternion',
	'goo/renderer/MeshData',
	'goo/geometrypack/Surface',

	'goo/animationpack/components/AnimationComponent',
	'goo/animationpack/SkeletonPose',
	'goo/animationpack/Skeleton',
	'goo/animationpack/Joint',
	'goo/animationpack/state/SteadyState',
	'goo/animationpack/blendtree/ClipSource',
	'goo/animationpack/clip/AnimationClip',
	'goo/animationpack/clip/JointChannel',
	'goo/animationpack/systems/AnimationSystem'

], function (
	V,
	Material,
	ShaderLib,
	Box,
	Vector3,
	Quaternion,
	MeshData,
	Surface,

	AnimationComponent,
	SkeletonPose,
	Skeleton,
	Joint,
	SteadyState,
	ClipSource,
	AnimationClip,
	JointChannel,
	AnimationSystem
) {
	'use strict';

	V.describe('Skeleton Animation Test');

	function addSkeltonAttributeData(meshData) {

		var skeletonMaps = MeshData.defaultMap([MeshData.JOINTIDS, MeshData.WEIGHTS]);
		meshData.attributeMap[MeshData.JOINTIDS] = skeletonMaps[MeshData.JOINTIDS];
		meshData.attributeMap[MeshData.WEIGHTS] = skeletonMaps[MeshData.WEIGHTS];
		// rebuildData generates dataviews on the new attributes.
		meshData.rebuildData(meshData.vertexCount, meshData.indexCount, true);
		// These are probably used somewhere.
		meshData.weightsPerVertex = 4; // Default weights count
		meshData.type = MeshData.SKINMESH;
	}

	function addPaletteMap(meshData) {
		var jointData = meshData.dataViews.JOINTIDS;
		// Code stolen from meshdatahandler
		var buffer = meshData.getAttributeBuffer(MeshData.JOINTIDS);
		// Map skeleton joint index local joint index
		var localJointMap = [];

		var localIndex = 0;
		for (var idx = 0; idx < jointData.length; idx++) {
			var jointIndex = jointData[idx];
			if (localJointMap[jointIndex] === undefined) {
				// If vertex has joint index, add to localmap
				localJointMap[jointIndex] = localIndex++;
			}
			// Set vertex joint index to local index
			buffer.set([localJointMap[jointIndex]], idx);
		}
		// Make a reverse map from local joint to skeleton joint
		// We will use this later in animation shader code
		var localMap = [];
		for (var jointIndex = 0; jointIndex < localJointMap.length; jointIndex++) {
			var localIndex = localJointMap[jointIndex];
			if (localIndex !== null) {
				localMap[localIndex] = jointIndex;
			}
		}
		meshData.paletteMap = [0,1];  // The palettemap is used in the animation shader code.
	}

	function addWeirdCube(world) {

		var j2 = new Joint('j2');
		j2._index = 0;
		j2._parentIndex = Joint.NO_PARENT;

		var j1 = new Joint('rootjoint');
		j1._index = 1;
		j1._parentIndex = j2._index;

		var joints = [j2, j1];

		var skeleton = new Skeleton('My very own skeleton', joints);
		var skeletonPose = new SkeletonPose(skeleton);
		var animComp = new AnimationComponent(skeletonPose);

		var times = [0.0, 1.0, 2.0];

		var rots = [];
		var q1 = new Quaternion();
		var q2 = new Quaternion();
		q2.fromAngleNormalAxis(Math.PI, Vector3.UNIT_Y);
		Array.prototype.push.apply(rots, q1.data);
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q1.data);

		var trans = [
			0,0,0,
			0,0,0,
			0,0,0
		];

		var scales = [
			1,1,1,
			1,1,1,
			1,1,1,
		];

		var rootChannel = new JointChannel(
			j1._index,
			j1._name,
			times,
			rots,
			trans,
			scales,
			'SCurve3'
			);

		var j2Channel = new JointChannel(
			j2._index,
			j2._name,
			times,
			[0,0,0,1,
			0,0,0,1,
			0,0,0,1,],
			[
			0,0,0,
			0,1,0,
			0,0,0],
			scales,
			'SCurve3');

		var animChannels = [rootChannel, j2Channel];
		var clip = new AnimationClip('My animation Clip', animChannels);
		var clipSource = new ClipSource(clip);
		clipSource._clipInstance._loopCount = -1;  // -1 for looping infinetly
		var animState = new SteadyState('My animation state');
		animState.setClipSource(clipSource);
		var animLayer = animComp.layers[0];  // Default animation layer
		animLayer.setState('RootRotateState', animState);
		animLayer.setCurrentState(animState, true);

		var meshData = new Box();
		// The Box does not create skeleton related attributes, doin' it manually
		addSkeltonAttributeData(meshData);

		var positions = meshData.dataViews.POSITION;
		var vertIndices = [];
		for (var i = 0; i < positions.length; i+=3) {
			var y = positions[i+1];
			if (y > 0) {
				vertIndices.push(i/3);
			}
		}

		var weightData = meshData.dataViews.WEIGHTS;
		for (var i = 0; i < weightData.length; i++) {
			weightData[i] = 1;
		}

		var jointData = meshData.dataViews.JOINTIDS;
		for (var i = 0; i < jointData.length; i++) {
			jointData[i] = 0;
		}

		for (var i = 0; i < vertIndices.length; i++) {
			jointData[vertIndices[i]*4] = 1;
		}

		addPaletteMap(meshData);

		// Ubershader contains the animation shader logic , plus any other feature.
		var boxEntity = world.createEntity(meshData, new Material(ShaderLib.uber));
		boxEntity.set(animComp);

		// The entity's meshdatacomponent needs the currentPose to be set to the SkeletonPose.
		boxEntity.meshDataComponent.currentPose = boxEntity.animationComponent._skeletonPose;
		boxEntity.addToWorld();
	}

	function addFoldingPaper(world) {

		// Create skeleton joint hierarchy
		var rootJoint = new Joint()

		var size = 10;
		var vertCount = 100;
		var meshData = Surface.createTessellatedFlat(size, size, vertCount, vertCount);
		var material = new Material(ShaderLib.uber);
		material.cullState.enabled = false;
		var surfaceEntity = world.createEntity(meshData, material);
		surfaceEntity.addToWorld();
	}

	function init() {

		var goo = V.initGoo();
		var world = goo.world;

		// The animationsystem calls the animation components, updating
		// the animation data every frame.
		var animSystem = new AnimationSystem();
		world.setSystem(animSystem);

		//addWeirdCube(world);

		addFoldingPaper(world);

		V.addLights();

		V.addOrbitCamera(new Vector3(15, Math.PI / 2, 0.3));

		V.process();
	}

	init();
});
<commit_msg>Moving movn.<commit_after>require([
	'lib/V',
	'goo/renderer/Material',
	'goo/renderer/shaders/ShaderLib',
	'goo/shapes/Box',
	'goo/math/Vector3',
	'goo/math/Quaternion',
	'goo/renderer/MeshData',
	'goo/geometrypack/Surface',

	'goo/animationpack/components/AnimationComponent',
	'goo/animationpack/SkeletonPose',
	'goo/animationpack/Skeleton',
	'goo/animationpack/Joint',
	'goo/animationpack/state/SteadyState',
	'goo/animationpack/blendtree/ClipSource',
	'goo/animationpack/clip/AnimationClip',
	'goo/animationpack/clip/JointChannel',
	'goo/animationpack/systems/AnimationSystem'

], function (
	V,
	Material,
	ShaderLib,
	Box,
	Vector3,
	Quaternion,
	MeshData,
	Surface,

	AnimationComponent,
	SkeletonPose,
	Skeleton,
	Joint,
	SteadyState,
	ClipSource,
	AnimationClip,
	JointChannel,
	AnimationSystem
) {
	'use strict';

	V.describe('Skeleton Animation Test');

	function addSkeltonAttributeData(meshData) {

		var skeletonMaps = MeshData.defaultMap([MeshData.JOINTIDS, MeshData.WEIGHTS]);
		meshData.attributeMap[MeshData.JOINTIDS] = skeletonMaps[MeshData.JOINTIDS];
		meshData.attributeMap[MeshData.WEIGHTS] = skeletonMaps[MeshData.WEIGHTS];
		// rebuildData generates dataviews on the new attributes.
		meshData.rebuildData(meshData.vertexCount, meshData.indexCount, true);
		// These are probably used somewhere.
		meshData.weightsPerVertex = 4; // Default weights count
		meshData.type = MeshData.SKINMESH;
	}

	function addPaletteMap(meshData) {
		var jointData = meshData.dataViews.JOINTIDS;
		// Code stolen from meshdatahandler
		var buffer = meshData.getAttributeBuffer(MeshData.JOINTIDS);
		// Map skeleton joint index local joint index
		var localJointMap = [];

		var localIndex = 0;
		for (var idx = 0; idx < jointData.length; idx++) {
			var jointIndex = jointData[idx];
			if (localJointMap[jointIndex] === undefined) {
				// If vertex has joint index, add to localmap
				localJointMap[jointIndex] = localIndex++;
			}
			// Set vertex joint index to local index
			buffer.set([localJointMap[jointIndex]], idx);
		}
		// Make a reverse map from local joint to skeleton joint
		// We will use this later in animation shader code
		var localMap = [];
		for (var jointIndex = 0; jointIndex < localJointMap.length; jointIndex++) {
			var localIndex = localJointMap[jointIndex];
			if (localIndex !== null) {
				localMap[localIndex] = jointIndex;
			}
		}
		meshData.paletteMap = [0,1];  // The palettemap is used in the animation shader code.
	}

	function addWeirdCube(world) {

		var j2 = new Joint('j2');
		j2._index = 0;
		j2._parentIndex = Joint.NO_PARENT;

		var j1 = new Joint('asdfsfd');
		j1._index = 1;
		j1._parentIndex = j2._index;

		var joints = [j2, j1];

		var skeleton = new Skeleton('My very own skeleton', joints);
		var skeletonPose = new SkeletonPose(skeleton);
		var animComp = new AnimationComponent(skeletonPose);

		var times = [0.0, 1.0, 2.0];

		var rots = [];
		var q1 = new Quaternion();
		var q2 = new Quaternion();
		q2.fromAngleNormalAxis(Math.PI, Vector3.UNIT_Y);
		Array.prototype.push.apply(rots, q1.data);
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q1.data);

		var trans = [
			0,0,0,
			0,0,0,
			0,0,0
		];

		var scales = [
			1,1,1,
			1,1,1,
			1,1,1,
		];

		var rootChannel = new JointChannel(
			j1._index,
			j1._name,
			times,
			rots,
			trans,
			scales,
			'SCurve3'
			);

		var j2Channel = new JointChannel(
			j2._index,
			j2._name,
			times,
			[0,0,0,1,
			0,0,0,1,
			0,0,0,1,],
			[
			0,0,0,
			0,1,0,
			0,0,0],
			scales,
			'SCurve3');

		var animChannels = [rootChannel, j2Channel];
		var clip = new AnimationClip('My animation Clip', animChannels);
		var clipSource = new ClipSource(clip);
		clipSource._clipInstance._loopCount = -1;  // -1 for looping infinetly
		var animState = new SteadyState('My animation state');
		animState.setClipSource(clipSource);
		var animLayer = animComp.layers[0];  // Default animation layer
		animLayer.setState('RootRotateState', animState);
		animLayer.setCurrentState(animState, true);

		var meshData = new Box();
		// The Box does not create skeleton related attributes, doin' it manually
		addSkeltonAttributeData(meshData);

		var positions = meshData.dataViews.POSITION;
		var vertIndices = [];
		for (var i = 0; i < positions.length; i+=3) {
			var y = positions[i+1];
			if (y > 0) {
				vertIndices.push(i/3);
			}
		}

		var weightData = meshData.dataViews.WEIGHTS;
		for (var i = 0; i < weightData.length; i++) {
			weightData[i] = 1;
		}

		var jointData = meshData.dataViews.JOINTIDS;
		for (var i = 0; i < jointData.length; i++) {
			jointData[i] = 0;
		}

		for (var i = 0; i < vertIndices.length; i++) {
			jointData[vertIndices[i]*4] = 1;
		}

		addPaletteMap(meshData);

		// Ubershader contains the animation shader logic , plus any other feature.
		var boxEntity = world.createEntity(meshData, new Material(ShaderLib.uber));
		boxEntity.set(animComp);

		// The entity's meshdatacomponent needs the currentPose to be set to the SkeletonPose.
		boxEntity.meshDataComponent.currentPose = boxEntity.animationComponent._skeletonPose;
		boxEntity.addToWorld();
	}

	function createJointChannel(joint, times, t, r, s, blendType) {
		return new JointChannel(
			joint._index,
			joint._name,
			times,
			r,
			t,
			s,
			blendType
		);
	}

	function addFoldingPaper(world) {

		var joints = [];

		// Create skeleton joint hierarchy
		var rootJoint = new Joint('RootJoint');
		rootJoint._parentIndex = Joint.NO_PARENT;
		rootJoint._index = 0;
		joints.push(rootJoint);

		var leftSideJoint = new Joint('Ls');
		leftSideJoint._index = 1;
		leftSideJoint._parentIndex = rootJoint._index
		joints.push(leftSideJoint);

		var skeleton = new Skeleton('PaperSkeleton', joints);
		var skeletonPose = new SkeletonPose(skeleton);
		var animComp = new AnimationComponent(skeletonPose);

		var times = [0.0, 1.0, 2.0];
		var rots = [];
		var q1 = new Quaternion();
		var q2 = new Quaternion();
		Array.prototype.push.apply(rots, q1.data);
		Array.prototype.push.apply(rots, q1.data);
		Array.prototype.push.apply(rots, q1.data);

		var trans = [
			0,0,0,
			0,1,0,
			0,0,0
		];

		var scales = [
			1,1,1,
			1,1,1,
			1,1,1,
		];

		var rootChannel = createJointChannel(rootJoint, times, trans, rots, scales, 'SCurve3');

		rots = [];
		q2.fromAngleNormalAxis(Math.PI * 0.5, Vector3.UNIT_Y);
		Array.prototype.push.apply(rots, q1.data);
		Array.prototype.push.apply(rots, q2.data);
		Array.prototype.push.apply(rots, q1.data);

		var trans = [
			0,0,0,
			0,0,0,
			0,0,0
		];

		var scales = [
			1,1,1,
			1,1,1,
			1,1,1,
		];

		var leftChannel = createJointChannel(leftSideJoint, times, trans, rots, scales, 'SCurve3');

		var animChannels = [rootChannel, leftChannel];
		var clip = new AnimationClip('My animation Clip', animChannels);
		var clipSource = new ClipSource(clip);
		clipSource._clipInstance._loopCount = -1;  // -1 for looping infinetly
		var animState = new SteadyState('My animation state');
		animState.setClipSource(clipSource);
		var animLayer = animComp.layers[0];  // Default animation layer
		animLayer.setState('RootRotateState', animState);
		animLayer.setCurrentState(animState, true);

		var size = 10;
		var vertCount = 100;
		var meshData = Surface.createTessellatedFlat(size, size, vertCount, vertCount);

		addSkeltonAttributeData(meshData);
		addPaletteMap(meshData);
		meshData.paletteMap = [0, 1];

		var weightData = meshData.dataViews.WEIGHTS;
		for (var i = 0; i < weightData.length; i+=4) {
			weightData[i] = 1;
			weightData[i+1] = 0;
			weightData[i+2] = 0;
			weightData[i+3] = 0;
		}

		var jointData = meshData.dataViews.JOINTIDS;
		for (var i = 0; i < jointData.length; i+=4) {
			jointData[i] = 1;
		}

		var material = new Material(ShaderLib.uber);
		material.cullState.enabled = false;
		var surfaceEntity = world.createEntity(meshData, material);
		surfaceEntity.set(animComp);
		surfaceEntity.meshDataComponent.currentPose = surfaceEntity.animationComponent._skeletonPose;
		surfaceEntity.addToWorld();
	}

	function init() {

		var goo = V.initGoo();
		var world = goo.world;

		// The animationsystem calls the animation components, updating
		// the animation data every frame.
		var animSystem = new AnimationSystem();
		world.setSystem(animSystem);

		//addWeirdCube(world);

		addFoldingPaper(world);

		V.addLights();

		V.addOrbitCamera(new Vector3(15, Math.PI / 2, 0.3));

		V.process();
	}

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


<commit_before>/*
 *  Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */

var widgets = require('jupyter-js-widgets');
var _ = require('underscore');
var $ = require('jquery');

var TableScope = require('./tableDisplay/tableScope');

require('datatables.net-dt/css/jquery.dataTables.css');
require('datatables.net-colreorder-dt/css/colReorder.dataTables.css');
require('datatables.net-fixedcolumns-dt/css/fixedColumns.dataTables.css');
require('datatables.net-keytable-dt/css/keyTable.dataTables.css');
require('jquery-contextmenu/dist/jquery.contextMenu.css');
require('./tableDisplay/css/datatables.scss');

var TableDisplayModel = widgets.DOMWidgetModel.extend({
  defaults: function() {
    return _.extend({}, widgets.DOMWidgetModel.prototype.defaults.apply(this), {
      _model_name: 'TableDisplayModel',
      _view_name: 'TableDisplayView',
      _model_module: 'beakerx',
      _view_module: 'beakerx'
    });
  }
});

// Custom View. Renders the widget model.
var TableDisplayView = widgets.DOMWidgetView.extend({
  render: function() {
    var that = this;

    this._currentScope = null;

    this.$el.addClass('beaker-table-display');

    this.displayed.then(function() {
      var tableModel = that.model.get('model');
      if (tableModel.tooManyRows) {
        that.showWarning(tableModel);
      }
      that.initTableDisplay(tableModel);

      that.listenTo(that.model, 'beakerx-tabSelected', function() {
        that._currentScope.adjustRedraw();
      });
    });
  },

  update: function() {
    TableDisplayView.__super__.update.apply(this);

    var tableModelUpdateData = this.model.get('model');

    this._currentScope.updateModelData(tableModelUpdateData);
    this._currentScope.doResetAll();
  },

  initTableDisplay: function(data) {
    this._currentScope = new TableScope('wrap_'+this.id);
    var tmpl = this._currentScope.buildTemplate();
    var tmplElement = $(tmpl);

    tmplElement.appendTo(this.$el);

    this._currentScope.setWidgetModel(this.model);
    this._currentScope.setModelData(data);
    this._currentScope.setElement(tmplElement.children('.dtcontainer'));
    this._currentScope.enableJupyterKeyHandler();
    this._currentScope.run();
    this._currentScope.initColumLimitModal();
    this._currentScope.setWidgetView(this);
  },

  showWarning: function(data) {
    var rowLength = data.rowLength;
    var columnLength = data.columnNames.length;
    var rowLimit = data.rowLimit;
    var tmpl = '
' +
      '
Error: table is too big to display. ' +
      'The limit is ' + rowLimit + ' rows, but this table has ' + rowLength + ' rows. ' +
      'The first 1000 rows are displayed as a preview.

';
    var tmplElement = $(tmpl);
    tmplElement.appendTo(this.$el);
  }

});

module.exports = {
  TableDisplayModel: TableDisplayModel,
  TableDisplayView: TableDisplayView
};
<commit_msg>#5070 fix the adjustRedraw error of tableDisplay (#5750)<commit_after>/*
 *  Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */

var widgets = require('jupyter-js-widgets');
var _ = require('underscore');
var $ = require('jquery');

var TableScope = require('./tableDisplay/tableScope');

require('datatables.net-dt/css/jquery.dataTables.css');
require('datatables.net-colreorder-dt/css/colReorder.dataTables.css');
require('datatables.net-fixedcolumns-dt/css/fixedColumns.dataTables.css');
require('datatables.net-keytable-dt/css/keyTable.dataTables.css');
require('jquery-contextmenu/dist/jquery.contextMenu.css');
require('./tableDisplay/css/datatables.scss');

var TableDisplayModel = widgets.DOMWidgetModel.extend({
  defaults: function() {
    return _.extend({}, widgets.DOMWidgetModel.prototype.defaults.apply(this), {
      _model_name: 'TableDisplayModel',
      _view_name: 'TableDisplayView',
      _model_module: 'beakerx',
      _view_module: 'beakerx'
    });
  }
});

// Custom View. Renders the widget model.
var TableDisplayView = widgets.DOMWidgetView.extend({
  render: function() {
    var that = this;

    this._currentScope = null;

    this.$el.addClass('beaker-table-display');

    this.displayed.then(function() {
      var tableModel = that.model.get('model');
      if (tableModel.tooManyRows) {
        that.showWarning(tableModel);
      }
      that.initTableDisplay(tableModel);

      that.listenTo(that.model, 'beakerx-tabSelected', function() {
          that._currentScope && that._currentScope.adjustRedraw();
      });
    });
  },

  update: function() {
    TableDisplayView.__super__.update.apply(this);

    var tableModelUpdateData = this.model.get('model');

    this._currentScope.updateModelData(tableModelUpdateData);
    this._currentScope.doResetAll();
  },

  initTableDisplay: function(data) {
    this._currentScope = new TableScope('wrap_'+this.id);
    var tmpl = this._currentScope.buildTemplate();
    var tmplElement = $(tmpl);

    tmplElement.appendTo(this.$el);

    this._currentScope.setWidgetModel(this.model);
    this._currentScope.setModelData(data);
    this._currentScope.setElement(tmplElement.children('.dtcontainer'));
    this._currentScope.enableJupyterKeyHandler();
    this._currentScope.run();
    this._currentScope.initColumLimitModal();
    this._currentScope.setWidgetView(this);
  },

  showWarning: function(data) {
    var rowLength = data.rowLength;
    var columnLength = data.columnNames.length;
    var rowLimit = data.rowLimit;
    var tmpl = '
' +
      '
Error: table is too big to display. ' +
      'The limit is ' + rowLimit + ' rows, but this table has ' + rowLength + ' rows. ' +
      'The first 1000 rows are displayed as a preview.

';
    var tmplElement = $(tmpl);
    tmplElement.appendTo(this.$el);
  }

});

module.exports = {
  TableDisplayModel: TableDisplayModel,
  TableDisplayView: TableDisplayView
};
<|endoftext|>


<commit_before>/*
Listen for clicks in the popup.

If the click is not on one of the beasts, return early.

Otherwise, the text content of the node is the name of the beast we want.

Run the "beastify.js" content script in the active tab, calling setBeast()
once the content script has executed.

Inside setBeast(), get the active tab, then send it a message containing
the chosen beast's name. This message will be received by the content script
we just executed.
*/
document.addEventListener("click", function(e) {
  if (!e.target.classList.contains("beast")) {
    return;
  }

  var chosenBeast = e.target.textContent;

  chrome.tabs.executeScript(null, {
    file: "/content_scripts/beastify.js"
  });

  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {beast: chosenBeast});
  });

});
<commit_msg>corrected a  comment<commit_after>/*
Listen for clicks in the popup.

If the click is not on one of the beasts, return early.

Otherwise, the text content of the node is the name of the beast we want.

Inject the "beastify.js" content script in the active tab.

Then get the active tab and send "beastify.js" a message
containing the chosen beast's name.
*/
document.addEventListener("click", function(e) {
  if (!e.target.classList.contains("beast")) {
    return;
  }

  var chosenBeast = e.target.textContent;

  chrome.tabs.executeScript(null, {
    file: "/content_scripts/beastify.js"
  });

  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {beast: chosenBeast});
  });

});
<|endoftext|>


<commit_before>'use strict';

const tracker = require('./memory.js');
const fs = require('fs');
require('../trace');

tracker.start();

const stream = fs.createReadStream('/dev/random');
stream.resume();

setTimeout(function () {
    stream.pause();
    setTimeout(function () {
      tracker.stop();
    }, 5 * 1000);
}, 5 * 60 * 1000);
<commit_msg>[cleanup] memory benchmark<commit_after>'use strict';

const tracker = require('./memory.js');
const fs = require('fs');
require('../trace.js');

tracker.start();

const stream = fs.createReadStream('/dev/random');
stream.resume();

setTimeout(function () {
    stream.pause();
    setTimeout(function () {
      tracker.stop();
    }, 5 * 1000);
}, 5 * 60 * 1000);
<|endoftext|>


<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 parseArgs = require('minimist');
var process = require('process');
var assert = require('assert');
var path = require('path');
var StaticConfig = require('static-config');

var HyperbahnApplication = require('../app.js');

function HyperbahnWorker(opts) {
    /*eslint max-statements: [2, 25]*/
    if (!(this instanceof HyperbahnWorker)) {
        return new HyperbahnWorker(opts);
    }

    var self = this;

    assert(opts.serverPort, 'serverPort required');
    assert(opts.serverServiceName, 'serverServiceName required');
    assert(opts.instances, 'instances required');
    assert(opts.workerPort, 'workerPort required');

    assert(opts.sentryPort, 'sentryPort required');
    assert(opts.kafkaPort, 'kafkaPort required');

    self.statsdPort = Number(opts.statsdPort);
    self.kafkaPort = Number(opts.kafkaPort);
    self.sentryPort = Number(opts.sentryPort);
    self.config = self.createConfig();
    self.app = HyperbahnApplication(self.config, {
        processTitle: process.title,
        argv: {
            port: Number(opts.workerPort)
        }
    });

    self.instances = Number(opts.instances);
    self.serverServiceName = opts.serverServiceName;
    self.serverPort = Number(opts.serverPort);
}

HyperbahnWorker.prototype.start = function start() {
    var self = this;

    self.app.bootstrapAndListen(onAppReady);

    function onAppReady(err) {
        if (err) {
            throw err;
        }

        var basePort = self.serverPort;
        var serviceProxy = self.app.clients.serviceProxy;

        for (var i = 0; i < self.instances; i++) {
            var targetHostPort = '127.0.0.1:' + (basePort + i);

            serviceProxy.refreshServicePeer(
                self.serverServiceName, targetHostPort
            );
        }
    }
};

HyperbahnWorker.prototype.createConfig = function createConfig() {
    var self = this;

    var configDir = path.join(__dirname, '..', 'config');

    return StaticConfig({
        files: [
            path.join(configDir, 'production.json')
        ],
        seedConfig: {
            'clients.uber-statsd-client': {
                host: '127.0.0.1',
                port: self.statsdPort
            },
            'clients.logtron.kafka': {
                leafHost: '127.0.0.1',
                leafPort: self.kafkaPort
            },
            'clients.logtron.sentry': {
                id: 'http://bs:bs@localhost:' + self.sentryPort
            },
            'tchannel.host': '127.0.0.1'
        }
    });
};

if (require.main === module) {
    var argv = parseArgs(process.argv.slice(2));
    process.title = 'nodejs-benchmarks-hyperbahn_worker';

    var worker = HyperbahnWorker(argv);
    worker.start();
}
<commit_msg>benchmarks/hyperbahn-worker: use an uncaught exception handler<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 parseArgs = require('minimist');
var process = require('process');
var assert = require('assert');
var path = require('path');
var StaticConfig = require('static-config');

var HyperbahnApplication = require('../app.js');

function HyperbahnWorker(opts) {
    /*eslint max-statements: [2, 25]*/
    if (!(this instanceof HyperbahnWorker)) {
        return new HyperbahnWorker(opts);
    }

    var self = this;

    assert(opts.serverPort, 'serverPort required');
    assert(opts.serverServiceName, 'serverServiceName required');
    assert(opts.instances, 'instances required');
    assert(opts.workerPort, 'workerPort required');

    assert(opts.sentryPort, 'sentryPort required');
    assert(opts.kafkaPort, 'kafkaPort required');

    self.statsdPort = Number(opts.statsdPort);
    self.kafkaPort = Number(opts.kafkaPort);
    self.sentryPort = Number(opts.sentryPort);
    self.config = self.createConfig();
    self.app = HyperbahnApplication(self.config, {
        processTitle: process.title,
        argv: {
            port: Number(opts.workerPort)
        }
    });

    self.instances = Number(opts.instances);
    self.serverServiceName = opts.serverServiceName;
    self.serverPort = Number(opts.serverPort);
}

HyperbahnWorker.prototype.start = function start() {
    var self = this;

    // attach before throwing exception
    process.on('uncaughtException', self.app.clients.onError);

    self.app.bootstrapAndListen(onAppReady);

    function onAppReady(err) {
        if (err) {
            throw err;
        }

        var basePort = self.serverPort;
        var serviceProxy = self.app.clients.serviceProxy;

        for (var i = 0; i < self.instances; i++) {
            var targetHostPort = '127.0.0.1:' + (basePort + i);

            serviceProxy.refreshServicePeer(
                self.serverServiceName, targetHostPort
            );
        }
    }
};

HyperbahnWorker.prototype.createConfig = function createConfig() {
    var self = this;

    var configDir = path.join(__dirname, '..', 'config');

    return StaticConfig({
        files: [
            path.join(configDir, 'production.json')
        ],
        seedConfig: {
            'clients.uber-statsd-client': {
                host: '127.0.0.1',
                port: self.statsdPort
            },
            'clients.logtron.kafka': {
                leafHost: '127.0.0.1',
                leafPort: self.kafkaPort
            },
            'clients.logtron.sentry': {
                id: 'http://bs:bs@localhost:' + self.sentryPort
            },
            'tchannel.host': '127.0.0.1'
        }
    });
};

if (require.main === module) {
    var argv = parseArgs(process.argv.slice(2));
    process.title = 'nodejs-benchmarks-hyperbahn_worker';

    var worker = HyperbahnWorker(argv);
    worker.start();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2005-2012 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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.
 */
/**
 * Show growl with message, title and theme passed in
 *
 * @param message message of this jGrowl
 * @param title title of this jGrowl, can be empty string for none
 * @param theme class to append to jGrowl classes, can be empty string for none
 */
function showGrowl(message, title, theme) {
    var context = getContext();
    if (theme) {
        context.jGrowl(message, { header: title, theme: theme});
    }
    else {
        context.jGrowl(message, { header: title});
    }
}

/**
 * Set default growl options for this view
 *
 * @param options
 */
function setGrowlDefaults(options) {
    var context = getContext();
    context.jGrowl.defaults = context.extend(context.jGrowl.defaults, options);
}

/**
 * Uses jQuery plug-in to show a loading notification for a page request. See
 * <link>http://plugins.jquery.com/project/showLoading</link> for documentation
 * on options.
 *
 * @param showLoading -
 *          boolean that indicates whether the loading indicator should be shown
 *          (true) or hidden (false)
 */
function createLoading(showLoading) {
    var loadingMessage =  '
Loading...
';
    var savingMessage = '
Saving...
';

    var methodToCall = jq("input[name='methodToCall']").val();
    var unblockUIOnLoading = jq("input[name='unblockUIOnLoading']").val();

    if (unblockUIOnLoading == null || unblockUIOnLoading.toUpperCase() == "false".toUpperCase()) {
        if (top == self) {
            //no portal
            if (showLoading) {
                if (methodToCall && methodToCall.toUpperCase() == "save".toUpperCase()) {
                    jq.blockUI({message: savingMessage});
                }
                else {
                    jq.blockUI({message: loadingMessage});
                }
            }
            else {
                jq.unblockUI();
            }
        }
        else if (top.jq == null) {
            if (showLoading) {
                if (methodToCall && methodToCall.toUpperCase() == "save".toUpperCase()) {
                    top.$.blockUI({message: savingMessage});
                }
                else {
                    top.$.blockUI({message: loadingMessage});
                }
            }
            else {
                top.$.unblockUI();
            }
        }
        else {
            if (showLoading) {
                if (methodToCall && methodToCall.toUpperCase() == "save".toUpperCase()) {
                    top.jq.blockUI({message: savingMessage});
                }
                else {
                    top.jq.blockUI({message: loadingMessage});
                }
            }
            else {
                top.jq.unblockUI();
            }
        }
    }
}

function clearServerErrorColors(errorDivId){
    if (errorDivId) {
        var div = jq("#" + errorDivId);
        var label = jq("#" + errorDivId.replace("errors_div", "label"));
        var highlightLine = "";

        //check to see if the option to highlight fields is on
        if (div.length > 0 && !div.hasClass("noHighlight")) {
            if (div.parent().is("td") || (div.parent().is(".refreshWrapper") && div.parent().parent().is("td"))) {
                highlightLine = div.closest("td");
            }
            else {
                highlightLine = div.closest(".fieldLine");
            }

            if (highlightLine.length > 0) {
                highlightLine.removeClass("kr-serverError");
            }
        }
    }
}

/**
 * Applies the error coloring for fields with errors, warnings, or information
 */
function applyErrorColors(errorDivId, errorNum, warningNum, infoNum, clientSide) {
    if (errorDivId) {
        var div = jq("#" + errorDivId);
        var label = jq("#" + errorDivId.replace("errors_div", "label"));
        var highlightLine = "";

        //check to see if the option to highlight fields is on
        if (div.length > 0 && !div.hasClass("noHighlight")) {
            if (div.parent().is("td") || (div.parent().is(".refreshWrapper") && div.parent().parent().is("td"))) {
                highlightLine = div.closest("td");
            }
            else {
                highlightLine = div.closest(".fieldLine");
            }

            if (highlightLine.length > 0) {

                if (errorNum && !clientSide) {

                    highlightLine.addClass("kr-serverError");
                    label.addClass("kr-serverError");
                }
                else if (errorNum) {
                    highlightLine.addClass("kr-clientError");
                    label.addClass("kr-clientError");
                }
                else if (warningNum) {
                    highlightLine.addClass("kr-warning");
                    label.addClass("kr-warning");
                }
                else if (infoNum) {
                    highlightLine.addClass("kr-information");
                    label.addClass("kr-information");
                }
                else {
                    //we are only removing errors client side - no knowledge of warnings/infos
                    if (div.parent().hasClass("kr-errorsField")) {
                        var error_ul = div.parent().find(".kr-errorMessages").find("ul.errorLines");
                        var moreErrors = false;
                        error_ul.each(function() {
                            jq(this).children().each(function() {
                                if (jq(this).css("display") != "none") {
                                    moreErrors = true;
                                    return false;
                                }
                            });
                            if (moreErrors) {
                                return false;
                            }
                        });

                        label.removeClass("kr-clientError");
                        if (!moreErrors) {
                            highlightLine.removeClass("kr-clientError");
                        }
                    }
                    else {
                        highlightLine.removeClass("kr-clientError");
                        label.removeClass("kr-clientError");
                    }
                }
            }
        }

        //highlight tab that contains errors - no setting to turn this off because it is necessary
        var tabDiv = div.closest(".ui-tabs-panel");
        if (tabDiv.length > 0) {
            var tabId = tabDiv.attr("id");
            var tabAnchor = jq("a[href='#" + tabId + "']");
            var errorIcon = jq("#" + tabId + "_errorIcon");

            if (tabAnchor.length > 0) {
                var hasErrors = false;
                if (errorNum) {
                    hasErrors = true;
                }
                else {
                    var error_li = tabDiv.find(".kr-errorMessages").find("li");
                    error_li.each(function() {
                        if (jq(this).css("display") != "none") {
                            hasErrors = true;
                        }
                    });
                }

                if (hasErrors) {
                    tabAnchor.addClass("kr-clientError");
                    if (errorIcon.length == 0) {
                        tabAnchor.append("");
                    }
                }
                else if (!hasErrors) {
                    tabAnchor.removeClass("kr-clientError");
                    errorIcon.remove();
                }
            }
        }
    }
}

/**
 * Shows the field error icon if errorCount is greater than one and errorsField
 * has the option turned on
 */
function showFieldIcon(errorsDivId, errorCount) {
    if (errorsDivId) {
        var div = jq("#" + errorsDivId);
        var inputId = errorsDivId.replace("_errors_div", "");

        if (inputId) {
            var input = jq("#" + inputId);
            var errorIcon = jq("#" + inputId + "_errorIcon");

            if (div.length > 0 && div.hasClass("addFieldIcon") && errorCount && errorIcon.length == 0) {
                if (input.length > 0) {
                    input.after("");
                }
                else {
                    // try for radios and checkboxes
                    input = jq("#" + errorDivId.replace("errors_div", "attribute1"));
                    if (input.length > 0) {
                        input.after("");
                    }
                }
            }
            else if (div.length > 0 && div.hasClass("addFieldIcon") && errorCount == 0) {
                if (errorIcon.length > 0) {
                    errorIcon.remove();
                }
            }
        }
    }
}

/**
 * Adds the icon that indicates the contents of a field have changed from the compared value (for instance the new side
 * on maintenance documents) to the field markers span
 *
 * @param fieldId - id for the field the icon should be added to
 */
function showChangeIcon(fieldId) {
    var fieldMarkerSpan = jq("#" + fieldId + "_attribute_markers");
    var fieldIcon = jq("#" + fieldId + "_changeIcon");

    if (fieldMarkerSpan.length > 0 && fieldIcon.length == 0) {
        fieldMarkerSpan.append("");
    }
}

/**
 * Add icon to a group header that indicates the data for the group has changed
 *
 * @param headerFieldId - id for the header field the icon should be added to
 */
function showChangeIconOnHeader(headerFieldId) {
    var headerSpan = jq("#" + headerFieldId + "_header");
    var headerIcon = jq("#" + headerFieldId + "_changeIcon");

    if (headerSpan.length > 0 && headerIcon.length == 0) {
        headerSpan.append("");
    }
}

// Applies the watermark to the input with the id specified
function createWatermark(id, watermark) {
    jq("#" + id).watermark(watermark);
}

/**
 * If the content is an incident report view, replaces the current view with the incident report and
 * returns true, otherwise returns false
 *
 * @param content
 * @returns {Boolean} true if there was an incident, false otherwise
 */
function handleIncidentReport(content) {
    var viewId = jq("#viewId", content);
    if (viewId.length && viewId.val() === "Incident-Report") {
        jq('#view_div').replaceWith(jq('#view_div', content));

        runHiddenScripts("view_div");
        return true;
    }
    else {
        return false;
    }
}<commit_msg>KULRICE-5332 : Update incident report view id in script.<commit_after>/*
 * Copyright 2005-2012 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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.
 */
/**
 * Show growl with message, title and theme passed in
 *
 * @param message message of this jGrowl
 * @param title title of this jGrowl, can be empty string for none
 * @param theme class to append to jGrowl classes, can be empty string for none
 */
function showGrowl(message, title, theme) {
    var context = getContext();
    if (theme) {
        context.jGrowl(message, { header: title, theme: theme});
    }
    else {
        context.jGrowl(message, { header: title});
    }
}

/**
 * Set default growl options for this view
 *
 * @param options
 */
function setGrowlDefaults(options) {
    var context = getContext();
    context.jGrowl.defaults = context.extend(context.jGrowl.defaults, options);
}

/**
 * Uses jQuery plug-in to show a loading notification for a page request. See
 * <link>http://plugins.jquery.com/project/showLoading</link> for documentation
 * on options.
 *
 * @param showLoading -
 *          boolean that indicates whether the loading indicator should be shown
 *          (true) or hidden (false)
 */
function createLoading(showLoading) {
    var loadingMessage =  '
Loading...
';
    var savingMessage = '
Saving...
';

    var methodToCall = jq("input[name='methodToCall']").val();
    var unblockUIOnLoading = jq("input[name='unblockUIOnLoading']").val();

    if (unblockUIOnLoading == null || unblockUIOnLoading.toUpperCase() == "false".toUpperCase()) {
        if (top == self) {
            //no portal
            if (showLoading) {
                if (methodToCall && methodToCall.toUpperCase() == "save".toUpperCase()) {
                    jq.blockUI({message: savingMessage});
                }
                else {
                    jq.blockUI({message: loadingMessage});
                }
            }
            else {
                jq.unblockUI();
            }
        }
        else if (top.jq == null) {
            if (showLoading) {
                if (methodToCall && methodToCall.toUpperCase() == "save".toUpperCase()) {
                    top.$.blockUI({message: savingMessage});
                }
                else {
                    top.$.blockUI({message: loadingMessage});
                }
            }
            else {
                top.$.unblockUI();
            }
        }
        else {
            if (showLoading) {
                if (methodToCall && methodToCall.toUpperCase() == "save".toUpperCase()) {
                    top.jq.blockUI({message: savingMessage});
                }
                else {
                    top.jq.blockUI({message: loadingMessage});
                }
            }
            else {
                top.jq.unblockUI();
            }
        }
    }
}

function clearServerErrorColors(errorDivId){
    if (errorDivId) {
        var div = jq("#" + errorDivId);
        var label = jq("#" + errorDivId.replace("errors_div", "label"));
        var highlightLine = "";

        //check to see if the option to highlight fields is on
        if (div.length > 0 && !div.hasClass("noHighlight")) {
            if (div.parent().is("td") || (div.parent().is(".refreshWrapper") && div.parent().parent().is("td"))) {
                highlightLine = div.closest("td");
            }
            else {
                highlightLine = div.closest(".fieldLine");
            }

            if (highlightLine.length > 0) {
                highlightLine.removeClass("kr-serverError");
            }
        }
    }
}

/**
 * Applies the error coloring for fields with errors, warnings, or information
 */
function applyErrorColors(errorDivId, errorNum, warningNum, infoNum, clientSide) {
    if (errorDivId) {
        var div = jq("#" + errorDivId);
        var label = jq("#" + errorDivId.replace("errors_div", "label"));
        var highlightLine = "";

        //check to see if the option to highlight fields is on
        if (div.length > 0 && !div.hasClass("noHighlight")) {
            if (div.parent().is("td") || (div.parent().is(".refreshWrapper") && div.parent().parent().is("td"))) {
                highlightLine = div.closest("td");
            }
            else {
                highlightLine = div.closest(".fieldLine");
            }

            if (highlightLine.length > 0) {

                if (errorNum && !clientSide) {

                    highlightLine.addClass("kr-serverError");
                    label.addClass("kr-serverError");
                }
                else if (errorNum) {
                    highlightLine.addClass("kr-clientError");
                    label.addClass("kr-clientError");
                }
                else if (warningNum) {
                    highlightLine.addClass("kr-warning");
                    label.addClass("kr-warning");
                }
                else if (infoNum) {
                    highlightLine.addClass("kr-information");
                    label.addClass("kr-information");
                }
                else {
                    //we are only removing errors client side - no knowledge of warnings/infos
                    if (div.parent().hasClass("kr-errorsField")) {
                        var error_ul = div.parent().find(".kr-errorMessages").find("ul.errorLines");
                        var moreErrors = false;
                        error_ul.each(function() {
                            jq(this).children().each(function() {
                                if (jq(this).css("display") != "none") {
                                    moreErrors = true;
                                    return false;
                                }
                            });
                            if (moreErrors) {
                                return false;
                            }
                        });

                        label.removeClass("kr-clientError");
                        if (!moreErrors) {
                            highlightLine.removeClass("kr-clientError");
                        }
                    }
                    else {
                        highlightLine.removeClass("kr-clientError");
                        label.removeClass("kr-clientError");
                    }
                }
            }
        }

        //highlight tab that contains errors - no setting to turn this off because it is necessary
        var tabDiv = div.closest(".ui-tabs-panel");
        if (tabDiv.length > 0) {
            var tabId = tabDiv.attr("id");
            var tabAnchor = jq("a[href='#" + tabId + "']");
            var errorIcon = jq("#" + tabId + "_errorIcon");

            if (tabAnchor.length > 0) {
                var hasErrors = false;
                if (errorNum) {
                    hasErrors = true;
                }
                else {
                    var error_li = tabDiv.find(".kr-errorMessages").find("li");
                    error_li.each(function() {
                        if (jq(this).css("display") != "none") {
                            hasErrors = true;
                        }
                    });
                }

                if (hasErrors) {
                    tabAnchor.addClass("kr-clientError");
                    if (errorIcon.length == 0) {
                        tabAnchor.append("");
                    }
                }
                else if (!hasErrors) {
                    tabAnchor.removeClass("kr-clientError");
                    errorIcon.remove();
                }
            }
        }
    }
}

/**
 * Shows the field error icon if errorCount is greater than one and errorsField
 * has the option turned on
 */
function showFieldIcon(errorsDivId, errorCount) {
    if (errorsDivId) {
        var div = jq("#" + errorsDivId);
        var inputId = errorsDivId.replace("_errors_div", "");

        if (inputId) {
            var input = jq("#" + inputId);
            var errorIcon = jq("#" + inputId + "_errorIcon");

            if (div.length > 0 && div.hasClass("addFieldIcon") && errorCount && errorIcon.length == 0) {
                if (input.length > 0) {
                    input.after("");
                }
                else {
                    // try for radios and checkboxes
                    input = jq("#" + errorDivId.replace("errors_div", "attribute1"));
                    if (input.length > 0) {
                        input.after("");
                    }
                }
            }
            else if (div.length > 0 && div.hasClass("addFieldIcon") && errorCount == 0) {
                if (errorIcon.length > 0) {
                    errorIcon.remove();
                }
            }
        }
    }
}

/**
 * Adds the icon that indicates the contents of a field have changed from the compared value (for instance the new side
 * on maintenance documents) to the field markers span
 *
 * @param fieldId - id for the field the icon should be added to
 */
function showChangeIcon(fieldId) {
    var fieldMarkerSpan = jq("#" + fieldId + "_attribute_markers");
    var fieldIcon = jq("#" + fieldId + "_changeIcon");

    if (fieldMarkerSpan.length > 0 && fieldIcon.length == 0) {
        fieldMarkerSpan.append("");
    }
}

/**
 * Add icon to a group header that indicates the data for the group has changed
 *
 * @param headerFieldId - id for the header field the icon should be added to
 */
function showChangeIconOnHeader(headerFieldId) {
    var headerSpan = jq("#" + headerFieldId + "_header");
    var headerIcon = jq("#" + headerFieldId + "_changeIcon");

    if (headerSpan.length > 0 && headerIcon.length == 0) {
        headerSpan.append("");
    }
}

// Applies the watermark to the input with the id specified
function createWatermark(id, watermark) {
    jq("#" + id).watermark(watermark);
}

/**
 * If the content is an incident report view, replaces the current view with the incident report and
 * returns true, otherwise returns false
 *
 * @param content
 * @returns {Boolean} true if there was an incident, false otherwise
 */
function handleIncidentReport(content) {
    var viewId = jq("#viewId", content);
    if (viewId.length && viewId.val() === "Uif-IncidentReportView") {
        jq('#view_div').replaceWith(content);
        runHiddenScripts("view_div");
        return true;
    }
    else {
        return false;
    }
}<|endoftext|>