<commit_before>// jscs:disable maximumLineLength
eg.module("infiniteGridService", [window.jQuery, eg, window, document], function($, ns, global, doc) {
	var PERSIST_KEY = "__INFINITEGRIDSERVICE_PERSISTKEY__";
	/**
	 * Infinite cascading grid layout service for infiniteGrid
	 * @ko infiniteGrid를 통한 무한 그리드 레이아웃 서비스
	 *
	 * @param {String} DOM Element to be InfiniteGrid <ko>타겟 엘리먼트</ko>
	 * @param {Object} [Options] A set of key/value pairs that configure the InfiniteGridService <ko>key/value 형태의 옵션</ko>
	 * @param {Number} [options.count=240] Count DOM count for recycle. If value is -1, DOM does increase without limit -1. <ko>재사용할 DOM 갯수. -1일 경우 DOM은 계속 늘어남</ko>
	 * @param {Number} [options.threshold=300] Threshold Scroll coordinate threshold <ko>append, prepend 이벤트가 발생하기 위한 스크롤 좌표 임계치</ko>
	 * @param {Boolean} [options.usePersist=true] usePersist Determines whether allows persist <ko>persist 사용 여부</ko>
	 */
	ns.InfiniteGridService = ns.Class.extend(ns.Component, {
		/**
		 * Constructor
		 * @param {String} element selector
		 * @param {Object} options
		 */
		construct: function(element, options) {
			this._$wrapper = $(element);

			this._prevScrollTop = 0;
			this._inserting = false;

			this._topElement = null;
			this._bottomElemment = null;

			this._EVENT_NAMESPACE = ".infiniteGridService" +
					Math.floor((Math.random() * 100000) + 1);

			this._options = $.extend({
				count: 240,
				threshold: 300,
				usePersist: true
			}, options);

			if (this._isEnablePersist()) {
				this._$wrapper.addClass("NO_TAP_HIGHLIGHT");
			}

			this._infiniteGrid = new eg.InfiniteGrid(element, this._options);

			this.activate();
		},
		_getScrollTop: function() {
			return doc.body.scrollTop || doc.documentElement.scrollTop;
		},
		_setBoundaryElements: function() {
			var element;

			if (element = this._infiniteGrid.getTopElement()) {
				this._topElement = element;
			}

			if (element = this._infiniteGrid.getBottomElement()) {
				this._bottomElemment = element;
			}
		},
		_isEnablePersist: function() {
			return (this._options.usePersist && $.persist.isNeeded());
		},
		_onScroll: function() {
			if (this._inserting || this._infiniteGrid.isProcessing()) {
				return;
			}

			var scrollTop = this._getScrollTop();

			if (eg.agent().os.name === "ios" && scrollTop === 0) {
				return;
			}

			if (this._prevScrollTop < scrollTop) {
				if (this._bottomElemment) {
					var bottomElementBoundingClientRect =
						this._bottomElemment.getBoundingClientRect();

					if (bottomElementBoundingClientRect.top <=
							doc.documentElement.clientHeight + this._options.threshold) {
						this.trigger("append");
					}
				}
			} else {
				if (this._topElement) {
					var topElementBoundingClientRect =
						this._topElement.getBoundingClientRect();

					if (topElementBoundingClientRect.bottom >=
							(0 - this._options.threshold)) {
						this._fit();
						this.trigger("prepend");
					}
				}
			}

			this._prevScrollTop = this._getScrollTop();
		},
		_onLayoutComplete: function(e) {
			if (!e.isAppend) {
				global.scrollTo(0, this._getScrollTop() + e.distance);
			}

			this._setBoundaryElements();
			this.trigger("layoutComplete", e);
			this._inserting = false;
		},
		_insertAjax: function(mode, url, options, callback) {
			if ($.isFunction(options)) {
				callback = options;
				options = undefined;
			}

			return $.ajax(url, options)
					.done($.proxy(function(data) {
						if (callback) {
							data = callback(data);
						}
						this._infiniteGrid[mode]($(data));
					}, this))
					.fail($.proxy(function() {
						this._inserting = false;
					}, this));
		},
		_fit: function() {
			var scrollTop = this._getScrollTop();
			var croppedHeight = this._infiniteGrid.fit();
			if (croppedHeight > 0) {
				global.scrollTo(0, scrollTop - croppedHeight);
			}
		},
		/**
		 * Activate
		 * @ko 활성화
		 * @method eg.InfiniteGridService#activate
		 * @return {Object} infiniteGridService Instance itself <ko>인스턴스</ko>
		 */
		activate: function() {
			$(global).on("scroll" + this._EVENT_NAMESPACE, $.proxy(this._onScroll, this));
			this._infiniteGrid.on("layoutComplete", $.proxy(this._onLayoutComplete, this));

			return this;
		},
		/**
		 * Deactivate
		 * @ko 비활성화
		 * @method eg.InfiniteGridService#deactivate
		 * @return {Object} infiniteGridService Instance itself <ko>인스턴스</ko>
		 */
		deactivate: function() {
			$(global).off("scrollend" + this._EVENT_NAMESPACE);
			this._infiniteGrid.off("layoutComplete");
			return this;
		},
		/**
		 * Append elements
		 * @ko 하단에 요소 추가
		 * @method eg.InfiniteGridService#append
		 * @param {String|jQuery} elements DOM Element to append in a target <ko>타겟요소에 추가할 DOM 엘리먼트</ko>
		 * @return {Number} Length The number of elements to prepended <ko>추가한 요소의 갯수</ko>
		 * @example
		 *    infiniteGridService.append("<li> contents </li>");
		 *    infiniteGridService.append($("<li> contents </li>"));
		 */
		append: function(elements) {
			this._inserting = true;
			return this._infiniteGrid.append($(elements));
		},
		/**
		 * Prepend elements
		 * @ko 상단에 요소 추가
		 * @method eg.InfiniteGridService#preppend
		 * @param {String|jQuery} elements DOM Element to append in a target <ko>타겟요소에 추가할 DOM 엘리먼트</ko>
		 * @return {Number} Length The number of elements to prepended <ko>추가한 요소의 갯수</ko>
		 * @example
		 *    infiniteGridService.prepend("<li> contents </li>");
		 *    infiniteGridService.prepend($("<li> contents </li>"));
		 */
		prepend: function(elements) {
			this._inserting = true;
			return this._infiniteGrid.prepend($(elements));
		},
		/**
		 * Append Ajax response elements
		 * @ko 하단에 Ajax 호출 결과 추가
		 * @method eg.InfiniteGridService#appendAjax
		 * @param {String} url URL A string containing the URL to which the request is sent <ko>요청할 URL</ko>
		 * @param {Object} [settings] A set of key/value pairs that configure the Ajax request <ko>Ajax 설정 객체</ko>
		 * @param {Function} [callback] A function to be called when the before append. The function receives one argument: data will append <ko>요청 완료 후 실행 할 콜백. 응답 데이터를 파라메터로 받음</ko>
		 * @return {Object} jqXHR
		 * @example
		 *    infiniteGridService.ajaxAppend("http://server.com/contents", function(data) {
		 *        return $(data);
		 *    } );
		 */
		appendAjax: function(url, settings, callback) {
			this._inserting = true;
			return this._insertAjax("append", url, settings, callback);
		},
		/**
		 * Prepend Ajax response elements
		 * @ko 상단에 요소 추가
		 * @method eg.InfiniteGridService#preppendAjax
		 * @param {String} url URL A string containing the URL to which the request is sent <ko>요청할 URL</ko>
		 * @param {Object} [settings] A set of key/value pairs that configure the Ajax request <ko>Ajax 설정 객체</ko>
		 * @param {Function} [callback] A function to be called when the before append. The function receives one argument: data to prepended <ko>요청 완료 후 실행 할 콜백. 응답 데이터를 파라메터로 받음</ko>
		 * @return {Object} jqXHR
		 * @example
			infiniteGridService.ajaxPrepend("http://server.com/contents", function(data) {
				return $(data);
			} );
		 */
		prependAjax: function(url, settings, callback) {
			this._inserting = true;
			return this._insertAjax("prepend", url, settings, callback);
		},
		/**
		 * Stores state
		 * @ko 상태 저장
		 * @method eg.InfiniteGridService#store
		 * @param {String} [key] The type of keys maintained <ko>저장/복원을 위해 관리하는 키</ko>
		 * @return {Object} instance itself
		 * @example
			infiniteGridService.store();
			infiniteGridService.store("customKey");
		*/
		store: function(key) {
			if (this._isEnablePersist()) {
				var data;

				key = key || PERSIST_KEY;

				data = {
					"infiniteGridStatus": this._infiniteGrid.getStatus(),
					"scrollTop": this._getScrollTop()
				};

				this.trigger("beforeStore", data);
				$.persist(key, data);
			}

			return this;
		},
		/**
		 * Restores state
		 * @ko 상태 복원
		 * @method eg.InfiniteGridService#restore
		 * @param {String} [key] The type of keys maintained <ko>저장/복원을 위해 관리하는 키</ko>
		 * @return {Boolean} Determine if state restored
		 * @example
			infiniteGridService.restore();
			infiniteGridService.restore("customKey");
		*/
		restore: function(key) {
			var data;
			var isRestored = false;

			if (this._isEnablePersist()) {

				key = key || PERSIST_KEY;

				data = $.persist(key);

				if (data) {
					this._infiniteGrid.setStatus(data.infiniteGridStatus);
					global.scrollTo(0, data.scrollTop);
					this._setBoundaryElements();
					isRestored = true;
				}

				this.trigger("restore", data);
			}

			return isRestored;
		},
		/**
		 * Clear elements
		 * @ko 요소를 지움
		 * @method eg.infiniteGridService#clear
		 */
		clear: function() {
			this._infiniteGrid.clear();
			return this;
		},
		/**
		 * Release resources and off custom events
		 * @ko 모든 커스텀 이벤트와 자원 해제
		 * @method eg.infiniteGridService#destroy
		 */
		destroy: function() {
			if (this._infiniteGrid) {
				this.deactivate();
				this._infiniteGrid.destroy();
				this._infiniteGrid = null;
			}
		}
	});
});<commit_msg>refactor: change default count options<commit_after>// jscs:disable maximumLineLength
eg.module("infiniteGridService", [window.jQuery, eg, window, document], function($, ns, global, doc) {
	var PERSIST_KEY = "__INFINITEGRIDSERVICE_PERSISTKEY__";
	/**
	 * Infinite cascading grid layout service for infiniteGrid
	 * @ko infiniteGrid를 통한 무한 그리드 레이아웃 서비스
	 *
	 * @param {String} DOM Element to be InfiniteGrid <ko>타겟 엘리먼트</ko>
	 * @param {Object} [Options] A set of key/value pairs that configure the InfiniteGridService <ko>key/value 형태의 옵션</ko>
	 * @param {Number} [options.count=240] Count DOM count for recycle. If value is -1, DOM does increase without limit -1. <ko>재사용할 DOM 갯수. -1일 경우 DOM은 계속 늘어남</ko>
	 * @param {Number} [options.threshold=300] Threshold Scroll coordinate threshold <ko>append, prepend 이벤트가 발생하기 위한 스크롤 좌표 임계치</ko>
	 * @param {Boolean} [options.usePersist=true] usePersist Determines whether allows persist <ko>persist 사용 여부</ko>
	 */
	ns.InfiniteGridService = ns.Class.extend(ns.Component, {
		/**
		 * Constructor
		 * @param {String} element selector
		 * @param {Object} options
		 */
		construct: function(element, options) {
			this._$wrapper = $(element);

			this._prevScrollTop = 0;
			this._inserting = false;

			this._topElement = null;
			this._bottomElemment = null;

			this._EVENT_NAMESPACE = ".infiniteGridService" +
					Math.floor((Math.random() * 100000) + 1);

			this._options = $.extend({
				count: 180,
				threshold: 300,
				usePersist: true
			}, options);

			if (this._isEnablePersist()) {
				this._$wrapper.addClass("NO_TAP_HIGHLIGHT");
			}

			this._infiniteGrid = new eg.InfiniteGrid(element, this._options);

			this.activate();
		},
		_getScrollTop: function() {
			return doc.body.scrollTop || doc.documentElement.scrollTop;
		},
		_setBoundaryElements: function() {
			var element;

			if (element = this._infiniteGrid.getTopElement()) {
				this._topElement = element;
			}

			if (element = this._infiniteGrid.getBottomElement()) {
				this._bottomElemment = element;
			}
		},
		_isEnablePersist: function() {
			return (this._options.usePersist && $.persist.isNeeded());
		},
		_onScroll: function() {
			if (this._inserting || this._infiniteGrid.isProcessing()) {
				return;
			}

			var scrollTop = this._getScrollTop();

			if (eg.agent().os.name === "ios" && scrollTop === 0) {
				return;
			}

			if (this._prevScrollTop < scrollTop) {
				if (this._bottomElemment) {
					var bottomElementBoundingClientRect =
						this._bottomElemment.getBoundingClientRect();

					if (bottomElementBoundingClientRect.top <=
							doc.documentElement.clientHeight + this._options.threshold) {
						this.trigger("append");
					}
				}
			} else {
				if (this._topElement) {
					var topElementBoundingClientRect =
						this._topElement.getBoundingClientRect();

					if (topElementBoundingClientRect.bottom >=
							(0 - this._options.threshold)) {
						this._fit();
						this.trigger("prepend");
					}
				}
			}

			this._prevScrollTop = this._getScrollTop();
		},
		_onLayoutComplete: function(e) {
			if (!e.isAppend) {
				global.scrollTo(0, this._getScrollTop() + e.distance);
			}

			this._setBoundaryElements();
			this.trigger("layoutComplete", e);
			this._inserting = false;
		},
		_insertAjax: function(mode, url, options, callback) {
			if ($.isFunction(options)) {
				callback = options;
				options = undefined;
			}

			return $.ajax(url, options)
					.done($.proxy(function(data) {
						if (callback) {
							data = callback(data);
						}
						this._infiniteGrid[mode]($(data));
					}, this))
					.fail($.proxy(function() {
						this._inserting = false;
					}, this));
		},
		_fit: function() {
			var scrollTop = this._getScrollTop();
			var croppedHeight = this._infiniteGrid.fit();
			if (croppedHeight > 0) {
				global.scrollTo(0, scrollTop - croppedHeight);
			}
		},
		/**
		 * Activate
		 * @ko 활성화
		 * @method eg.InfiniteGridService#activate
		 * @return {Object} infiniteGridService Instance itself <ko>인스턴스</ko>
		 */
		activate: function() {
			$(global).on("scroll" + this._EVENT_NAMESPACE, $.proxy(this._onScroll, this));
			this._infiniteGrid.on("layoutComplete", $.proxy(this._onLayoutComplete, this));

			return this;
		},
		/**
		 * Deactivate
		 * @ko 비활성화
		 * @method eg.InfiniteGridService#deactivate
		 * @return {Object} infiniteGridService Instance itself <ko>인스턴스</ko>
		 */
		deactivate: function() {
			$(global).off("scrollend" + this._EVENT_NAMESPACE);
			this._infiniteGrid.off("layoutComplete");
			return this;
		},
		/**
		 * Append elements
		 * @ko 하단에 요소 추가
		 * @method eg.InfiniteGridService#append
		 * @param {String|jQuery} elements DOM Element to append in a target <ko>타겟요소에 추가할 DOM 엘리먼트</ko>
		 * @return {Number} Length The number of elements to prepended <ko>추가한 요소의 갯수</ko>
		 * @example
		 *    infiniteGridService.append("<li> contents </li>");
		 *    infiniteGridService.append($("<li> contents </li>"));
		 */
		append: function(elements) {
			this._inserting = true;
			return this._infiniteGrid.append($(elements));
		},
		/**
		 * Prepend elements
		 * @ko 상단에 요소 추가
		 * @method eg.InfiniteGridService#preppend
		 * @param {String|jQuery} elements DOM Element to append in a target <ko>타겟요소에 추가할 DOM 엘리먼트</ko>
		 * @return {Number} Length The number of elements to prepended <ko>추가한 요소의 갯수</ko>
		 * @example
		 *    infiniteGridService.prepend("<li> contents </li>");
		 *    infiniteGridService.prepend($("<li> contents </li>"));
		 */
		prepend: function(elements) {
			this._inserting = true;
			return this._infiniteGrid.prepend($(elements));
		},
		/**
		 * Append Ajax response elements
		 * @ko 하단에 Ajax 호출 결과 추가
		 * @method eg.InfiniteGridService#appendAjax
		 * @param {String} url URL A string containing the URL to which the request is sent <ko>요청할 URL</ko>
		 * @param {Object} [settings] A set of key/value pairs that configure the Ajax request <ko>Ajax 설정 객체</ko>
		 * @param {Function} [callback] A function to be called when the before append. The function receives one argument: data will append <ko>요청 완료 후 실행 할 콜백. 응답 데이터를 파라메터로 받음</ko>
		 * @return {Object} jqXHR
		 * @example
		 *    infiniteGridService.ajaxAppend("http://server.com/contents", function(data) {
		 *        return $(data);
		 *    } );
		 */
		appendAjax: function(url, settings, callback) {
			this._inserting = true;
			return this._insertAjax("append", url, settings, callback);
		},
		/**
		 * Prepend Ajax response elements
		 * @ko 상단에 요소 추가
		 * @method eg.InfiniteGridService#preppendAjax
		 * @param {String} url URL A string containing the URL to which the request is sent <ko>요청할 URL</ko>
		 * @param {Object} [settings] A set of key/value pairs that configure the Ajax request <ko>Ajax 설정 객체</ko>
		 * @param {Function} [callback] A function to be called when the before append. The function receives one argument: data to prepended <ko>요청 완료 후 실행 할 콜백. 응답 데이터를 파라메터로 받음</ko>
		 * @return {Object} jqXHR
		 * @example
			infiniteGridService.ajaxPrepend("http://server.com/contents", function(data) {
				return $(data);
			} );
		 */
		prependAjax: function(url, settings, callback) {
			this._inserting = true;
			return this._insertAjax("prepend", url, settings, callback);
		},
		/**
		 * Stores state
		 * @ko 상태 저장
		 * @method eg.InfiniteGridService#store
		 * @param {String} [key] The type of keys maintained <ko>저장/복원을 위해 관리하는 키</ko>
		 * @return {Object} instance itself
		 * @example
			infiniteGridService.store();
			infiniteGridService.store("customKey");
		*/
		store: function(key) {
			if (this._isEnablePersist()) {
				var data;

				key = key || PERSIST_KEY;

				data = {
					"infiniteGridStatus": this._infiniteGrid.getStatus(),
					"scrollTop": this._getScrollTop()
				};

				this.trigger("beforeStore", data);
				$.persist(key, data);
			}

			return this;
		},
		/**
		 * Restores state
		 * @ko 상태 복원
		 * @method eg.InfiniteGridService#restore
		 * @param {String} [key] The type of keys maintained <ko>저장/복원을 위해 관리하는 키</ko>
		 * @return {Boolean} Determine if state restored
		 * @example
			infiniteGridService.restore();
			infiniteGridService.restore("customKey");
		*/
		restore: function(key) {
			var data;
			var isRestored = false;

			if (this._isEnablePersist()) {

				key = key || PERSIST_KEY;

				data = $.persist(key);

				if (data) {
					this._infiniteGrid.setStatus(data.infiniteGridStatus);
					global.scrollTo(0, data.scrollTop);
					this._setBoundaryElements();
					isRestored = true;
				}

				this.trigger("restore", data);
			}

			return isRestored;
		},
		/**
		 * Clear elements
		 * @ko 요소를 지움
		 * @method eg.infiniteGridService#clear
		 */
		clear: function() {
			this._infiniteGrid.clear();
			return this;
		},
		/**
		 * Release resources and off custom events
		 * @ko 모든 커스텀 이벤트와 자원 해제
		 * @method eg.infiniteGridService#destroy
		 */
		destroy: function() {
			if (this._infiniteGrid) {
				this.deactivate();
				this._infiniteGrid.destroy();
				this._infiniteGrid = null;
			}
		}
	});
});<|endoftext|>


<commit_before>var DocsParser = require('./docsparser.js');
var escape = DocsParser.escape;
//var Snippets = atom.packages.activePackages.snippets.mainModule;

var DocBlockrAtom;
module.exports =
  DocBlockrAtom = (function() {

    function DocBlockrAtom() {
      var self = this;
      var settings = atom.config.getSettings().docblockr;
      this.editor_settings = settings;

      atom.workspaceView.command('docblockr:parse', function(event) {
        var regex = /^\s*(\/\*|###)[*!]\s*$/;
        if(self.validate_request(regex))
          self.parse_command(false);
        else
          event.abortKeyBinding();
      });

      atom.workspaceView.command('docblockr:parse_inline', function(event) {
        var regex = /^\s*\/\*{2}$/;
        if(self.validate_request(regex))
          self.parse_command(true);
        else
          event.abortKeyBinding();
      });
    }

    DocBlockrAtom.prototype.validate_request = function(regex) {
      /**
       *  Multiple cursor behaviour:
       *   1. Add mulitple snippets dependent on cursor pos, this makes traversing
       *        snippets not possible
       *   2. So we will iterate over the cursors and find the first among the cursors
       *        that satisfies the regex, the rest of the cursors will be deleted.
       */

      var editor = atom.workspace.getActiveEditor();
      this.cursors = [];
      var cursor, i, len;

      var cursor_positions = editor.getCursors();
      for (i = 0, len = cursor_positions.length; i < len; i++) {
        var cursor_position = cursor_positions[i].getBufferPosition();
        var preceding_text = editor.getTextInBufferRange([[cursor_position.row, 0], cursor_position]);
        if(preceding_text.search(regex) > -1) {
          this.cursors.push(cursor_position);
          break;
        }
      }
      if(this.cursors.length > 0) {
        cursor_positions.splice(i,1);
        cursor_positions.forEach(function(value) {
          value.destroy();
        });
        return true;
      }
      else
        return false;
    };

    DocBlockrAtom.prototype.parse_command = function(inline) {
      var editor = atom.workspace.getActiveEditor();
      if (typeof editor === 'undefined' || editor === null) {
        return;
      }
      this.initialize(editor, inline);
      if(this.parser.is_existing_comment(this.line)) {
        this.write(editor, '\n *' + this.indentSpaces);
        return;
      }

      // erase characters in the view (will be added to the output later)
      this.erase(editor, this.trailing_range);

      // match against a function declaration.
      var out = this.parser.parse(this.line);
      var snippet = this.generate_snippet(out, inline);
      // atom doesnt currently support, snippet end by default
      // so add $0
      if(snippet.search(/\${0:/) < 0)
        snippet+= '$0';
      this.write(editor, snippet);
    };

    DocBlockrAtom.prototype.initialize = function(editor, inline) {
      inline = (typeof inline === 'undefined') ? false : inline;
      var cursor_position = editor.getCursorBufferPosition(); // will handle only one instance
      // Get trailing string
      var line_length = editor.lineLengthForBufferRow(cursor_position.row);
      this.trailing_range = [cursor_position, [cursor_position.row, line_length]];
      this.trailing_string = editor.getTextInBufferRange(this.trailing_range);
      // drop trailing */
      this.trailing_string = this.trailing_string.replace(/\s*\*\/\s*$/, '');
      this.trailing_string = escape(this.trailing_string);

      this.parser = parser = this.get_parser(editor);
      parser.inline = inline;

      this.indentSpaces = this.repeat(' ', Math.max(0, (this.editor_settings.indentation_spaces || 1)));
      this.prefix = '*';

      settingsAlignTags = this.editor_settings.align_tags || 'deep';
      this.deepAlignTags = settingsAlignTags == 'deep';
      this.shallowAlignTags = ((settingsAlignTags == 'shallow') || (settingsAlignTags === true));

      // use trailing string as a description of the function
      if(this.trailingString)
          parser.setNameOverride(this.trailingString);

      // read the next line
      cursor_position = cursor_position.copy();
      cursor_position.row+= 1;
      this.line = parser.get_definition(editor, cursor_position, this.read_line);
    };

    DocBlockrAtom.prototype.counter = function() {
      var count = 0;
      return (function() {
        return ++count;
      });
    };

    DocBlockrAtom.prototype.repeat = function(string, number) {
      return Array(number + 1).join(string);
    };

    DocBlockrAtom.prototype.write = function(editor, str) {
      // will insert data at last cursor position
      var Snippets = atom.packages.activePackages.snippets.mainModule;
      Snippets.insert(str, editor);
    };

    DocBlockrAtom.prototype.erase = function(editor, range) {
      var buffer = editor.getBuffer();
      buffer.delete(range);
    };

    DocBlockrAtom.prototype.fill_array = function(len) {
      var a = [];
      var i = 0;
      while (i < len) {
        a[i] = 0;
        i++;
      }
      return a;
    };

    DocBlockrAtom.prototype.read_line = function(editor, point) {
        // TODO: no longer works
        if(point >= editor.getText().length)
            return;
        return editor.lineForBufferRow(point.row);
    };

    DocBlockrAtom.prototype.get_parser = function(editor) {
      var scope = editor.getGrammar().scopeName;
      var regex = /\bsource\.([a-z+\-]+)/;
      var matches = regex.exec(scope);
      var source_lang = (matches === null)? 'js': matches[1];

      var settings = atom.config.getSettings().docblockr;

      if(source_lang === "php")
          return new DocsParser.PhpParser(settings);
      else if(source_lang === "coffee")
          return new DocsParser.CoffeeParser(settings);
      else if((source_lang === "actionscript") || (source_lang == 'haxe'))
          return new DocsParser.ActionscriptParser(settings);
      else if((source_lang === "c++") || (source_lang === 'c') || (source_lang === 'cuda-c++'))
          return new DocsParser.CppParser(settings);
      else if((source_lang === 'objc') || (source_lang === 'objc++'))
          return new DocsParser.ObjCParser(settings);
      else if((source_lang === 'java') || (source_lang === 'groovy'))
          return new DocsParser.JavaParser(settings);
      else if(source_lang === 'rust')
          return new DocsParser.RustParser(settings);
      else if(source_lang === 'ts')
          return new DocsParser.TypescriptParser(settings);
      return new DocsParser.JsParser(settings);
    };

    DocBlockrAtom.prototype.generate_snippet = function(out, inline) {
      //# substitute any variables in the tags
      if(out)
        out = this.substitute_variables(out);

      // align the tags
      if(out && (this.shallowAlignTags || this.deepAlignTags) && (!inline))
        out = this.align_tags(out);

      // fix all the tab stops so they're consecutive
      if(out)
        out = this.fix_tab_stops(out);

      if(inline) {
        if(out)
          return (' ' + out[0] + ' */');
        else
          return (' $0 */');
      }
      else
        return (this.create_snippet(out) + (this.editor_settings.newline_after_block ? '\n' : ''));
    };

    DocBlockrAtom.prototype.substitute_variables = function(out) {
      function get_var(match, group, str) {
        var var_name = group;
        if(var_name == 'datetime') {
            var datetime = new Date();
            return format_time(datetime);
        }
        else if(var_name == 'date') {
          var datetime = new Date();
          return datetime.toISOString().replace(/T.*/, '');
        }
        else
          return match;
      }
      function format_time(datetime) {
        function length_fix(x) {
          if(x < 10)
            x = '0' + x;
          return x;
        }
        var hour = length_fix(datetime.getHours());
        var min = length_fix(datetime.getMinutes());
        var sec = length_fix(datetime.getSeconds());
        var tz = datetime.getTimezoneOffset() / -60;
        var tz_string;
        if(tz >= 0)
          tz_string = '+';
        else
          tz_string = '-';
        tz_string+=  length_fix(Math.floor(Math.abs(tz)).toString()) + ((tz % 1) * 60);
        datetime = datetime.toISOString().replace(/T.*/, '');
        return datetime+= 'T' + hour + ':' + min + ':' + sec + tz_string;
      }
      function sub_line(line) {
        var regex = new RegExp('\{\{([^}]+)\}\}', 'g');
        return line.replace(regex, get_var);
      }
      return out.map(sub_line);
    };

    DocBlockrAtom.prototype.align_tags = function(out) {
      var output_width = function(str){
        // get the length of a string, after it is output as a snippet,
        // "${1:foo}" --> 3
        return str.replace(/[$][{]\d+:([^}]+)[}]/, '$1').replace('\\$', '$').length;
      };
      // count how many columns we have
      var maxCols = 0;
      // this is a 2d list of the widths per column per line
      var widths = [];
      var return_tag;
      // Grab the return tag if required.
      if(this.editor_settings.per_section_indent)
          return_tag = this.editor_settings.return_tag || '@return';
      else
          return_tag = false;

      for(var i=0; i<out.length; i++) {
        if(out[i].startsWith('@')) {
          // Ignore the return tag if we're doing per-section indenting.
          if(return_tag && out[i].startsWith(return_tag))
              continue;
          // ignore all the words after `@author`
          var columns = (!out[i].startsWith('@author')) ? out[i].split(' ') : ['@author'];
          widths.push(columns.map(output_width));
          maxCols = Math.max(maxCols, widths[widths.length - 1].length);
        }
      }
      // initialise a list to 0
      var maxWidths = this.fill_array(maxCols);

      if(this.shallowAlignTags)
          maxCols = 1;

      for(i = 0; i < maxCols; i++) {
        for(var j = 0; j < widths.length; j++) {
          if(i < widths[j].length)
            maxWidths[i] = Math.max(maxWidths[i], widths[j][i]);
        }
      }
      // Convert to a dict so we can use .get()
      // maxWidths = dict(enumerate(maxWidths))

      // Minimum spaces between line columns
      var minColSpaces = this.editor_settings.min_spaces_between_columns || 1;
      for(i = 0; i_len = out.length, i < i_len; i++) {
        // format the spacing of columns, but ignore the author tag. (See #197)
        if((out[i].startsWith('@')) && (!out[i].startsWith('@author'))) {
          var new_out = [];
          var split_array = out[i].split(' ');
          for(var j=0; j_len = split_array.length, j < j_len; j++) {
            new_out.push(split_array[j]);
            new_out.push(this.repeat(' ', minColSpaces) + (
                                      this.repeat(' ', ((maxWidths[j] || 0) - output_width(split_array[j])))
                                    ));
          }
          out[i] = new_out.join('').trim();
        }
      }
      return out;
    };

    DocBlockrAtom.prototype.fix_tab_stops = function(out) {
      var tab_index = this.counter();
      var swap_tabs = function(match, group1, group2, str) {
        return (group1 + tab_index() + group2);
      };
      var i, len;
      for(i=0; len = out.length, i<len; i++)
        out[i] = out[i].replace(/(\$\{)\d+(:[^}]+\})/g, swap_tabs);
      return out;
    };

    DocBlockrAtom.prototype.create_snippet = function(out) {
      var snippet = '';
      var closer = this.parser.settings.commentCloser;
      var regex = new RegExp('^\s*@([a-zA-Z]+)');
      var i, len;
      if(out) {
        if(this.editor_settings.spacer_between_sections === true) {
          var last_tag = null;
          for(i=0; len = out.length, i < len; i++) {
            var match = regex.exec(out[i]);
            if(match && (last_tag != match[1])) {
              last_tag = match[1];
              out.splice(i, 0 , '');
            }
          }
        }
        else if(this.editor_settings.spacer_between_sections == 'after_description') {
          var lastLineIsTag = false;
          for(i=0; len = out.length, i < len; i++) {
            var match = regex.exec(out[i]);
            if(match) {
              if(!lastLineIsTag)
                out.splice(i, 0, '');
              lastLineIsTag = true;
            }
          }
        }
        for(i=0; len = out.length, i < len; i++) {
          snippet+= '\n ' + this.prefix + (out[i] ? (this.indentSpaces + out[i]) : '');
        }
      }
      else
        snippet+= '\n ' + this.prefix + this.indentSpaces + '${0:' + this.trailing_string + '}';

      snippet+= '\n' + closer;
      return snippet;
    };

    return DocBlockrAtom;
})();<commit_msg>Fixes inline comment snippet<commit_after>var DocsParser = require('./docsparser.js');
var escape = DocsParser.escape;
//var Snippets = atom.packages.activePackages.snippets.mainModule;

var DocBlockrAtom;
module.exports =
  DocBlockrAtom = (function() {

    function DocBlockrAtom() {
      var self = this;
      var settings = atom.config.getSettings().docblockr;
      this.editor_settings = settings;

      atom.workspaceView.command('docblockr:parse', function(event) {
        var regex = /^\s*(\/\*|###)[*!]\s*$/;
        if(self.validate_request(regex))
          self.parse_command(false);
        else
          event.abortKeyBinding();
      });

      atom.workspaceView.command('docblockr:parse_inline', function(event) {
        var regex = /^\s*\/\*{2}$/;
        if(self.validate_request(regex))
          self.parse_command(true);
        else
          event.abortKeyBinding();
      });
    }

    DocBlockrAtom.prototype.validate_request = function(regex) {
      /**
       *  Multiple cursor behaviour:
       *   1. Add mulitple snippets dependent on cursor pos, this makes traversing
       *        snippets not possible
       *   2. So we will iterate over the cursors and find the first among the cursors
       *        that satisfies the regex, the rest of the cursors will be deleted.
       */

      var editor = atom.workspace.getActiveEditor();
      this.cursors = [];
      var cursor, i, len;

      var cursor_positions = editor.getCursors();
      for (i = 0, len = cursor_positions.length; i < len; i++) {
        var cursor_position = cursor_positions[i].getBufferPosition();
        var preceding_text = editor.getTextInBufferRange([[cursor_position.row, 0], cursor_position]);
        if(preceding_text.search(regex) > -1) {
          this.cursors.push(cursor_position);
          break;
        }
      }
      if(this.cursors.length > 0) {
        cursor_positions.splice(i,1);
        cursor_positions.forEach(function(value) {
          value.destroy();
        });
        return true;
      }
      else
        return false;
    };

    DocBlockrAtom.prototype.parse_command = function(inline) {
      var editor = atom.workspace.getActiveEditor();
      if (typeof editor === 'undefined' || editor === null) {
        return;
      }
      this.initialize(editor, inline);
      if(this.parser.is_existing_comment(this.line)) {
        this.write(editor, '\n *' + this.indentSpaces);
        return;
      }

      // erase characters in the view (will be added to the output later)
      this.erase(editor, this.trailing_range);

      // match against a function declaration.
      var out = this.parser.parse(this.line);
      var snippet = this.generate_snippet(out, inline);
      // atom doesnt currently support, snippet end by default
      // so add $0
      if((snippet.search(/\${0:/) < 0) && (snippet.search(/\$0/) < 0))
        snippet+= '$0';
      this.write(editor, snippet);
    };

    DocBlockrAtom.prototype.initialize = function(editor, inline) {
      inline = (typeof inline === 'undefined') ? false : inline;
      var cursor_position = editor.getCursorBufferPosition(); // will handle only one instance
      // Get trailing string
      var line_length = editor.lineLengthForBufferRow(cursor_position.row);
      this.trailing_range = [cursor_position, [cursor_position.row, line_length]];
      this.trailing_string = editor.getTextInBufferRange(this.trailing_range);
      // drop trailing */
      this.trailing_string = this.trailing_string.replace(/\s*\*\/\s*$/, '');
      this.trailing_string = escape(this.trailing_string);

      this.parser = parser = this.get_parser(editor);
      parser.inline = inline;

      this.indentSpaces = this.repeat(' ', Math.max(0, (this.editor_settings.indentation_spaces || 1)));
      this.prefix = '*';

      settingsAlignTags = this.editor_settings.align_tags || 'deep';
      this.deepAlignTags = settingsAlignTags == 'deep';
      this.shallowAlignTags = ((settingsAlignTags == 'shallow') || (settingsAlignTags === true));

      // use trailing string as a description of the function
      if(this.trailingString)
          parser.setNameOverride(this.trailingString);

      // read the next line
      cursor_position = cursor_position.copy();
      cursor_position.row+= 1;
      this.line = parser.get_definition(editor, cursor_position, this.read_line);
    };

    DocBlockrAtom.prototype.counter = function() {
      var count = 0;
      return (function() {
        return ++count;
      });
    };

    DocBlockrAtom.prototype.repeat = function(string, number) {
      return Array(number + 1).join(string);
    };

    DocBlockrAtom.prototype.write = function(editor, str) {
      // will insert data at last cursor position
      var Snippets = atom.packages.activePackages.snippets.mainModule;
      Snippets.insert(str, editor);
    };

    DocBlockrAtom.prototype.erase = function(editor, range) {
      var buffer = editor.getBuffer();
      buffer.delete(range);
    };

    DocBlockrAtom.prototype.fill_array = function(len) {
      var a = [];
      var i = 0;
      while (i < len) {
        a[i] = 0;
        i++;
      }
      return a;
    };

    DocBlockrAtom.prototype.read_line = function(editor, point) {
        // TODO: no longer works
        if(point >= editor.getText().length)
            return;
        return editor.lineForBufferRow(point.row);
    };

    DocBlockrAtom.prototype.get_parser = function(editor) {
      var scope = editor.getGrammar().scopeName;
      var regex = /\bsource\.([a-z+\-]+)/;
      var matches = regex.exec(scope);
      var source_lang = (matches === null)? 'js': matches[1];

      var settings = atom.config.getSettings().docblockr;

      if(source_lang === "php")
          return new DocsParser.PhpParser(settings);
      else if(source_lang === "coffee")
          return new DocsParser.CoffeeParser(settings);
      else if((source_lang === "actionscript") || (source_lang == 'haxe'))
          return new DocsParser.ActionscriptParser(settings);
      else if((source_lang === "c++") || (source_lang === 'c') || (source_lang === 'cuda-c++'))
          return new DocsParser.CppParser(settings);
      else if((source_lang === 'objc') || (source_lang === 'objc++'))
          return new DocsParser.ObjCParser(settings);
      else if((source_lang === 'java') || (source_lang === 'groovy'))
          return new DocsParser.JavaParser(settings);
      else if(source_lang === 'rust')
          return new DocsParser.RustParser(settings);
      else if(source_lang === 'ts')
          return new DocsParser.TypescriptParser(settings);
      return new DocsParser.JsParser(settings);
    };

    DocBlockrAtom.prototype.generate_snippet = function(out, inline) {
      //# substitute any variables in the tags
      if(out)
        out = this.substitute_variables(out);

      // align the tags
      if(out && (this.shallowAlignTags || this.deepAlignTags) && (!inline))
        out = this.align_tags(out);

      // fix all the tab stops so they're consecutive
      if(out)
        out = this.fix_tab_stops(out);

      if(inline) {
        if(out)
          return (' ' + out[0] + ' */');
        else
          return (' $0 */');
      }
      else
        return (this.create_snippet(out) + (this.editor_settings.newline_after_block ? '\n' : ''));
    };

    DocBlockrAtom.prototype.substitute_variables = function(out) {
      function get_var(match, group, str) {
        var var_name = group;
        if(var_name == 'datetime') {
            var datetime = new Date();
            return format_time(datetime);
        }
        else if(var_name == 'date') {
          var datetime = new Date();
          return datetime.toISOString().replace(/T.*/, '');
        }
        else
          return match;
      }
      function format_time(datetime) {
        function length_fix(x) {
          if(x < 10)
            x = '0' + x;
          return x;
        }
        var hour = length_fix(datetime.getHours());
        var min = length_fix(datetime.getMinutes());
        var sec = length_fix(datetime.getSeconds());
        var tz = datetime.getTimezoneOffset() / -60;
        var tz_string;
        if(tz >= 0)
          tz_string = '+';
        else
          tz_string = '-';
        tz_string+=  length_fix(Math.floor(Math.abs(tz)).toString()) + ((tz % 1) * 60);
        datetime = datetime.toISOString().replace(/T.*/, '');
        return datetime+= 'T' + hour + ':' + min + ':' + sec + tz_string;
      }
      function sub_line(line) {
        var regex = new RegExp('\{\{([^}]+)\}\}', 'g');
        return line.replace(regex, get_var);
      }
      return out.map(sub_line);
    };

    DocBlockrAtom.prototype.align_tags = function(out) {
      var output_width = function(str){
        // get the length of a string, after it is output as a snippet,
        // "${1:foo}" --> 3
        return str.replace(/[$][{]\d+:([^}]+)[}]/, '$1').replace('\\$', '$').length;
      };
      // count how many columns we have
      var maxCols = 0;
      // this is a 2d list of the widths per column per line
      var widths = [];
      var return_tag;
      // Grab the return tag if required.
      if(this.editor_settings.per_section_indent)
          return_tag = this.editor_settings.return_tag || '@return';
      else
          return_tag = false;

      for(var i=0; i<out.length; i++) {
        if(out[i].startsWith('@')) {
          // Ignore the return tag if we're doing per-section indenting.
          if(return_tag && out[i].startsWith(return_tag))
              continue;
          // ignore all the words after `@author`
          var columns = (!out[i].startsWith('@author')) ? out[i].split(' ') : ['@author'];
          widths.push(columns.map(output_width));
          maxCols = Math.max(maxCols, widths[widths.length - 1].length);
        }
      }
      // initialise a list to 0
      var maxWidths = this.fill_array(maxCols);

      if(this.shallowAlignTags)
          maxCols = 1;

      for(i = 0; i < maxCols; i++) {
        for(var j = 0; j < widths.length; j++) {
          if(i < widths[j].length)
            maxWidths[i] = Math.max(maxWidths[i], widths[j][i]);
        }
      }
      // Convert to a dict so we can use .get()
      // maxWidths = dict(enumerate(maxWidths))

      // Minimum spaces between line columns
      var minColSpaces = this.editor_settings.min_spaces_between_columns || 1;
      for(i = 0; i_len = out.length, i < i_len; i++) {
        // format the spacing of columns, but ignore the author tag. (See #197)
        if((out[i].startsWith('@')) && (!out[i].startsWith('@author'))) {
          var new_out = [];
          var split_array = out[i].split(' ');
          for(var j=0; j_len = split_array.length, j < j_len; j++) {
            new_out.push(split_array[j]);
            new_out.push(this.repeat(' ', minColSpaces) + (
                                      this.repeat(' ', ((maxWidths[j] || 0) - output_width(split_array[j])))
                                    ));
          }
          out[i] = new_out.join('').trim();
        }
      }
      return out;
    };

    DocBlockrAtom.prototype.fix_tab_stops = function(out) {
      var tab_index = this.counter();
      var swap_tabs = function(match, group1, group2, str) {
        return (group1 + tab_index() + group2);
      };
      var i, len;
      for(i=0; len = out.length, i<len; i++)
        out[i] = out[i].replace(/(\$\{)\d+(:[^}]+\})/g, swap_tabs);
      return out;
    };

    DocBlockrAtom.prototype.create_snippet = function(out) {
      var snippet = '';
      var closer = this.parser.settings.commentCloser;
      var regex = new RegExp('^\s*@([a-zA-Z]+)');
      var i, len;
      if(out) {
        if(this.editor_settings.spacer_between_sections === true) {
          var last_tag = null;
          for(i=0; len = out.length, i < len; i++) {
            var match = regex.exec(out[i]);
            if(match && (last_tag != match[1])) {
              last_tag = match[1];
              out.splice(i, 0 , '');
            }
          }
        }
        else if(this.editor_settings.spacer_between_sections == 'after_description') {
          var lastLineIsTag = false;
          for(i=0; len = out.length, i < len; i++) {
            var match = regex.exec(out[i]);
            if(match) {
              if(!lastLineIsTag)
                out.splice(i, 0, '');
              lastLineIsTag = true;
            }
          }
        }
        for(i=0; len = out.length, i < len; i++) {
          snippet+= '\n ' + this.prefix + (out[i] ? (this.indentSpaces + out[i]) : '');
        }
      }
      else
        snippet+= '\n ' + this.prefix + this.indentSpaces + '${0:' + this.trailing_string + '}';

      snippet+= '\n' + closer;
      return snippet;
    };

    return DocBlockrAtom;
})();<|endoftext|>


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

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var testCase = require('nodeunit').testCase;
var restify = require('restify');
var Logger = require('bunyan');

var PROVISIONER_PORT = 5309;
var client;

function setup(cb) {
    client = restify.createJsonClient({
        agent: false,
        url: 'http://localhost:' + PROVISIONER_PORT
    });
    cb();
}

function teardown(cb) {
    cb();
}

function testExecuteTaskHttp(test) {
    test.expect(3);
    client.get('/tasks', function (err, req, res, tasks) {
        test.ifError(err);
        test.ok(res, 'got a response');
        test.equal(res.statusCode, 200, 'GET /tasks returned 200');
        test.done();
    });
}

module.exports = {
    setUp: setup,
    tearDown: teardown,
    'execute a task via http': testExecuteTaskHttp
};
<commit_msg>AGENT-902 test should connect to correct IP.<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/.
 */

/*
 * Copyright (c) 2015, Joyent, Inc.
 */

var testCase = require('nodeunit').testCase;
var restify = require('restify');
var Logger = require('bunyan');
var smartdcconfig = require('../lib/smartdc-config');

var PROVISIONER_PORT = 5309;
var client;

function firstAdminIp(sysinfo) {
    var interfaces;

    interfaces = sysinfo['Network Interfaces'];

    for (var iface in interfaces) {
        if (!interfaces.hasOwnProperty(iface)) {
            continue;
        }

        var nic = interfaces[iface]['NIC Names'];
        var isAdmin = nic.indexOf('admin') !== -1;
        if (isAdmin) {
            var ip = interfaces[iface].ip4addr;
            return ip;
        }
    }

    throw new Error('No NICs with name "admin" detected.');
}

function setup(cb) {
    smartdcconfig.sysinfo(function (err, sysinfo) {
        var adminip;

        if (err) {
            cb(err);
            return;
        }

        adminip = firstAdminIp(sysinfo);
        if (!adminip) {
            throw new Error('failed to find admin IP');
        }

        client = restify.createJsonClient({
            agent: false,
            url: 'http://' + adminip + ':' + PROVISIONER_PORT
        });
        cb();
    });
}

function teardown(cb) {
    cb();
}

function testExecuteTaskHttp(test) {
    test.expect(3);
    client.get('/tasks', function (err, req, res, tasks) {
        test.ifError(err);
        if (!err) {
            test.ok(res, 'got a response');
            test.equal(res.statusCode, 200, 'GET /tasks returned 200');
        }
        test.done();
    });
}

module.exports = {
    setUp: setup,
    tearDown: teardown,
    'execute a task via http': testExecuteTaskHttp
};
<|endoftext|>


<commit_before>// test template recursion

var common = require('./common');
var assert = common.assert;
var render = common.whiskers.render;

common.expected = 1;

var context = {
  level: 1,
  children: [
    {
      level: 2,
      children: [
        {level: 3}
      ]
    }
  ]
};

var partials = {
  recurse: '{level}{for child in children}{>recurse}{/for}'
};

assert.equal(render('{>recurse}', context, partials), '4');
<commit_msg>Testing partial depth more than recursion<commit_after>// test template recursion

var common = require('./common');
var assert = common.assert;
var render = common.whiskers.render;

common.expected = 1;

var context = {
  title: 'Bob',
  authors: [
    {
      name: 'Liz',
      pets: [
        {name: 'Errol'}
      ]
    },
    {name: 'Jan'}
  ]
};

var partials = {
  author: 'author: {author.name}{for pet in author.pets}{>comma} {>pet}{/for}',
  pet: 'pet: {pet.name}',
  comma: ','
};

console.log(render('book: {title}{for author in authors}{>comma} {>author}{/for}', context, partials));
//assert.equal(render('{level}{for child in children}{>level2}{/for}', context, partials), '123');
<|endoftext|>


<commit_before>'use strict';

// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var extend = require('util-extend');
var fs = require('fs');
var test = require('tape');

var ohm = require('..');
var util = require('./util');

// --------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------

var arithmeticGrammarSource = fs.readFileSync('test/arithmetic.ohm').toString();

// Combines the properties of `obj1` and `props` into a new object.
function combine(obj1, props) {
  return extend(extend({}, obj1), props);
}

// --------------------------------------------------------------------
// Tests
// --------------------------------------------------------------------

test('basic semantics', function(t) {
  var expr = ohm.makeGrammar(arithmeticGrammarSource);

  var s = expr.semantics();
  s.addOperation('value', {
    addExpr_plus: function(x, op, y) {
      return x.value() + y.value();
    },
    mulExpr_times: function(x, op, y) {
      return x.value() * y.value();
    },
    number_rec: function(n, d) {
      return n.value() * 10 + d.value();
    },
    digit: function(expr) {
      return expr.value().charCodeAt(0) - '0'.charCodeAt(0);
    },
    _default: ohm.actions.passThrough,
    _terminal: function() {
      return this.node.primitiveValue;
    }
  });

  function match(source) {
    return expr.match(source, 'expr');
  }

  t.ok(match('1*(2+3)-4/5'), 'expr is recognized');

  t.equal(s(match('1+2')).value(), 3, 'single addExpr');
  t.equal(s(match('13+10*2*3')).value(), 73, 'more complicated case');
  t.throws(function() { s.addOperation('value'); }, 'throws when name already exists');

  t.ok(s.addOperation('one', {}).addOperation('two', {}), 'chaining');
  t.throws(function() { s(null).value(); }, /expected a node/);
  t.throws(function() { s(false).value(); }, /expected a node/);
  t.throws(function() { s().value(); }, /expected a node/);
  t.throws(function() { s(3).value(); }, /expected a node/);
  t.throws(function() { s('asdf').value(); }, /expected a node/);

  // Cannot use the semantics on nodes from another grammar.
  var g = ohm.makeGrammar('G {}');
  t.throws(function() { s(g.match('a', 'letter')).value(); }, /Cannot use node from grammar/);

  // TODO: Decide how this should work. Also, test with a subgrammar that has different arity
  // for some rules.
  // g = ohm.makeGrammar('Expr2 <: Expr {}', {Expr:expr});
  // t.equal(s(g.match('1+2', 'expr')).value(), 3);

  // An operation that produces a list of the values of all the numbers in the tree.
  s.addOperation('numberValues', {
    addExpr_plus: function(x, op, y) {
      return x.numberValues().concat(y.numberValues());
    },
    mulExpr_times: function(x, op, y) {
      return x.numberValues().concat(y.numberValues());
    },
    number: function(n) {
      return [n.value()];
    },
    _default: ohm.actions.passThrough
  });
  t.deepEqual(s(match('13+10*2*3')).numberValues(), [13, 10, 2, 3]);
  t.deepEqual(s(match('9')).numberValues(), [9]);

  t.end();
});

test('_many nodes', function(t) {
  var g = ohm.makeGrammar('G { letters = letter* }');
  var actions = {
    _default: ohm.actions.passThrough,
    _terminal: ohm.actions.getPrimitiveValue
  };
  var s = g.semantics().addOperation('op', combine(actions, {_many: ohm.actions.makeArray}));
  var m = g.match('abc', 'letters');
  t.deepEqual(s(m).op(), ['a', 'b', 'c'], 'makeArray works');

  s = g.semantics().addOperation('op', combine(actions, {_many: ohm.actions.passThrough}));
  t.throws(function() { s(m).op(); }, /passThrough/, 'throws with passThrough');

  t.throws(function() {
    g.semantics().addOperation('op', combine(actions, {_many: ohm.actions.getPrimitiveValue}));
  }, /wrong arity/, 'throws with getPrimitiveValue');

  s = g.semantics().addOperation('op', combine(actions, {
    _many: function(letters) {
      t.ok(letters.every(function(l) {
        return typeof l.op === 'function';
      }), 'only arg is an array of wrappers');
      t.equal(typeof this.op, 'function', '`this` has an op() method');
      t.equal(this.node.ctorName, '_many', '`this.node` is the actual node');
      return letters.map(function(l) { return l.op(); }).join(',');
    }
  }));
  t.equal(s(m).op(), 'a,b,c');

  t.end();
});

test('_terminal nodes', function(t) {
  var g = ohm.makeGrammar('G { letters = letter* }');
  var actions = {
    _default: ohm.actions.passThrough,
    _many: ohm.actions.makeArray
  };
  var s = g.semantics().addOperation('op', combine(actions, {
    _terminal: ohm.actions.getPrimitiveValue
  }));
  var m = g.match('abc', 'letters');
  t.deepEqual(s(m).op(), ['a', 'b', 'c'], 'getPrimitiveValue works');

  t.throws(function() {
    g.semantics().addOperation('op', combine(actions, {_terminal: ohm.actions.passThrough}));
  }, /wrong arity/, 'throws with passThrough');

  t.throws(function() {
    g.semantics().addOperation('op', combine(actions, {_terminal: ohm.actions.makeArray}));
  }, /wrong arity/, 'throws with makeArray');

  s = g.semantics().addOperation('op', combine(actions, {
    _terminal: function() {
      t.equal(arguments.length, 0, 'there are no arguments');
      t.equal(this.node.ctorName, '_terminal');
      t.equal(this.node.children.length, 0, 'node has no children');
      return this.node.primitiveValue;
    }
  }));
  t.deepEqual(s(m).op(), ['a', 'b', 'c']);

  t.end();
});

test('semantic action arity checks', function(t) {
  var g = ohm.makeGrammar('G {}');
  function makeOperation(grammar, actions) {
    return grammar.semantics().addOperation('op' + util.uniqueId(), actions);
  }
  function ignore0() {}
  function ignore1(a) {}
  function ignore2(a, b) {}

  t.ok(makeOperation(g, {}), 'empty actions with empty grammar');
  t.ok(makeOperation(g, {foo: null}), 'unrecognized action names are ignored');

  t.throws(function() { makeOperation(g, {_many: ignore0}); }, /arity/, '_many');
  t.ok(makeOperation(g, {_many: ignore1}), '_many works with one arg');

  t.throws(function() { makeOperation(g, {_default: ignore0}); }, /arity/, '_default is checked');
  t.ok(makeOperation(g, {_default: ignore1}), '_default works with one arg');

  t.throws(function() {
    makeOperation(g, {_terminal: ignore1});
  }, /arity/, '_terminal is checked');
  t.ok(makeOperation(g, {_terminal: ignore0}), '_terminal works with no args');

  t.throws(function() {
    makeOperation(g, {letter: ignore0});
  }, /arity/, 'built-in rules are checked');
  t.ok(makeOperation(g, {letter: ignore1}), 'letter works with one arg');

  g = util.makeGrammar([
    'G {',
    '  one = two',
    '  two = "2" letter',
    '}']);
  t.ok(makeOperation(g, {one: ignore1, two: ignore2}));

  t.throws(function() {
    makeOperation(g, {one: ignore0, two: ignore2});
  }, /wrong arity/, "'one', is checked");
  t.throws(function() {
    makeOperation(g, {one: ignore1, two: ignore0});
  }, /wrong arity/, "'two' is checked");

  var g2 = ohm.makeGrammar('G2 <: G {}', {G: g});
  t.throws(function() {
    makeOperation(g2, {one: ignore2});
  }, /wrong arity/, 'supergrammar rules are checked');
  t.ok(makeOperation(g2, {one: ignore1}), 'works with one arg');

  var g3 = ohm.makeGrammar('G3 <: G { one := "now" "two" }', {G: g});
  t.throws(function() {
    makeOperation(g3, {one: ignore1});
  }, /wrong arity/, 'changing arity in an overridden rule');
  t.ok(makeOperation(g3, {one: ignore2}));

  t.end();
});

test('extending semantics', function(t) {
  var ns = util.makeGrammars([
    'G { ',
    '  one = "one"',
    '  two = "two"',
    '}',
    'G2 <: G {',
    '  one := "eins" "!"',
    '  three = "drei"',
    '}']);
  var s = ns.G.semantics().
      addOperation('value', {
        one: function(_) { return 1; },
        two: function(_) { return 2; },
        _terminal: ohm.actions.getPrimitiveValue
      }).
      addOperation('valueTimesTwo', {
        _default: function(children) { return this.value() * 2; }
      });
  t.throws(function() { ns.G2.semantics(s).addOperation('value', {}); }, /already exists/);
  t.throws(function() { ns.G2.semantics(s).extendOperation('value', {}); }, /wrong arity/);
  t.throws(function() { ns.G2.semantics(s).extendOperation('foo', {}); }, /no inherited operation/);
  t.throws(function() { ns.G.semantics().extendOperation('value', {}); }, /no inherited operation/);

  var s2 = ns.G2.semantics(s).extendOperation('value', {
    one: function(str, _) { return 21; },  // overriding
    three: function(str) { return 3; }     // adding a new case
  });
  var m = ns.G2.match('eins!', 'one');
  t.equal(s2(m).value(), 21);
  t.equal(s2(m).valueTimesTwo(), 42);

  m = ns.G2.match('two', 'two');
  t.equal(s2(m).value(), 2);
  t.equal(s2(m).valueTimesTwo(), 4);

  m = ns.G2.match('drei', 'three');
  t.equal(s2(m).value(), 3);
  t.equal(s2(m).valueTimesTwo(), 6);

  t.end();
});
<commit_msg>added tests that ensure that a node from one grammar can't be used with a semantics from another<commit_after>'use strict';

// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var extend = require('util-extend');
var fs = require('fs');
var test = require('tape');

var ohm = require('..');
var util = require('./util');

// --------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------

var arithmeticGrammarSource = fs.readFileSync('test/arithmetic.ohm').toString();

// Combines the properties of `obj1` and `props` into a new object.
function combine(obj1, props) {
  return extend(extend({}, obj1), props);
}

// --------------------------------------------------------------------
// Tests
// --------------------------------------------------------------------

test('basic semantics', function(t) {
  var expr = ohm.makeGrammar(arithmeticGrammarSource);

  var s = expr.semantics();
  s.addOperation('value', {
    addExpr_plus: function(x, op, y) {
      return x.value() + y.value();
    },
    mulExpr_times: function(x, op, y) {
      return x.value() * y.value();
    },
    number_rec: function(n, d) {
      return n.value() * 10 + d.value();
    },
    digit: function(expr) {
      return expr.value().charCodeAt(0) - '0'.charCodeAt(0);
    },
    _default: ohm.actions.passThrough,
    _terminal: function() {
      return this.node.primitiveValue;
    }
  });

  function match(source) {
    return expr.match(source, 'expr');
  }

  t.ok(match('1*(2+3)-4/5'), 'expr is recognized');

  t.equal(s(match('1+2')).value(), 3, 'single addExpr');
  t.equal(s(match('13+10*2*3')).value(), 73, 'more complicated case');
  t.throws(function() { s.addOperation('value'); }, 'throws when name already exists');

  t.ok(s.addOperation('one', {}).addOperation('two', {}), 'chaining');
  t.throws(function() { s(null).value(); }, /expected a node/);
  t.throws(function() { s(false).value(); }, /expected a node/);
  t.throws(function() { s().value(); }, /expected a node/);
  t.throws(function() { s(3).value(); }, /expected a node/);
  t.throws(function() { s('asdf').value(); }, /expected a node/);

  // Cannot use the semantics on nodes from another grammar.
  var g = ohm.makeGrammar('G {}');
  t.throws(function() { s(g.match('a', 'letter')).value(); }, /Cannot use node from grammar/);

  // TODO: Decide how this should work. Also, test with a subgrammar that has different arity
  // for some rules.
  // g = ohm.makeGrammar('Expr2 <: Expr {}', {Expr:expr});
  // t.equal(s(g.match('1+2', 'expr')).value(), 3);

  // An operation that produces a list of the values of all the numbers in the tree.
  s.addOperation('numberValues', {
    addExpr_plus: function(x, op, y) {
      return x.numberValues().concat(y.numberValues());
    },
    mulExpr_times: function(x, op, y) {
      return x.numberValues().concat(y.numberValues());
    },
    number: function(n) {
      return [n.value()];
    },
    _default: ohm.actions.passThrough
  });
  t.deepEqual(s(match('13+10*2*3')).numberValues(), [13, 10, 2, 3]);
  t.deepEqual(s(match('9')).numberValues(), [9]);

  t.end();
});

test('_many nodes', function(t) {
  var g = ohm.makeGrammar('G { letters = letter* }');
  var actions = {
    _default: ohm.actions.passThrough,
    _terminal: ohm.actions.getPrimitiveValue
  };
  var s = g.semantics().addOperation('op', combine(actions, {_many: ohm.actions.makeArray}));
  var m = g.match('abc', 'letters');
  t.deepEqual(s(m).op(), ['a', 'b', 'c'], 'makeArray works');

  s = g.semantics().addOperation('op', combine(actions, {_many: ohm.actions.passThrough}));
  t.throws(function() { s(m).op(); }, /passThrough/, 'throws with passThrough');

  t.throws(function() {
    g.semantics().addOperation('op', combine(actions, {_many: ohm.actions.getPrimitiveValue}));
  }, /wrong arity/, 'throws with getPrimitiveValue');

  s = g.semantics().addOperation('op', combine(actions, {
    _many: function(letters) {
      t.ok(letters.every(function(l) {
        return typeof l.op === 'function';
      }), 'only arg is an array of wrappers');
      t.equal(typeof this.op, 'function', '`this` has an op() method');
      t.equal(this.node.ctorName, '_many', '`this.node` is the actual node');
      return letters.map(function(l) { return l.op(); }).join(',');
    }
  }));
  t.equal(s(m).op(), 'a,b,c');

  t.end();
});

test('_terminal nodes', function(t) {
  var g = ohm.makeGrammar('G { letters = letter* }');
  var actions = {
    _default: ohm.actions.passThrough,
    _many: ohm.actions.makeArray
  };
  var s = g.semantics().addOperation('op', combine(actions, {
    _terminal: ohm.actions.getPrimitiveValue
  }));
  var m = g.match('abc', 'letters');
  t.deepEqual(s(m).op(), ['a', 'b', 'c'], 'getPrimitiveValue works');

  t.throws(function() {
    g.semantics().addOperation('op', combine(actions, {_terminal: ohm.actions.passThrough}));
  }, /wrong arity/, 'throws with passThrough');

  t.throws(function() {
    g.semantics().addOperation('op', combine(actions, {_terminal: ohm.actions.makeArray}));
  }, /wrong arity/, 'throws with makeArray');

  s = g.semantics().addOperation('op', combine(actions, {
    _terminal: function() {
      t.equal(arguments.length, 0, 'there are no arguments');
      t.equal(this.node.ctorName, '_terminal');
      t.equal(this.node.children.length, 0, 'node has no children');
      return this.node.primitiveValue;
    }
  }));
  t.deepEqual(s(m).op(), ['a', 'b', 'c']);

  t.end();
});

test('semantic action arity checks', function(t) {
  var g = ohm.makeGrammar('G {}');
  function makeOperation(grammar, actions) {
    return grammar.semantics().addOperation('op' + util.uniqueId(), actions);
  }
  function ignore0() {}
  function ignore1(a) {}
  function ignore2(a, b) {}

  t.ok(makeOperation(g, {}), 'empty actions with empty grammar');
  t.ok(makeOperation(g, {foo: null}), 'unrecognized action names are ignored');

  t.throws(function() { makeOperation(g, {_many: ignore0}); }, /arity/, '_many');
  t.ok(makeOperation(g, {_many: ignore1}), '_many works with one arg');

  t.throws(function() { makeOperation(g, {_default: ignore0}); }, /arity/, '_default is checked');
  t.ok(makeOperation(g, {_default: ignore1}), '_default works with one arg');

  t.throws(function() {
    makeOperation(g, {_terminal: ignore1});
  }, /arity/, '_terminal is checked');
  t.ok(makeOperation(g, {_terminal: ignore0}), '_terminal works with no args');

  t.throws(function() {
    makeOperation(g, {letter: ignore0});
  }, /arity/, 'built-in rules are checked');
  t.ok(makeOperation(g, {letter: ignore1}), 'letter works with one arg');

  g = util.makeGrammar([
    'G {',
    '  one = two',
    '  two = "2" letter',
    '}']);
  t.ok(makeOperation(g, {one: ignore1, two: ignore2}));

  t.throws(function() {
    makeOperation(g, {one: ignore0, two: ignore2});
  }, /wrong arity/, "'one', is checked");
  t.throws(function() {
    makeOperation(g, {one: ignore1, two: ignore0});
  }, /wrong arity/, "'two' is checked");

  var g2 = ohm.makeGrammar('G2 <: G {}', {G: g});
  t.throws(function() {
    makeOperation(g2, {one: ignore2});
  }, /wrong arity/, 'supergrammar rules are checked');
  t.ok(makeOperation(g2, {one: ignore1}), 'works with one arg');

  var g3 = ohm.makeGrammar('G3 <: G { one := "now" "two" }', {G: g});
  t.throws(function() {
    makeOperation(g3, {one: ignore1});
  }, /wrong arity/, 'changing arity in an overridden rule');
  t.ok(makeOperation(g3, {one: ignore2}));

  t.end();
});

test('extending semantics', function(t) {
  var ns = util.makeGrammars([
    'G { ',
    '  one = "one"',
    '  two = "two"',
    '}',
    'G2 <: G {',
    '  one := "eins" "!"',
    '  three = "drei"',
    '}']);
  var s = ns.G.semantics().
      addOperation('value', {
        one: function(_) { return 1; },
        two: function(_) { return 2; },
        _terminal: ohm.actions.getPrimitiveValue
      }).
      addOperation('valueTimesTwo', {
        _default: function(children) { return this.value() * 2; }
      });
  t.throws(function() { ns.G2.semantics(s).addOperation('value', {}); }, /already exists/);
  t.throws(function() { ns.G2.semantics(s).extendOperation('value', {}); }, /wrong arity/);
  t.throws(function() { ns.G2.semantics(s).extendOperation('foo', {}); }, /no inherited operation/);
  t.throws(function() { ns.G.semantics().extendOperation('value', {}); }, /no inherited operation/);

  var s2 = ns.G2.semantics(s).extendOperation('value', {
    one: function(str, _) { return 21; },  // overriding
    three: function(str) { return 3; }     // adding a new case
  });
  var m = ns.G2.match('eins!', 'one');
  t.equal(s2(m).value(), 21);
  t.equal(s2(m).valueTimesTwo(), 42);

  m = ns.G2.match('two', 'two');
  t.equal(s2(m).value(), 2);
  t.equal(s2(m).valueTimesTwo(), 4);

  m = ns.G2.match('drei', 'three');
  t.equal(s2(m).value(), 3);
  t.equal(s2(m).valueTimesTwo(), 6);

  t.end();
});

test('mixing nodes from one grammar with semantics from another', function(t) {
  var ns = util.makeGrammars([
    'G {',
    '  start = "aaa"',
    '}',
    'GPrime <: G {',
    '  start := "bbb"',
    '}',
    'Unrelated {',
    '  start = "asdf"',
    '}'
  ]);

  var s = ns.G.semantics().addOperation('value', {
    start: function(x) { return x.value() + 'choo!'; },
    _terminal: function() { return this.node.primitiveValue; }
  });

  var m = ns.G.match('aaa', 'start');
  t.equal(s(m).value(), 'aaachoo!');

  m = ns.GPrime.match('bbb', 'start');
  t.throws(function() { s(m).value(); }, /node from grammar/);

  m = ns.Unrelated.match('asdf', 'start');
  t.throws(function() { s(m).value(); }, /node from grammar/);

  t.end();
});
<|endoftext|>


<commit_before>var coap = require('coap');

var sendNumber = function() {
    // 1 to 100
    var number = Math.round(Math.random() * 100 + 1);
    var obj = {temperature: number, temp: number};
    var data = JSON.stringify(obj);

    console.log('Pushing: ' + data);

    var clientWriable = coap.request('coap://192.168.1.100:8000/object/5550937980d51931b3000009/send');
    clientWriable.end(new Buffer(data));
};

sendNumber();

process.exit(0);
<commit_msg>Fix test, send to localhost<commit_after>var coap = require('coap');

var sendNumber = function() {
    // 1 to 100
    var number = Math.round(Math.random() * 100 + 1);
    var obj = {temperature: number, temp: number};
    var data = JSON.stringify(obj);

    console.log('Pushing: ' + data);

    var clientWriable = coap.request('coap://localhost:8000/object/5550937980d51931b3000009/send');
    clientWriable.end(new Buffer(data));
};

sendNumber();
process.exit(0);
<|endoftext|>


<commit_before>define([
	"engine/map/entity",
	"basic/mapbuilder",
	"physics/jello"
], function(
	Entity,
	MapBuilder,
	Jello
) {
	var Layer = mini.Class.subclass({
		initialize: function(name) {
			this.name = name || "";
			this.entities = [];
			this.enabled = true;

			this.zIndex = 0;
			this.scrollFactor = Jello.Vector2.One.copy();
			this.scale = Jello.Vector2.One.copy();

			this._canvas = document.createElement('canvas');
		},

		// Update all entities.
		update: function() {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				if(typeof this.world !== "undefined")
					this.world.update(1/60); // env.time.timePassed

				// TODO: adjust to use dedicated getter and setter
				// update Floom fluid system
				if(typeof this.getFluidSystem() !== "undefined")
					this.getFluidSystem().update(); // env.time.timePassed

				for(var index in this.entities) {
					if(!this.entities.hasOwnProperty(index)) continue;

					this.entities[index].update();
				}

				if(typeof this.interaction === "function")
					this.interaction.call(this);

				env.camera.popLayer();
			}
		},

		prepareRendering: function() {
			this._canvas.width = env.canvas.extent.x;
			this._canvas.height = env.canvas.extent.y;
			env.renderer.renderToTexture(this._canvas);
			env.renderer.pushLayer(this);
		},

		finishRendering: function() {
			env.renderer.popLayer();
			env.renderer.renderNormally();
		},

		draw: function(renderer) {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				this.prepareRendering();

				this._normalDraw(renderer);
				this._debugDraw(renderer);

				this.finishRendering();
				env.camera.popLayer();
			}
		},

		_normalDraw: function(renderer) {
			// draw Floom fluid system
			if(typeof this.getFluidSystem() !== "undefined")
				this.getFluidSystem().draw(renderer);

			// draw Entities
			for(var index in this.entities) {
				if(!this.entities.hasOwnProperty(index)) continue;

				this.entities[index].draw(renderer);
			}
		},

		_debugDraw: function(debugDraw) {
			for(var index in this.entities) {
				if(!this.entities.hasOwnProperty(index)) continue;

				this.entities[index].debugDraw(debugDraw);
			}

			if(typeof this.world !== "undefined")
				this.world.debugDraw(debugDraw);
		},

		/*
		 * Soft body engine
		 */
		setWorld: function(world) {
			this.world = world;
			if(typeof Editor === "undefined")
				MapBuilder.setUpTestMap(this, this.world);

			return this;
		},

		getWorld: function() {
			return this.world;
		},

		/*
		 * Fluid System
		 */
		setFluidSystem: function(fluidSystem) {
			this.fluidSystem = fluidSystem;
		},

		getFluidSystem: function() {
			return this.fluidSystem;
		},

		/*
		 * Manage Entities
		 */
		addEntity: function(entity) {
			this.entities.push(entity);

			return this;
		},

		getEntities: function() {
			return this.entities;
		},

		getEntityWithName: function(name) {
			return this.getEntitiesWithName(name)[0];
		},

		getEntitiesWithName: function(name) {
			return _.filter(this.entities, function(entity) {
				return entity.name == name;
			}, this);
		},

		getEntityWithTag: function(tag) {
			return this.getEntitiesWithTag(tag)[0];
		},

		getEntitiesWithTag: function(tag) {
			return _.filter(this.entities, function(entity) {
				return entity.hasTag(tag);
			}, this);
		},

		/*
		 * Interactions
		 */
		setInteraction: function(callback) {
			this.interaction = callback;
		},

		/*
		 * Interaction and debug
		 */
		initDatGui: function(mapFolder, index) {
			if(!Bloob.debug || !Bloob.debug.datGui) return;
			if(typeof this.world === "undefined") return;
			var layerFolder = mapFolder.addFolder('Layer' + index);
			layerFolder.open();
			layerFolder.add(Jello.Material.Default, 'friction').name('Friction').min(-2).max(2).listen().step(0.1);
			layerFolder.add(Jello.Material.Default, 'elasticity').name('Elasticity').min(-2).max(2).listen().step(0.1);
			layerFolder.add(this.world.gravitation, 'x').name('Gravitation_x').listen().min(-20).max(20).step(0.01);
			layerFolder.add(this.world.gravitation, 'y').name('Gravitation_y').listen().min(-20).max(20).step(0.01);
			layerFolder.add(this, 'zIndex').listen().min(0.01).max(20).step(0.01);
			layerFolder.add(this.scrollFactor, 'x').name('ScrollFactor_x').listen();
			layerFolder.add(this.scrollFactor, 'y').name('ScrollFactor_y').listen();
			layerFolder.add(this.scale, 'x').name('Scale_x').listen();
			layerFolder.add(this.scale, 'y').name('Scale_y').listen();
		}
	});

	Layer.prototype.toJson = function() {
		var json = {
			name: this.name,
			zIndex: this.zIndex,
			scrollFactor: this.scrollFactor.toJson(),
			scale: this.scale.toJson(),
			entities: []
		};

		// Serialize world if existing.
		if(typeof this.world !== "undefined")
			json.world = this.world.toJson();

		var entities = this.getEntities();
		for(var i = 0; i < entities.length; i++) {
			json.entities.push(entities[i].toJson());
		}
		return json;
	};

	Layer.fromJson = function(json) {
		var layer = new Layer(json.name);

		if(typeof json.world !== "undefined") {
			var world = Jello.World.fromJson(json.world);
			layer.setWorld(world);
		}
		if(typeof json.zIndex !== "undefined") {
			layer.zIndex = json.zIndex;
		}
		if(typeof json.scrollFactor !== "undefined") {
			layer.scrollFactor = Jello.Vector2.fromJson(json.scrollFactor);
		}
		if(typeof json.scale !== "undefined") {
			layer.scale = Jello.Vector2.fromJson(json.scale);
		}

		if(typeof json.entities !== "undefined") {
			for(var index in json.entities)
				Entity.fromJson(json.entities[index], layer.getWorld()).addToLayer(layer);
		}

		return layer;
	};

	Layer.WorldLayer = Layer;

	return Layer;
});
<commit_msg>refactored added methods to be private<commit_after>define([
	"engine/map/entity",
	"basic/mapbuilder",
	"physics/jello"
], function(
	Entity,
	MapBuilder,
	Jello
) {
	var Layer = mini.Class.subclass({
		initialize: function(name) {
			this.name = name || "";
			this.entities = [];
			this.enabled = true;

			this.zIndex = 0;
			this.scrollFactor = Jello.Vector2.One.copy();
			this.scale = Jello.Vector2.One.copy();

			this._canvas = document.createElement('canvas');
		},

		// Update all entities.
		update: function() {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				if(typeof this.getWorld() !== "undefined")
					this.getWorld().update(1/60); // env.time.timePassed

				// update Floom fluid system
				if(typeof this.getFluidSystem() !== "undefined")
					this.getFluidSystem().update(); // env.time.timePassed

				for(var index in this.entities) {
					if(!this.entities.hasOwnProperty(index)) continue;

					this.entities[index].update();
				}

				if(typeof this.interaction === "function")
					this.interaction.call(this);

				env.camera.popLayer();
			}
		},

		_prepareRendering: function() {
			this._canvas.width = env.canvas.extent.x;
			this._canvas.height = env.canvas.extent.y;
			env.renderer.renderToTexture(this._canvas);
			env.renderer.pushLayer(this);
		},

		_finishRendering: function() {
			env.renderer.popLayer();
			env.renderer.renderNormally();
		},

		draw: function(renderer) {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				this._prepareRendering();

				renderer.clear();
				this._normalDraw(renderer);
				this._debugDraw(renderer);

				this._finishRendering();
				env.camera.popLayer();
			}
		},

		_normalDraw: function(renderer) {
			// draw Floom fluid system
			if(typeof this.getFluidSystem() !== "undefined")
				this.getFluidSystem().draw(renderer);

			// draw Entities
			var entityCount = this.entities.length;
			for(var i = 0; i < entityCount; i++) {
				this.entities[i].draw(renderer);
			}
		},

		_debugDraw: function(renderer) {
			// draw Entities
			var entityCount = this.entities.length;
			for(var i = 0; i < entityCount; i++) {
				this.entities[i].debugDraw(renderer);
			}

			if(typeof this.getWorld() !== "undefined")
				this.getWorld().debugDraw(renderer);
		},

		/*
		 * Soft body engine
		 */
		setWorld: function(world) {
			this.world = world;
			if(typeof Editor === "undefined")
				MapBuilder.setUpTestMap(this, this.world);

			return this;
		},

		getWorld: function() {
			return this.world;
		},

		/*
		 * Fluid System
		 */
		setFluidSystem: function(fluidSystem) {
			this.fluidSystem = fluidSystem;
		},

		getFluidSystem: function() {
			return this.fluidSystem;
		},

		/*
		 * Manage Entities
		 */
		addEntity: function(entity) {
			this.entities.push(entity);

			return this;
		},

		getEntities: function() {
			return this.entities;
		},

		getEntityWithName: function(name) {
			return this.getEntitiesWithName(name)[0];
		},

		getEntitiesWithName: function(name) {
			return _.filter(this.entities, function(entity) {
				return entity.name == name;
			}, this);
		},

		getEntityWithTag: function(tag) {
			return this.getEntitiesWithTag(tag)[0];
		},

		getEntitiesWithTag: function(tag) {
			return _.filter(this.entities, function(entity) {
				return entity.hasTag(tag);
			}, this);
		},

		/*
		 * Interactions
		 */
		setInteraction: function(callback) {
			this.interaction = callback;
		},

		/*
		 * Interaction and debug
		 */
		initDatGui: function(mapFolder, index) {
			if(!Bloob.debug || !Bloob.debug.datGui) return;
			if(typeof this.world === "undefined") return;
			var layerFolder = mapFolder.addFolder('Layer' + index);
			layerFolder.open();
			layerFolder.add(Jello.Material.Default, 'friction').name('Friction').min(-2).max(2).listen().step(0.1);
			layerFolder.add(Jello.Material.Default, 'elasticity').name('Elasticity').min(-2).max(2).listen().step(0.1);
			layerFolder.add(this.world.gravitation, 'x').name('Gravitation_x').listen().min(-20).max(20).step(0.01);
			layerFolder.add(this.world.gravitation, 'y').name('Gravitation_y').listen().min(-20).max(20).step(0.01);
			layerFolder.add(this, 'zIndex').listen().min(0.01).max(20).step(0.01);
			layerFolder.add(this.scrollFactor, 'x').name('ScrollFactor_x').listen();
			layerFolder.add(this.scrollFactor, 'y').name('ScrollFactor_y').listen();
			layerFolder.add(this.scale, 'x').name('Scale_x').listen();
			layerFolder.add(this.scale, 'y').name('Scale_y').listen();
		}
	});

	Layer.prototype.toJson = function() {
		var json = {
			name: this.name,
			zIndex: this.zIndex,
			scrollFactor: this.scrollFactor.toJson(),
			scale: this.scale.toJson(),
			entities: []
		};

		// Serialize world if existing.
		if(typeof this.world !== "undefined")
			json.world = this.world.toJson();

		var entities = this.getEntities();
		for(var i = 0; i < entities.length; i++) {
			json.entities.push(entities[i].toJson());
		}
		return json;
	};

	Layer.fromJson = function(json) {
		var layer = new Layer(json.name);

		if(typeof json.world !== "undefined") {
			var world = Jello.World.fromJson(json.world);
			layer.setWorld(world);
		}
		if(typeof json.zIndex !== "undefined") {
			layer.zIndex = json.zIndex;
		}
		if(typeof json.scrollFactor !== "undefined") {
			layer.scrollFactor = Jello.Vector2.fromJson(json.scrollFactor);
		}
		if(typeof json.scale !== "undefined") {
			layer.scale = Jello.Vector2.fromJson(json.scale);
		}

		if(typeof json.entities !== "undefined") {
			for(var index in json.entities)
				Entity.fromJson(json.entities[index], layer.getWorld()).addToLayer(layer);
		}

		return layer;
	};

	Layer.WorldLayer = Layer;

	return Layer;
});
<|endoftext|>


<commit_before>var len = 0;
var toString = {}.toString;
var vertxNext;
var customSchedulerFn;

export var asap = function asap(callback, arg) {
  queue[len] = callback;
  queue[len + 1] = arg;
  len += 2;
  if (len === 2) {
    // If len is 2, that means that we need to schedule an async flush.
    // If additional callbacks are queued before the queue is flushed, they
    // will be processed by this flush that we are scheduling.
    if (customSchedulerFn) {
      customSchedulerFn(flush);
    } else {
      scheduleFlush();
    }
  }
}

export function setScheduler(scheduleFn) {
  customSchedulerFn = scheduleFn;
}

export function setAsap(asapFn) {
  asap = asapFn;
}

var browserWindow = (typeof window !== 'undefined') ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';

// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  typeof importScripts !== 'undefined' &&
  typeof MessageChannel !== 'undefined';

// node
function useNextTick() {
  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  // see https://github.com/cujojs/when/issues/410 for details
  return function() {
    process.nextTick(flush);
  };
}

// vertx
function useVertxTimer() {
  return function() {
    vertxNext(flush);
  };
}

function useMutationObserver() {
  var iterations = 0;
  var observer = new BrowserMutationObserver(flush);
  var node = document.createTextNode('');
  observer.observe(node, { characterData: true });

  return function() {
    node.data = (iterations = ++iterations % 2);
  };
}

// web worker
function useMessageChannel() {
  var channel = new MessageChannel();
  channel.port1.onmessage = flush;
  return function () {
    channel.port2.postMessage(0);
  };
}

function useSetTimeout() {
  return function() {
    setTimeout(flush, 1);
  };
}

var queue = new Array(1000);
function flush() {
  for (var i = 0; i < len; i+=2) {
    var callback = queue[i];
    var arg = queue[i+1];

    callback(arg);

    queue[i] = undefined;
    queue[i+1] = undefined;
  }

  len = 0;
}

function attemptVertx() {
  try {
    var r = require;
    var vertx = r('vertx');
    vertxNext = vertx.runOnLoop || vertx.runOnContext;
    return useVertxTimer();
  } catch(e) {
    return useSetTimeout();
  }
}

var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
  scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
  scheduleFlush = useMutationObserver();
} else if (isWorker) {
  scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
  scheduleFlush = attemptVertx();
} else {
  scheduleFlush = useSetTimeout();
}
<commit_msg>Remove unused variable<commit_after>var len = 0;
var vertxNext;
var customSchedulerFn;

export var asap = function asap(callback, arg) {
  queue[len] = callback;
  queue[len + 1] = arg;
  len += 2;
  if (len === 2) {
    // If len is 2, that means that we need to schedule an async flush.
    // If additional callbacks are queued before the queue is flushed, they
    // will be processed by this flush that we are scheduling.
    if (customSchedulerFn) {
      customSchedulerFn(flush);
    } else {
      scheduleFlush();
    }
  }
}

export function setScheduler(scheduleFn) {
  customSchedulerFn = scheduleFn;
}

export function setAsap(asapFn) {
  asap = asapFn;
}

var browserWindow = (typeof window !== 'undefined') ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';

// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  typeof importScripts !== 'undefined' &&
  typeof MessageChannel !== 'undefined';

// node
function useNextTick() {
  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  // see https://github.com/cujojs/when/issues/410 for details
  return function() {
    process.nextTick(flush);
  };
}

// vertx
function useVertxTimer() {
  return function() {
    vertxNext(flush);
  };
}

function useMutationObserver() {
  var iterations = 0;
  var observer = new BrowserMutationObserver(flush);
  var node = document.createTextNode('');
  observer.observe(node, { characterData: true });

  return function() {
    node.data = (iterations = ++iterations % 2);
  };
}

// web worker
function useMessageChannel() {
  var channel = new MessageChannel();
  channel.port1.onmessage = flush;
  return function () {
    channel.port2.postMessage(0);
  };
}

function useSetTimeout() {
  return function() {
    setTimeout(flush, 1);
  };
}

var queue = new Array(1000);
function flush() {
  for (var i = 0; i < len; i+=2) {
    var callback = queue[i];
    var arg = queue[i+1];

    callback(arg);

    queue[i] = undefined;
    queue[i+1] = undefined;
  }

  len = 0;
}

function attemptVertx() {
  try {
    var r = require;
    var vertx = r('vertx');
    vertxNext = vertx.runOnLoop || vertx.runOnContext;
    return useVertxTimer();
  } catch(e) {
    return useSetTimeout();
  }
}

var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
  scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
  scheduleFlush = useMutationObserver();
} else if (isWorker) {
  scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
  scheduleFlush = attemptVertx();
} else {
  scheduleFlush = useSetTimeout();
}
<|endoftext|>


<commit_before>(function (module) {

    module.controller('gridViewModel', [function () {

        var gridData = [
            { LastName: 'Graham', FirstName: 'Mike', FavoriteColor: 'green', GitHubID: 'cmichaelgraham' },
            { LastName: 'Vader', FirstName: 'Darth', FavoriteColor: 'black', GitHubID: 'darthvader' },
            { LastName: 'Solo', FirstName: 'Han', FavoriteColor: 'white', GitHubID: 'hansolo' },
            { LastName: 'Hut', FirstName: 'Jabba', FavoriteColor: 'brown', GitHubID: 'jabbathehut' }
        ];

        var gridOptions = {
            data: 'vm.gridData',
            enableGridMenu: true,
            columnDefs: [
                { name: 'LastName', field: 'LastName', width: '25%' },
                { name: 'FirstName', field: 'FirstName', width: '25%' },
                { name: 'FavoriteColor', field: 'FavoriteColor', width: '25%' },
                { name: 'GitHubID', field: 'GitHubID', width: '25%' }
            ]
        };

        var o = {
            message: 'this is the grid-viewmodel message...',
            gridData: gridData,
            gridOptions: gridOptions
        };

        return o;
    }]);

}(angular.module('app')));<commit_msg>added code to call the gridApi core handleWindowResize when the window is resized.  same result though<commit_after>(function (module) {

    module.controller('gridViewModel', ['$window', '$timeout', function ($window, $timeout) {

        var gridData = [
            { LastName: 'Graham', FirstName: 'Mike', FavoriteColor: 'green', GitHubID: 'cmichaelgraham' },
            { LastName: 'Vader', FirstName: 'Darth', FavoriteColor: 'black', GitHubID: 'darthvader' },
            { LastName: 'Solo', FirstName: 'Han', FavoriteColor: 'white', GitHubID: 'hansolo' },
            { LastName: 'Hut', FirstName: 'Jabba', FavoriteColor: 'brown', GitHubID: 'jabbathehut' }
        ];

        var gridOptions = {
            data: 'vm.gridData',
            enableGridMenu: true,
            columnDefs: [
                { name: 'LastName', field: 'LastName', width: '25%' },
                { name: 'FirstName', field: 'FirstName', width: '25%' },
                { name: 'FavoriteColor', field: 'FavoriteColor', width: '25%' },
                { name: 'GitHubID', field: 'GitHubID', width: '25%' }
            ],
            onRegisterApi: function (gridApi) {
                o.gridApi = gridApi;
            }
        };

        var w = angular.element($window);
        w.bind('resize', function () {
            if (o.gridApi) {
                $timeout(function () {
                    o.gridApi.core.handleWindowResize();
                }, 100);
            }
        });

        var o = {
            message: 'this is the grid-viewmodel message...',
            gridData: gridData,
            gridOptions: gridOptions
        };

        return o;
    }]);

}(angular.module('app')));<|endoftext|>


<commit_before>var http = require('http');
var browserify = require('browserify');
var React = require('react');
var Navigation = require('navigation');
var NavigationShared = require('./NavigationShared');
var NavigationServer = require('./NavigationServer');
var PersonSearch = require('./PersonSearch');

http.createServer(function(req, res) {
	if (req.url === '/favicon.ico') {
		res.statusCode = 404;
		res.end();
		return;
	}
	if (req.url === '/app.js') {
		browserify('./NavigationClient.js', { standalone: 'NavigationClient' })
			.bundle()
			.pipe(res)
		return;
	}
	var matches = req.url.match(/^\/data\/people\/(\d+)$/);
	if (matches) {
		PersonSearch.search(+matches[1], function(people){
			res.write(JSON.stringify(people));
			res.end();
		});
		return;
	}
	matches = req.url.match(/^\/data\/person\/(\d+)$/);
	if (matches) {
		PersonSearch.getDetails(+matches[1], function(person){
			res.write(JSON.stringify(person));
			res.end();
		});
		return;
	}
	Navigation.StateController.navigateLink(req.url);
	NavigationServer.getProps(function(props){
		Navigation.StateController.navigateLink(req.url);
		res.write('
')
		res.write(React.renderToString(React.createElement(NavigationShared.getComponent(), props)));
		res.write('
')
		res.end();
	});
}).listen(8080);

function safeStringify(props) {
  return JSON.stringify(props).replace(/<\/script/g, '<\\/script').replace(/


<commit_before>module.exports = Snackbar;

/**
 * Creates a snackbar component. It is possible to pass a global options object as an attribute. For public methods, see ./actions.
 */
function Snackbar() {}

Snackbar.prototype.view = __dirname + '/views';
Snackbar.prototype.style = __dirname + '/styles';
Snackbar.prototype.name = 'snackbar';
Snackbar.prototype.components = [];

require('./operations');
require('./actions');
require('./viewhelpers');

Snackbar.prototype.init = function(model) {
  this.globalOptions = this.getAttribute('options');

  model.set('queue', []);
};
<commit_msg>Removed unused file<commit_after>module.exports = Snackbar;

/**
 * Creates a snackbar component. It is possible to pass a global options object as an attribute. For public methods, see ./actions.
 */
function Snackbar() {}

Snackbar.prototype.view = __dirname + '/views';
Snackbar.prototype.style = __dirname + '/styles';
Snackbar.prototype.name = 'snackbar';
Snackbar.prototype.components = [];

require('./operations');
require('./actions');

Snackbar.prototype.init = function(model) {
  this.globalOptions = this.getAttribute('options');

  model.set('queue', []);
};
<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { computed, action, set as emSet } from "@ember/object";
import { equal, bool } from "@ember/object/computed";

export default class OxifieldMainComponent extends Component {
    @equal("args.field.type", "bool") isBool;
    @bool("args.field.error") hasError;

    @computed("args.field.type")
    get type() {
        return "oxifield-" + this.args.field.type;
    }

    @computed("args.field.size", "args.field.keysize")
    get sFieldSize() {
        var keys, keysize, size;
        keys = this.args.field.keys;
        size = this.args.field.size;
        keysize = this.args.field.keysize;
        if (!size) {
            if (keys) {
                if (!keysize) { keysize = 2 }
                size = 7 - keysize;
            } else {
                size = 7;
            }
        }
        return 'col-md-' + size;
    }

    /*
    keyPress: function(event) {
        if (event.keyCode === 9) {
            if (this.args.field.clonable) {
                if (this.args.field.value) {
                    this.addClone(this.args.field);
                    event.stopPropagation();
                    return event.preventDefault();
                }
            }
        }
    },
    */

    @action
    addClone(field) {
        this.addClone(this.args.field);
    }

    @action
    delClone(field) {
        this.delClone(this.args.field);
    }

    @action
    optionSelected(value, label) {
        emSet(this.args.field, "value", value);
        emSet(this.args.field, "error", null);
        this.onChange()
    }

    @action
    onChange() {
        console.warn("oxifield-main: onChange");
        this.args.fieldChanged(this.args.field);
    }
}
<commit_msg>JS: reset error state in field changes in oxifield-main<commit_after>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { computed, action, set as emSet } from "@ember/object";
import { equal, bool } from "@ember/object/computed";

export default class OxifieldMainComponent extends Component {
    @equal("args.field.type", "bool") isBool;
    @bool("args.field.error") hasError;

    @computed("args.field.type")
    get type() {
        return "oxifield-" + this.args.field.type;
    }

    @computed("args.field.size", "args.field.keysize")
    get sFieldSize() {
        var keys, keysize, size;
        keys = this.args.field.keys;
        size = this.args.field.size;
        keysize = this.args.field.keysize;
        if (!size) {
            if (keys) {
                if (!keysize) { keysize = 2 }
                size = 7 - keysize;
            } else {
                size = 7;
            }
        }
        return 'col-md-' + size;
    }

    /*
    keyPress: function(event) {
        if (event.keyCode === 9) {
            if (this.args.field.clonable) {
                if (this.args.field.value) {
                    this.addClone(this.args.field);
                    event.stopPropagation();
                    return event.preventDefault();
                }
            }
        }
    },
    */

    @action
    addClone(field) {
        this.addClone(this.args.field);
    }

    @action
    delClone(field) {
        this.delClone(this.args.field);
    }

    @action
    optionSelected(value, label) {
        emSet(this.args.field, "value", value);
        emSet(this.args.field, "error", null);
        this.onChange()
    }

    @action
    onChange() {
        console.warn("oxifield-main: onChange");
        emSet(this.args.field, "error", null);
        this.args.fieldChanged(this.args.field);
    }
}
<|endoftext|>