<commit_before>define(function (require, exports, module) {

var _ = require('underscore');
var $ = require('jquery');
var marionette = require('marionette');
var backbone = require('backbone');
var RenderNode = require('famous/core/RenderNode');
var ContainerSurface = require('famous/surfaces/ContainerSurface');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var Transform = require('famous/core/Transform');
var Entity = require('famous/core/Entity');
var Context = require('famous/core/Context');
var Engine = require('famous/core/Engine');
var events = require('./events');

var FamousView = marionette.View.extend({

    //size: null,
    nestedSubviews: false,
    shouldInitializeRenderable: false,
    modifier: null,
    zIndex: 1,
    superview: null,
    subviews: null,
    root: null,
    context: null,
    _spec: null,
    _needsDisplay: false,

    // we need to own initialize, this includes marionette.View()
    // AND backbone.View()
    constructor: function(options){
        options || (options = {});

        this.children = this.subviews = new backbone.ChildViewContainer();

        /* >>> BEGIN marionette.View() override */
         _.bindAll(this, 'render');

        // this exposes view options to the view initializer
        // this is a backfill since backbone removed the assignment
        // of this.options
        // at some point however this may be removed
        this.options = _.extend({}, _.result(this, 'options'), _.isFunction(options) ? options.call(this) : options);
        // parses out the @ui DSL for events
        this.events = this.normalizeUIKeys(_.result(this, 'events'));

        if (_.isObject(this.behaviors)) {
          new marionette.Behaviors(this);
        }

        // we explicitely defer the full backbone.View initialization
        // till later... we only need parts of it now.

        /* >>> BEGIN backbone.View() override */

        // we are literally taking everything from Backbone.View's constructor
        // except _ensureElement and delegateEvents
        // the famous context may not be available on this view yet,
        // in which case we cannot cerate the famous element ($el)
        // and we can't delegateEvents if we have no $el.

        this.cid = _.uniqueId('view');

        // duplicating this from backbone, don't readily see another way to grab it. =(
        // we only add 'context' for a convenience

        var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
        var richOptions = ['context', 'modifier', 'nestedSubviews'];
        var propertyOptions = ['size'];
        var styleOptions = ['zIndex'];

        // conform to famous surface property structure,
        // the naming here is unfortunate for now.
        this.properties = {properties: {}};

        _.extend(this, _.pick(options, viewOptions.concat(styleOptions, richOptions)));
        _.extend(this.properties, _.pick(options, propertyOptions));

        this.properties.size = _.result(this.properties, 'size') || _.result(this, 'size');
        this.properties.properties.zIndex = this.zIndex;

        this.initialize.apply(this, arguments);

        /* <<< END backbone.View() */
        marionette.MonitorDOMRefresh(this);
        this.listenTo(this, 'show', this.onShowCalled);
        /* <<< END marionette.View() override */
    },

    _prepareModification: function(duration, requireModifier){
        if(requireModifier !== false) requireModifier = true;

        var deferred = $.Deferred();

        if(!this.modifier && requireModifier){
            throw new Error('Please set a modifier on the view');
        }

        var self = this;

        var tick = function(){
            self._render();
        };

        var callback = function(){
            Engine.removeListener('postrender', tick);
            deferred.resolve(this);
        }.bind(this);

        if(!duration){
            this._render();
        }else{
            Engine.on('postrender', tick);
        }

        return {deferred: deferred.promise(), callback: callback};
    },

    setTransform: function(transform, transition, index){
        index || (index = 0);

        var target;
        var duration = transition && transition.duration ? transition.duration : null;
        var obj = this._prepareModification(duration);

        if(_.isArray(this._modifier)){
            target = this._modifier[index];
        } else {
            target = this._modifier;
        }

        target.setTransform(transform, transition, obj.callback);

        return obj.deferred;
    },

    getFamousId: function(){
        if(this.renderable){
            return this.renderable.id;
        }

        return null;
    },

    render: function(){
        if(this.root === null || this.needsDisplay()){
            this._render();
        }
        return this._spec;
    },

    invalidate: function(){
        this._render();
        this.triggerRichInvalidate();
    },

    _render: function(){
        var spec;
        this.root = this.createRenderNode();

        spec = this.root.render();
        this._spec = spec;
        this.triggerRichRender();
    },

    triggerRichRender: function(){
        this.trigger(events.RENDER, this);
    },

    triggerRichInvalidate: function(){
        this.trigger(events.INVALIDATE, this);
    },

    needsDisplay: function(){
        return this._needsDisplay;
    },

    setNeedsDisplay: function(value){
        this._needsDisplay = value;
    },

    resetNestedNode: function(container){
        var resetNode = new RenderNode();
        var currentNode = container.context._node;
        resetNode._prevResults = currentNode._prevResults || {};
        resetNode._resultCache = resetNode._prevResults;
        container.context._node = resetNode;
    },

    createNestedNode: function(context){
        var container = new ContainerSurface(this.properties);

        if(!this.renderable){
            this._ensureElement(container, context);
        }

        if (this.className){
            container.addClass(_.result(this, 'className'));
        }

        return container;
    },

    applyModifiers: function(modifiers, node){
        if(_.isArray(modifiers)){

            _.each(modifiers, function(modifier){
                node = node.add(modifier);
            });

        } else {
            node = node.add(modifiers);
        }

        return node;
    },

    createRenderNode: function(){
        var root = new RenderNode();
        var relative = root;
        var context = this.context;

        if(this.modifier){
            var modifiers = _.result(this, 'modifier');
            relative = this.applyModifiers(modifiers, root);

            this._modifier = modifiers;
        }

        if(this.nestedSubviews){
            if(!this.container){
                this.container = this.createNestedNode(this.context);
            }

            this.resetNestedNode(this.container);

            relative.add(this.container);
            context = this.container.context;
            relative = this.container;
        }

        if(!this.renderable && _.result(this, 'shouldInitializeRenderable')){
            this.renderable = this.initializeRenderable();
        }

        if(this.renderable){
            relative.add(this.renderable);
        }

        this.children.each(function(view){
            view.context = context;
            view.superview = this;
            relative.add(view);
        }, this);

        return root;
    },

    addSubview: function(view, zIndex){

        function setZIndex(value){
            view.zIndex = value;
            view.properties.properties.zIndex = value;
        }

        if(!zIndex && view.zIndex <= this.zIndex){
            setZIndex(this.zIndex + 1);
        } else if(zIndex){
            setZIndex(zIndex);
        }

        this.listenTo(view, events.INVALIDATE, this.subviewDidChange);
        this.children.add(view);

        if(this.root){
            this.invalidate();
        }
    },

    subviewDidChange: function(view){
        // consider an alternate way to index this information?
        // so we don't have to step through the array each time?
        // might not be worth it, might be worth it.
        // we'd need to keep that index up to date, so it
        // might be more housekeeping than is worth it.

        if(this._spec === null) this._spec = [];

        var spec = view._spec;

        var arr = this._spec.target || this._spec;
        var famousId = view.getFamousId();

        // this is a view without a renderable
        if(famousId === null && _.isArray(this._spec)){

            if(_.isNull(spec) || _.isArray(spec)){
                this._spec = spec;
            } else {
                this._spec.push(spec);
            }
            this.triggerRichInvalidate();
            return;
        }

        for(var i=1; i < arr.length; i++){
            var obj = arr[i];
            var id;

            if(_.isNumber(obj)){
                id = obj;
            } else if (_.isNumber(obj.target)){
                id = obj.target;
            } else if(_.isArray(obj.target)) {
                id = obj.target[0];
            } else {
                console.log(obj);
                throw new Error('An unexpected error occured '+
                                'when updating render spec.');
            }

            if(id == famousId){
                arr[i] = spec;
                break;
            }
        }

        this.triggerRichInvalidate();
    },

    removeSubview: function(view){
        this.children.remove(view);
        this.stopListening(view, events.INVALIDATE, this.subviewDidChange);

        if(this.root){
            this.invalidate();
        }
    },

    removeFromSuperview: function(){
        this.superview.removeSubview(this);
    },

    setSize: function(value){
        this.properties.size = value;

        if(this.root){
            this.invalidate();
        }
    },

    getSize: function(){
        if(!this.properties.size){
            this.properties.size = _.result(this.properties, 'size') || [undefined, undefined];
        }

        return this.properties.size;
    },

    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` properties.
    _ensureElement: function(renderable, context) {
      if (!this.el) {
        // this wrongly assumes it will always have a
        // .commit function. Will need to poribably rethink this.

        if (this.className){
            renderable.addClass(_.result(this, 'className'));
        }

        if(!renderable._currTarget){
            renderable.setup(context._allocator);
        }

        var $el = $(renderable._currTarget);

        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');

        // var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
        $el.attr(attrs);
        this.setElement($el, false);
      } else {
        this.setElement(_.result(this, 'el'), false);
      }

      // this is a new event for rich.
      // a FamousView with nestedSubviews will have
      // an $el, but a FamousView that does not have
      // nestedSubviews enabled will not have an $el.
      // onElement is what you want if you need to know about
      // weather or not an element is available.
      this.triggerMethod('element', this);
    },

    // override Backbone.View.remove()
    remove: function(){
        // Famo.us recycles elements, removing the $el
        // here has a high chance of causing problems.
        // otherwise this is basically the same as
        // Backbone.View.remove()

        // this.$el.remove();
        this.children = null;
        this.root = null;
        this.undelegateEvents();
        this.stopListening();
        return this;
    },

});
exports.FamousView = FamousView;

});
<commit_msg>moving undelegateEvents function into $el conditional<commit_after>define(function (require, exports, module) {

var _ = require('underscore');
var $ = require('jquery');
var marionette = require('marionette');
var backbone = require('backbone');
var RenderNode = require('famous/core/RenderNode');
var ContainerSurface = require('famous/surfaces/ContainerSurface');
var Surface = require('famous/core/Surface');
var Modifier = require('famous/core/Modifier');
var Transform = require('famous/core/Transform');
var Entity = require('famous/core/Entity');
var Context = require('famous/core/Context');
var Engine = require('famous/core/Engine');
var events = require('./events');

var FamousView = marionette.View.extend({

    //size: null,
    nestedSubviews: false,
    shouldInitializeRenderable: false,
    modifier: null,
    zIndex: 1,
    superview: null,
    subviews: null,
    root: null,
    context: null,
    _spec: null,
    _needsDisplay: false,

    // we need to own initialize, this includes marionette.View()
    // AND backbone.View()
    constructor: function(options){
        options || (options = {});

        this.children = this.subviews = new backbone.ChildViewContainer();

        /* >>> BEGIN marionette.View() override */
         _.bindAll(this, 'render');

        // this exposes view options to the view initializer
        // this is a backfill since backbone removed the assignment
        // of this.options
        // at some point however this may be removed
        this.options = _.extend({}, _.result(this, 'options'), _.isFunction(options) ? options.call(this) : options);
        // parses out the @ui DSL for events
        this.events = this.normalizeUIKeys(_.result(this, 'events'));

        if (_.isObject(this.behaviors)) {
          new marionette.Behaviors(this);
        }

        // we explicitely defer the full backbone.View initialization
        // till later... we only need parts of it now.

        /* >>> BEGIN backbone.View() override */

        // we are literally taking everything from Backbone.View's constructor
        // except _ensureElement and delegateEvents
        // the famous context may not be available on this view yet,
        // in which case we cannot cerate the famous element ($el)
        // and we can't delegateEvents if we have no $el.

        this.cid = _.uniqueId('view');

        // duplicating this from backbone, don't readily see another way to grab it. =(
        // we only add 'context' for a convenience

        var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
        var richOptions = ['context', 'modifier', 'nestedSubviews'];
        var propertyOptions = ['size'];
        var styleOptions = ['zIndex'];

        // conform to famous surface property structure,
        // the naming here is unfortunate for now.
        this.properties = {properties: {}};

        _.extend(this, _.pick(options, viewOptions.concat(styleOptions, richOptions)));
        _.extend(this.properties, _.pick(options, propertyOptions));

        this.properties.size = _.result(this.properties, 'size') || _.result(this, 'size');
        this.properties.properties.zIndex = this.zIndex;

        this.initialize.apply(this, arguments);

        /* <<< END backbone.View() */
        marionette.MonitorDOMRefresh(this);
        this.listenTo(this, 'show', this.onShowCalled);
        /* <<< END marionette.View() override */
    },

    _prepareModification: function(duration, requireModifier){
        if(requireModifier !== false) requireModifier = true;

        var deferred = $.Deferred();

        if(!this.modifier && requireModifier){
            throw new Error('Please set a modifier on the view');
        }

        var self = this;

        var tick = function(){
            self._render();
        };

        var callback = function(){
            Engine.removeListener('postrender', tick);
            deferred.resolve(this);
        }.bind(this);

        if(!duration){
            this._render();
        }else{
            Engine.on('postrender', tick);
        }

        return {deferred: deferred.promise(), callback: callback};
    },

    setTransform: function(transform, transition, index){
        index || (index = 0);

        var target;
        var duration = transition && transition.duration ? transition.duration : null;
        var obj = this._prepareModification(duration);

        if(_.isArray(this._modifier)){
            target = this._modifier[index];
        } else {
            target = this._modifier;
        }

        target.setTransform(transform, transition, obj.callback);

        return obj.deferred;
    },

    getFamousId: function(){
        if(this.renderable){
            return this.renderable.id;
        }

        return null;
    },

    render: function(){
        if(this.root === null || this.needsDisplay()){
            this._render();
        }
        return this._spec;
    },

    invalidate: function(){
        this._render();
        this.triggerRichInvalidate();
    },

    _render: function(){
        var spec;
        this.root = this.createRenderNode();

        spec = this.root.render();
        this._spec = spec;
        this.triggerRichRender();
    },

    triggerRichRender: function(){
        this.trigger(events.RENDER, this);
    },

    triggerRichInvalidate: function(){
        this.trigger(events.INVALIDATE, this);
    },

    needsDisplay: function(){
        return this._needsDisplay;
    },

    setNeedsDisplay: function(value){
        this._needsDisplay = value;
    },

    resetNestedNode: function(container){
        var resetNode = new RenderNode();
        var currentNode = container.context._node;
        resetNode._prevResults = currentNode._prevResults || {};
        resetNode._resultCache = resetNode._prevResults;
        container.context._node = resetNode;
    },

    createNestedNode: function(context){
        var container = new ContainerSurface(this.properties);

        if(!this.renderable){
            this._ensureElement(container, context);
        }

        if (this.className){
            container.addClass(_.result(this, 'className'));
        }

        return container;
    },

    applyModifiers: function(modifiers, node){
        if(_.isArray(modifiers)){

            _.each(modifiers, function(modifier){
                node = node.add(modifier);
            });

        } else {
            node = node.add(modifiers);
        }

        return node;
    },

    createRenderNode: function(){
        var root = new RenderNode();
        var relative = root;
        var context = this.context;

        if(this.modifier){
            var modifiers = _.result(this, 'modifier');
            relative = this.applyModifiers(modifiers, root);

            this._modifier = modifiers;
        }

        if(this.nestedSubviews){
            if(!this.container){
                this.container = this.createNestedNode(this.context);
            }

            this.resetNestedNode(this.container);

            relative.add(this.container);
            context = this.container.context;
            relative = this.container;
        }

        if(!this.renderable && _.result(this, 'shouldInitializeRenderable')){
            this.renderable = this.initializeRenderable();
        }

        if(this.renderable){
            relative.add(this.renderable);
        }

        this.children.each(function(view){
            view.context = context;
            view.superview = this;
            relative.add(view);
        }, this);

        return root;
    },

    addSubview: function(view, zIndex){

        function setZIndex(value){
            view.zIndex = value;
            view.properties.properties.zIndex = value;
        }

        if(!zIndex && view.zIndex <= this.zIndex){
            setZIndex(this.zIndex + 1);
        } else if(zIndex){
            setZIndex(zIndex);
        }

        this.listenTo(view, events.INVALIDATE, this.subviewDidChange);
        this.children.add(view);

        if(this.root){
            this.invalidate();
        }
    },

    subviewDidChange: function(view){
        // consider an alternate way to index this information?
        // so we don't have to step through the array each time?
        // might not be worth it, might be worth it.
        // we'd need to keep that index up to date, so it
        // might be more housekeeping than is worth it.

        if(this._spec === null) this._spec = [];

        var spec = view._spec;

        var arr = this._spec.target || this._spec;
        var famousId = view.getFamousId();

        // this is a view without a renderable
        if(famousId === null && _.isArray(this._spec)){

            if(_.isNull(spec) || _.isArray(spec)){
                this._spec = spec;
            } else {
                this._spec.push(spec);
            }
            this.triggerRichInvalidate();
            return;
        }

        for(var i=1; i < arr.length; i++){
            var obj = arr[i];
            var id;

            if(_.isNumber(obj)){
                id = obj;
            } else if (_.isNumber(obj.target)){
                id = obj.target;
            } else if(_.isArray(obj.target)) {
                id = obj.target[0];
            } else {
                console.log(obj);
                throw new Error('An unexpected error occured '+
                                'when updating render spec.');
            }

            if(id == famousId){
                arr[i] = spec;
                break;
            }
        }

        this.triggerRichInvalidate();
    },

    removeSubview: function(view){
        this.children.remove(view);
        this.stopListening(view, events.INVALIDATE, this.subviewDidChange);

        if(this.root){
            this.invalidate();
        }
    },

    removeFromSuperview: function(){
        this.superview.removeSubview(this);
    },

    setSize: function(value){
        this.properties.size = value;

        if(this.root){
            this.invalidate();
        }
    },

    getSize: function(){
        if(!this.properties.size){
            this.properties.size = _.result(this.properties, 'size') || [undefined, undefined];
        }

        return this.properties.size;
    },

    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` properties.
    _ensureElement: function(renderable, context) {
      if (!this.el) {
        // this wrongly assumes it will always have a
        // .commit function. Will need to poribably rethink this.

        if (this.className){
            renderable.addClass(_.result(this, 'className'));
        }

        if(!renderable._currTarget){
            renderable.setup(context._allocator);
        }

        var $el = $(renderable._currTarget);

        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');

        // var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
        $el.attr(attrs);
        this.setElement($el, false);
      } else {
        this.setElement(_.result(this, 'el'), false);
      }

      // this is a new event for rich.
      // a FamousView with nestedSubviews will have
      // an $el, but a FamousView that does not have
      // nestedSubviews enabled will not have an $el.
      // onElement is what you want if you need to know about
      // weather or not an element is available.
      this.triggerMethod('element', this);
    },

    // override Backbone.View.remove()
    remove: function(){
        // Famo.us recycles elements, removing the $el
        // here has a high chance of causing problems.
        // otherwise this is basically the same as
        // Backbone.View.remove()

        // this.$el.remove();
        this.children = null;
        this.root = null;
        if(this.$el){
            this.undelegateEvents();
        }
        this.stopListening();
        return this;
    },

});
exports.FamousView = FamousView;

});
<|endoftext|>


<commit_before>// [START sd_logging_import]
const { Logging } = require('@google-cloud/logging');
// [END sd_logging_import]
const functions = require('firebase-functions');

// [START sd_example_function]
exports.helloError = functions.https.onRequest((request, response) => {
  console.log('I am a log entry!');
  response.send('Hello World...');
});
// [END sd_example_function]

// [START sd_logging_setup]
// Instantiate the StackDriver Logging SDK. The project ID will
// be automatically inferred from the Cloud Functions environment.
const logging = new Logging();
const log = logging.log('my-custom-log-name');

// This metadata is attached to each log entry. This specifies a fake
// Cloud Function called 'Custom Metrics' in order to make your custom
// log entries appear in the Cloud Functions logs viewer.
const METADATA = {
  resource: {
    type: 'cloud_function',
    labels: {
      function_name: 'CustomMetrics',
      region: 'us-central1'
    }
  }
};
// [END sd_logging_setup]

function writeLog() {
  // [START sd_write_log]
  // Data to write to the log. This can be a JSON object with any properties
  // of the event you want to record.
  const data = {
    event: 'my-event',
    value: 'foo-bar-baz',

    // Optional 'message' property will show up in the Firebase
    // console and other human-readable logging surfaces
    message: 'my-event: foo-bar-baz'
  };

  // Write to the log. The log.write() call returns a Promise if you want to
  // make sure that the log was written successfully.
  const entry = log.entry(METADATA, data);
  log.write(entry);
  // [END sd_write_log]
}
<commit_msg>Remove reference to obsolete Stackdriver branding (#241)<commit_after>// [START sd_logging_import]
const { Logging } = require('@google-cloud/logging');
// [END sd_logging_import]
const functions = require('firebase-functions');

// [START sd_example_function]
exports.helloError = functions.https.onRequest((request, response) => {
  console.log('I am a log entry!');
  response.send('Hello World...');
});
// [END sd_example_function]

// [START sd_logging_setup]
// Instantiate the logging SDK. The project ID will
// be automatically inferred from the Cloud Functions environment.
const logging = new Logging();
const log = logging.log('my-custom-log-name');

// This metadata is attached to each log entry. This specifies a fake
// Cloud Function called 'Custom Metrics' in order to make your custom
// log entries appear in the Cloud Functions logs viewer.
const METADATA = {
  resource: {
    type: 'cloud_function',
    labels: {
      function_name: 'CustomMetrics',
      region: 'us-central1'
    }
  }
};
// [END sd_logging_setup]

function writeLog() {
  // [START sd_write_log]
  // Data to write to the log. This can be a JSON object with any properties
  // of the event you want to record.
  const data = {
    event: 'my-event',
    value: 'foo-bar-baz',

    // Optional 'message' property will show up in the Firebase
    // console and other human-readable logging surfaces
    message: 'my-event: foo-bar-baz'
  };

  // Write to the log. The log.write() call returns a Promise if you want to
  // make sure that the log was written successfully.
  const entry = log.entry(METADATA, data);
  log.write(entry);
  // [END sd_write_log]
}
<|endoftext|>


<commit_before>/*
  Copyright 2008 Google Inc.

  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.
*/

// global vars
var gModeAMPM = null;
var gAlarmAM = null;
var gAlarmDefault = null;
var gRevertKeypress = false;
var gSavedEditValue = "";

/**
 * Method called when options are opened
 */
function onOpen() {
  oString1.innerText = ALARM_SET;
  oString2.innerText = DEFAULT_ALARM;
  oString3.innerText = USE_FILE;
  oString5.innerText = CITY + ":";
  oString6.innerText = DISPLAY_WORLD;
  oString7.innerText = BROWSE;
  oStringAM.innerText = AM;
  oStringPM.innerText = PM;

  oCheckbox1.value = options.getValue(OPT_ALARM);
  gAlarmDefault = options.getValue(OPT_DEFAULT_RINGER);
  oFilePath.value = options.getValue(OPT_FILE_PATH);
  oCityName.value = options.getValue(OPT_ADDRESS);

  gModeAMPM = options.getValue(OPT_MODE) == MODE_AMPM ? true : false;
  oAMPM.visible = gModeAMPM;

  var hours = options.getValue(OPT_HOURS);
  gAlarmAM = hours < 12 ? true : false;

  if (gModeAMPM && hours > 12) {
    hours = hours - 12;
  }

  if (gAlarmAM && gModeAMPM && hours == 0) {
    hours = 12;
  }

  oHours.value = timeString(hours);
  oMinutes.value = timeString(options.getValue(OPT_MINUTES));

  if (gAlarmAM) {
    oAM.src = "images\\radiobutton_chk.png";
    oPM.src = "images\\radiobutton.png";
  } else {
    oAM.src = "images\\radiobutton.png";
    oPM.src = "images\\radiobutton_chk.png";
  }

  if (gAlarmDefault) {
    oCheckbox2.src = "images\\radiobutton_chk.png";
    oCheckbox3.src = "images\\radiobutton.png";
  } else {
    oCheckbox2.src = "images\\radiobutton.png";
    oCheckbox3.src = "images\\radiobutton_chk.png";
  }

  if (oCheckbox1.value) {
    oAlarmOptions.visible = true;
    if (gAlarmDefault) {
      oFileOptions.visible = false;
    } else {
      oFileOptions.visible = true;
    }
  } else {
    oAlarmOptions.visible = false;
  }
}

/**
 * Method called when user hits "ok" button
 */
function _onOk() {
  // check validity of file path
  var path = oFilePath.value;
  if (oCheckbox1.value && !gAlarmDefault) {
    var fso;
    fso = framework.system.filesystem;
    if (!fso.FileExists(path)) {
      gAlarmDefault = true;
    }
  }

  debug.trace(oHours.value + ":" + oMinutes.value);
  var hours = -1;
  var minutes = -1;

  try {
    hours = Math.floor(parseFloat(oHours.value));
  } catch(e) {
    hours = -1;
  }

  try {
    minutes = Math.floor(parseFloat(oMinutes.value));
  } catch(e) {
    minutes = -1;
  }

  // Convert hours as necesary for am/pm business
  if (gModeAMPM && !gAlarmAM && hours != 12) {
    hours += 12;
  }

  if (gModeAMPM && gAlarmAM && hours == 12) {
    hours -= 12;
  }

  // Checks for bad hours and minutes inputs.
  // This should never happen, but handle just in case
  if (!(hours >= 0 && hours < 25)) {
    hours = 12;
  }

  if (!(minutes >= 0 && minutes <= 59)) {
    minutes = 0;
  }

  options.putValue(OPT_ALARM, oCheckbox1.value);
  options.putValue(OPT_DEFAULT_RINGER, gAlarmDefault);
  options.putValue(OPT_FILE_PATH, oFilePath.value);
  options.putValue(OPT_CITY, oCityName.value);
  options.putValue(OPT_HOURS, hours);
  options.putValue(OPT_MINUTES, minutes);
}

/**
 * Called when user hits cancel button
 */
function _onCancel() {
}

/**
 * Called when alarm checkbox changes
 */
function _alarmChk() {
  if (oCheckbox1.value) {
    oAlarmOptions.visible = true;
    if (gAlarmDefault) {
      oFileOptions.visible = false;
    } else {
      oFileOptions.visible = true;
    }
  } else {
    oAlarmOptions.visible = false;
  }
}

/**
 * Handles default alarm checkbox click
 */
function _defaultAlarmChk() {
  debug.trace("check default");
  gAlarmDefault = true;
  oCheckbox2.src = "images\\radiobutton_chk.png";
  oCheckbox3.src = "images\\radiobutton.png";
  if (oCheckbox1.value) {
    oAlarmOptions.visible = true;
    if (gAlarmDefault) {
      oFileOptions.visible = false;
    } else {
      oFileOptions.visible = true;
    }
  } else {
    oAlarmOptions.visible = false;
  }
}

/**
 * Handles use file checkbox click
 */
function _useFileChk() {
  debug.trace("check file");
  gAlarmDefault = false;
  oCheckbox2.src = "images\\radiobutton.png";
  oCheckbox3.src = "images\\radiobutton_chk.png";
  if (oCheckbox1.value) {
    oAlarmOptions.visible = true;
    if (gAlarmDefault) {
      oFileOptions.visible = false;
    } else {
      oFileOptions.visible = true;
    }
  } else {
    oAlarmOptions.visible = false;
  }
}

/**
 * Handles AM checkbox click
 */
function _amChk() {
  debug.trace("check am");
  gAlarmAM = true;
  oAM.src = "images\\radiobutton_chk.png";
  oPM.src = "images\\radiobutton.png";
}

/**
 * Handles PM checkbox click
 */
function _pmChk() {
  debug.trace("check pm");
  gAlarmAM = false;
  oAM.src = "images\\radiobutton.png";
  oPM.src = "images\\radiobutton_chk.png";
}

/**
 * checkbox change
 */
function chkchange() {
  debug.trace("am: " + oAM.value + " pm: " + oPM.value + " def: " + oCheckbox2.value + " fil: " + oCheckbox3.value);
}

/**
 * Turns an int into a 2 digit time string
 * @param {Number} n is a time field
 */
function timeString(n) {
  if (n < 10) {
    return "0" + n;
  } else {
    return "" + n;
  }
}

/**
 * Open a browse dialog
 */
function _doBrowse() {
  debug.trace("launch browse");
  var file = BrowseForFile("Music Files|*.mp3;*.wma;*.wav");
  oFilePath.value = file;
}

/**
 * Handles event that gives keycode of what's about to be entered into time box
 * @param {String} id 'h' for hours and 'm' for minutes tells which box
 */
function _keyPress(id) {
  var elem;
  if (id == 'h') {
    elem = oHours;
  } else {
    elem = oMinutes;
  }

  gSavedEditValue = elem.value;

  if (event.keycode == 9) {
    gRevertKeypress = true;
    if (id == 'h') {
      // give focus to minutes
      gSavedEditValue = oMinutes.value;
      oMinutes.focus();
    }
  } else if (event.keycode == 35 ||
             event.keycode == 36 ||
             event.keycode == 46 ||
             event.keycode == 8 ||
             (event.keycode > 47 && event.keycode < 58) ||
             (event.keycode > 95 && event.keycode < 106)) {
    gRevertKeypress = false;
  } else {
    gRevertKeypress = true;
  }
}

/**
 * Handles event that fires after change to time box is made
 * @param {String} id 'h' for hours and 'm' for minutes
 */
function _valueChange(id) {
  var elem;
  var numValue;

  if (id == 'h') {
    elem = oHours;
  } else {
    elem = oMinutes;
  }

  if (gRevertKeypress || elem.value.length > 2) {
    elem.value = gSavedEditValue;
  }

  try {
    numValue = parseInt(elem.value);
    if (id == 'h') {
      if (gModeAMPM && numValue > 12) {
        gRevertKeypress = true;
      } else if (numValue > 23) {
        gRevertKeypress = true;
      }
    } else if (id == 'm') {
      if (numValue > 59) {
        gRevertKeypress = true;
      }
    }
  } catch(e) {
    gRevertKeypress = true;
  }

  if (gRevertKeypress) {
    elem.value = gSavedEditValue;
  }

  gRevertKeypress = false;
}

/**
 * Handles key down for path edit box
 */
function _pathKeyDown() {
  // Save value prior to change
  gRevertKeypress = true;
  gSavedEditValue = oFilePath.value;
}

/**
 * Handles value change for path edit box
 */
function _pathChange() {
  // don't allow user to edit value.
  // revert changes while still letting user navigate box
  if (oFilePath.value != gSavedEditValue && gRevertKeypress) {
    oFilePath.value = gSavedEditValue;
  }

  gRevertKeypress = false;
}
<commit_msg> r1617@suzhe:  suzhe | 2010-01-15 09:55:44 +0800  Fix a typo.  <commit_after>/*
  Copyright 2008 Google Inc.

  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.
*/

// global vars
var gModeAMPM = null;
var gAlarmAM = null;
var gAlarmDefault = null;
var gRevertKeypress = false;
var gSavedEditValue = "";

/**
 * Method called when options are opened
 */
function _onOpen() {
  oString1.innerText = ALARM_SET;
  oString2.innerText = DEFAULT_ALARM;
  oString3.innerText = USE_FILE;
  oString5.innerText = CITY + ":";
  oString6.innerText = DISPLAY_WORLD;
  oString7.innerText = BROWSE;
  oStringAM.innerText = AM;
  oStringPM.innerText = PM;

  oCheckbox1.value = options.getValue(OPT_ALARM);
  gAlarmDefault = options.getValue(OPT_DEFAULT_RINGER);
  oFilePath.value = options.getValue(OPT_FILE_PATH);
  oCityName.value = options.getValue(OPT_ADDRESS);

  gModeAMPM = options.getValue(OPT_MODE) == MODE_AMPM ? true : false;
  oAMPM.visible = gModeAMPM;

  var hours = options.getValue(OPT_HOURS);
  gAlarmAM = hours < 12 ? true : false;

  if (gModeAMPM && hours > 12) {
    hours = hours - 12;
  }

  if (gAlarmAM && gModeAMPM && hours == 0) {
    hours = 12;
  }

  oHours.value = timeString(hours);
  oMinutes.value = timeString(options.getValue(OPT_MINUTES));

  if (gAlarmAM) {
    oAM.src = "images\\radiobutton_chk.png";
    oPM.src = "images\\radiobutton.png";
  } else {
    oAM.src = "images\\radiobutton.png";
    oPM.src = "images\\radiobutton_chk.png";
  }

  if (gAlarmDefault) {
    oCheckbox2.src = "images\\radiobutton_chk.png";
    oCheckbox3.src = "images\\radiobutton.png";
  } else {
    oCheckbox2.src = "images\\radiobutton.png";
    oCheckbox3.src = "images\\radiobutton_chk.png";
  }

  if (oCheckbox1.value) {
    oAlarmOptions.visible = true;
    if (gAlarmDefault) {
      oFileOptions.visible = false;
    } else {
      oFileOptions.visible = true;
    }
  } else {
    oAlarmOptions.visible = false;
  }
}

/**
 * Method called when user hits "ok" button
 */
function _onOk() {
  // check validity of file path
  var path = oFilePath.value;
  if (oCheckbox1.value && !gAlarmDefault) {
    var fso;
    fso = framework.system.filesystem;
    if (!fso.FileExists(path)) {
      gAlarmDefault = true;
    }
  }

  debug.trace(oHours.value + ":" + oMinutes.value);
  var hours = -1;
  var minutes = -1;

  try {
    hours = Math.floor(parseFloat(oHours.value));
  } catch(e) {
    hours = -1;
  }

  try {
    minutes = Math.floor(parseFloat(oMinutes.value));
  } catch(e) {
    minutes = -1;
  }

  // Convert hours as necesary for am/pm business
  if (gModeAMPM && !gAlarmAM && hours != 12) {
    hours += 12;
  }

  if (gModeAMPM && gAlarmAM && hours == 12) {
    hours -= 12;
  }

  // Checks for bad hours and minutes inputs.
  // This should never happen, but handle just in case
  if (!(hours >= 0 && hours < 25)) {
    hours = 12;
  }

  if (!(minutes >= 0 && minutes <= 59)) {
    minutes = 0;
  }

  options.putValue(OPT_ALARM, oCheckbox1.value);
  options.putValue(OPT_DEFAULT_RINGER, gAlarmDefault);
  options.putValue(OPT_FILE_PATH, oFilePath.value);
  options.putValue(OPT_CITY, oCityName.value);
  options.putValue(OPT_HOURS, hours);
  options.putValue(OPT_MINUTES, minutes);
}

/**
 * Called when user hits cancel button
 */
function _onCancel() {
}

/**
 * Called when alarm checkbox changes
 */
function _alarmChk() {
  if (oCheckbox1.value) {
    oAlarmOptions.visible = true;
    if (gAlarmDefault) {
      oFileOptions.visible = false;
    } else {
      oFileOptions.visible = true;
    }
  } else {
    oAlarmOptions.visible = false;
  }
}

/**
 * Handles default alarm checkbox click
 */
function _defaultAlarmChk() {
  debug.trace("check default");
  gAlarmDefault = true;
  oCheckbox2.src = "images\\radiobutton_chk.png";
  oCheckbox3.src = "images\\radiobutton.png";
  if (oCheckbox1.value) {
    oAlarmOptions.visible = true;
    if (gAlarmDefault) {
      oFileOptions.visible = false;
    } else {
      oFileOptions.visible = true;
    }
  } else {
    oAlarmOptions.visible = false;
  }
}

/**
 * Handles use file checkbox click
 */
function _useFileChk() {
  debug.trace("check file");
  gAlarmDefault = false;
  oCheckbox2.src = "images\\radiobutton.png";
  oCheckbox3.src = "images\\radiobutton_chk.png";
  if (oCheckbox1.value) {
    oAlarmOptions.visible = true;
    if (gAlarmDefault) {
      oFileOptions.visible = false;
    } else {
      oFileOptions.visible = true;
    }
  } else {
    oAlarmOptions.visible = false;
  }
}

/**
 * Handles AM checkbox click
 */
function _amChk() {
  debug.trace("check am");
  gAlarmAM = true;
  oAM.src = "images\\radiobutton_chk.png";
  oPM.src = "images\\radiobutton.png";
}

/**
 * Handles PM checkbox click
 */
function _pmChk() {
  debug.trace("check pm");
  gAlarmAM = false;
  oAM.src = "images\\radiobutton.png";
  oPM.src = "images\\radiobutton_chk.png";
}

/**
 * checkbox change
 */
function chkchange() {
  debug.trace("am: " + oAM.value + " pm: " + oPM.value + " def: " + oCheckbox2.value + " fil: " + oCheckbox3.value);
}

/**
 * Turns an int into a 2 digit time string
 * @param {Number} n is a time field
 */
function timeString(n) {
  if (n < 10) {
    return "0" + n;
  } else {
    return "" + n;
  }
}

/**
 * Open a browse dialog
 */
function _doBrowse() {
  debug.trace("launch browse");
  var file = BrowseForFile("Music Files|*.mp3;*.wma;*.wav");
  oFilePath.value = file;
}

/**
 * Handles event that gives keycode of what's about to be entered into time box
 * @param {String} id 'h' for hours and 'm' for minutes tells which box
 */
function _keyPress(id) {
  var elem;
  if (id == 'h') {
    elem = oHours;
  } else {
    elem = oMinutes;
  }

  gSavedEditValue = elem.value;

  if (event.keycode == 9) {
    gRevertKeypress = true;
    if (id == 'h') {
      // give focus to minutes
      gSavedEditValue = oMinutes.value;
      oMinutes.focus();
    }
  } else if (event.keycode == 35 ||
             event.keycode == 36 ||
             event.keycode == 46 ||
             event.keycode == 8 ||
             (event.keycode > 47 && event.keycode < 58) ||
             (event.keycode > 95 && event.keycode < 106)) {
    gRevertKeypress = false;
  } else {
    gRevertKeypress = true;
  }
}

/**
 * Handles event that fires after change to time box is made
 * @param {String} id 'h' for hours and 'm' for minutes
 */
function _valueChange(id) {
  var elem;
  var numValue;

  if (id == 'h') {
    elem = oHours;
  } else {
    elem = oMinutes;
  }

  if (gRevertKeypress || elem.value.length > 2) {
    elem.value = gSavedEditValue;
  }

  try {
    numValue = parseInt(elem.value);
    if (id == 'h') {
      if (gModeAMPM && numValue > 12) {
        gRevertKeypress = true;
      } else if (numValue > 23) {
        gRevertKeypress = true;
      }
    } else if (id == 'm') {
      if (numValue > 59) {
        gRevertKeypress = true;
      }
    }
  } catch(e) {
    gRevertKeypress = true;
  }

  if (gRevertKeypress) {
    elem.value = gSavedEditValue;
  }

  gRevertKeypress = false;
}

/**
 * Handles key down for path edit box
 */
function _pathKeyDown() {
  // Save value prior to change
  gRevertKeypress = true;
  gSavedEditValue = oFilePath.value;
}

/**
 * Handles value change for path edit box
 */
function _pathChange() {
  // don't allow user to edit value.
  // revert changes while still letting user navigate box
  if (oFilePath.value != gSavedEditValue && gRevertKeypress) {
    oFilePath.value = gSavedEditValue;
  }

  gRevertKeypress = false;
}
<|endoftext|>


<commit_before>import SimpleSchema from 'simpl-schema';
import UserEventLog from '/both/collections/userEventLog';
import { checkUserPermissions } from '../utils';

Residencies = new Mongo.Collection('residencies');

var ResidenciesSchema = new SimpleSchema({
  residentId: {
    type: String
  },
  homeId: {
    type: String,
    custom() {
      return !!this.docId ? 'notAllowed' : undefined;
    },
  },
  moveIn: {
    type: Date,
    autoValue: function() {
      if (this.isSet) {
        // Get move in date from form
        const moveInDate = new Date(this.value);

        // set move in to midnight UTC
        moveInDate.setUTCHours(0, 0, 0, 0);

        return moveInDate;
      }
    }
  },
  moveOut: {
    type: Date,
    optional: true,
    autoValue: function() {
      if (this.isSet) {
        // Get move out date from form
        const moveOutDate = new Date(this.value);

        if (moveOutDate) {
          // set move out to midnight UTC
          moveOutDate.setUTCHours(0, 0, 0, 0);

          return moveOutDate;
        }
      }
    },
    custom() {
      const moveOut = this.value;
      const moveIn = this.field("moveIn").value;
      const result = validateDate(moveIn, moveOut);
      if (!result) {
        return "badDate";
      }
    }
  }
});

Residencies.attachSchema(ResidenciesSchema);
ResidenciesSchema.addValidator(function() {
  const residencyId = this.docId;
  /*
    The data collected from the form is in this.obj so,
    If this.obj exists:
      -If residency exists i.e. in edit mode:
        The form data is in $set (a mongo modifier)
      -else in create mode:
        the data is in this.obj
    else the object must be empty

    Ref: https://github.com/aldeed/meteor-simple-schema/blob/master/DOCS.md#the-object-to-validate
  */
  let currentRecord = this.obj || {}
  if (!!residencyId) {
    /* If edit, select the object set for updating. */
    currentRecord = this.obj.$set;
  }

  let resident = Residencies.findOne({_id:residencyId});
  let residentId = resident.residentId;
  let { moveOut, moveIn } = currentRecord;

  /* Error message key to indicate the entry is not allowed */
  if (hasOtherActiveResidencies(residentId, residencyId, moveOut, moveIn)) return "notAllowed";
})
Residencies.allow({
  insert: function (userId, doc) {
    const schemaType = "residency";
    const action = "insert";
    return checkUserPermissions({ schemaType, action, userId, doc });
  },
  update: function (userId, doc) {
    const schemaType = "residency";
    const action = "update";
    const residencyId = doc._id;
    const residency = Residencies.findOne({
      $and: [
        {
          _id: residencyId,

        },
        {
          moveOut: {
            $exists: true
          }
        }
      ]
    });
    const hasDeparted = !!residency ? true : false;

    return checkUserPermissions({
      schemaType,
      action,
      userId,
      doc,
      hasDeparted
    });
  },
  remove: function (userId) {
    const schemaType = "residency";
    const action = "remove";
    return checkUserPermissions({ schemaType, action, userId });
  }
});

Residencies.after.insert(function (userId, residency) {
  // Add event log
  UserEventLog.insert({
    userId,
    action: 'insert',
    entityType: 'residency',
    entityId: residency._id,
  })
});

Residencies.after.update(function (userId, residency) {
  // Add event log
  UserEventLog.insert({
    userId,
    action: 'update',
    entityType: 'residency',
    entityId: residency._id,
  })
});

Residencies.after.remove(function (userId, residency) {
  // Add event log
  UserEventLog.insert({
    userId,
    action: 'remove',
    entityType: 'residency',
    entityId: residency._id,
  })
});

/*
Verifies whethers the move out date
if specified is always greater than move in Date
*/
function validateDate(moveIn, moveOut) {
  const moveOutDate = new Date(moveOut).getTime();
  const moveInDate = new Date(moveIn).getTime();
  /* it checks if moveout date if exists and is before
  the movein date it will throw an error */
  if (!isNaN(moveOutDate) && moveOutDate > 0 && moveInDate > moveOutDate) return false
  /*
  In all other cases, i.e
  1) if the moveOut date is not specified or
  2) it is a date greater than move in date, it returns true */
  return true
}

function hasOtherActiveResidencies(residentId, residencyId, moveOut, moveIn) {
  // In edit server method is called
  if (Meteor.isServer) {
    return Meteor.call("hasOtherActiveResidencies", {
      residentId,
      residencyId,
      moveOut,
      moveIn
    });
  } else {
    // When adding new residency method executed from client
    Meteor.call(
      "hasOtherActiveResidencies",
      { residentId, residencyId, moveOut, moveIn },
      function (err, response) {
        /* Error message key to indicate the entry is not allowed */
        if (!err) return response;
      }
    );
  }
}<commit_msg>handling case for create<commit_after>import SimpleSchema from 'simpl-schema';
import UserEventLog from '/both/collections/userEventLog';
import { checkUserPermissions } from '../utils';

Residencies = new Mongo.Collection('residencies');

var ResidenciesSchema = new SimpleSchema({
  residentId: {
    type: String
  },
  homeId: {
    type: String,
    custom() {
      return !!this.docId ? 'notAllowed' : undefined;
    },
  },
  moveIn: {
    type: Date,
    autoValue: function() {
      if (this.isSet) {
        // Get move in date from form
        const moveInDate = new Date(this.value);

        // set move in to midnight UTC
        moveInDate.setUTCHours(0, 0, 0, 0);

        return moveInDate;
      }
    }
  },
  moveOut: {
    type: Date,
    optional: true,
    autoValue: function() {
      if (this.isSet) {
        // Get move out date from form
        const moveOutDate = new Date(this.value);

        if (moveOutDate) {
          // set move out to midnight UTC
          moveOutDate.setUTCHours(0, 0, 0, 0);

          return moveOutDate;
        }
      }
    },
    custom() {
      const moveOut = this.value;
      const moveIn = this.field("moveIn").value;
      const result = validateDate(moveIn, moveOut);
      if (!result) {
        return "badDate";
      }
    }
  }
});

Residencies.attachSchema(ResidenciesSchema);
ResidenciesSchema.addValidator(function() {
  const residencyId = this.docId;
  /*
    The data collected from the form is in this.obj so,
    If this.obj exists:
      -If residency exists i.e. in edit mode:
        The form data is in $set (a mongo modifier)
      -else in create mode:
        the data is in this.obj
    else the object must be empty

    Ref: https://github.com/aldeed/meteor-simple-schema/blob/master/DOCS.md#the-object-to-validate
  */
  let currentRecord = this.obj || {}
  if (!!residencyId) {
    /* If edit, select the object set for updating. */
    currentRecord = this.obj.$set;
  }

  let residentId;
  if (!!residencyId) {
    let resident = Residencies.findOne({ _id: residencyId });
    residentId = resident.residentId;
  } else {
    residentId = currentRecord.residentId;
  }

  let { moveOut, moveIn } = currentRecord;

  /* Error message key to indicate the entry is not allowed */
  if (hasOtherActiveResidencies(residentId, residencyId, moveOut, moveIn)) return "notAllowed";
})
Residencies.allow({
  insert: function (userId, doc) {
    const schemaType = "residency";
    const action = "insert";
    return checkUserPermissions({ schemaType, action, userId, doc });
  },
  update: function (userId, doc) {
    const schemaType = "residency";
    const action = "update";
    const residencyId = doc._id;
    const residency = Residencies.findOne({
      $and: [
        {
          _id: residencyId,

        },
        {
          moveOut: {
            $exists: true
          }
        }
      ]
    });
    const hasDeparted = !!residency ? true : false;

    return checkUserPermissions({
      schemaType,
      action,
      userId,
      doc,
      hasDeparted
    });
  },
  remove: function (userId) {
    const schemaType = "residency";
    const action = "remove";
    return checkUserPermissions({ schemaType, action, userId });
  }
});

Residencies.after.insert(function (userId, residency) {
  // Add event log
  UserEventLog.insert({
    userId,
    action: 'insert',
    entityType: 'residency',
    entityId: residency._id,
  })
});

Residencies.after.update(function (userId, residency) {
  // Add event log
  UserEventLog.insert({
    userId,
    action: 'update',
    entityType: 'residency',
    entityId: residency._id,
  })
});

Residencies.after.remove(function (userId, residency) {
  // Add event log
  UserEventLog.insert({
    userId,
    action: 'remove',
    entityType: 'residency',
    entityId: residency._id,
  })
});

/*
Verifies whethers the move out date
if specified is always greater than move in Date
*/
function validateDate(moveIn, moveOut) {
  const moveOutDate = new Date(moveOut).getTime();
  const moveInDate = new Date(moveIn).getTime();
  /* it checks if moveout date if exists and is before
  the movein date it will throw an error */
  if (!isNaN(moveOutDate) && moveOutDate > 0 && moveInDate > moveOutDate) return false
  /*
  In all other cases, i.e
  1) if the moveOut date is not specified or
  2) it is a date greater than move in date, it returns true */
  return true
}

function hasOtherActiveResidencies(residentId, residencyId, moveOut, moveIn) {
  // In edit server method is called
  if (Meteor.isServer) {
    return Meteor.call("hasOtherActiveResidencies", {
      residentId,
      residencyId,
      moveOut,
      moveIn
    });
  } else {
    // When adding new residency method executed from client
    Meteor.call(
      "hasOtherActiveResidencies",
      { residentId, residencyId, moveOut, moveIn },
      function (err, response) {
        /* Error message key to indicate the entry is not allowed */
        if (!err) return response;
      }
    );
  }
}<|endoftext|>


<commit_before>"use strict";

var QuadrapusEnemy = function(world, options) {
	this.world = world;

	this.spriteName = options.spriteName || null;
	this.color = "#00FFFF";

	this.side = options.side;
	this.type = "enemy";
	this.active = true;
	this.width = 55;
	this.height = 30;
	this.speed = 1.5;
	this.velX = 0;
	this.velY = 0;
	if (this.side === "right") {
		this.x = -this.width;
	} else {
		this.x = this.world.width + this.width;
	}
	this.y = this.world.height / 2;

	this.hitboxMetrics = {
		x: 0,
		y: 0,
		width: 55,
		height: 30
	};

	this.hitbox = {
		x: this.x + this.hitboxMetrics.x,
		y: this.y + this.hitboxMetrics.y,
		width: this.hitboxMetrics.width,
		height: this.hitboxMetrics.height
	};
};

QuadrapusEnemy.prototype.explode = function(source) {
	this.active = false;
};

QuadrapusEnemy.prototype.update = function() {
	if (this.side === "right") {
		if (this.velX < this.speed) {
			this.velX++;
		}
	} else {
		if (this.velX > -this.speed) {
			this.velX--;
		}
	}

	this.x += this.velX;

	if (this.side === "right" && this.x > this.world.width) {
		this.active = false;
	} else if (this.side === "left" && this.x < -this.width) {
		this.active = false;
	}

	this.updateHitbox();
};

QuadrapusEnemy.prototype.draw = function() {
	if (this.spriteName === null) {
		this.world.drawRectangle(this.color, this.x, this.y, this.width, this.height);
	} else {
		this.world.drawSprite(this.spriteName, this.x, this.y, this.width, this.height);
	}
};

QuadrapusEnemy.prototype.updateHitbox = function() {
	this.hitbox = {
		x: this.x + this.hitboxMetrics.x,
		y: this.y + this.hitboxMetrics.y,
		width: this.hitboxMetrics.width,
		height: this.hitboxMetrics.height
	};
};
<commit_msg>Update EnemyQuadrapus.js<commit_after>"use strict";

var QuadrapusEnemy = function(world, options) {
	this.world = world;

	this.spriteName = options.spriteName || null;
	this.color = "#00FFFF";

	this.side = options.side;
	this.type = "enemy";
	this.active = true;
	this.width = 55;
	this.height = 30;
	this.speed = 1.4;
	this.velX = 0;
	this.velY = 0;
	if (this.side === "right") {
		this.x = -this.width;
	} else {
		this.x = this.world.width + this.width;
	}
	this.direction = "down";
	this.y = this.world.height / 2 - this.width / 2;

	this.hitboxMetrics = {
		x: 0,
		y: 0,
		width: 55,
		height: 30
	};

	this.hitbox = {
		x: this.x + this.hitboxMetrics.x,
		y: this.y + this.hitboxMetrics.y,
		width: this.hitboxMetrics.width,
		height: this.hitboxMetrics.height
	};
};

QuadrapusEnemy.prototype.explode = function(source) {
	this.active = false;
};

QuadrapusEnemy.prototype.update = function() {
	if (this.side === "right") {
		this.velX = this.speed;
	} else {
		this.velX = -this.speed;
	}

	if (this.direction === "down") {
		this.velY = 0.5;
		if (this.y > this.world.height / 2 + this.height / 2) {
			this.direction = "up";
		}
	} else {
		this.velY = -0.5;
		if (this.y < this.world.height / 2 - this.width / 2) {
			this.direction = "down";
		}
	}

	this.x += this.velX;
	this.y += this.velY;

	if (this.side === "right" && this.x > this.world.width) {
		this.active = false;
	} else if (this.side === "left" && this.x < -this.width) {
		this.active = false;
	}

	this.updateHitbox();
};

QuadrapusEnemy.prototype.draw = function() {
	if (this.spriteName === null) {
		this.world.drawRectangle(this.color, this.x, this.y, this.width, this.height);
	} else {
		this.world.drawSprite(this.spriteName, this.x, this.y, this.width, this.height);
	}
};

QuadrapusEnemy.prototype.updateHitbox = function() {
	this.hitbox = {
		x: this.x + this.hitboxMetrics.x,
		y: this.y + this.hitboxMetrics.y,
		width: this.hitboxMetrics.width,
		height: this.hitboxMetrics.height
	};
};
<|endoftext|>


<commit_before>import { getProjectId, getClusterId, bulkAdd } from 'ui/utils/navigation-tree';
import { get } from '@ember/object';

const rootNav = [
  // Project
  {
    scope:          'project',
    id:             'infra',
    localizedLabel: 'nav.infra.tab',
    ctx:            [getProjectId],
    submenu:        [
      {
        id:             'containers',
        localizedLabel: 'nav.containers.tab',
        route:          'authenticated.project.index',
        ctx:            [getProjectId],
        resource:       ['workload', 'ingress', 'service'],
        resourceScope:  'project',
        currentWhen:    [
          'containers',
          'workload',
          'ingresses',
          'authenticated.project.dns',
          'volumes',
        ],
      },
      {
        id:             'hpa',
        localizedLabel: 'nav.infra.hpa',
        route:          'authenticated.project.hpa',
        ctx:            [getProjectId],
        resource:       ['horizontalpodautoscaler'],
        resourceScope:  'project',
      },
      {
        id:             'pipelines',
        localizedLabel: 'nav.infra.pipelines',
        route:          'authenticated.project.pipeline.pipelines',
        ctx:            [getProjectId],
        resource:       [],
        resourceScope:  'project',
      },
      {
        id:             'istio',
        localizedLabel: 'nav.tools.istio',
        route:          'authenticated.project.istio.index',
        ctx:            [getProjectId],
        resource:       [],
        resourceScope:  'project',
        currentWhen:    [
          'authenticated.project.istio.project-istio',
        ],
      },
      {
        id:             'infra-secrets',
        localizedLabel: 'nav.infra.secrets',
        route:          'authenticated.project.secrets',
        ctx:            [getProjectId],
        resource:       ['namespacedsecret', 'secret', 'dockercredential', 'certificate'],
        resourceScope:  'project',
        currentWhen:    [
          'authenticated.project.certificates',
          'authenticated.project.registries',
          'authenticated.project.secrets',
        ],
      },
      {
        id:             'infra-config-maps',
        localizedLabel: 'nav.infra.configMaps',
        route:          'authenticated.project.config-maps',
        ctx:            [getProjectId],
        resource:       ['configmap'],
        resourceScope:  'project',
      },
    ],
  },
  {
    scope:          'project',
    id:             'project-apps',
    localizedLabel: 'nav.apps.tab',
    route:          'apps-tab',
    ctx:            [getProjectId],
    resource:       ['app'],
    resourceScope:  'project',
  },
  {
    scope:          'project',
    id:             'namespaces',
    localizedLabel: 'nav.project.namespaces',
    route:          'authenticated.project.ns.index',
    ctx:            [getProjectId],
    resource:       ['namespace'],
    resourceScope:  'cluster',
  },
  {
    scope:          'project',
    id:             'project-security-roles',
    localizedLabel: 'nav.infra.members',
    route:          'authenticated.project.security.members',
    resource:       ['projectroletemplatebinding'],
    resourceScope:  'global',
    ctx:            [getProjectId],
  },
  {
    scope:          'project',
    id:             'project-tools',
    localizedLabel: 'nav.tools.tab',
    ctx:            [getProjectId],
    resource:       [],
    resourceScope:  'global',
    submenu:        [
      {
        id:             'tools-alerts',
        localizedLabel: 'nav.tools.alerts',
        route:          'authenticated.project.alert',
        resource:       [],
        ctx:            [getProjectId],
        resourceScope:  'global',
      },
      {
        id:             'manage-catalogs',
        localizedLabel: 'nav.tools.catalogs',
        route:          'authenticated.project.project-catalogs',
        ctx:            [getProjectId],
        resource:       ['catalog', 'project-catalog'],
        resourceScope:  'global',
      },
      {
        id:             'tools-logging',
        localizedLabel: 'nav.tools.logging',
        route:          'authenticated.project.logging',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getProjectId],
      },
      {
        id:             'tools-monitoring',
        localizedLabel: 'nav.tools.monitoring',
        route:          'authenticated.project.monitoring.project-setting',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getProjectId],
      },
      {
        id:             'tools-pipeline',
        localizedLabel: 'nav.tools.pipeline',
        route:          'authenticated.project.pipeline.settings',
        resource:       ['sourcecodeproviderconfig'],
        resourceScope:  'project',
        ctx:            [getProjectId],
      },
    ]
  },
  // Cluster
  {
    scope:          'cluster',
    id:             'cluster-k8s',
    localizedLabel: 'nav.cluster.dashboard',
    route:          'authenticated.cluster.monitoring.index',
    ctx:            [getClusterId],
    resource:       ['node'],
    resourceScope:  'global',
  },
  {
    scope:          'cluster',
    id:             'cluster-nodes',
    localizedLabel: 'nav.cluster.nodes',
    route:          'authenticated.cluster.nodes',
    ctx:            [getClusterId],
    resource:       ['node'],
    resourceScope:  'global',
  },
  {
    scope:          'cluster',
    id:             'cluster-storage',
    localizedLabel: 'nav.cluster.storage.tab',
    ctx:            [getClusterId],
    resource:       ['clusterroletemplatebinding'],
    resourceScope:  'global',
    submenu:        [
      {
        scope:          'cluster',
        id:             'cluster-storage-volumes',
        localizedLabel: 'nav.cluster.storage.volumes',
        route:          'authenticated.cluster.storage.persistent-volumes.index',
        ctx:            [getClusterId],
        resource:       ['project'],
        resourceScope:  'global',
      },
      {
        scope:          'cluster',
        id:             'cluster-storage-classes',
        localizedLabel: 'nav.cluster.storage.classes',
        route:          'authenticated.cluster.storage.classes.index',
        ctx:            [getClusterId],
        resource:       ['project'],
        resourceScope:  'global',
      },
    ]
  },
  {
    scope:          'cluster',
    id:             'cluster-projects',
    localizedLabel: 'nav.cluster.projects',
    route:          'authenticated.cluster.projects.index',
    ctx:            [getClusterId],
    resource:       ['project'],
    resourceScope:  'global',
  },
  {
    scope:          'cluster',
    id:             'cluster-security-roles',
    localizedLabel: 'nav.cluster.members',
    route:          'authenticated.cluster.security.members.index',
    resource:       ['clusterroletemplatebinding'],
    resourceScope:  'global',
    ctx:            [getClusterId],
  },
  {
    scope:          'cluster',
    id:             'cluster-tools',
    localizedLabel: 'nav.tools.tab',
    ctx:            [getClusterId],
    resource:       [],
    resourceScope:  'global',
    submenu:        [
      {
        id:             'cluster-tools-alert',
        localizedLabel: 'nav.tools.alerts',
        route:          'authenticated.cluster.alert',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getClusterId],
      },
      {
        id:             'cluster-tools-backups',
        localizedLabel: 'nav.tools.backups',
        route:          'authenticated.cluster.backups',
        resourceScope:  'global',
        resource:       ['etcdbackup'],
        ctx:            [getClusterId],
        condition() {
          return get(this, 'cluster.rancherKubernetesEngineConfig')
        }
      },
      {
        scope:          'cluster',
        id:             'cluster-catalogs',
        localizedLabel: 'nav.admin.catalogs',
        route:          'authenticated.cluster.cluster-catalogs',
        ctx:            [getClusterId],
        resource:       ['catalog', 'cluster-catalog'],
        resourceScope:  'global',
      },
      {
        id:             'cluster-tools-notifiers',
        localizedLabel: 'nav.tools.notifiers',
        route:          'authenticated.cluster.notifier',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getClusterId],
      },
      {
        id:             'cluster-tools-logging',
        localizedLabel: 'nav.tools.logging',
        route:          'authenticated.cluster.logging',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getClusterId],
      },
      {
        id:             'cluster-tools-monitoring',
        localizedLabel: 'nav.tools.monitoring',
        route:          'authenticated.cluster.monitoring.cluster-setting',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getClusterId],
      },
      {
        id:                       'cluster-tools-istio',
        localizedLabel:           'nav.tools.istio',
        route:                    'authenticated.cluster.istio.cluster-setting',
        resourceScope:            'global',
        resource:                 [],
        ctx:                      [getClusterId],
      },
      {
        id:                       'cluster-tools-cis-scan',
        localizedLabel:           'nav.tools.cisScans',
        route:                    'authenticated.cluster.cis/scan',
        resourceScope:            'global',
        resource:                 [],
        ctx:                      [getClusterId],
      },
      { divider: true },
      {
        id:                       'cluster-tools-backup',
        localizedLabel:           'nav.tools.backup',
        dashboardLink:            '/backup',
        condition() {
          return get(this, 'cluster.id') === 'local';
        }
      },
      {
        id:                       'cluster-tools-gatekeeper',
        localizedLabel:           'nav.tools.gatekeeper',
        dashboardLink:            '/gatekeeper',
      },
      {
        id:                       'cluster-tools-rio',
        localizedLabel:           'nav.tools.rio',
        dashboardLink:            '/rio',
      },
    ],
  },

  // Global
  {
    scope:          'global',
    id:             'global-clusters',
    localizedLabel: 'nav.admin.clusters.tab',
    route:          'global-admin.clusters',
    resource:       ['cluster'],
    resourceScope:  'global',
  },
  {
    scope:          'global',
    id:             'multi-cluster-apps',
    localizedLabel: 'nav.admin.multiClusterApps',
    route:          'global-admin.multi-cluster-apps',
    resource:       ['multiclusterapp'],
    resourceScope:  'global',
  },
  {
    scope:          'global',
    id:             'global-settings',
    localizedLabel: 'nav.settings.tab',
    route:          'global-admin.settings.advanced',
    resourceScope:  'global',
  },
  {
    scope:          'global',
    id:             'global-security',
    localizedLabel: 'nav.admin.security.tab',
    submenu:        [
      {
        scope:          'global',
        id:             'global-accounts',
        localizedLabel: 'nav.admin.security.accounts',
        route:          'global-admin.security.accounts.users',
        resource:       ['user'],
        resourceScope:  'global',
      },
      {
        scope:          'global',
        id:             'global-group-accounts',
        localizedLabel: 'nav.admin.security.groupAccounts',
        route:          'global-admin.security.accounts.groups',
        resource:       ['globalrolebinding'],
        resourceScope:  'global',
      },
      {
        id:             'global-security-roles',
        localizedLabel: 'nav.admin.security.roles',
        route:          'global-admin.security.roles.index',
        resource:       ['roletemplate'],
        resourceScope:  'global',
      },
      {
        id:             'global-security-roles',
        localizedLabel: 'nav.admin.security.podSecurityPolicies',
        route:          'global-admin.security.policies',
        resource:       ['podsecuritypolicytemplate'],
        resourceScope:  'global',
      },
      {
        id:             'global-security-authentication',
        localizedLabel: 'nav.admin.security.authentication',
        route:          'global-admin.security.authentication',
        condition() {
          const authConfigs = this.get('globalStore').all('authConfig');

          return authConfigs.get('length') > 0;
        }
      },
    ],
  },
  {
    scope:          'global',
    id:             'global-tools',
    localizedLabel: 'nav.tools.tab',
    submenu:        [
      {
        scope:          'global',
        id:             'global-catalogs',
        localizedLabel: 'nav.admin.catalogs',
        route:          'global-admin.catalog',
        resource:       ['catalog'],
        resourceScope:  'global',
      },
      {
        scope:          'global',
        id:             'nodes-node-drivers',
        localizedLabel: 'nav.admin.drivers',
        route:          'nodes.custom-drivers',
        resource:       ['nodedriver', 'kontainerdriver'],
        resourceScope:  'global',
      },
      {
        id:             'global-dns-entries',
        localizedLabel: 'nav.admin.globalDnsEntries',
        route:          'global-admin.global-dns.entries',
        resource:       ['globaldns'],
        resourceScope:  'global',
      },
      {
        id:             'global-dns-providers',
        localizedLabel: 'nav.admin.globalDnsProviders',
        route:          'global-admin.global-dns.providers',
        resource:       ['globaldnsprovider'],
        resourceScope:  'global',
      },
      // {
      //   id:             'global-registry',
      //   localizedLabel: 'nav.admin.globalRegistry',
      //   route:          'global-admin.global-registry',
      //   // There is no schema for global registry. But we can use global dns to check if it is a HA env.
      //   resource:       ['globaldns'],
      //   resourceScope:  'global',
      // },
      {
        id:             'rke-template',
        localizedLabel: 'nav.admin.clusters.rkeTemplate',
        route:          'global-admin.cluster-templates',
        resource:       ['clustertemplate'],
        resourceScope:  'global',
      },
      { divider: true },
      {
        id:                'tools-fleet',
        localizedLabel:    'nav.tools.fleet',
        dashboardBaseLink:  '/c/local/fleet',
      },
    ],
  },
//  {
//    scope: 'global',
//    id: 'global-advanced',
//    localizedLabel: 'nav.admin.settings.advanced',
//    route: 'global-admin.settings.advanced',
//    disabled: true,
//  },
]

export function initialize(/* appInstance*/) {
  bulkAdd(rootNav);
}

export default {
  name:       'nav',
  initialize,
  after:      'store',
};
<commit_msg>comment out rio link as it is hidden in dashboard<commit_after>import { getProjectId, getClusterId, bulkAdd } from 'ui/utils/navigation-tree';
import { get } from '@ember/object';

const rootNav = [
  // Project
  {
    scope:          'project',
    id:             'infra',
    localizedLabel: 'nav.infra.tab',
    ctx:            [getProjectId],
    submenu:        [
      {
        id:             'containers',
        localizedLabel: 'nav.containers.tab',
        route:          'authenticated.project.index',
        ctx:            [getProjectId],
        resource:       ['workload', 'ingress', 'service'],
        resourceScope:  'project',
        currentWhen:    [
          'containers',
          'workload',
          'ingresses',
          'authenticated.project.dns',
          'volumes',
        ],
      },
      {
        id:             'hpa',
        localizedLabel: 'nav.infra.hpa',
        route:          'authenticated.project.hpa',
        ctx:            [getProjectId],
        resource:       ['horizontalpodautoscaler'],
        resourceScope:  'project',
      },
      {
        id:             'pipelines',
        localizedLabel: 'nav.infra.pipelines',
        route:          'authenticated.project.pipeline.pipelines',
        ctx:            [getProjectId],
        resource:       [],
        resourceScope:  'project',
      },
      {
        id:             'istio',
        localizedLabel: 'nav.tools.istio',
        route:          'authenticated.project.istio.index',
        ctx:            [getProjectId],
        resource:       [],
        resourceScope:  'project',
        currentWhen:    [
          'authenticated.project.istio.project-istio',
        ],
      },
      {
        id:             'infra-secrets',
        localizedLabel: 'nav.infra.secrets',
        route:          'authenticated.project.secrets',
        ctx:            [getProjectId],
        resource:       ['namespacedsecret', 'secret', 'dockercredential', 'certificate'],
        resourceScope:  'project',
        currentWhen:    [
          'authenticated.project.certificates',
          'authenticated.project.registries',
          'authenticated.project.secrets',
        ],
      },
      {
        id:             'infra-config-maps',
        localizedLabel: 'nav.infra.configMaps',
        route:          'authenticated.project.config-maps',
        ctx:            [getProjectId],
        resource:       ['configmap'],
        resourceScope:  'project',
      },
    ],
  },
  {
    scope:          'project',
    id:             'project-apps',
    localizedLabel: 'nav.apps.tab',
    route:          'apps-tab',
    ctx:            [getProjectId],
    resource:       ['app'],
    resourceScope:  'project',
  },
  {
    scope:          'project',
    id:             'namespaces',
    localizedLabel: 'nav.project.namespaces',
    route:          'authenticated.project.ns.index',
    ctx:            [getProjectId],
    resource:       ['namespace'],
    resourceScope:  'cluster',
  },
  {
    scope:          'project',
    id:             'project-security-roles',
    localizedLabel: 'nav.infra.members',
    route:          'authenticated.project.security.members',
    resource:       ['projectroletemplatebinding'],
    resourceScope:  'global',
    ctx:            [getProjectId],
  },
  {
    scope:          'project',
    id:             'project-tools',
    localizedLabel: 'nav.tools.tab',
    ctx:            [getProjectId],
    resource:       [],
    resourceScope:  'global',
    submenu:        [
      {
        id:             'tools-alerts',
        localizedLabel: 'nav.tools.alerts',
        route:          'authenticated.project.alert',
        resource:       [],
        ctx:            [getProjectId],
        resourceScope:  'global',
      },
      {
        id:             'manage-catalogs',
        localizedLabel: 'nav.tools.catalogs',
        route:          'authenticated.project.project-catalogs',
        ctx:            [getProjectId],
        resource:       ['catalog', 'project-catalog'],
        resourceScope:  'global',
      },
      {
        id:             'tools-logging',
        localizedLabel: 'nav.tools.logging',
        route:          'authenticated.project.logging',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getProjectId],
      },
      {
        id:             'tools-monitoring',
        localizedLabel: 'nav.tools.monitoring',
        route:          'authenticated.project.monitoring.project-setting',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getProjectId],
      },
      {
        id:             'tools-pipeline',
        localizedLabel: 'nav.tools.pipeline',
        route:          'authenticated.project.pipeline.settings',
        resource:       ['sourcecodeproviderconfig'],
        resourceScope:  'project',
        ctx:            [getProjectId],
      },
    ]
  },
  // Cluster
  {
    scope:          'cluster',
    id:             'cluster-k8s',
    localizedLabel: 'nav.cluster.dashboard',
    route:          'authenticated.cluster.monitoring.index',
    ctx:            [getClusterId],
    resource:       ['node'],
    resourceScope:  'global',
  },
  {
    scope:          'cluster',
    id:             'cluster-nodes',
    localizedLabel: 'nav.cluster.nodes',
    route:          'authenticated.cluster.nodes',
    ctx:            [getClusterId],
    resource:       ['node'],
    resourceScope:  'global',
  },
  {
    scope:          'cluster',
    id:             'cluster-storage',
    localizedLabel: 'nav.cluster.storage.tab',
    ctx:            [getClusterId],
    resource:       ['clusterroletemplatebinding'],
    resourceScope:  'global',
    submenu:        [
      {
        scope:          'cluster',
        id:             'cluster-storage-volumes',
        localizedLabel: 'nav.cluster.storage.volumes',
        route:          'authenticated.cluster.storage.persistent-volumes.index',
        ctx:            [getClusterId],
        resource:       ['project'],
        resourceScope:  'global',
      },
      {
        scope:          'cluster',
        id:             'cluster-storage-classes',
        localizedLabel: 'nav.cluster.storage.classes',
        route:          'authenticated.cluster.storage.classes.index',
        ctx:            [getClusterId],
        resource:       ['project'],
        resourceScope:  'global',
      },
    ]
  },
  {
    scope:          'cluster',
    id:             'cluster-projects',
    localizedLabel: 'nav.cluster.projects',
    route:          'authenticated.cluster.projects.index',
    ctx:            [getClusterId],
    resource:       ['project'],
    resourceScope:  'global',
  },
  {
    scope:          'cluster',
    id:             'cluster-security-roles',
    localizedLabel: 'nav.cluster.members',
    route:          'authenticated.cluster.security.members.index',
    resource:       ['clusterroletemplatebinding'],
    resourceScope:  'global',
    ctx:            [getClusterId],
  },
  {
    scope:          'cluster',
    id:             'cluster-tools',
    localizedLabel: 'nav.tools.tab',
    ctx:            [getClusterId],
    resource:       [],
    resourceScope:  'global',
    submenu:        [
      {
        id:             'cluster-tools-alert',
        localizedLabel: 'nav.tools.alerts',
        route:          'authenticated.cluster.alert',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getClusterId],
      },
      {
        id:             'cluster-tools-backups',
        localizedLabel: 'nav.tools.backups',
        route:          'authenticated.cluster.backups',
        resourceScope:  'global',
        resource:       ['etcdbackup'],
        ctx:            [getClusterId],
        condition() {
          return get(this, 'cluster.rancherKubernetesEngineConfig')
        }
      },
      {
        scope:          'cluster',
        id:             'cluster-catalogs',
        localizedLabel: 'nav.admin.catalogs',
        route:          'authenticated.cluster.cluster-catalogs',
        ctx:            [getClusterId],
        resource:       ['catalog', 'cluster-catalog'],
        resourceScope:  'global',
      },
      {
        id:             'cluster-tools-notifiers',
        localizedLabel: 'nav.tools.notifiers',
        route:          'authenticated.cluster.notifier',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getClusterId],
      },
      {
        id:             'cluster-tools-logging',
        localizedLabel: 'nav.tools.logging',
        route:          'authenticated.cluster.logging',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getClusterId],
      },
      {
        id:             'cluster-tools-monitoring',
        localizedLabel: 'nav.tools.monitoring',
        route:          'authenticated.cluster.monitoring.cluster-setting',
        resourceScope:  'global',
        resource:       [],
        ctx:            [getClusterId],
      },
      {
        id:                       'cluster-tools-istio',
        localizedLabel:           'nav.tools.istio',
        route:                    'authenticated.cluster.istio.cluster-setting',
        resourceScope:            'global',
        resource:                 [],
        ctx:                      [getClusterId],
      },
      {
        id:                       'cluster-tools-cis-scan',
        localizedLabel:           'nav.tools.cisScans',
        route:                    'authenticated.cluster.cis/scan',
        resourceScope:            'global',
        resource:                 [],
        ctx:                      [getClusterId],
      },
      { divider: true },
      {
        id:                       'cluster-tools-backup',
        localizedLabel:           'nav.tools.backup',
        dashboardLink:            '/backup',
        condition() {
          return get(this, 'cluster.id') === 'local';
        }
      },
      {
        id:                       'cluster-tools-gatekeeper',
        localizedLabel:           'nav.tools.gatekeeper',
        dashboardLink:            '/gatekeeper',
      },
      // {
      //   id:                       'cluster-tools-rio',
      //   localizedLabel:           'nav.tools.rio',
      //   dashboardLink:            '/rio',
      // },
    ],
  },

  // Global
  {
    scope:          'global',
    id:             'global-clusters',
    localizedLabel: 'nav.admin.clusters.tab',
    route:          'global-admin.clusters',
    resource:       ['cluster'],
    resourceScope:  'global',
  },
  {
    scope:          'global',
    id:             'multi-cluster-apps',
    localizedLabel: 'nav.admin.multiClusterApps',
    route:          'global-admin.multi-cluster-apps',
    resource:       ['multiclusterapp'],
    resourceScope:  'global',
  },
  {
    scope:          'global',
    id:             'global-settings',
    localizedLabel: 'nav.settings.tab',
    route:          'global-admin.settings.advanced',
    resourceScope:  'global',
  },
  {
    scope:          'global',
    id:             'global-security',
    localizedLabel: 'nav.admin.security.tab',
    submenu:        [
      {
        scope:          'global',
        id:             'global-accounts',
        localizedLabel: 'nav.admin.security.accounts',
        route:          'global-admin.security.accounts.users',
        resource:       ['user'],
        resourceScope:  'global',
      },
      {
        scope:          'global',
        id:             'global-group-accounts',
        localizedLabel: 'nav.admin.security.groupAccounts',
        route:          'global-admin.security.accounts.groups',
        resource:       ['globalrolebinding'],
        resourceScope:  'global',
      },
      {
        id:             'global-security-roles',
        localizedLabel: 'nav.admin.security.roles',
        route:          'global-admin.security.roles.index',
        resource:       ['roletemplate'],
        resourceScope:  'global',
      },
      {
        id:             'global-security-roles',
        localizedLabel: 'nav.admin.security.podSecurityPolicies',
        route:          'global-admin.security.policies',
        resource:       ['podsecuritypolicytemplate'],
        resourceScope:  'global',
      },
      {
        id:             'global-security-authentication',
        localizedLabel: 'nav.admin.security.authentication',
        route:          'global-admin.security.authentication',
        condition() {
          const authConfigs = this.get('globalStore').all('authConfig');

          return authConfigs.get('length') > 0;
        }
      },
    ],
  },
  {
    scope:          'global',
    id:             'global-tools',
    localizedLabel: 'nav.tools.tab',
    submenu:        [
      {
        scope:          'global',
        id:             'global-catalogs',
        localizedLabel: 'nav.admin.catalogs',
        route:          'global-admin.catalog',
        resource:       ['catalog'],
        resourceScope:  'global',
      },
      {
        scope:          'global',
        id:             'nodes-node-drivers',
        localizedLabel: 'nav.admin.drivers',
        route:          'nodes.custom-drivers',
        resource:       ['nodedriver', 'kontainerdriver'],
        resourceScope:  'global',
      },
      {
        id:             'global-dns-entries',
        localizedLabel: 'nav.admin.globalDnsEntries',
        route:          'global-admin.global-dns.entries',
        resource:       ['globaldns'],
        resourceScope:  'global',
      },
      {
        id:             'global-dns-providers',
        localizedLabel: 'nav.admin.globalDnsProviders',
        route:          'global-admin.global-dns.providers',
        resource:       ['globaldnsprovider'],
        resourceScope:  'global',
      },
      // {
      //   id:             'global-registry',
      //   localizedLabel: 'nav.admin.globalRegistry',
      //   route:          'global-admin.global-registry',
      //   // There is no schema for global registry. But we can use global dns to check if it is a HA env.
      //   resource:       ['globaldns'],
      //   resourceScope:  'global',
      // },
      {
        id:             'rke-template',
        localizedLabel: 'nav.admin.clusters.rkeTemplate',
        route:          'global-admin.cluster-templates',
        resource:       ['clustertemplate'],
        resourceScope:  'global',
      },
      { divider: true },
      {
        id:                'tools-fleet',
        localizedLabel:    'nav.tools.fleet',
        dashboardBaseLink:  '/c/local/fleet',
      },
    ],
  },
//  {
//    scope: 'global',
//    id: 'global-advanced',
//    localizedLabel: 'nav.admin.settings.advanced',
//    route: 'global-admin.settings.advanced',
//    disabled: true,
//  },
]

export function initialize(/* appInstance*/) {
  bulkAdd(rootNav);
}

export default {
  name:       'nav',
  initialize,
  after:      'store',
};
<|endoftext|>


<commit_before>// var webpack = require('webpack');
var candelaWebpack = require('../webpack');

var config = {};

config.entry = {
  'tests': './tests.js'
};

config.devtool = 'inline-source-map';

config.node = {
  fs: 'empty'
};

config.output = {
  path: 'build',
  filename: 'tests.js'
};
config.module = {
  loaders: [
    {
      test: /\.css/,
      loaders: ['style-loader', 'css-loader'],
      include: /node_modules\/nvd3/,
    },
  ]
};
delete config.plugins;

var final = candelaWebpack(config);

module.exports = final;
<commit_msg>test: use a more standard format for webpack config<commit_after>var candelaWebpack = require('../webpack');

module.exports = candelaWebpack({
  entry: {
    tests: './tests.js'
  },
  devtool: 'inline-source-map',
  node: {
    fs: 'empty'
  },
  output: {
    path: 'build',
      filename: 'tests.js'
  },
  module: {
    loaders: [
      {
        test: /\.css/,
        loaders: ['style-loader', 'css-loader'],
        include: /node_modules\/nvd3/,
      },
    ]
  }
});
<|endoftext|>


<commit_before>'use strict';
// A newable factory that spawns new resource
// objects, whichare a wrapper around ngResource
//
// Note that this approach right now doesn't work with totally freeform URL passed
// as route, because ngResource will always encode slashes.
// There is a pending issue for this https://github.com/angular/angular.js/issues/1388
//
// As it's not a top priority right now, we don't do anything. The quickest workaround
// (apart from patching angular) would be to fall back to $http.get()
//
angular.module('arethusa.core').factory('Resource', [
  '$resource',
  '$location',
  '$q',
  'spinner',
  function ($resource, $location, $q, spinner) {
    function paramsToObj(params) {
      return arethusaUtil.inject({}, params, function (obj, param, i) {
        obj[param] = $location.search()[param];
      });
    }

    function isJson(header) {
      if (header) return header.match('json');
    }

    function collectedParams(a, b) {
      return angular.extend(paramsToObj(a), b) || {};
    }

    function parseResponse(data, headers) {
      var res = {};
      res.data = isJson(headers()['content-type']) ? JSON.parse(data) : data;
      res.headers = headers;
      res.source = 'tbd';
      // we need to define and http interceptor
      return res;
    }

    function createAborter() {
      return $q.defer();
    }

    return function (conf,auth) {
      var self = this;
      this.route = conf.route;
      this.params = conf.params || [];
      this.auth = auth;
      auth.preflight();

      var aborter;

      function createResource() {
        aborter = createAborter();
        return $resource(self.route, null, {
          get: {
            method: 'GET',
            transformResponse: parseResponse,
            timeout: aborter.promise
          },
          save: {
            // TODO we need save and partial save -- latter will use PATCH
            method: 'POST',
            transformRequest: function(data,headers) {
              var contentType = self.mimetype || 'application/json';
              headers()["Content-Type"] = contentType;
              if (isJson(contentType)) {
                data = angular.toJson(data);
              }
              self.auth.transformRequest(headers);
              return data;
            },
            transformResponse: parseResponse
          }
        });
      }
      this.resource = createResource();

      function stopSpinning(req) {
        var promise = req.$promise;
        promise['finally'](spinner.stop);
        return promise;
      }

      this.get = function (otherParams) {
        spinner.spin();
        var params = collectedParams(self.params, otherParams);
        return stopSpinning(self.resource.get(params));
      };

      this.save = function (data,mimetype) {
        spinner.spin();
        var params = collectedParams(self.params,{});
        self.mimetype = mimetype;
        return stopSpinning(self.resource.save(params,data));
      };

      // This is not ideal - we have to re-create the complete resource, just
      // because we need one with a new resolvable promises, so that we can
      // abort it again.
      //
      // Needs another look. What I tried to do is to renew just the promise,
      // but not the complete promise. Wasn't really able to pull it off.
      // I guess the promise needs to be wrapped by another promise?!
      // It's no big deal to renew the resource, it just would be a little less
      // expensive to deal with a new promise only and leave the resource
      // untouched.
      this.abort = function() {
        aborter.resolve();
        self.resource = createResource();
      };
    };
  }
]);
<commit_msg>Add alias for save in resource<commit_after>'use strict';
// A newable factory that spawns new resource
// objects, whichare a wrapper around ngResource
//
// Note that this approach right now doesn't work with totally freeform URL passed
// as route, because ngResource will always encode slashes.
// There is a pending issue for this https://github.com/angular/angular.js/issues/1388
//
// As it's not a top priority right now, we don't do anything. The quickest workaround
// (apart from patching angular) would be to fall back to $http.get()
//
angular.module('arethusa.core').factory('Resource', [
  '$resource',
  '$location',
  '$q',
  'spinner',
  function ($resource, $location, $q, spinner) {
    function paramsToObj(params) {
      return arethusaUtil.inject({}, params, function (obj, param, i) {
        obj[param] = $location.search()[param];
      });
    }

    function isJson(header) {
      if (header) return header.match('json');
    }

    function collectedParams(a, b) {
      return angular.extend(paramsToObj(a), b) || {};
    }

    function parseResponse(data, headers) {
      var res = {};
      res.data = isJson(headers()['content-type']) ? JSON.parse(data) : data;
      res.headers = headers;
      res.source = 'tbd';
      // we need to define and http interceptor
      return res;
    }

    function createAborter() {
      return $q.defer();
    }

    return function (conf,auth) {
      var self = this;
      this.route = conf.route;
      this.params = conf.params || [];
      this.auth = auth;
      auth.preflight();

      var aborter;

      function createResource() {
        aborter = createAborter();
        return $resource(self.route, null, {
          get: {
            method: 'GET',
            transformResponse: parseResponse,
            timeout: aborter.promise
          },
          save: {
            // TODO we need save and partial save -- latter will use PATCH
            method: 'POST',
            transformRequest: function(data,headers) {
              var contentType = self.mimetype || 'application/json';
              headers()["Content-Type"] = contentType;
              if (isJson(contentType)) {
                data = angular.toJson(data);
              }
              self.auth.transformRequest(headers);
              return data;
            },
            transformResponse: parseResponse
          }
        });
      }
      this.resource = createResource();

      function stopSpinning(req) {
        var promise = req.$promise;
        promise['finally'](spinner.stop);
        return promise;
      }

      this.get = function (otherParams) {
        spinner.spin();
        var params = collectedParams(self.params, otherParams);
        return stopSpinning(self.resource.get(params));
      };

      this.save = function (data,mimetype) {
        spinner.spin();
        var params = collectedParams(self.params,{});
        self.mimetype = mimetype;
        return stopSpinning(self.resource.save(params,data));
      };

      this.post = this.save;

      // This is not ideal - we have to re-create the complete resource, just
      // because we need one with a new resolvable promises, so that we can
      // abort it again.
      //
      // Needs another look. What I tried to do is to renew just the promise,
      // but not the complete promise. Wasn't really able to pull it off.
      // I guess the promise needs to be wrapped by another promise?!
      // It's no big deal to renew the resource, it just would be a little less
      // expensive to deal with a new promise only and leave the resource
      // untouched.
      this.abort = function() {
        aborter.resolve();
        self.resource = createResource();
      };
    };
  }
]);
<|endoftext|>


<commit_before><commit_msg>Add support for array of actions and pass storeDispatcher to function<commit_after><|endoftext|>


<commit_before><commit_msg>fix multi docking error<commit_after><|endoftext|>


<commit_before><commit_msg>Add xaja file to libs<commit_after><|endoftext|>


<commit_before>import {IonicView, NavController, IonicApp} from 'ionic/ionic';
import {DataService} from '../service/data';
import {Http, HTTP_BINDINGS} from "angular2/http";
import {DateFormat} from '../components/date-format';

import {AboutPage} from '../about/about';
import {SchedulePage} from '../schedule/schedule';
import {SpeakersPage} from '../speakers/speakers';
import {MapPage} from '../map/map';

@IonicView({
  templateUrl: 'app/home/home.html',
  bindings: [DataService, Http],
  viewBindings: [HTTP_BINDINGS],
  directives: [DateFormat]
})

export class HomePage {
  constructor(nav: NavController, app: IonicApp) {
    this.nav = nav;
    this.app = app;
    this.AboutPage = AboutPage;
    this.MapPage = MapPage;
    this.SchedulePage = SchedulePage;
    this.SpeakersPage = SpeakersPage;
  }
}
<commit_msg>Remove extra bindings and viewbindings, not needed<commit_after>import {IonicView, NavController, IonicApp} from 'ionic/ionic';
import {DataService} from '../service/data';
import {Http, HTTP_BINDINGS} from "angular2/http";
import {DateFormat} from '../components/date-format';

import {AboutPage} from '../about/about';
import {SchedulePage} from '../schedule/schedule';
import {SpeakersPage} from '../speakers/speakers';
import {MapPage} from '../map/map';

@IonicView({
  templateUrl: 'app/home/home.html',
  directives: [DateFormat]
})

export class HomePage {
  constructor(nav: NavController, app: IonicApp) {
    this.nav = nav;
    this.app = app;
    this.AboutPage = AboutPage;
    this.MapPage = MapPage;
    this.SchedulePage = SchedulePage;
    this.SpeakersPage = SpeakersPage;
  }
}
<|endoftext|>