<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Owner: mark@famo.us
 * @license MPL 2.0
 * @copyright Famous Industries, Inc. 2014
 */

define(function(require, exports, module) {
    var Transform = require('./Transform');
    var Modifier = require('./Modifier');
    var RenderNode = require('./RenderNode');

    /**
     * Builds and renders a scene graph based on a declarative structure definition.
     * See the Scene examples in the examples distribution (http://github.com/Famous/examples.git).
     *
     * @class Scene
     * @constructor
     * @param {Object|Array|Spec} definition in the format of a render spec.
     */
    function Scene(definition) {
        this.id = null;
        this._objects = null;

        this.node = new RenderNode();
        this._definition = null;

        if (definition) this.load(definition);
    }

    var _MATRIX_GENERATORS = {
        'translate': Transform.translate,
        'rotate': Transform.rotate,
        'rotateX': Transform.rotateX,
        'rotateY': Transform.rotateY,
        'rotateZ': Transform.rotateZ,
        'rotateAxis': Transform.rotateAxis,
        'scale': Transform.scale,
        'skew': Transform.skew,
        'matrix3d': function() {
            return arguments;
        }
    };

    /**
     * Clone this scene
     *
     * @method create
     * @return {Scene} deep copy of this scene
     */
    Scene.prototype.create = function create() {
        return new Scene(this._definition);
    };

    function _resolveTransformMatrix(matrixDefinition) {
        for (var type in _MATRIX_GENERATORS) {
            if (type in matrixDefinition) {
                var args = matrixDefinition[type];
                if (!(args instanceof Array)) args = [args];
                return _MATRIX_GENERATORS[type].apply(this, args);
            }
        }
    }

    // parse transform into tree of render nodes, doing matrix multiplication
    // when available
    function _parseTransform(definition) {
        var transformDefinition = definition.transform;
        var opacity = definition.opacity;
        var origin = definition.origin;
        var align = definition.align;
        var size = definition.size;
        var transform = Transform.identity;
        if (transformDefinition instanceof Array) {
            if (transformDefinition.length === 16 && typeof transformDefinition[0] === 'number') {
                transform = transformDefinition;
            }
            else {
                for (var i = 0; i < transformDefinition.length; i++) {
                    transform = Transform.multiply(transform, _resolveTransformMatrix(transformDefinition[i]));
                }
            }
        }
        else if (transformDefinition instanceof Object) {
            transform = _resolveTransformMatrix(transformDefinition);
        }

        var result = new Modifier({
            transform: transform,
            opacity: opacity,
            origin: origin,
            align: align,
            size: size
        });
        return result;
    }

    function _parseArray(definition) {
        var result = new RenderNode();
        for (var i = 0; i < definition.length; i++) {
            var obj = _parse.call(this, definition[i]);
            if (obj) result.add(obj);
        }
        return result;
    }

    // parse object directly into tree of RenderNodes
    function _parse(definition) {
        var result;
        var id;
        if (definition instanceof Array) {
            result = _parseArray.call(this, definition);
        }
        else {
            id = this._objects.length;
            if (definition.render && (definition.render instanceof Function)) {
                result = definition;
            }
            else if (definition.target) {
                var targetObj = _parse.call(this, definition.target);
                var obj = _parseTransform.call(this, definition);

                result = new RenderNode(obj);
                result.add(targetObj);
                if (definition.id) this.id[definition.id] = obj;
            }
            else if (definition.id) {
                result = new RenderNode();
                this.id[definition.id] = result;
            }
        }
        this._objects[id] = result;
        return result;
    }

    /**
     * Builds and renders a scene graph based on a canonical declarative scene definition.
     * See examples/Scene/example.js.
     *
     * @method load
     * @param {Object} definition definition in the format of a render spec.
     */
    Scene.prototype.load = function load(definition) {
        this._definition = definition;
        this.id = {};
        this._objects = [];
        this.node.set(_parse.call(this, definition));
    };

    /**
     * Add renderables to this component's render tree
     *
     * @method add
     *
     * @param {Object} obj renderable object
     * @return {RenderNode} Render wrapping provided object, if not already a RenderNode
     */
    Scene.prototype.add = function add() {
        return this.node.add.apply(this.node, arguments);
    };

    /**
     * Generate a render spec from the contents of this component.
     *
     * @private
     * @method render
     * @return {number} Render spec for this component
     */
    Scene.prototype.render = function render() {
        return this.node.render.apply(this.node, arguments);
    };

    module.exports = Scene;
});
<commit_msg>Support function-wrapped transforms in Scene definitions.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Owner: mark@famo.us
 * @license MPL 2.0
 * @copyright Famous Industries, Inc. 2014
 */

define(function(require, exports, module) {
    var Transform = require('./Transform');
    var Modifier = require('./Modifier');
    var RenderNode = require('./RenderNode');

    /**
     * Builds and renders a scene graph based on a declarative structure definition.
     * See the Scene examples in the examples distribution (http://github.com/Famous/examples.git).
     *
     * @class Scene
     * @constructor
     * @param {Object|Array|Spec} definition in the format of a render spec.
     */
    function Scene(definition) {
        this.id = null;
        this._objects = null;

        this.node = new RenderNode();
        this._definition = null;

        if (definition) this.load(definition);
    }

    var _MATRIX_GENERATORS = {
        'translate': Transform.translate,
        'rotate': Transform.rotate,
        'rotateX': Transform.rotateX,
        'rotateY': Transform.rotateY,
        'rotateZ': Transform.rotateZ,
        'rotateAxis': Transform.rotateAxis,
        'scale': Transform.scale,
        'skew': Transform.skew,
        'matrix3d': function() {
            return arguments;
        }
    };

    /**
     * Clone this scene
     *
     * @method create
     * @return {Scene} deep copy of this scene
     */
    Scene.prototype.create = function create() {
        return new Scene(this._definition);
    };

    function _resolveTransformMatrix(matrixDefinition) {
        for (var type in _MATRIX_GENERATORS) {
            if (type in matrixDefinition) {
                var args = matrixDefinition[type];
                if (!(args instanceof Array)) args = [args];
                return _MATRIX_GENERATORS[type].apply(this, args);
            }
        }
    }

    // parse transform into tree of render nodes, doing matrix multiplication
    // when available
    function _parseTransform(definition) {
        var transformDefinition = definition.transform;
        var opacity = definition.opacity;
        var origin = definition.origin;
        var align = definition.align;
        var size = definition.size;
        var transform = Transform.identity;
        if (transformDefinition instanceof Array) {
            if (transformDefinition.length === 16 && typeof transformDefinition[0] === 'number') {
                transform = transformDefinition;
            }
            else {
                for (var i = 0; i < transformDefinition.length; i++) {
                    transform = Transform.multiply(transform, _resolveTransformMatrix(transformDefinition[i]));
                }
            }
        }
        else if (transformDefinition instanceof Function) {
            transform = transformDefinition;
        }
        else if (transformDefinition instanceof Object) {
            transform = _resolveTransformMatrix(transformDefinition);
        }

        var result = new Modifier({
            transform: transform,
            opacity: opacity,
            origin: origin,
            align: align,
            size: size
        });
        return result;
    }

    function _parseArray(definition) {
        var result = new RenderNode();
        for (var i = 0; i < definition.length; i++) {
            var obj = _parse.call(this, definition[i]);
            if (obj) result.add(obj);
        }
        return result;
    }

    // parse object directly into tree of RenderNodes
    function _parse(definition) {
        var result;
        var id;
        if (definition instanceof Array) {
            result = _parseArray.call(this, definition);
        }
        else {
            id = this._objects.length;
            if (definition.render && (definition.render instanceof Function)) {
                result = definition;
            }
            else if (definition.target) {
                var targetObj = _parse.call(this, definition.target);
                var obj = _parseTransform.call(this, definition);

                result = new RenderNode(obj);
                result.add(targetObj);
                if (definition.id) this.id[definition.id] = obj;
            }
            else if (definition.id) {
                result = new RenderNode();
                this.id[definition.id] = result;
            }
        }
        this._objects[id] = result;
        return result;
    }

    /**
     * Builds and renders a scene graph based on a canonical declarative scene definition.
     * See examples/Scene/example.js.
     *
     * @method load
     * @param {Object} definition definition in the format of a render spec.
     */
    Scene.prototype.load = function load(definition) {
        this._definition = definition;
        this.id = {};
        this._objects = [];
        this.node.set(_parse.call(this, definition));
    };

    /**
     * Add renderables to this component's render tree
     *
     * @method add
     *
     * @param {Object} obj renderable object
     * @return {RenderNode} Render wrapping provided object, if not already a RenderNode
     */
    Scene.prototype.add = function add() {
        return this.node.add.apply(this.node, arguments);
    };

    /**
     * Generate a render spec from the contents of this component.
     *
     * @private
     * @method render
     * @return {number} Render spec for this component
     */
    Scene.prototype.render = function render() {
        return this.node.render.apply(this.node, arguments);
    };

    module.exports = Scene;
});
<|endoftext|>


<commit_before>var BaseView, Handlebars, modelUtils, templateFinder, _;

templateFinder = require('./templateFinder');
Handlebars = require('handlebars');
_ = require('underscore');

// Lazy-required.
BaseView = null;
modelUtils = null;

module.exports = {
  view: function(viewName, block) {
    var ViewClass, html, options, view;

    BaseView = BaseView || require('./base/view');
    modelUtils = modelUtils || require('./modelUtils');
    viewName = modelUtils.underscorize(viewName);
    options = block.hash || {};

    // Pass through a reference to the app.
    if (this._app) {
      options.app = this._app;
    }

    // Pass through a reference to the parent view.
    if (this._view) {
      options.parentView = this._view;
    }

    // get the Backbone.View based on viewName
    ViewClass = BaseView.getView(viewName);
    view = new ViewClass(options);

    // create the outerHTML using className, tagName
    html = view.getHtml();
    return new Handlebars.SafeString(html);
  },

  partial: function(templateName, block) {
    var data, html, options, template;

    template = templateFinder.getTemplate(templateName);
    options = block.hash || {};
    data = _.isEmpty(options) ? this : options.context ? options.context : options;
    data = _.clone(data);
    data._app = data._app || this._app;
    html = template(data);
    return new Handlebars.SafeString(html);
  },

  json: function(object) {
    return new Handlebars.SafeString(JSON.stringify(object) || 'null');
  },

  /**
   * Extend `each` to pass through important context. By default, `each` calls
   * `options.fn` without a calling context.
   */
  each: function(context, options) {
    var callingContext = getOptionsFromContext(this);
    // Make sure `this._app`, `this._view`, etc are available.
    options.fn = options.fn.bind(callingContext);
    // Call the original helper with new context.
    Handlebars.helpers.each.call(this, context, options);
  }
};

/**
 * Grab important underscored properties from the current context.
 * These properties come from BaseView::decorateTemplateData().
 */
function getOptionsFromContext(obj) {
  var options, keys, value;

  keys = [
    '_app',
    '_view',
    '_model',
    '_collection'
  ];

  options = keys.reduce(function(memo, key) {
    value = obj[key];
    if (value) {
      memo[key] = value;
    }
    return memo;
  }, {});

  return options;
}<commit_msg>Fix custom 'each' Handlebars helper<commit_after>var BaseView, Handlebars, modelUtils, templateFinder, _;

templateFinder = require('./templateFinder');
Handlebars = require('handlebars');
_ = require('underscore');

// Lazy-required.
BaseView = null;
modelUtils = null;

var oldEach = Handlebars.helpers.each;

module.exports = {
  view: function(viewName, block) {
    var ViewClass, html, options, view;

    BaseView = BaseView || require('./base/view');
    modelUtils = modelUtils || require('./modelUtils');
    viewName = modelUtils.underscorize(viewName);
    options = block.hash || {};

    // Pass through a reference to the app.
    if (this._app) {
      options.app = this._app;
    }

    // Pass through a reference to the parent view.
    if (this._view) {
      options.parentView = this._view;
    }

    // get the Backbone.View based on viewName
    ViewClass = BaseView.getView(viewName);
    view = new ViewClass(options);

    // create the outerHTML using className, tagName
    html = view.getHtml();
    return new Handlebars.SafeString(html);
  },

  partial: function(templateName, block) {
    var data, html, options, template;

    template = templateFinder.getTemplate(templateName);
    options = block.hash || {};
    data = _.isEmpty(options) ? this : options.context ? options.context : options;
    data = _.clone(data);
    data._app = data._app || this._app;
    html = template(data);
    return new Handlebars.SafeString(html);
  },

  json: function(object) {
    return new Handlebars.SafeString(JSON.stringify(object) || 'null');
  },

  /**
   * Extend `each` to pass through important context. By default, `each` calls
   * `options.fn` without a calling context.
   */
  each: function(context, options) {
    var callingContext = getOptionsFromContext(this);
    // Make sure `this._app`, `this._view`, etc are available.
    options.fn = options.fn.bind(callingContext);
    // Call the original helper with new context.
    return oldEach.call(this, context, options);
  }
};

/**
 * Grab important underscored properties from the current context.
 * These properties come from BaseView::decorateTemplateData().
 */
function getOptionsFromContext(obj) {
  var options, keys, value;

  keys = [
    '_app',
    '_view',
    '_model',
    '_collection'
  ];

  options = keys.reduce(function(memo, key) {
    value = obj[key];
    if (value) {
      memo[key] = value;
    }
    return memo;
  }, {});

  return options;
}<|endoftext|>


<commit_before>import Vue from "vue";

export default Vue.extend({
    template: `

Group Name: {{params.value}}

                    Child {{(idx + 1)}} - {{header.headerName}}

Athlete's Name:

{{athlete}}

    `,
    data: function() {
        return {
            athlete: null
        };
    },
    beforeMount() {
        var params = this.params,
            isHeader = params.rowIndex === undefined,
            isGroupedHeader = !!params.colDef.children,
            valueToDisplay = params.value.value ? params.value.value : '- Missing -';

        this.setState({
            athlete: valueToDisplay,
            isHeader: isHeader,
            isGroupedHeader: isGroupedHeader
        });

        data.color = this.params.color || 'white';
    },
    methods: {
        setState(obj) {
            const that = this;

            Object.keys(obj).forEach(function(key) { that[key] = obj[key]; });
        }
    }
});<commit_msg>RTI-193 Vue Customer Header Toolip Example Throws Exception (not a regression)<commit_after>import Vue from "vue";

export default Vue.extend({
    template: `

Group Name: {{params.value}}

                    Child {{(idx + 1)}} - {{header.headerName}}

Athlete's Name:

{{athlete}}

    `,
    data: function() {
        return {
            athlete: null
        };
    },
    beforeMount() {
        var params = this.params,
            isHeader = params.rowIndex === undefined,
            isGroupedHeader = !!params.colDef.children,
            valueToDisplay = params.value.value ? params.value.value : '- Missing -';

        this.setState({
            athlete: valueToDisplay,
            isHeader: isHeader,
            isGroupedHeader: isGroupedHeader
        });
    },
    methods: {
        setState(obj) {
            const that = this;

            Object.keys(obj).forEach(function(key) { that[key] = obj[key]; });
        }
    }
});
<|endoftext|>


<commit_before>class MessagesComponent extends HTMLElement {
  constructor() {
    super();

    ajaxMessagemParoco();
  }
}

function ajaxMessagemParoco(href) {
  const xmlhttp = new XMLHttpRequest();
  const url = href ? href : `${backEndUrl}/api/mensagensParoco`;

  xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let data = JSON.parse(this.responseText);
      createMessages(data);
    }
  };

  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function createMessages(res) {
  createPaginationButtons(res);

  var message = document.querySelector("#message");

  for (let i = 0; i < res.data.length; i++) {
    let post_preview = document.createElement("div");
    post_preview.className = "post-preview";

    let post_ancher = document.createElement("a");
    let post_ancher_href = document.createAttribute("href");
    post_ancher_href.value = res.data[i].link;
    post_ancher.target = "_blank";
    post_ancher.setAttributeNode(post_ancher_href);

    let post_title = document.createElement("h2");
    post_title.className = "post-title";
    post_title.appendChild(document.createTextNode(res.data[i]["titulo"]));

    let post_subtitle = document.createElement("h3");
    post_subtitle.className = "post-subtitle";
    post_subtitle.appendChild(document.createTextNode(res.data[i]["subtitulo"]));

    post_ancher.appendChild(post_title);
    post_ancher.appendChild(post_subtitle);

    post_preview.appendChild(post_ancher);

    message.appendChild(post_preview);

    post_preview = document.createElement("div");
    post_preview.className = "post-preview";

    let post_paragraph = document.createElement("p");
    post_paragraph.className = "post-meta";
    post_paragraph.innerHTML = res.data[i].mensagem;

    post_preview.appendChild(post_paragraph);

    message.appendChild(post_preview);

    hr = document.createElement("hr");
    message.appendChild(hr);
  }
}

window.customElements.define("home-messages", MessagesComponent);

function createPaginationButtons(res) {
  let rowPagination = document.querySelector('#home-pagination');
  removePaginationButton(rowPagination);

  rowPagination.appendChild(viewButtons(res.prev_page_url, "Anterior"));
  for (let i = 1; i <= res.last_page; i++) {
    let button = viewButtons(`${res.path}?page=${i}`, i);
    if (i == res.current_page) button.firstElementChild.style.backgroundColor = '#ccc';
    rowPagination.appendChild(button);
  }
  rowPagination.appendChild(viewButtons(res.next_page_url, "PrÃ³ximo"));

  let links = document.querySelectorAll('.page-link');
  links.forEach(link => {
    link.addEventListener("click", function () {
      removePost();
      ajaxMessagemParoco(this.getAttribute('data-href'));
      window.scrollTo(0, 0);
    });
  });
 }

function viewButtons(url, i) {
  let li = document.createElement('li');
  li.className = `page-item`;
  li.innerHTML = `<a class="page-link" data-href="${url}">${i}</a>`;

  return li;
}

function removePost() {
  let messages = document.querySelector('#message');
  while (messages.firstChild) {
    messages.removeChild(messages.firstChild);
  }
}

function removePaginationButton(rowPagination) {
  while (rowPagination.firstChild) {
    rowPagination.removeChild(rowPagination.firstChild);
  }
}
<commit_msg>Commit<commit_after>class MessagesComponent extends HTMLElement {
  constructor() {
    super();

    ajaxMessagemParoco();
  }
}

function ajaxMessagemParoco(href) {
  const xmlhttp = new XMLHttpRequest();
  const url = href ? href : `${backEndUrl}/api/mensagensParoco`;

  xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let data = JSON.parse(this.responseText);
      createMessages(data);
    }
  };

  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function createMessages(res) {
  createPaginationButtons(res);

  var message = document.querySelector("#message");

  for (let i = 0; i < res.data.length; i++) {
    let post_preview = document.createElement("div");
    post_preview.className = "post-preview";

    let post_ancher = document.createElement("a");
    let post_ancher_href = document.createAttribute("href");
    post_ancher_href.value = res.data[i].link;
    post_ancher.target = "_blank";
    post_ancher.setAttributeNode(post_ancher_href);

    let post_title = document.createElement("h2");
    post_title.className = "post-title";
    post_title.appendChild(document.createTextNode(res.data[i]["titulo"]));

    let post_subtitle = document.createElement("h3");
    post_subtitle.className = "post-subtitle";
    post_subtitle.appendChild(document.createTextNode(res.data[i]["subtitulo"]));

    post_ancher.appendChild(post_title);
    post_ancher.appendChild(post_subtitle);

    post_preview.appendChild(post_ancher);

    message.appendChild(post_preview);

    post_preview = document.createElement("div");
    post_preview.className = "post-preview";

    let post_paragraph = document.createElement("p");
    post_paragraph.className = "post-meta";
    post_paragraph.innerHTML = res.data[i].mensagem;

    post_preview.appendChild(post_paragraph);

    message.appendChild(post_preview);

    hr = document.createElement("hr");
    message.appendChild(hr);
  }
}

window.customElements.define("home-messages", MessagesComponent);

function createPaginationButtons(res) {
  let rowPagination = document.querySelector('#home-pagination');
  removePaginationButton(rowPagination);

  rowPagination.appendChild(viewButtons(res.prev_page_url, "Anterior"));
  for (let i = 1; i <= res.last_page; i++) {
    let button = viewButtons(`${res.path}?page=${i}`, i);
    if (i == res.current_page) button.firstElementChild.style.backgroundColor = '#ccc';
    rowPagination.appendChild(button);
  }
  rowPagination.appendChild(viewButtons(res.next_page_url, "Próximo"));

  let links = document.querySelectorAll('.page-link');
  links.forEach(link => {
    link.addEventListener("click", function () {
      removePost();
      ajaxMessagemParoco(this.getAttribute('data-href'));
      window.scrollTo(0, 0);
    });
  });
 }

function viewButtons(url, i) {
  let li = document.createElement('li');
  li.className = `page-item`;
  li.innerHTML = `<a class="page-link" data-href="${url}">${i}</a>`;

  return li;
}

function removePost() {
  let messages = document.querySelector('#message');
  while (messages.firstChild) {
    messages.removeChild(messages.firstChild);
  }
}

function removePaginationButton(rowPagination) {
  while (rowPagination.firstChild) {
    rowPagination.removeChild(rowPagination.firstChild);
  }
}
<|endoftext|>


<commit_before>describe('retirementFormController', function() {
  var $scope, $controller, $httpBackend, miqService;

  beforeEach(module('ManageIQ'));

  beforeEach(inject(function($rootScope, _$controller_, _$httpBackend_, _miqService_) {
    miqService = _miqService_;
    spyOn(miqService, 'miqFlash');
    spyOn(miqService, 'miqAjaxButton');
    spyOn(miqService, 'sparkleOn');
    spyOn(miqService, 'sparkleOff');
    $scope = $rootScope.$new();
    $scope.retirementInfo = { retirementDate: '', retirementWarning: ''};
    $httpBackend = _$httpBackend_;
    $controller = _$controller_('retirementFormController', {
      $scope: $scope,
      objectIds: [1000000000001],
      miqService: miqService
    });
  }));

  beforeEach(inject(function(_$controller_) {
    var retirementFormResponse = {
      retirement_date: '12/31/2015',
      retirement_warning: '0'
    };
    $httpBackend.whenGET('retirement_info/1000000000001').respond(retirementFormResponse);
    $httpBackend.flush();
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('initialization', function() {
    it('sets the retirementDate to the value returned with http request', function() {
      expect($scope.retirementInfo.retirementDate).toEqual(new Date('2015-12-31'));
    });

    it('sets the retirementWarning to the value returned with http request', function() {
      expect($scope.retirementInfo.retirementWarning).toEqual('0');
    });
  });

  describe('#cancelClicked', function() {
    beforeEach(function() {
      $scope.angularForm = {
        $setPristine: function(value) {}
      };
      $scope.cancelClicked();
    });

    it('turns the spinner on via the miqService', function() {
      expect(miqService.sparkleOn).toHaveBeenCalled();
    });

    it('turns the spinner on once', function() {
      expect(miqService.sparkleOn.calls.count()).toBe(1);
    });

    it('delegates to miqService.miqAjaxButton', function() {
      expect(miqService.miqAjaxButton).toHaveBeenCalledWith('retire?button=cancel');
    });
  });

  describe('#saveClicked', function() {
    beforeEach(function() {
      $scope.angularForm = {
        $setPristine: function (value){}
      };
      $scope.saveClicked();
    });

    it('turns the spinner on via the miqService', function() {
      expect(miqService.sparkleOn).toHaveBeenCalled();
    });

    it('turns the spinner on once', function() {
      expect(miqService.sparkleOn.calls.count()).toBe(1);
    });

    it('delegates to miqService.miqAjaxButton', function() {
      var saveContent = {
        retire_date: $scope.retirementInfo.retirementDate,
        retire_warn: $scope.retirementInfo.retirementWarning
      };
      expect(miqService.miqAjaxButton).toHaveBeenCalledWith('retire?button=save', saveContent);
    });
  });
});
<commit_msg>Repair RetirementFormCtrl spec<commit_after>describe('retirementFormController', function() {
  var $scope, $controller, $httpBackend, miqService;

  beforeEach(module('ManageIQ'));

  beforeEach(inject(function($rootScope, _$controller_, _$httpBackend_, _miqService_) {
    miqService = _miqService_;
    spyOn(miqService, 'miqFlash');
    spyOn(miqService, 'miqAjaxButton');
    spyOn(miqService, 'sparkleOn');
    spyOn(miqService, 'sparkleOff');
    $scope = $rootScope.$new();
    $scope.retirementInfo = { retirementDate: '', retirementWarning: ''};
    $httpBackend = _$httpBackend_;
    $controller = _$controller_('retirementFormController as vm', {
      $scope: $scope,
      objectIds: [1000000000001],
      miqService: miqService
    });
  }));

  beforeEach(inject(function(_$controller_) {
    var retirementFormResponse = {
      retirement_date: '12/31/2015',
      retirement_warning: '0'
    };
    $httpBackend.whenGET('retirement_info/1000000000001').respond(retirementFormResponse);
    $httpBackend.flush();
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('initialization', function() {
    it('sets the retirementDate to the value returned with http request', function() {
      expect($scope.vm.retirementInfo.retirementDate).toEqual(new Date('2015-12-31'));
    });

    it('sets the retirementWarning to the value returned with http request', function() {
      expect($scope.vm.retirementInfo.retirementWarning).toEqual('0');
    });
  });

  describe('#cancelClicked', function() {
    beforeEach(function() {
      $scope.angularForm = {
        $setPristine: function(value) {}
      };
      $scope.vm.cancelClicked();
    });

    it('turns the spinner on via the miqService', function() {
      expect(miqService.sparkleOn).toHaveBeenCalled();
    });

    it('turns the spinner on once', function() {
      expect(miqService.sparkleOn.calls.count()).toBe(1);
    });

    it('delegates to miqService.miqAjaxButton', function() {
      expect(miqService.miqAjaxButton).toHaveBeenCalledWith('retire?button=cancel');
    });
  });

  describe('#saveClicked', function() {
    beforeEach(function() {
      $scope.angularForm = {
        $setPristine: function (value){}
      };
      $scope.vm.saveClicked();
    });

    it('turns the spinner on via the miqService', function() {
      expect(miqService.sparkleOn).toHaveBeenCalled();
    });

    it('turns the spinner on once', function() {
      expect(miqService.sparkleOn.calls.count()).toBe(1);
    });

    it('delegates to miqService.miqAjaxButton', function() {
      var saveContent = {
        retire_date: $scope.vm.retirementInfo.retirementDate,
        retire_warn: $scope.vm.retirementInfo.retirementWarning
      };
      expect(miqService.miqAjaxButton).toHaveBeenCalledWith('retire?button=save', saveContent);
    });
  });
});
<|endoftext|>


<commit_before>var page_cleaner_interval;

function find_start(parent, klass){

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    if (parent.hasClass(klass)){
        start = parent;
    } else {
        start = parent.find('.' + klass);
    }

    //console.debug('start for ' + klass + ' in ' + parent + ':');
    //console.debug(start);

    return start;
}
function parseBool(val) {
    if (typeof val === 'string') {
        if (val.toLowerCase() === 'true') {
            return true;

        } else if (val.toLowerCase() === 'false') {
            return false;

        } else {
            return null;

        }
    } else if (typeof val === 'int') {
        if (val === 0) {
            return false;

        } else {
            return true;

        }
    } else {
        return null;

    }
}
function update_instance(model, iid, created, new_html) {
    // This function will work with anything, but best for replacing a

    // with a new one, already rendered.
    //

    new_  = $(new_html);

    table = $('#model_' + model + '_table');
    old   = $('#' + model + '_' + iid);

    if (old.length) {
        // this instance was already known.
        // remove the old corresponding ROW.
        old.attr('id', 'old_' + old.attr('id'));
        old.addClass('to-remove');

        // in case of quick-multi-updates
        old.removeClass('new-fade');
        old.stop(true, true);

        old.before(new_);

        old.hide();

    } else {
        // we've got a new challenger, insert it at the end.
        last = table.find('tbody:last');

        last.append(new_);

        // Update the total number of elements.
        count = $('#model_' + model + '_count');
        count.html(parseInt(count.html()) + 1);

        if(parseInt(count.html()) == 1) {
            nomore = table.find('tfoot > tr.no-data');
            nomore.hide();
        }
    }

    new_.addClass('new-fade');
    new_.show();

    // don't forget links, modals, popovers…
    setup_everything(new_);

    //console.log('re-sort on ' + [table.get(0).config.sortList]);

    // re-sort the table.
    table.trigger("update")
        .trigger("sorton", [table.get(0).config.sortList]);
      //.trigger("appendCache");
      //.trigger("applyWidgets");

    // remove old stuff marked as such.
    page_cleaner();
}
function remove_instance(model, iid) {
    // This function will work with anything, but best for replacing a

    // with a new one, already rendered.

    table = $('#model_' + model + '_table');
    old   = $('#' + model + '_' + iid);

    if (old.length) {
        // this instance is in the page. Make it "whoosh!".
        old.attr('id', 'old_' + old.attr('id'));
        old.addClass('to-remove');

        // in case of quick-multi-updates
        old.removeClass('new-fade');
        old.stop(true, true);

        old.hide();

        // Update the total number of elements.
        count = $('#model_' + model + '_count');
        count.html(parseInt(count.html()) - 1);

        if(parseInt(count.html()) < 1) {
            nomore = table.find('tfoot > tr.no-data');
            nomore.show();
        }
    }

    // re-sort the table.
    table.trigger("update")
        .trigger("sorton", [table.get(0).config.sortList]);

    // remove old stuff marked as such.
    page_cleaner();
}
function popover_placement(objekt, parent) {

    if ($(parent).hasClass('popover-left')){
        return 'left';

    } else if ($(parent).hasClass('popover-bottom')){
        return 'bottom';

    } else if ($(parent).hasClass('popover-top')){
        return 'top';

    } else {
        return 'right';
    }
}
function page_cleaner() {
    // most of the time, this operation fails when run from inside the
    // update_instance() function, but succeeds when run from outside.
    // Don't ask me why. But it has to be done, else the page is more
    // and more cluttered when time passes by.

    try {
        $('body').find('.to-remove').each(function(){
            $(this).remove();
        });

    } catch (err) {
        try {
            //console.debug('page_cleaner: ' + err);

        } catch (err) {
            // nothing. Silently ignored.
        }
    }
}
function table_sort_extractor(node) {

    s = $(node).data('sort');

    if (typeof s === 'undefined') {
        return node.innerHTML;

    } else {
        return s;

    }
}
function setup_table_sorter() {
    $("table.sortable").tablesorter({
        //sortList: [[0, 0], [1, 0]],
        sortList: [[0, 0]],
        textExtraction: table_sort_extractor,
    });
    //.bind('sortEnd', function(sorter) {
    //  currentSort = sorter.target.config.sortList;
    //});
}
function setup_popovers(parent){

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    // We need the "click" for touch interfaces to be able to close
    // twitter popovers. Not needed for clickovers, though, which
    // work perfectly.
    // https://github.com/twitter/bootstrap/issues/3417
    parent.find('[rel="popover"]').popover({
            placement: popover_placement }).click(function(e) {
        $(this).popover('toggle');
    });
}
function setup_hover_muters(parent){

    find_start(parent, 'hover-unmute-children')
        .hover(function() {
            $(this).find('.hover-muted').animate({
                opacity: 1
            });
        }, function() {
            $(this).find('.hover-muted').stop(true, true).animate({
                opacity: 0
            });
    });
}
function setup_tooltips(parent){

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    // We need the "click" for touch interfaces to be able to close
    // twitter popovers. Not needed for clickovers, though, which
    // work perfectly.
    // https://github.com/twitter/bootstrap/issues/3417
    parent.find('[rel="tooltip"]').tooltip({
            placement: popover_placement }).click(function(e) {
        $(this).tooltip('toggle');
    });
}
function setup_clickovers(parent) {

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    parent.find('[rel="clickover"]').each(function(){

        params = {};

        if ($(this).hasClass('clickover-large')) {
            $.extend(params, { width: 400 });
        }

        if ($(this).hasClass('iframed')) {
            $.extend(params, { width: 800, height: 450 });
        }

        if ($(this).hasClass('clickover-auto-close')) {
            $.extend(params, { auto_close: 5000 });
        }

        // WARNING: don't use "data-clickover", it will conflict
        // with rel="clickover" and the clickover will not work.

        data_ = $(this).data('clickover-params');

        if (typeof data_ != 'undefined') {
            $.extend(params, eval(data_));
        }

        $.extend(params, { placement: popover_placement });

        $(this).clickover(params);
    });
}
function setup_delayed_loaders(parent) {
    // https://github.com/twitter/bootstrap/issues/2380

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    parent.find('.delayed-loader').each(function() {
        $(this).click(function(){
            target = $('body').find($(this).attr('href')).find('.delayed-target');

            //console.log('(delayed until now) loading of ' + target.attr('delayed-src'));

            target.attr('src', target.attr('delayed-src'));
        });
    });
}
function launch_faders(parent) {
    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    function flash_fade(objekt){
        curback = objekt.css('backgroundColor');

        objekt.animate({ backgroundColor: "#ffff99" }, 250, function() {
            objekt.delay(2500).animate({ backgroundColor: curback }, 1000);

            // Fade is done, object is not "new" anymore.
            objekt.removeClass('new-fade');
        });
    }

    if (parent.hasClass('new-fade')) {
        flash_fade(parent);
    }

    parent.find('.new-fade').each(flash_fade);
}
function setup_everything(parent) {

    setup_tooltips(parent);
    setup_hover_muters(parent);
    setup_popovers(parent);
    setup_clickovers(parent);
    setup_delayed_loaders(parent);

    try {
        setup_preferences_actions(parent);

    } catch (err) {
        // nothing. the preferences thing exists only
        //when user is authenticated, else it will fail.
    }

    launch_faders(parent);
}
function setup_auto_cleaner() {
    // every 10 minutes, the page is cleaned from old and orphaned elements.

    page_cleaner_interval = setInterval(page_cleaner, 600000);
}
function setup_keyboard() {

    $(document).keydown(function(ev) {

        var goto_location = null;

        if(ev.which == 37) {
            goto_location = $('a#previous');
        }

        if(ev.which == 39) {
            goto_location = $('a#next');
        }

        if (!!goto_location) {
            document.location = goto_location.attr('href');
            return false; // don't execute the default action (scrolling or whatever)
        }
    });
}
function common_init() {

    setup_everything();

    //setup_table_sorter();
    setup_auto_cleaner();

    setup_keyboard();

}
<commit_msg>A comment about use strict. My code breaks with it. Gosh.<commit_after>// warning: don't "use strict"; here, it will break things.
// I need to learn to write good JS first. Sorry for that.

var page_cleaner_interval;

function find_start(parent, klass){

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    if (parent.hasClass(klass)){
        start = parent;
    } else {
        start = parent.find('.' + klass);
    }

    //console.debug('start for ' + klass + ' in ' + parent + ':');
    //console.debug(start);

    return start;
}
function parseBool(val) {
    if (typeof val === 'string') {
        if (val.toLowerCase() === 'true') {
            return true;

        } else if (val.toLowerCase() === 'false') {
            return false;

        } else {
            return null;

        }
    } else if (typeof val === 'int') {
        if (val === 0) {
            return false;

        } else {
            return true;

        }
    } else {
        return null;

    }
}
function update_instance(model, iid, created, new_html) {
    // This function will work with anything, but best for replacing a

    // with a new one, already rendered.
    //

    new_  = $(new_html);

    table = $('#model_' + model + '_table');
    old   = $('#' + model + '_' + iid);

    if (old.length) {
        // this instance was already known.
        // remove the old corresponding ROW.
        old.attr('id', 'old_' + old.attr('id'));
        old.addClass('to-remove');

        // in case of quick-multi-updates
        old.removeClass('new-fade');
        old.stop(true, true);

        old.before(new_);

        old.hide();

    } else {
        // we've got a new challenger, insert it at the end.
        last = table.find('tbody:last');

        last.append(new_);

        // Update the total number of elements.
        count = $('#model_' + model + '_count');
        count.html(parseInt(count.html()) + 1);

        if(parseInt(count.html()) == 1) {
            nomore = table.find('tfoot > tr.no-data');
            nomore.hide();
        }
    }

    new_.addClass('new-fade');
    new_.show();

    // don't forget links, modals, popovers…
    setup_everything(new_);

    //console.log('re-sort on ' + [table.get(0).config.sortList]);

    // re-sort the table.
    table.trigger("update")
        .trigger("sorton", [table.get(0).config.sortList]);
      //.trigger("appendCache");
      //.trigger("applyWidgets");

    // remove old stuff marked as such.
    page_cleaner();
}
function remove_instance(model, iid) {
    // This function will work with anything, but best for replacing a

    // with a new one, already rendered.

    table = $('#model_' + model + '_table');
    old   = $('#' + model + '_' + iid);

    if (old.length) {
        // this instance is in the page. Make it "whoosh!".
        old.attr('id', 'old_' + old.attr('id'));
        old.addClass('to-remove');

        // in case of quick-multi-updates
        old.removeClass('new-fade');
        old.stop(true, true);

        old.hide();

        // Update the total number of elements.
        count = $('#model_' + model + '_count');
        count.html(parseInt(count.html()) - 1);

        if(parseInt(count.html()) < 1) {
            nomore = table.find('tfoot > tr.no-data');
            nomore.show();
        }
    }

    // re-sort the table.
    table.trigger("update")
        .trigger("sorton", [table.get(0).config.sortList]);

    // remove old stuff marked as such.
    page_cleaner();
}
function popover_placement(objekt, parent) {

    if ($(parent).hasClass('popover-left')){
        return 'left';

    } else if ($(parent).hasClass('popover-bottom')){
        return 'bottom';

    } else if ($(parent).hasClass('popover-top')){
        return 'top';

    } else {
        return 'right';
    }
}
function page_cleaner() {
    // most of the time, this operation fails when run from inside the
    // update_instance() function, but succeeds when run from outside.
    // Don't ask me why. But it has to be done, else the page is more
    // and more cluttered when time passes by.

    try {
        $('body').find('.to-remove').each(function(){
            $(this).remove();
        });

    } catch (err) {
        try {
            //console.debug('page_cleaner: ' + err);

        } catch (err) {
            // nothing. Silently ignored.
        }
    }
}
function table_sort_extractor(node) {

    s = $(node).data('sort');

    if (typeof s === 'undefined') {
        return node.innerHTML;

    } else {
        return s;

    }
}
function setup_table_sorter() {
    $("table.sortable").tablesorter({
        //sortList: [[0, 0], [1, 0]],
        sortList: [[0, 0]],
        textExtraction: table_sort_extractor,
    });
    //.bind('sortEnd', function(sorter) {
    //  currentSort = sorter.target.config.sortList;
    //});
}
function setup_popovers(parent){

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    // We need the "click" for touch interfaces to be able to close
    // twitter popovers. Not needed for clickovers, though, which
    // work perfectly.
    // https://github.com/twitter/bootstrap/issues/3417
    parent.find('[rel="popover"]').popover({
            placement: popover_placement }).click(function(e) {
        $(this).popover('toggle');
    });
}
function setup_hover_muters(parent){

    find_start(parent, 'hover-unmute-children')
        .hover(function() {
            $(this).find('.hover-muted').animate({
                opacity: 1
            });
        }, function() {
            $(this).find('.hover-muted').stop(true, true).animate({
                opacity: 0
            });
    });
}
function setup_tooltips(parent){

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    // We need the "click" for touch interfaces to be able to close
    // twitter popovers. Not needed for clickovers, though, which
    // work perfectly.
    // https://github.com/twitter/bootstrap/issues/3417
    parent.find('[rel="tooltip"]').tooltip({
            placement: popover_placement }).click(function(e) {
        $(this).tooltip('toggle');
    });
}
function setup_clickovers(parent) {

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    parent.find('[rel="clickover"]').each(function(){

        params = {};

        if ($(this).hasClass('clickover-large')) {
            $.extend(params, { width: 400 });
        }

        if ($(this).hasClass('iframed')) {
            $.extend(params, { width: 800, height: 450 });
        }

        if ($(this).hasClass('clickover-auto-close')) {
            $.extend(params, { auto_close: 5000 });
        }

        // WARNING: don't use "data-clickover", it will conflict
        // with rel="clickover" and the clickover will not work.

        data_ = $(this).data('clickover-params');

        if (typeof data_ != 'undefined') {
            $.extend(params, eval(data_));
        }

        $.extend(params, { placement: popover_placement });

        $(this).clickover(params);
    });
}
function setup_delayed_loaders(parent) {
    // https://github.com/twitter/bootstrap/issues/2380

    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    parent.find('.delayed-loader').each(function() {
        $(this).click(function(){
            target = $('body').find($(this).attr('href')).find('.delayed-target');

            //console.log('(delayed until now) loading of ' + target.attr('delayed-src'));

            target.attr('src', target.attr('delayed-src'));
        });
    });
}
function launch_faders(parent) {
    if (typeof parent == 'undefined') {
        parent = $('body');
    }

    function flash_fade(objekt){
        curback = objekt.css('backgroundColor');

        objekt.animate({ backgroundColor: "#ffff99" }, 250, function() {
            objekt.delay(2500).animate({ backgroundColor: curback }, 1000);

            // Fade is done, object is not "new" anymore.
            objekt.removeClass('new-fade');
        });
    }

    if (parent.hasClass('new-fade')) {
        flash_fade(parent);
    }

    parent.find('.new-fade').each(flash_fade);
}
function setup_everything(parent) {

    setup_tooltips(parent);
    setup_hover_muters(parent);
    setup_popovers(parent);
    setup_clickovers(parent);
    setup_delayed_loaders(parent);

    try {
        setup_preferences_actions(parent);

    } catch (err) {
        // nothing. the preferences thing exists only
        //when user is authenticated, else it will fail.
    }

    launch_faders(parent);
}
function setup_auto_cleaner() {
    // every 10 minutes, the page is cleaned from old and orphaned elements.

    page_cleaner_interval = setInterval(page_cleaner, 600000);
}
function setup_keyboard() {

    $(document).keydown(function(ev) {

        var goto_location = null;

        if(ev.which == 37) {
            goto_location = $('a#previous');
        }

        if(ev.which == 39) {
            goto_location = $('a#next');
        }

        if (!!goto_location) {
            document.location = goto_location.attr('href');
            return false; // don't execute the default action (scrolling or whatever)
        }
    });
}
function common_init() {

    setup_everything();

    //setup_table_sorter();
    setup_auto_cleaner();

    setup_keyboard();

}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014, Facebook, Inc. All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
var FileFinder = require('node-find-files');
var fs = require('fs');
var path = require('path');

var EXTRACT_DOCBLOCK_REGEX = /^\s*(\/\*\*?(?:.|\r?\n)*?\*\/)/;
var IS_JSHINT_DOCBLOCK = /\/\*\*?\s*jshint\s+[a-zA-Z0-9]+\s*:\s*[a-zA-Z0-9]+/;

var ROOT_DIR = path.resolve(__dirname, '..');

var EXAMPLES_DIR = path.join(ROOT_DIR, 'examples');
var COVERAGE_TEMPLATE_PATH = path.join(ROOT_DIR, 'src', 'coverageTemplate.js');
var NODE_MODULES_DIR = path.join(ROOT_DIR, 'node_modules');
var VENDOR_DIR = path.join(ROOT_DIR, 'vendor');
var WEBSITE_DIR = path.join(ROOT_DIR, 'website');

var LICENSE_HEADER = [
  ' * Copyright (c) 2014, Facebook, Inc. All rights reserved.',
  ' *',
  ' * This source code is licensed under the BSD-style license found in the',
  ' * LICENSE file in the root directory of this source tree. An additional ' +
                                                                    'grant',
  ' * of patent rights can be found in the PATENTS file in the same directory.',
].join('\n');

function needsLicenseHeader(fileData) {
  if (/^#!/.test(fileData)) {
    fileData = fileData.split('\n');
    fileData.shift();
    fileData = fileData.join('\n');
  }
  return fileData.indexOf(LICENSE_HEADER) === -1;
}

function addLicenseHeader(fileData) {
  var preamble = '';
  var epilogue = '\n */'

  if (/^#!/.test(fileData)) {
    fileData = fileData.split('\n');
    preamble += fileData.shift() + '\n';
    fileData = fileData.join('\n');
  }

  preamble += '/**\n';

  var startingDocblock = EXTRACT_DOCBLOCK_REGEX.exec(fileData);
  if (startingDocblock && !IS_JSHINT_DOCBLOCK.test(startingDocblock)) {
    startingDocblock = startingDocblock[0];

    fileData = fileData.substr(startingDocblock.length);

    // Strip of starting/ending tokens
    var strippedDocblock =
      startingDocblock
        .replace(/^\/\*\*?\s*/, '')
        .replace(/\s*\*\/$/, '');

    if (strippedDocblock.trim().charAt(0) !== '*') {
      strippedDocblock = '* ' + strippedDocblock.trim();
    }

    epilogue = '\n *\n ' + strippedDocblock + epilogue;
  }

  return preamble + LICENSE_HEADER + epilogue + '\n' + fileData;
}

function main() {
  var finder = new FileFinder({
    rootFolder: ROOT_DIR,
    filterFunction: function(pathStr) {
      return (
        pathStr !== COVERAGE_TEMPLATE_PATH
        && pathStr.substr(0, EXAMPLES_DIR.length) !== EXAMPLES_DIR
        && pathStr.substr(0, NODE_MODULES_DIR.length) !== NODE_MODULES_DIR
        && pathStr.substr(0, VENDOR_DIR.length) !== VENDOR_DIR
        && pathStr.substr(0, WEBSITE_DIR.length) !== WEBSITE_DIR
        && path.extname(pathStr) === '.js'
      );
    }
  });

  finder.on('error', function(err) {
    console.error('Error: ' + (err.stack || err.msg || err));
    process.exit(1);
  });

  finder.on('match', function(pathStr) {
    console.log('Reading ' + pathStr + '...');
    fs.readFile(pathStr, 'utf8', function(err, fileData) {
      if (err) {
        throw err;
      }

      if (needsLicenseHeader(fileData)) {
        console.log('Adding license header to ' + pathStr + '...');
        addLicenseHeader(fileData);
        fs.writeFile(pathStr, addLicenseHeader(fileData), function(err) {
          if (err) {
            throw err;
          }
          console.log('Successfully updated ' + pathStr + '!');
        });
      }
    });
  });

  finder.startSearch();
}

if (require.main === module) {
  main();
}
<commit_msg>Remove licensify.<commit_after><|endoftext|>


<commit_before>/* qqq : implement */

let _;

if( typeof module !== 'undefined' )
{
  _ = require( 'wTools' );
  require( 'wConsequence' );
}

//

function Hydrogen()
{

}

//

function Oxygen()
{

}<commit_msg>BuildingH20 task, some idea very beginning<commit_after>/* qqq : implement */
let _;

if( typeof module !== 'undefined' )
{
  _ = require( 'wTools' );
  require( 'wConsequence' );
}

let hydTotal = 100;
let oxTotal = 50;
const molecul = _.Consequence({ capacity : 0 });

run( hydTotal, oxTotal );

//

function run( h, o )
{
  for( let i = 0; i < h; i++ )
  Hydrogen();

  for( let i = 0; i < o; i++ )
  Oxygen();
}

//

function Hydrogen()
{
  return _.time.out( _.intRandom( [ 0, 10000 ] ), () =>
  {
    molecul.take( 'h' );
    molecul.thenGive( ( atom ) =>
    {
      console.log( atom );
    } )
  } )
}

//

function Oxygen()
{
  return _.time.out( _.intRandom( [ 0, 10000 ] ), () =>
  {
    molecul.take( 'o' );
    molecul.thenGive( ( atom ) =>
    {
      console.log( atom );
    } )
  } )
}
<|endoftext|>


<commit_before>import { animate, stop } from "./animate";
import Promise from "./promise";

export default function predefinedTransitions(){
  this.setDefault({duration: 250});

  this.define('moveOver', function(oldView, insertNewView, dimension, direction, opts) {
    var property  = 'translate' + dimension.toUpperCase(),
        oldParams = {},
        newParams = {};

    oldParams[property] = (100 * direction) + '%';
    newParams[property] = ["0%", (-100 * direction) + '%'];

    stop(oldView);
    return insertNewView().then(function(newView){
      return Promise.all([
        animate(oldView, oldParams, opts),
        animate(newView, newParams, opts)
      ]);
    });
  });

  // The terminology here describes the direction that the content
  // moves. An alternative frame of reference is to describe which way
  // the view's point-of-view moves, which has the opposite sense.
  this.define('toRight', 'moveOver', 'x',  1 );
  this.define('toLeft',  'moveOver', 'x', -1 );
  this.define('toUp',    'moveOver', 'y', -1 );
  this.define('toDown',  'moveOver', 'y',  1 );

  // BEGIN-SNIPPET cross-fade-definition
  this.define('crossFade', function(oldView, insertNewView, opts) {
    stop(oldView);
    return insertNewView().then(function(newView) {
      return Promise.all([
        animate(oldView, {opacity: 0}, opts),
        animate(newView, {opacity: [1, 0]}, opts)
      ]);
    });
  });
  // END-SNIPPET

  this.define('fade', function(oldView, insertNewView, opts) {
    stop(oldView);
    return animate(oldView, {opacity: 0}, opts)
      .then(insertNewView)
      .then(function(newView){
        return animate(newView, {opacity: [1, 0]}, opts);
      });
  });

  this.define('rotateBelow', function(oldView, insertNewView, opts) {
    var direction = 1;
    if (opts && opts.direction === 'cw') {
      direction = -1;
    }
    stop(oldView);
    return insertNewView().then(function(newView) {
      oldView.$().css('transform-origin', '50% 150%');
      newView.$().css('transform-origin', '50% 150%');
      return Promise.all([
        animate(oldView, { rotateZ: -90*direction + 'deg' }, opts),
        animate(newView, { rotateZ: ['0deg', 90*direction+'deg'] }, opts),
      ]);
    });
  });
}
<commit_msg>annotate<commit_after>import { animate, stop } from "./animate";
import Promise from "./promise";

export default function predefinedTransitions(){
  this.setDefault({duration: 250});

  this.define('moveOver', function(oldView, insertNewView, dimension, direction, opts) {
    var property  = 'translate' + dimension.toUpperCase(),
        oldParams = {},
        newParams = {};

    oldParams[property] = (100 * direction) + '%';
    newParams[property] = ["0%", (-100 * direction) + '%'];

    stop(oldView);
    return insertNewView().then(function(newView){
      return Promise.all([
        animate(oldView, oldParams, opts),
        animate(newView, newParams, opts)
      ]);
    });
  });

  // The terminology here describes the direction that the content
  // moves. An alternative frame of reference is to describe which way
  // the view's point-of-view moves, which has the opposite sense.
  this.define('toRight', 'moveOver', 'x',  1 );
  this.define('toLeft',  'moveOver', 'x', -1 );
  this.define('toUp',    'moveOver', 'y', -1 );
  this.define('toDown',  'moveOver', 'y',  1 );

  // BEGIN-SNIPPET cross-fade-definition
  this.define('crossFade', function(oldView, insertNewView, opts) {
    stop(oldView);
    return insertNewView().then(function(newView) {
      return Promise.all([
        animate(oldView, {opacity: 0}, opts),
        animate(newView, {opacity: [1, 0]}, opts)
      ]);
    });
  });
  // END-SNIPPET

  // BEGIN-SNIPPET fade-definition
  this.define('fade', function(oldView, insertNewView, opts) {
    stop(oldView);
    return animate(oldView, {opacity: 0}, opts)
      .then(insertNewView)
      .then(function(newView){
        return animate(newView, {opacity: [1, 0]}, opts);
      });
  });
  // END-SNIPPET

  this.define('rotateBelow', function(oldView, insertNewView, opts) {
    var direction = 1;
    if (opts && opts.direction === 'cw') {
      direction = -1;
    }
    stop(oldView);
    return insertNewView().then(function(newView) {
      oldView.$().css('transform-origin', '50% 150%');
      newView.$().css('transform-origin', '50% 150%');
      return Promise.all([
        animate(oldView, { rotateZ: -90*direction + 'deg' }, opts),
        animate(newView, { rotateZ: ['0deg', 90*direction+'deg'] }, opts),
      ]);
    });
  });
}
<|endoftext|>


<commit_before>import defaults from './defaults';
import noop from './noop';

import remove from './methods/remove';
import reveal from './methods/reveal';
import sync from './methods/sync';
import watch from './methods/watch';

import { transformSupported, transitionSupported } from '../utils/browser';
import { getNode, logger } from '../utils/core';
import { deepAssign } from '../utils/generic';

export default function ScrollReveal (options = {}) {

	// Returns a new instance without `new` keyword.
	if (typeof this === 'undefined' || Object.getPrototypeOf(this) !== ScrollReveal.prototype) {
		return new ScrollReveal(options);
	}

	if (!ScrollReveal.isSupported()) {
		logger('This browser is not supported.');
		return noop;
	}

	this.initialized = false;
	document.documentElement.classList.add('sr');

	try {
		Object.defineProperty(this, 'defaults', {
			get: (() => {
				const config = {};
				deepAssign(config, defaults, options);
				return () => config;
			})(),
		});
	} catch (error) {
		logger(error.message);
		return noop;
	}

	this.store = {
		containers: [],
		elements: [],
		history: [],
		sequences: [],
	};

	const container = getNode(this.defaults.container);
	if (container) {
		this.store.containers.push(container);
	} else {
		logger('Failed to instantiate due to missing container.');
		return noop;
	}
}

ScrollReveal.isSupported = () => transformSupported() && transitionSupported();

ScrollReveal.prototype.remove = remove;
ScrollReveal.prototype.reveal = reveal;
ScrollReveal.prototype.sync = sync;
ScrollReveal.prototype.watch = watch;

/* istanbul ignore next */
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
	define(() => ScrollReveal);
} else if (typeof module !== 'undefined' && module.exports) {
	module.exports = ScrollReveal;
} else {
	window.ScrollReveal = ScrollReveal;
}
<commit_msg>refactor instantiation<commit_after>import defaults from './defaults';
import noop from './noop';

import remove from './methods/remove';
import reveal from './methods/reveal';
import sync from './methods/sync';
import watch from './methods/watch';

import { transformSupported, transitionSupported } from '../utils/browser';
import { getNode, logger } from '../utils/core';
import { deepAssign } from '../utils/generic';

export default function ScrollReveal (options = {}) {

	// Returns a new instance without `new` keyword.
	if (typeof this === 'undefined' || Object.getPrototypeOf(this) !== ScrollReveal.prototype) {
		return new ScrollReveal(options);
	}

	if (!ScrollReveal.isSupported()) {
		logger('This browser is not supported.');
		return noop;
	}

	try {
		Object.defineProperty(this, 'defaults', {
			get: (() => {
				const config = {};
				deepAssign(config, defaults, options);
				return () => config;
			})(),
		});
	} catch (error) {
		logger(error.message);
		return noop;
	}

	const container = getNode(this.defaults.container);
	if (!container) {
		logger('Failed to instantiate due to missing container.');
		return noop;
	}

	document.documentElement.classList.add('sr');

	this.store = {
		containers: [],
		elements: [],
		history: [],
		sequences: [],
	};

	this.store.containers.push(container);
	this.initialized = false;
}

ScrollReveal.isSupported = () => transformSupported() && transitionSupported();

ScrollReveal.prototype.remove = remove;
ScrollReveal.prototype.reveal = reveal;
ScrollReveal.prototype.sync = sync;
ScrollReveal.prototype.watch = watch;

/* istanbul ignore next */
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
	define(() => ScrollReveal);
} else if (typeof module !== 'undefined' && module.exports) {
	module.exports = ScrollReveal;
} else {
	window.ScrollReveal = ScrollReveal;
}
<|endoftext|>


<commit_before>/**
 *  @desc Tests for the Glue Api
 *  @author Jeroen Reurings
 *  @copyright © 2013 - SpilGames
 */
(function (Glue) {
    describe('glue.api', function () {
        'use strict';
        describe('Api', function () {
            describe('Modules', function () {
                it('Should be able to create and import a created module', function (done) {
                    glue.module.create('glue/module1', function () {
                        return function () {
                            var name = 'module1';
                            return {
                                getName: function () {
                                    return name;
                                }
                            };
                        };
                    });
                    glue.module.get(['glue/module1'], function (Module1) {
                        expect(Module1().getName()).toEqual('module1');
                        done();
                    });
                });
            });
            describe('Entities', function () {
                it('Should be able to create an entity which gets updated and drawn in the game loop', function () {
                    var updated = false,
                        drawn = false;

                    glue.module.create('entity/player', ['glue/entity/base'],
                        function (BaseEntity) {
                        return function (x, y, settings) {
                                // construct a new base entity instance
                            var base = new BaseEntity(x, y, settings),
                                // set the initial color to white
                                color = 'white',
                                // set the font we want to use
                                font = new me.Font('Verdana', 15, 'black'),
                                // set the text
                                text = 'Player entity',
                                // mix in some custom methods
                                obj = base.mix({
                                    draw: function (context) {
                                        context.fillStyle = color;
                                        context.fillRect(
                                            this.pos.x,
                                            this.pos.y,
                                            this.width,
                                            this.height
                                        );
                                        font.draw(context, text, this.pos.x, this.pos.y);
                                    }
                                });

                            return obj;
                        };
                    });

                    glue.module.get(['entity/player'], function (Entity) {
                        me.game.add(Entity(100, 100, {
                            name: 'testPlayer2',
                            width: 100,
                            height: 100
                        }), 2);
                        expect(me.game.getEntityByName('testPlayer')[0].name).toEqual('testPlayer');
                        setTimeout(function () {
                            expect(updated).toBeTruthy();
                            expect(drawn).toBeTruthy();
                        }, 30);
                    });
                });

            });
        });
    });
}(glue));
<commit_msg>added updated and drawn<commit_after>/**
 *  @desc Tests for the Glue Api
 *  @author Jeroen Reurings
 *  @copyright © 2013 - SpilGames
 */
(function (Glue) {
    describe('glue.api', function () {
        'use strict';
        describe('Api', function () {
            describe('Modules', function () {
                it('Should be able to create and import a created module', function (done) {
                    glue.module.create('glue/module1', function () {
                        return function () {
                            var name = 'module1';
                            return {
                                getName: function () {
                                    return name;
                                }
                            };
                        };
                    });
                    glue.module.get(['glue/module1'], function (Module1) {
                        expect(Module1().getName()).toEqual('module1');
                        done();
                    });
                });
            });
            describe('Entities', function () {
                it('Should be able to create an entity which gets updated and drawn in the game loop', function (done) {
                    var updated = false,
                        drawn = false;

                    glue.module.create('entity/player', ['glue/entity/base'],
                        function (BaseEntity) {
                        return function (x, y, settings) {
                                // construct a new base entity instance
                            var base = new BaseEntity(x, y, settings),
                                // set the initial color to white
                                color = 'white',
                                // set the font we want to use
                                font = new me.Font('Verdana', 15, 'black'),
                                // set the text
                                text = 'Player entity',
                                // mix in some custom methods
                                obj = base.mix({
                                    draw: function (context) {
                                        drawn = true;
                                        context.fillStyle = color;
                                        context.fillRect(
                                            this.pos.x,
                                            this.pos.y,
                                            this.width,
                                            this.height
                                        );
                                        font.draw(context, text, this.pos.x, this.pos.y);
                                    },
                                    update: function () {
                                        updated = true;
                                    }
                                });
                            // return the mixed object
                            return obj;
                        };
                    });

                    glue.module.get(['entity/player'], function (Entity) {
                        me.game.add(Entity(100, 100, {
                            name: 'testplayer',
                            width: 100,
                            height: 100
                        }), 1);
                        expect(me.game.getEntityByName('testplayer')[0].name).toEqual('testplayer');
                        setTimeout(function () {
                            expect(updated).toBeTruthy();
                            expect(drawn).toBeTruthy();
                            done();
                        }, 30);
                    });
                });

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


<commit_before>module.exports = {
  presets: [
    ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', modules: false }],
    '@babel/preset-react',
    '@babel/preset-flow',
  ],
  plugins: [
    'babel-plugin-emotion',
    'babel-plugin-macros',
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-proposal-object-rest-spread',
    '@babel/plugin-proposal-export-default-from',
  ],
  env: {
    test: {
      presets: [['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }]],
      plugins: ['babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node'],
    },
  },
  overrides: [
    {
      test: './examples/vue-kitchen-sink',
      presets: ['babel-preset-vue'],
    },
    {
      test: [
        './lib/core/src/server',
        './lib/node-logger',
        './lib/codemod',
        './addons/storyshots',
        './addons/storysource/src/loader',
        './app/**/src/server/**',
        './app/**/src/bin/**',
        './dangerfile.js',
      ],
      presets: [
        [
          '@babel/preset-env',
          {
            shippedProposals: true,
            useBuiltIns: 'usage',
            targets: {
              node: '8.11',
            },
          },
        ],
      ],
    },
  ],
};
<commit_msg>Fix storyshots in jest<commit_after>module.exports = {
  presets: [
    ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }],
    '@babel/preset-react',
    '@babel/preset-flow',
  ],
  plugins: [
    'babel-plugin-emotion',
    'babel-plugin-macros',
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-proposal-object-rest-spread',
    '@babel/plugin-proposal-export-default-from',
  ],
  env: {
    test: {
      presets: [['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }]],
      plugins: ['babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node'],
    },
  },
  overrides: [
    {
      test: './examples/vue-kitchen-sink',
      presets: ['babel-preset-vue'],
    },
    {
      test: [
        './lib/core/src/server',
        './lib/node-logger',
        './lib/codemod',
        './addons/storyshots',
        './addons/storysource/src/loader',
        './app/**/src/server/**',
        './app/**/src/bin/**',
        './dangerfile.js',
      ],
      presets: [
        [
          '@babel/preset-env',
          {
            shippedProposals: true,
            useBuiltIns: 'usage',
            targets: {
              node: '8.11',
            },
          },
        ],
      ],
    },
  ],
};
<|endoftext|>