<commit_before>/*******************************************************************************
Copyright (c) 2013, Yahoo.
All rights reserved.

Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.

* Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the
  following disclaimer in the documentation and/or other
  materials provided with the distribution.

* Neither the name of Yahoo nor the names of its
  contributors may be used to endorse or promote products
  derived from this software without specific prior
  written permission of Yahoo.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
// < 1.6
_production = (typeof(_production) === "undefined") ? _PRODUCTION : _production;
// < 1.5
if (typeof(common) === "undefined") {
	common = {};
	platform = ((typeof(platform) === "undefined") || (platform === null)) ? {} : platform;
	(function common_compatibility_singleton() {
		platform.config = ("config" in platform) ? platform.config : {};
		common.dump = KONtx.Class.helpers.dump;
		common.merge = KONtx.Class.helpers.merge;
		common.clone = KONtx.Class.helpers.unlink;
		common.bind = function common_bind(source, target) {
			return Function.bindTo(target, source);
		};
		common.debug = {
			log: (function common_debug_log_singleton() {
				var tag = "[" + (widget.name || "") + "]";
				var method = function common_debug_log() {
					!_production && log(tag + " {" + String(this) + "} " + Array.slice(arguments).join(", "));
				};
				return method;
			})()
		};
		common.toString = function common_toString() {
			var result = "";
			if (arguments[0]) {
				result = String(arguments[0]);
			} else {
				result = this.ClassName || this.Name || (this.config && this.config.name) || this.name || "Nameless Class Definition";
			}
			return result;
		};
		common.isEmpty = function common_isEmpty(source) {
			if (source == null) {
				return true;
			}
			var type = common.typeOf(source);
			switch (type) {
				case "string":
					return (source.length > 0) ? false : true;
				case "number":
					return false;
				case "object":
					for (var property in source) {
						if (source.hasOwnProperty(property)) {
							return false;
						}
					}
					return true;
				default:
					return type ? false : true;
			}
		};
		common.typeOf = function common_typeOf(source) {

			if (source == undefined) {

				return false;

			}

			switch (source.constructor) {

				case Object:

					return "object";

				case Array:

					return "array";

				case Number:

					return isFinite(source) ? "number" : false;

				case Glow:

					return "glow";

				case Date:

					return "date";

				case Function:

					return "function";

				default:

					if (typeof(source.length) === "number") {

						if (source.callee) {

							return "arguments";

						} else if (source.item) {

							return "collection";

						}

					}

					if (source.__instanceID || source._ktxID) {

						return "instance";

					}

					if (source.nodeName) {

						return source.nodeName;

					}

			}

			return typeof(source);

		};
        common.Object = {};
        common.Object.keys = function common_Object_keys(source) {
            var list = [];
            for (var key in source) {
                list.push(key);
            }
            return list;
        };
        common.Object.from = function common_Object_from(source) {
            var item = {};
            if (common.isObject(source)) {
                item = source;
            } else {
                item[source] = arguments[1];
            }
            return item;
        };
        common.isObject = function common_isObject(source) {
            return common.typeOf(source) === "object";
        };
        common.toObject = function common_toObject() {
            return common.Object.from.apply(false, arguments);
        };
        common.manifest = (function common_manifest_singleton() {
            var instance = {
                stack: {},
                add: function common_manifest_add() {
                    var run = 1;
                    switch (run) {
                        case 0:
                            if (typeof(arguments[0]) === "string") {
                                arguments[0] = common.toObject(arguments[0], arguments[1]);
                                arguments[1] = "";
                            }
                            for (var key in arguments[0]) {
                                var result = null;
                                var file = null;
                                var value = arguments[0][key];
                                var path = arguments[1];
                                if (value) {
                                    if (typeof(value) === "string") {
                                        result = (path || "") + value;
                                    } else {
                                        if ("file" in value) {
                                            file = value.file;
                                            value.file = (path || "") + file;
                                        }
                                        result = value;
                                    }
                                    if (result) {
                                        this.stack[key] = result;
                                    }
                                }
                            }
                            break;
                        case 1:
                            if (typeof(arguments[0]) === "string") {
                                this.stack[arguments[0]] = arguments[1];
                            } else {
                                for (var i in arguments[0]) {
                                    if (arguments.length > 1) {
                                        if (typeof(arguments[0][i]) === "string") {
                                            arguments[0][i] = arguments[1] + arguments[0][i];
                                        } else {
                                            arguments[0][i].file = arguments[1] + arguments[0][i].file;
                                        }
                                    }
                                    this.stack[i] = arguments[0][i];
                                }
                            }
                            break;
                    }
                },
                get: function common_manifest_get(entry) {
                    return (entry && (entry in this.stack)) ? this.stack[entry] : false;
                }
            };
            return instance;
        })();
	})();
}
// < 1.7
if (!("level" in common.debug)) {
    (function common_debug_level() {
        var logLevel = [_production ? false : true];
        common.debug.__defineSetter__("level", function (level) {
            logLevel = [];
            for (var i = 0; i <= Number(level); i++) {
                logLevel[i] = true;
            }
        });
        common.debug.__defineGetter__("level", function () {
            return logLevel;
        });
    })();
    common.debug.level = 2;
}
// < 1.6
if (!("Element" in common)) {
	common.Element = {};
	common.Element.getBounds = function (source, absolute) {
		var convertor = absolute ? "convertPointToWindow" : "convertPointToParent";
		var element = source.element;
		var upper = element[convertor](0, 0);
		var lower = element[convertor](element.width, element.height);
		return {
			width: element.width,
			height: element.height,
			top: upper.y,
			right: lower.x,
			bottom: lower.y,
			left: upper.x
		};
	};
}
// < 1.6
if (!("String" in common)) {
    common.String = {};
}
// < 1.5
if (!("trim" in common.String)) {
    common.String.trim = function common_String_trim(source) {
        return source.replace(/^\s+|\s+$/g, "");
    };
}
// < 1.6
if (!("cleanWhitespace" in common.String)) {
    common.String.cleanWhitespace = function common_String_cleanWhitespace(source) {
        return common.String.trim(source.replace(/\s{2,}/g, " "));
    };
}
// < 1.5
if (!("getViewConfig" in KONtx.application)) {
	KONtx.application.getViewConfig = function () {
		return false;
	}
}
// < 1.5
if (!("viewTypes" in KONtx.application)) {
	KONtx.application.viewTypes = {
		"SNIPPETS": "snippet",
		"SNIPPET": "snippet",
		"SNIPPET-ANCHOR": "snippet",
		"SIDEBAR": "sidebar",
		"SIDEBAR-ENTRY": "sidebar",
		"SIDE_BAR": "sidebar",
		"FULLSCREEN": "fullscreen",
		"FULL_SCREEN": "fullscreen",
		"FAT_TRAY": "fat-tray",
		"SKINNY_TRAY": "skinny-tray"
	};
}
// < 1.4
if (!("isPhysicalNetworkDown" in KONtx.application)) {
    KONtx.application.isPhysicalNetworkDown = function () {
        return (typeof(KONtx.application.getNetworkDownStatus) == "function") ? KONtx.application.getNetworkDownStatus() : KONtx.application.getNetworkDownStatus;
    };
}
// < 1.3.10
if (!("getDefaultViewportBounds" in KONtx.mediaplayer)) {
	KONtx.mediaplayer.getDefaultViewportBounds = function () {
		return {
			x: 0,
			y: 0,
			width: 1920,
			height: 1080
		};
	};
}
<commit_msg>changed indentation in compatibility lib<commit_after>/*******************************************************************************
Copyright (c) 2013, Yahoo.
All rights reserved.

Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:

* Redistributions of source code must retain the above
  copyright notice, this list of conditions and the
  following disclaimer.

* Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the
  following disclaimer in the documentation and/or other
  materials provided with the distribution.

* Neither the name of Yahoo nor the names of its
  contributors may be used to endorse or promote products
  derived from this software without specific prior
  written permission of Yahoo.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
// < 1.6
_production = (typeof(_production) === "undefined") ? _PRODUCTION : _production;
// < 1.5
if (typeof(common) === "undefined") {
	common = {};
	platform = ((typeof(platform) === "undefined") || (platform === null)) ? {} : platform;
	(function common_compatibility_singleton() {
		platform.config = ("config" in platform) ? platform.config : {};
		common.dump = KONtx.Class.helpers.dump;
		common.merge = KONtx.Class.helpers.merge;
		common.clone = KONtx.Class.helpers.unlink;
		common.bind = function common_bind(source, target) {
			return Function.bindTo(target, source);
		};
		common.debug = {
			log: (function common_debug_log_singleton() {
				var tag = "[" + (widget.name || "") + "]";
				var method = function common_debug_log() {
					!_production && log(tag + " {" + String(this) + "} " + Array.slice(arguments).join(", "));
				};
				return method;
			})()
		};
		common.toString = function common_toString() {
			var result = "";
			if (arguments[0]) {
				result = String(arguments[0]);
			} else {
				result = this.ClassName || this.Name || (this.config && this.config.name) || this.name || "Nameless Class Definition";
			}
			return result;
		};
		common.isEmpty = function common_isEmpty(source) {
			if (source == null) {
				return true;
			}
			var type = common.typeOf(source);
			switch (type) {
				case "string":
					return (source.length > 0) ? false : true;
				case "number":
					return false;
				case "object":
					for (var property in source) {
						if (source.hasOwnProperty(property)) {
							return false;
						}
					}
					return true;
				default:
					return type ? false : true;
			}
		};
		common.typeOf = function common_typeOf(source) {

			if (source == undefined) {

				return false;

			}

			switch (source.constructor) {

				case Object:

					return "object";

				case Array:

					return "array";

				case Number:

					return isFinite(source) ? "number" : false;

				case Glow:

					return "glow";

				case Date:

					return "date";

				case Function:

					return "function";

				default:

					if (typeof(source.length) === "number") {

						if (source.callee) {

							return "arguments";

						} else if (source.item) {

							return "collection";

						}

					}

					if (source.__instanceID || source._ktxID) {

						return "instance";

					}

					if (source.nodeName) {

						return source.nodeName;

					}

			}

			return typeof(source);

		};
		common.Object = {};
		common.Object.keys = function common_Object_keys(source) {
			var list = [];
			for (var key in source) {
				list.push(key);
			}
			return list;
		};
		common.Object.from = function common_Object_from(source) {
			var item = {};
			if (common.isObject(source)) {
				item = source;
			} else {
				item[source] = arguments[1];
			}
			return item;
		};
		common.isObject = function common_isObject(source) {
			return common.typeOf(source) === "object";
		};
		common.toObject = function common_toObject() {
			return common.Object.from.apply(false, arguments);
		};
		common.manifest = (function common_manifest_singleton() {
			var instance = {
				stack: {},
				add: function common_manifest_add() {
					var run = 1;
					switch (run) {
						case 0:
							if (typeof(arguments[0]) === "string") {
								arguments[0] = common.toObject(arguments[0], arguments[1]);
								arguments[1] = "";
							}
							for (var key in arguments[0]) {
								var result = null;
								var file = null;
								var value = arguments[0][key];
								var path = arguments[1];
								if (value) {
									if (typeof(value) === "string") {
										result = (path || "") + value;
									} else {
										if ("file" in value) {
											file = value.file;
											value.file = (path || "") + file;
										}
										result = value;
									}
									if (result) {
										this.stack[key] = result;
									}
								}
							}
							break;
						case 1:
							if (typeof(arguments[0]) === "string") {
								this.stack[arguments[0]] = arguments[1];
							} else {
								for (var i in arguments[0]) {
									if (arguments.length > 1) {
										if (typeof(arguments[0][i]) === "string") {
											arguments[0][i] = arguments[1] + arguments[0][i];
										} else {
											arguments[0][i].file = arguments[1] + arguments[0][i].file;
										}
									}
									this.stack[i] = arguments[0][i];
								}
							}
							break;
					}
				},
				get: function common_manifest_get(entry) {
					return (entry && (entry in this.stack)) ? this.stack[entry] : false;
				}
			};
			return instance;
		})();
	})();
}
// < 1.7
if (!("level" in common.debug)) {
	(function common_debug_level() {
		var logLevel = [_production ? false : true];
		common.debug.__defineSetter__("level", function (level) {
			logLevel = [];
			for (var i = 0; i <= Number(level); i++) {
				logLevel[i] = true;
			}
		});
		common.debug.__defineGetter__("level", function () {
			return logLevel;
		});
	})();
	common.debug.level = 2;
}
// < 1.6
if (!("Element" in common)) {
	common.Element = {};
	common.Element.getBounds = function (source, absolute) {
		var convertor = absolute ? "convertPointToWindow" : "convertPointToParent";
		var element = source.element;
		var upper = element[convertor](0, 0);
		var lower = element[convertor](element.width, element.height);
		return {
			width: element.width,
			height: element.height,
			top: upper.y,
			right: lower.x,
			bottom: lower.y,
			left: upper.x
		};
	};
}
// < 1.6
if (!("String" in common)) {
	common.String = {};
}
// < 1.5
if (!("trim" in common.String)) {
	common.String.trim = function common_String_trim(source) {
		return source.replace(/^\s+|\s+$/g, "");
	};
}
// < 1.6
if (!("cleanWhitespace" in common.String)) {
	common.String.cleanWhitespace = function common_String_cleanWhitespace(source) {
		return common.String.trim(source.replace(/\s{2,}/g, " "));
	};
}
// < 1.5
if (!("getViewConfig" in KONtx.application)) {
	KONtx.application.getViewConfig = function () {
		return false;
	}
}
// < 1.5
if (!("viewTypes" in KONtx.application)) {
	KONtx.application.viewTypes = {
		"SNIPPETS": "snippet",
		"SNIPPET": "snippet",
		"SNIPPET-ANCHOR": "snippet",
		"SIDEBAR": "sidebar",
		"SIDEBAR-ENTRY": "sidebar",
		"SIDE_BAR": "sidebar",
		"FULLSCREEN": "fullscreen",
		"FULL_SCREEN": "fullscreen",
		"FAT_TRAY": "fat-tray",
		"SKINNY_TRAY": "skinny-tray"
	};
}
// < 1.4
if (!("isPhysicalNetworkDown" in KONtx.application)) {
	KONtx.application.isPhysicalNetworkDown = function () {
		return (typeof(KONtx.application.getNetworkDownStatus) == "function") ? KONtx.application.getNetworkDownStatus() : KONtx.application.getNetworkDownStatus;
	};
}
// < 1.3.10
if (!("getDefaultViewportBounds" in KONtx.mediaplayer)) {
	KONtx.mediaplayer.getDefaultViewportBounds = function () {
		return {
			x: 0,
			y: 0,
			width: 1920,
			height: 1080
		};
	};
}
<|endoftext|>


<commit_before>'use strict';

require('../globals');

var util = require('../util'),
  setter = util.setter,
  getter = util.getter,
  time = require('./time');

var axis = module.exports = {};

axis.names = function(props) {
  return util.keys(util.keys(props).reduce(function(a, x) {
    var s = props[x].scale;
    if (s === X || s === Y) a[props[x].scale] = 1;
    return a;
  }, {}));
};

axis.defs = function(names, encoding, layout, stats, opt) {
  return names.reduce(function(a, name) {
    a.push(axis.def(name, encoding, layout, stats, opt));
    return a;
  }, []);
};

axis.def = function(name, encoding, layout, stats, opt) {
  var isCol = name == COL,
    isRow = name == ROW,
    type = isCol ? 'x' : isRow ? 'y' : name,
    rowOffset = axis.titleOffset(encoding, layout, Y) + 20;

  var def = {
    type: type,
    scale: name,
    properties: {}
  };

  def = axis.grid(def, name, encoding, layout, rowOffset);
  def = axis.title(def, name, encoding, layout, opt);

  def.titleOffset = axis.titleOffset(encoding, layout, name);

  if (isRow || isCol) {
    def = axis.hideTicks(def);
  }

  if (isCol) {
    def.orient = 'top';
  }

  if (isRow) {
    def.offset = rowOffset;
  }

  if (name == X) {
    if (encoding.has(Y) && encoding.isOrdinalScale(Y) && encoding.cardinality(Y, stats) > 30) {
      def.orient = 'top';
    }

    if (encoding.isDimension(X) || encoding.isType(X, T)) {
      var isTop = def.orient ==='top',
        labelProps = isTop ? {
            angle: {value: 90},
            align: {value: 'left'},
            baseline: {value: 'middle'}
          } : {
            angle: {value: 270},
            align: {value: 'right'},
            baseline: {value: 'middle'}
          };

      setter(def, ['properties','labels'], labelProps);
    } else { // Q
      def.ticks = 5;
    }
  }

  def = axis.labels(def, name, encoding, layout, stats, opt);

  return def;
};

axis.grid = function(def, name, encoding, layout, rowOffset) {
  var cellPadding = layout.cellPadding,
    isCol = name == COL,
    isRow = name == ROW;

  if (encoding.axis(name).grid) {
    def.grid = true;
    def.layer = 'back';

    if (isCol) {
      // set grid property -- put the lines on the right the cell
      def.properties.grid = {
        x: {
          offset: layout.cellWidth * (1+ cellPadding/2.0),
          // default value(s) -- vega doesn't do recursive merge
          scale: 'col'
        },
        y: {
          value: -layout.cellHeight * (cellPadding/2),
        },
        stroke: { value: encoding.config('cellGridColor') },
        opacity: { value: encoding.config('cellGridOpacity') }
      };
    } else if (isRow) {
      // set grid property -- put the lines on the top
      def.properties.grid = {
        y: {
          offset: -layout.cellHeight * (cellPadding/2),
          // default value(s) -- vega doesn't do recursive merge
          scale: 'row'
        },
        x: {
          value: rowOffset
        },
        x2: {
          offset: rowOffset + (layout.cellWidth * 0.05),
          // default value(s) -- vega doesn't do recursive merge
          group: 'mark.group.width',
          mult: 1
        },
        stroke: { value: encoding.config('cellGridColor') },
        opacity: { value: encoding.config('cellGridOpacity') }
      };
    } else {
      def.properties.grid = {
        stroke: { value: encoding.config('gridColor') },
        opacity: { value: encoding.config('gridOpacity') }
      };
    }
  }
  return def;
};

axis.hideTicks = function(def) {
  setter(def, ['properties', 'ticks'], {
    opacity: {value: 0}
  });
  setter(def, ['properties', 'majorTicks'], {
    opacity: {value: 0}
  });
  setter(def, ['properties', 'axis'], {
    opacity: {value: 0}
  });
  return def;
};

axis.title = function (def, name, encoding, layout) {
  if (!encoding.axis(name).title) return def;

  var maxlength = null,
    fieldTitle = encoding.fieldTitle(name);
  if (name===X) {
    maxlength = layout.cellWidth / encoding.config('characterWidth');
  } else if (name === Y) {
    maxlength = layout.cellHeight / encoding.config('characterWidth');
  }

  def.title = maxlength ? util.truncate(fieldTitle, maxlength) : fieldTitle;

  if (name === ROW) {
    setter(def, ['properties','title'], {
      angle: {value: 0},
      align: {value: 'right'},
      baseline: {value: 'middle'},
      dy: {value: (-layout.height/2) -20}
    });
  }

  return def;
};

axis.labels = function (def, name, encoding, layout, stats, opt) {
  // jshint unused:false

  var timeUnit = encoding.field(name).timeUnit,
    fieldStats = stats[encoding.field(name).name];

  // add custom label for time type
  if (encoding.isType(name, T) && timeUnit && (time.hasScale(timeUnit))) {
    setter(def, ['properties','labels','text','scale'], 'time-'+ timeUnit);
  }

  if (encoding.axis(name).format) {
    def.format = encoding.axis(name).format;
  } else if (encoding.isType(name, Q) || fieldStats.type === 'number') {
    def.format = encoding.numberFormat(fieldStats);
  } else if (encoding.isType(name, T)) {
    if (!timeUnit) {
      def.format = encoding.config('timeFormat');
    } else if (timeUnit === 'year') {
      def.format = 'd';
    }
  } else if (encoding.isTypes(name, [N, O]) && encoding.axis(name).maxLabelLength) {
    var textTemplatePath = ['properties','labels','text','template'];
    setter(def, textTemplatePath, '{{data | truncate:' + encoding.axis(name).maxLabelLength + '}}');
  } else {
    // nothing
  }

  return def;
};

axis.titleOffset = function (encoding, layout, name) {
  var value = encoding.axis(name).titleOffset;
  if (value) {
    return value;
  }
  switch (name) {
    //FIXME make this adjustable
    case ROW: return 0;
    case COL: return 35;
  }
  return getter(layout, [name, 'axisTitleOffset']);
};
<commit_msg>remove rowOffset<commit_after>'use strict';

require('../globals');

var util = require('../util'),
  setter = util.setter,
  getter = util.getter,
  time = require('./time');

var axis = module.exports = {};

axis.names = function(props) {
  return util.keys(util.keys(props).reduce(function(a, x) {
    var s = props[x].scale;
    if (s === X || s === Y) a[props[x].scale] = 1;
    return a;
  }, {}));
};

axis.defs = function(names, encoding, layout, stats, opt) {
  return names.reduce(function(a, name) {
    a.push(axis.def(name, encoding, layout, stats, opt));
    return a;
  }, []);
};

axis.def = function(name, encoding, layout, stats, opt) {
  var isCol = name == COL,
    isRow = name == ROW,
    type = isCol ? 'x' : isRow ? 'y' : name;

  var def = {
    type: type,
    scale: name,
    properties: {}
  };

  if(isRow) def.offset = axis.titleOffset(encoding, layout, Y) + 20;

  def = axis.grid(def, name, encoding, layout);
  def = axis.title(def, name, encoding, layout, opt);

  def.titleOffset = axis.titleOffset(encoding, layout, name);

  if (isRow || isCol) def = axis.hideTicks(def);

  if (isCol) {
    def.orient = 'top';
  }

  if (name == X) {
    if (encoding.has(Y) && encoding.isOrdinalScale(Y) && encoding.cardinality(Y, stats) > 30) {
      def.orient = 'top';
    }

    if (encoding.isDimension(X) || encoding.isType(X, T)) {
      var isTop = def.orient ==='top',
        labelProps = isTop ? {
            angle: {value: 90},
            align: {value: 'left'},
            baseline: {value: 'middle'}
          } : {
            angle: {value: 270},
            align: {value: 'right'},
            baseline: {value: 'middle'}
          };

      setter(def, ['properties','labels'], labelProps);
    } else { // Q
      def.ticks = 5;
    }
  }

  def = axis.labels(def, name, encoding, layout, stats, opt);

  return def;
};

axis.grid = function(def, name, encoding, layout) {
  var cellPadding = layout.cellPadding,
    isCol = name == COL,
    isRow = name == ROW;

  if (encoding.axis(name).grid) {
    def.grid = true;
    def.layer = 'back';

    if (isCol) {
      // set grid property -- put the lines on the right the cell
      def.properties.grid = {
        x: {
          offset: layout.cellWidth * (1+ cellPadding/2.0),
          // default value(s) -- vega doesn't do recursive merge
          scale: 'col'
        },
        y: {
          value: -layout.cellHeight * (cellPadding/2),
        },
        stroke: { value: encoding.config('cellGridColor') },
        opacity: { value: encoding.config('cellGridOpacity') }
      };
    } else if (isRow) {
      // set grid property -- put the lines on the top
      def.properties.grid = {
        y: {
          offset: -layout.cellHeight * (cellPadding/2),
          // default value(s) -- vega doesn't do recursive merge
          scale: 'row'
        },
        x: {
          value: def.offset
        },
        x2: {
          offset: def.offset + (layout.cellWidth * 0.05),
          // default value(s) -- vega doesn't do recursive merge
          group: 'mark.group.width',
          mult: 1
        },
        stroke: { value: encoding.config('cellGridColor') },
        opacity: { value: encoding.config('cellGridOpacity') }
      };
    } else {
      def.properties.grid = {
        stroke: { value: encoding.config('gridColor') },
        opacity: { value: encoding.config('gridOpacity') }
      };
    }
  }
  return def;
};

axis.hideTicks = function(def) {
  setter(def, ['properties', 'ticks'], {
    opacity: {value: 0}
  });
  setter(def, ['properties', 'majorTicks'], {
    opacity: {value: 0}
  });
  setter(def, ['properties', 'axis'], {
    opacity: {value: 0}
  });
  return def;
};

axis.title = function (def, name, encoding, layout) {
  if (!encoding.axis(name).title) return def;

  var maxlength = null,
    fieldTitle = encoding.fieldTitle(name);
  if (name===X) {
    maxlength = layout.cellWidth / encoding.config('characterWidth');
  } else if (name === Y) {
    maxlength = layout.cellHeight / encoding.config('characterWidth');
  }

  def.title = maxlength ? util.truncate(fieldTitle, maxlength) : fieldTitle;

  if (name === ROW) {
    setter(def, ['properties','title'], {
      angle: {value: 0},
      align: {value: 'right'},
      baseline: {value: 'middle'},
      dy: {value: (-layout.height/2) -20}
    });
  }

  return def;
};

axis.labels = function (def, name, encoding, layout, stats, opt) {
  // jshint unused:false

  var timeUnit = encoding.field(name).timeUnit,
    fieldStats = stats[encoding.field(name).name];

  // add custom label for time type
  if (encoding.isType(name, T) && timeUnit && (time.hasScale(timeUnit))) {
    setter(def, ['properties','labels','text','scale'], 'time-'+ timeUnit);
  }

  if (encoding.axis(name).format) {
    def.format = encoding.axis(name).format;
  } else if (encoding.isType(name, Q) || fieldStats.type === 'number') {
    def.format = encoding.numberFormat(fieldStats);
  } else if (encoding.isType(name, T)) {
    if (!timeUnit) {
      def.format = encoding.config('timeFormat');
    } else if (timeUnit === 'year') {
      def.format = 'd';
    }
  } else if (encoding.isTypes(name, [N, O]) && encoding.axis(name).maxLabelLength) {
    var textTemplatePath = ['properties','labels','text','template'];
    setter(def, textTemplatePath, '{{data | truncate:' + encoding.axis(name).maxLabelLength + '}}');
  } else {
    // nothing
  }

  return def;
};

axis.titleOffset = function (encoding, layout, name) {
  var value = encoding.axis(name).titleOffset;
  if (value) {
    return value;
  }
  switch (name) {
    //FIXME make this adjustable
    case ROW: return 0;
    case COL: return 35;
  }
  return getter(layout, [name, 'axisTitleOffset']);
};
<|endoftext|>


<commit_before>$(function() {

  var startTime = new Date();
  var lastOffset = 1.0;
  var currentTime = function() {
    return lastOffset;
  };

  var chartSize = {n: 15.0, step: 5.0};

  $('body').on('click', '.js-adjust-window', function() {
    console.log(chartSize);
    chartSize = $(this).data();
  });

  var clips = 0;
  function StripChart(container, name) {
    container = container.append('div').attr('class', 'chart');
    container.append('h3').text(name);

    var data = [];

    var margin = {top: 10, right: 10, bottom: 20, left: 70},
        width = 960 - margin.left - margin.right,
        height = 80 - margin.top - margin.bottom;

    var make_x_scale = function() {
      var t, range;
      if (chartSize.all) {
        t = currentTime();
        range = width;
      } else {
        t = d3.max([currentTime(), chartSize.n]);
        range = t * width / chartSize.n;
      }
      return d3.scale.linear()
        .domain([0, t])
        .range([0, range]);
    };
    var x = make_x_scale();

    var make_y_scale = function() {
      return d3.scale.linear()
        .domain(d3.extent(data, function(d) { return d.y; }))
        .range([height, 0]);
    };
    var y = make_y_scale();

    var line = d3.svg.line()
        .x(function(d) { return x(d.x); })
        .y(function(d) { return y(d.y); });

    var svg = container.append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var clipId = "clip" + (clips++);
    svg.append("defs").append("clipPath")
        .attr("id", clipId)
      .append("rect")
        .attr("width", width)
        .attr("height", height);

    var make_x_axis = function() {
      var baseAxis = d3.svg.axis().scale(x).orient("bottom");
      if (chartSize.all) {
        return baseAxis.ticks(10);
      } else {
        var t = currentTime();
        var ticks = [];
        var i;
        for(i = 0; i <= t; i += chartSize.step) {
          ticks.push(i);
        }
        for(; i <= chartSize.n; i += chartSize.step) {
          ticks.push(i);
        }
        return baseAxis.tickValues(ticks);
      }
    };
    var xAxis = svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.svg.axis().scale(x).orient("bottom"));

    var make_y_axis = function() {
      return d3.svg.axis().scale(y).ticks(4).orient("left");
    };
    var yAxis = svg.append("g")
        .attr("class", "y axis")
        .call(make_y_axis());

    var path = svg.append("g")
        .attr("clip-path", "url(#" + clipId + ")")
      .append("path")
        .data([data])
        .attr("class", "line")
        .attr("d", line);

    var updateInterval = 500;
    var tick = function() {
      x = make_x_scale();
      y = make_y_scale();

      var t = currentTime();
      var xtrans = x((!chartSize.all && t > chartSize.n) ? (chartSize.n - t) : 0);

      xAxis
          .call(make_x_axis())
        .transition().duration(updateInterval).ease('linear')
          .attr("transform", "translate(" + xtrans + "," + height + ")");

      yAxis.call(make_y_axis());

      path
          .attr("d", line)
        .transition()
          .duration(updateInterval)
          .ease("linear")
          .attr("transform", "translate(" + xtrans + ")")
          .each('end', tick);
    }

    tick();

    this.addPoint = function(point) {
      data.push(point);
    };
  }

  var charts = {};
  var ws = new WebSocket($('body').data('websocket'));
  ws.onmessage = function(e) {
    var data = JSON.parse(e.data);
    var i;
    for (i = 0; i < data.samples.length; i++) {
      var sample = data.samples[i];
      var chart = charts[sample.name];
      lastOffset = data.offset;
      if (!chart)
        chart = charts[sample.name] = new StripChart(d3.select('body'), sample.name);
      if (sample.rss)
        chart.addPoint({x: data.offset, y: sample.rss});
    }
  };

});
<commit_msg>Make graphs bigger when you click on them.<commit_after>$(function() {

  var startTime = new Date();
  var lastOffset = 1.0;
  var currentTime = function() {
    return lastOffset;
  };

  var chartSize = {n: 15.0, step: 5.0};

  $('body').on('click', '.js-adjust-window', function() {
    chartSize = $(this).data();
  });

  $('body').on('click', '.chart', function() {
    $(this).data('chart').toggleSize();
  });

  var clips = 0;
  function StripChart(container, name) {
    container = container.append('div').attr('class', 'chart');
    $(container[0][0]).data('chart', this);
    container.append('h3').text(name);

    var data = [];

    var margin = {top: 10, right: 10, bottom: 20, left: 70},
        width = 960 - margin.left - margin.right,
        lgHeight = 500 - margin.top - margin.bottom,
        smHeight = 80 - margin.top - margin.bottom,
        height = smHeight;

    var make_x_scale = function() {
      var t, range;
      if (chartSize.all) {
        t = currentTime();
        range = width;
      } else {
        t = d3.max([currentTime(), chartSize.n]);
        range = t * width / chartSize.n;
      }
      return d3.scale.linear()
        .domain([0, t])
        .range([0, range]);
    };
    var x = make_x_scale();

    var make_y_scale = function() {
      return d3.scale.linear()
        .domain(d3.extent(data, function(d) { return d.y; }))
        .range([height, 0]);
    };
    var y = make_y_scale();

    var line = d3.svg.line()
        .x(function(d) { return x(d.x); })
        .y(function(d) { return y(d.y); });

    var svgElement = container.append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
    var svg = svgElement.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var clipId = "clip" + (clips++);
    var clipRect = svg.append("defs").append("clipPath")
        .attr("id", clipId)
      .append("rect")
        .attr("width", width)
        .attr("height", height);

    var make_x_axis = function() {
      var baseAxis = d3.svg.axis().scale(x).orient("bottom");
      if (chartSize.all) {
        return baseAxis.ticks(10);
      } else {
        var t = currentTime();
        var ticks = [];
        var i;
        for(i = 0; i <= t; i += chartSize.step) {
          ticks.push(i);
        }
        for(; i <= chartSize.n; i += chartSize.step) {
          ticks.push(i);
        }
        return baseAxis.tickValues(ticks);
      }
    };
    var xAxis = svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.svg.axis().scale(x).orient("bottom"));

    var make_y_axis = function() {
      return d3.svg.axis().scale(y).ticks(4).orient("left");
    };
    var yAxis = svg.append("g")
        .attr("class", "y axis")
        .call(make_y_axis());

    var path = svg.append("g")
        .attr("clip-path", "url(#" + clipId + ")")
      .append("path")
        .data([data])
        .attr("class", "line")
        .attr("d", line);

    var updateInterval = 500;
    var tick = function() {
      x = make_x_scale();
      y = make_y_scale();

      var t = currentTime();
      var xtrans = x((!chartSize.all && t > chartSize.n) ? (chartSize.n - t) : 0);

      svgElement.attr("height", height + margin.top + margin.bottom);
      clipRect.attr("height", height);

      xAxis
          .call(make_x_axis())
        .transition().duration(updateInterval).ease('linear')
          .attr("transform", "translate(" + xtrans + "," + height + ")");

      yAxis.call(make_y_axis());

      path
          .attr("d", line)
        .transition()
          .duration(updateInterval)
          .ease("linear")
          .attr("transform", "translate(" + xtrans + ")")
          .each('end', tick);
    }

    tick();

    this.addPoint = function(point) {
      data.push(point);
    };

    this.toggleSize = function() {
      height = (height == lgHeight) ? smHeight : lgHeight;
    };
  }

  var charts = {};
  var ws = new WebSocket($('body').data('websocket'));
  ws.onmessage = function(e) {
    var data = JSON.parse(e.data);
    var i;
    for (i = 0; i < data.samples.length; i++) {
      var sample = data.samples[i];
      var chart = charts[sample.name];
      lastOffset = data.offset;
      if (!chart)
        chart = charts[sample.name] = new StripChart(d3.select('body'), sample.name);
      if (sample.rss)
        chart.addPoint({x: data.offset, y: sample.rss});
    }
  };

});
<|endoftext|>


<commit_before>(function() {
	var global = this;

	/**
	 * @param ybcbr {bufferY, bufferCb, bufferCr, strideY, strideCb, strideCr, width, height, hdec, vdec}
	 * @param TypedArray output: CanvasPixelArray or Uint8ClampedArray to draw RGB into
	 */
	global.convertYCbCr = function convertYCbCr(ybcbr, output) {
		var width = ybcbr.width,
			height = ybcbr.height,
			hdec = ybcbr.hdec,
			vdec = ybcbr.vdec,
			bytesY = new Uint8Array(ybcbr.bufferY),
			bytesCb = new Uint8Array(ybcbr.bufferCb),
			bytesCr = new Uint8Array(ybcbr.bufferCr),
			processLine,
			strideY = ybcbr.strideY,
			strideCb = ybcbr.strideCb,
			strideCr = ybcbr.strideCr;

		if (hdec == vdec == 1) {
			// Optimize for 4:2:0, which is most common
			processLine = function convertYCbCr_processLine_420(y) {
				var xdec = 0,
					ydec = y >> vdec,
					YPtr = y * strideY,
					CbPtr = ydec * strideCb,
					CrPtr = ydec * strideCr,
					outPtr = y * 4 * width,
					colorY0, colorY1, colorCb, colorCr,
					multY0, multY1,
					multCrR, multCbG, multCrG, multCbB;

				for (var x = 0; x < width; x += 2) {
					xdec = x >> hdec;
					colorY0 = bytesY[YPtr + x];
					colorY1 = bytesY[YPtr + x + 1];
					colorCb = bytesCb[CbPtr + xdec];
					colorCr = bytesCr[CrPtr + xdec];

					// Quickie YUV conversion
					// https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.2020_conversion
					// multiplied by 256 for integer-friendliness
					multCrR = (409 * colorCr);
					multCbG = (100 * colorCb);
					multCrG = (208 * colorCr);
					multCbB = (516 * colorCb);

					multY0 = (298 * colorY0);
					output[outPtr++] = (multY0 + multCrR - 57088) >> 8;
					output[outPtr++] = (multY0 - multCbG - multCrG + 34816) >> 8;
					output[outPtr++] = (multY0 + multCbB - 70912) >> 8;
					output[outPtr++] = 255;

					multY1 = (298 * colorY1);
					output[outPtr++] = (multY1 + multCrR - 57088) >> 8;
					output[outPtr++] = (multY1 - multCbG - multCrG + 34816) >> 8;
					output[outPtr++] = (multY1 + multCbB - 70912) >> 8;
					output[outPtr++] = 255;
				}
			}
			for (var y = 0; y < height; y++) {
				processLine(y);
			}
		} else {
			failout();
			processLine = function convertYCbCr_processLine_clamped(y) {
				var xdec = 0,
					ydec = y >> vdec,
					YPtr = y * strideY,
					CbPtr = ydec * strideCb,
					CrPtr = ydec * strideCr,
					outPtr = y * 4 * width,
					colorY, colorCb, colorCr;

				for (var x = 0; x < width; x++) {
					xdec = x >> hdec;
					colorY = bytesY[YPtr + x];
					colorCb = bytesCb[CbPtr + xdec];
					colorCr = bytesCr[CrPtr + xdec];

					// Quickie YUV conversion
					// https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.2020_conversion
					// multiplied by 256 for integer-friendliness
					multY = (298 * colorY);
					output[outPtr++] = (multY + (409 * colorCr) - 57088) >> 8;
					output[outPtr++] = (multY - (100 * colorCb) - (208 * colorCr) + 34816) >> 8;
					output[outPtr++] = (multY + (516 * colorCb) - 70912) >> 8;
					output[outPtr++] = 255;
				}
			}
			for (var y = 0; y < height; y++) {
				processLine(y);
			}
		}
	}
})();
<commit_msg>whoops, stray debug line<commit_after>(function() {
	var global = this;

	/**
	 * @param ybcbr {bufferY, bufferCb, bufferCr, strideY, strideCb, strideCr, width, height, hdec, vdec}
	 * @param TypedArray output: CanvasPixelArray or Uint8ClampedArray to draw RGB into
	 */
	global.convertYCbCr = function convertYCbCr(ybcbr, output) {
		var width = ybcbr.width,
			height = ybcbr.height,
			hdec = ybcbr.hdec,
			vdec = ybcbr.vdec,
			bytesY = new Uint8Array(ybcbr.bufferY),
			bytesCb = new Uint8Array(ybcbr.bufferCb),
			bytesCr = new Uint8Array(ybcbr.bufferCr),
			processLine,
			strideY = ybcbr.strideY,
			strideCb = ybcbr.strideCb,
			strideCr = ybcbr.strideCr;

		if (hdec == vdec == 1) {
			// Optimize for 4:2:0, which is most common
			processLine = function convertYCbCr_processLine_420(y) {
				var xdec = 0,
					ydec = y >> vdec,
					YPtr = y * strideY,
					CbPtr = ydec * strideCb,
					CrPtr = ydec * strideCr,
					outPtr = y * 4 * width,
					colorY0, colorY1, colorCb, colorCr,
					multY0, multY1,
					multCrR, multCbG, multCrG, multCbB;

				for (var x = 0; x < width; x += 2) {
					xdec = x >> hdec;
					colorY0 = bytesY[YPtr + x];
					colorY1 = bytesY[YPtr + x + 1];
					colorCb = bytesCb[CbPtr + xdec];
					colorCr = bytesCr[CrPtr + xdec];

					// Quickie YUV conversion
					// https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.2020_conversion
					// multiplied by 256 for integer-friendliness
					multCrR = (409 * colorCr);
					multCbG = (100 * colorCb);
					multCrG = (208 * colorCr);
					multCbB = (516 * colorCb);

					multY0 = (298 * colorY0);
					output[outPtr++] = (multY0 + multCrR - 57088) >> 8;
					output[outPtr++] = (multY0 - multCbG - multCrG + 34816) >> 8;
					output[outPtr++] = (multY0 + multCbB - 70912) >> 8;
					output[outPtr++] = 255;

					multY1 = (298 * colorY1);
					output[outPtr++] = (multY1 + multCrR - 57088) >> 8;
					output[outPtr++] = (multY1 - multCbG - multCrG + 34816) >> 8;
					output[outPtr++] = (multY1 + multCbB - 70912) >> 8;
					output[outPtr++] = 255;
				}
			}
			for (var y = 0; y < height; y++) {
				processLine(y);
			}
		} else {
			processLine = function convertYCbCr_processLine_clamped(y) {
				var xdec = 0,
					ydec = y >> vdec,
					YPtr = y * strideY,
					CbPtr = ydec * strideCb,
					CrPtr = ydec * strideCr,
					outPtr = y * 4 * width,
					colorY, colorCb, colorCr;

				for (var x = 0; x < width; x++) {
					xdec = x >> hdec;
					colorY = bytesY[YPtr + x];
					colorCb = bytesCb[CbPtr + xdec];
					colorCr = bytesCr[CrPtr + xdec];

					// Quickie YUV conversion
					// https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.2020_conversion
					// multiplied by 256 for integer-friendliness
					multY = (298 * colorY);
					output[outPtr++] = (multY + (409 * colorCr) - 57088) >> 8;
					output[outPtr++] = (multY - (100 * colorCb) - (208 * colorCr) + 34816) >> 8;
					output[outPtr++] = (multY + (516 * colorCb) - 70912) >> 8;
					output[outPtr++] = 255;
				}
			}
			for (var y = 0; y < height; y++) {
				processLine(y);
			}
		}
	}
})();
<|endoftext|>


<commit_before>var mapping = {
	styles: ['css', 'less', 'scss', 'styl'],
	scripts: ['js', 'jsx', 'es6', 'es', 'coffee'],
	templates: ['jade', 'json', 'html', 'htm']
}

module.exports = function(gulp, config, watch) {

	if(config.mapping) {
		Object.keys(config.mapping).forEach(function(key) {
			mapping[key] = config.mapping[key]
		})
	}

	Object.keys(mapping).forEach(function(key) {
		mapping[key].map(function(i) {
			var ext = '.' + i.replace(/^\./, '') // remove . from the beginning of the string
			return new RegExp(ext + '$')
		})
	})

	return function(done) {
		var c = require('better-console')
		c.info('Watching sources for change and recompilation...')

		var minimatch = require('minimatch')
		var path = require('path')
		var runcmd = require('../helpers/runcmd')
		var glob = '**/*.{css,styl,scss,less,js,jsx,es6,es,coffee,jade,json,html,htm}'
		var globDist = config.dist_folder + '/**/*.*'

		var completeHandler = function(e) {
			if(config.hooks && config.hooks.watch) runcmd(config.hooks.watch)
		}

		var changeHandler = function(filepath) {
			// Filter dist sources
			if (minimatch(filepath, globDist)) {
				return
			}

			config._lastChanged = filepath

			var handler = false

			Object.keys(mapping).forEach(function (key) {

				mapping[key].forEach(function(regexp) {
					if(filepath.match(regexp)) {
						handler = key
					}
				})
			})

			if (!handler) {
				c.warn('! unknown extension', path.extname(filepath), filepath)
				return
			}

			gulp.start(handler, completeHandler)
		}

		watch(glob, changeHandler)

		done()
	}
}
<commit_msg>Fixed wrong use of .map resulting in mismatch in rebuild tasks<commit_after>var mapping = {
	styles: ['css', 'less', 'scss', 'styl'],
	scripts: ['js', 'jsx', 'es6', 'es', 'coffee'],
	templates: ['jade', 'json', 'html', 'htm']
}

module.exports = function(gulp, config, watch) {

	if(config.mapping) {
		Object.keys(config.mapping).forEach(function(key) {
			mapping[key] = config.mapping[key]
		})
	}

	Object.keys(mapping).forEach(function(key) {
		mapping[key] = mapping[key].map(function(i) {
			var ext = '.' + i.replace(/^\./, '') // remove . from the beginning of the string
			return new RegExp(ext + '$')
		})
	})

	return function(done) {
		var c = require('better-console')
		c.info('Watching sources for change and recompilation...')

		var minimatch = require('minimatch')
		var path = require('path')
		var runcmd = require('../helpers/runcmd')
		var glob = '**/*.{css,styl,scss,less,js,jsx,es6,es,coffee,jade,json,html,htm}'
		var globDist = config.dist_folder + '/**/*.*'

		var completeHandler = function(e) {
			if(config.hooks && config.hooks.watch) runcmd(config.hooks.watch)
		}

		var changeHandler = function(filepath) {
			// Filter dist sources
			if (minimatch(filepath, globDist)) {
				return
			}

			config._lastChanged = filepath

			var handler = false

			Object.keys(mapping).forEach(function (key) {

				mapping[key].forEach(function(regexp) {
					if(filepath.match(regexp)) {
						handler = key
					}
				})
			})

			if (!handler) {
				c.warn('! unknown extension', path.extname(filepath), filepath)
				return
			}

			gulp.start(handler, completeHandler)
		}

		watch(glob, changeHandler)

		done()
	}
}
<|endoftext|>


<commit_before>var GameboyJS;
(function (GameboyJS) {
"use strict";

var Debug = {};
// Output a range of 16 memory addresses
Debug.view_memory = function(addr, memory) {
    addr = addr & 0xFFF0;
    var pad = '00';
    var str = addr.toString(16) + ':';
    for (var i = addr; i < addr + 0x10; i++) {
        if ((i & 0x1) == 0) {
            str += ' ';
        }
        var val = memory[i] || 0;

        val = val.toString(16);
        str += pad.substring(val.length) + val;
    }

    return str;
}

Debug.view_tile = function(screen, index) {
    var tileData = screen.readTileData(index, 0x8800);

    var pixelData = new Array(8 * 8)
    for (var line = 0; line < 8; line++) {
        var b1 = tileData.shift();
        var b2 = tileData.shift();

        for (var pixel = 0; pixel < 8; pixel++) {
            var mask = (1 << (7-pixel));
            var colorValue = ((b1 & mask) >> (7-pixel)) + ((b2 & mask) >> (7-pixel))*2;
            pixelData[line * 8 + pixel] = colorValue;
        }
    }

    var i = 0;
    while (pixelData.length) {
        console.log(i++ + ' ' + pixelData.splice(0, 8).join(''));
    }
}
GameboyJS.Debug = Debug;
}(GameboyJS || (GameboyJS = {})));
<commit_msg>add sprite debug utility<commit_after>var GameboyJS;
(function (GameboyJS) {
"use strict";

var Debug = {};
// Output a range of 16 memory addresses
Debug.view_memory = function(addr, memory) {
    addr = addr & 0xFFF0;
    var pad = '00';
    var str = addr.toString(16) + ':';
    for (var i = addr; i < addr + 0x10; i++) {
        if ((i & 0x1) == 0) {
            str += ' ';
        }
        var val = memory[i] || 0;

        val = val.toString(16);
        str += pad.substring(val.length) + val;
    }

    return str;
};

Debug.view_tile = function(screen, index, dataStart) {
    dataStart = dataStart || 0x8800;
    var tileData = screen.readTileData(index, dataStart);

    var pixelData = new Array(8 * 8)
    for (var line = 0; line < 8; line++) {
        var b1 = tileData.shift();
        var b2 = tileData.shift();

        for (var pixel = 0; pixel < 8; pixel++) {
            var mask = (1 << (7-pixel));
            var colorValue = ((b1 & mask) >> (7-pixel)) + ((b2 & mask) >> (7-pixel))*2;
            pixelData[line * 8 + pixel] = colorValue;
        }
    }

    var i = 0;
    while (pixelData.length) {
        console.log(i++ + ' ' + pixelData.splice(0, 8).join(''));
    }
};

Debug.list_visible_sprites = function(memory) {
    var indexes = new Array();
    for (var i = 0xFE00; i < 0xFE9F; i += 4) {
        var x = memory.oamram(i + 1);
        var tileIndex = memory.oamram(i + 2);
        if (x == 0 || x >= 168) {
            continue;
        }
        indexes.push(tileIndex);
    }

    return indexes;
};
GameboyJS.Debug = Debug;
}(GameboyJS || (GameboyJS = {})));
<|endoftext|>


<commit_before>'use strict';

var EventHandler = require('./../utilities/event-handler');

function Timelines(timelineGroups) {
    EventHandler.apply(this);
    this._timelineGroups = timelineGroups || {};
}

Timelines.prototype = Object.create(EventHandler.prototype);
Timelines.prototype.constructor = Timelines;

module.exports = Timelines;<commit_msg>wip: implement .get()<commit_after>'use strict';

var EventHandler = require('./../utilities/event-handler');
// var TimelineHelper = require('./../utilities/TimelineHelper');

function Timelines(timelineGroups) {
    EventHandler.apply(this);
    this._timelineGroups = timelineGroups || {};
    this._currentTimeline = null;
}

Timelines.prototype = Object.create(EventHandler.prototype);
Timelines.prototype.constructor = Timelines;

Timelines.prototype.get = function(timelineName) {
    this._currentTimeline = timelineName;
    return this;
}

Timelines.prototype.start = function() {
    console.log(this._currentTimeline, 'starting...');
}

module.exports = Timelines;<|endoftext|>


<commit_before>/* Helpers for debuging */

var debug = module.exports = {};
var util = require("util");

Object.defineProperty(debug, '__stack', {
	get: function(){
		var orig, err, stack;
		try {
			orig = Error.prepareStackTrace;
			Error.prepareStackTrace = function(_, stack){ return stack; };
			err = new Error();
			Error.captureStackTrace(err, arguments.callee);
			stack = err.stack;
		} finally {
			Error.prepareStackTrace = orig;
		}
		return stack;
	}
});

Object.defineProperty(debug, '__line', {
	get: function(){
		return debug.__stack[1].getLineNumber();
	}
});

/** Returns true if the app is running in production mode */
debug.isProduction = function () {
	return (process.env.NODE_ENV === "production");
};

/** Returns true if the app is running in development mode */
debug.isDevelopment = function () {
	return debug.isProduction() ? false : true;
};

/** Returns value converted to string and trimmed from white spaces around it */
function inspect_values(x) {
	if(typeof x === "string") { return x; }
	return util.inspect(x);
}

/** Returns value trimmed from white spaces around it */
function trim_values(x) {
	return (''+x).replace(/ +$/, "").replace(/^ +/, "");
}

/** */
Object.defineProperty(debug, 'log', {
	get: function(){

		var stack = debug.__stack;
		var location = stack[1].getFileName() || 'unknown';

		var line = stack[1].getLineNumber();
		if(line) {
			location += ':' + line;
		}

		var func = stack[1].getFunctionName();
		if(func) {
			location += '@' + func+'()';
		}

		return function () {
		    if(!debug.isProduction()) {
		        var args = Array.prototype.slice.call(arguments);
				var cols = [];
		        util.debug( [location+':'].concat(args).map(inspect_values).map(trim_values).join(" ") );
		    }
		};
	}
});

/* EOF */
<commit_msg>Improved code<commit_after>/* Helpers for debuging */

var debug = module.exports = {};
var util = require("util");

Object.defineProperty(debug, '__stack', {
	get: function(){
		var orig, err, stack;
		try {
			orig = Error.prepareStackTrace;
			Error.prepareStackTrace = function(_, stack){ return stack; };
			err = new Error();
			Error.captureStackTrace(err, arguments.callee);
			stack = err.stack;
		} finally {
			Error.prepareStackTrace = orig;
		}
		return stack;
	}
});

Object.defineProperty(debug, '__line', {
	get: function(){
		return debug.__stack[1].getLineNumber();
	}
});

/** Returns true if the app is running in production mode */
debug.isProduction = function () {
	return (process.env.NODE_ENV === "production");
};

/** Returns true if the app is running in development mode */
debug.isDevelopment = function () {
	return debug.isProduction() ? false : true;
};

/** Returns value converted to string and trimmed from white spaces around it */
function inspect_values(x) {
	if(typeof x === "string") { return x; }
	return util.inspect(x);
}

/** Returns value trimmed from white spaces around it */
function trim_values(x) {
	return (''+x).replace(/ +$/, "").replace(/^ +/, "");
}

/** Helper function that can be called but does nothing */
function do_nothing() {
}

/** */
Object.defineProperty(debug, 'log', {
	get: function(){

		// Disable in production
		if(debug.isProduction()) {
			return do_nothing;
		}

		var stack = debug.__stack;
		var location = stack[1].getFileName() || 'unknown';

		var line = stack[1].getLineNumber();
		if(line) {
			location += ':' + line;
		}

		var func = stack[1].getFunctionName();
		if(func) {
			location += '@' + func+'()';
		}

		return function () {
	        var args = Array.prototype.slice.call(arguments);
			var cols = [];
	        util.debug( [location+':'].concat(args).map(inspect_values).map(trim_values).join(" ") );
		};
	}
});

/* EOF */
<|endoftext|>


<commit_before>(function(exports) {

if(typeof(google) === 'undefined' || typeof(google.maps) === 'undefined') return;

function GMapsTorqueLayer(options) {
  var self = this;
  if (!torque.isBrowserSupported()) {
    throw new Error("browser is not supported by torque");
  }
  this.key = 0;
  this.shader = null;
  this.ready = false;
  this.options = _.extend({}, options);
  _.defaults(this.options, {
    provider: 'windshaft',
    renderer: 'point',
    resolution: 2,
    steps: 100,
    visible: true
  });
  if (options.cartocss) {
    _.extend(this.options,
        torque.common.TorqueLayer.optionsFromCartoCSS(options.cartocss));
  }

  this.hidden = !this.options.visible;

  this.animator = new torque.Animator(function(time) {
    var k = time | 0;
    if(self.key !== k) {
      self.setKey(k);
    }
  }, this.options);

  this.play = this.animator.start.bind(this.animator);
  this.stop = this.animator.stop.bind(this.animator);
  this.pause = this.animator.pause.bind(this.animator);
  this.toggle = this.animator.toggle.bind(this.animator);
  this.setDuration = this.animator.duration.bind(this.animator);
  this.isRunning = this.animator.isRunning.bind(this.animator);

  CanvasLayer.call(this, {
    map: this.options.map,
    //resizeHandler: this.redraw,
    animate: false,
    updateHandler: this.render,
    readyHandler: this.initialize
  });

}

/**
 * torque layer
 */
GMapsTorqueLayer.prototype = _.extend({},
  CanvasLayer.prototype,
  torque.GMapsTileLoader.prototype,
  torque.Event,
  {

  providers: {
    'sql_api': torque.providers.json,
    'url_template': torque.providers.jsonarray,
    'windshaft': torque.providers.windshaft
  },

  renderers: {
    'point': torque.renderer.Point,
    'pixel': torque.renderer.Rectangle
  },

  initialize: function() {
    var self = this;

    this.onTileAdded = this.onTileAdded.bind(this);

    this.options.ready = function() {
      self.fire("change:bounds", {
        bounds: self.provider.getBounds()
      });
      self.animator.steps(self.provider.getSteps());
      self.animator.rescale();
      self.fire('change:steps', {
        steps: self.provider.getSteps()
      });
      self.setKey(self.key);
    };

    this.provider = new this.providers[this.options.provider](this.options);
    this.renderer = new this.renderers[this.options.renderer](this.getCanvas(), this.options);

    // this listener should be before tile loader
    this._cacheListener = google.maps.event.addListener(this.options.map, 'zoom_changed', function() {
      self.renderer && self.renderer.clearSpriteCache();
    });

    this._initTileLoader(this.options.map, this.getProjection());

    if (this.shader) {
      this.renderer.setShader(this.shader);
    }

  },

  hide: function() {
    if(this.hidden) return this;
    this.pause();
    this.clear();
    this.hidden = true;
    return this;
  },

  show: function() {
    if(!this.hidden) return this;
    this.hidden = false;
    this.play();
    return this;
  },

  setSQL: function(sql) {
    if (!this.provider || !this.provider.setSQL) {
      throw new Error("this provider does not support SQL");
    }
    this.provider.setSQL(sql);
    this._reloadTiles();
    return this;
  },

  setBlendMode: function(_) {
    this.renderer && this.renderer.setBlendMode(_);
    this.redraw();
  },

  setSteps: function(steps) {
    this.provider && this.provider.setSteps(steps);
    this.animator && this.animator.steps(steps);
    this._reloadTiles();
  },

  setColumn: function(column, isTime) {
    this.provider && this.provider.setColumn(column, isTime);
    this._reloadTiles();
  },

  getTimeBounds: function() {
    return this.provider && this.provider.getKeySpan();
  },

  getCanvas: function() {
    return this.canvas;
  },

    // for each tile shown on the map request the data
  onTileAdded: function(t) {
    var self = this;
    this.provider.getTileData(t, t.zoom, function(tileData) {
      // don't load tiles that are not being shown
      if (t.zoom !== self.options.map.getZoom()) return;
      self._tileLoaded(t, tileData);
      if (tileData) {
        self.redraw();
      }
    });
  },

  clear: function() {
    var canvas = this.canvas;
    canvas.width = canvas.width;
  },

  /**
   * render the selectef key
   * don't call this function directly, it's called by
   * requestAnimationFrame. Use redraw to refresh it
   */
  render: function() {
    if(this.hidden) return;
    var t, tile, pos;
    var canvas = this.canvas;
    canvas.width = canvas.width;
    var ctx = canvas.getContext('2d');

    // renders only a "frame"
    for(t in this._tiles) {
      tile = this._tiles[t];
      if (tile) {
        pos = this.getTilePos(tile.coord);
        ctx.setTransform(1, 0, 0, 1, pos.x, pos.y);
        this.renderer.renderTile(tile, this.key, pos.x, pos.y);
      }
    }
  },

  /**
   * set key to be shown. If it's a single value
   * it renders directly, if it's an array it renders
   * accumulated
   */
  setKey: function(key) {
    this.key = key;
    this.animator.step(key);
    this.redraw();
    this.fire('change:time', { time: this.getTime(), step: this.key });
  },

  /**
   * helper function, does the same than ``setKey`` but only
   * accepts scalars.
   */
  setStep: function(time) {
    if(time === undefined || time.length !== undefined) {
      throw new Error("setTime only accept scalars");
    }
    this.setKey(time);
  },

  /**
   * transform from animation step to Date object
   * that contains the animation time
   *
   * ``step`` should be between 0 and ``steps - 1``
   */
  stepToTime: function(step) {
    if (!this.provider) return 0;
    var times = this.provider.getKeySpan();
    var time = times.start + (times.end - times.start)*(step/this.provider.getSteps());
    return new Date(time);
  },

  getStep: function() {
    return this.key;
  },

  /**
   * returns the animation time defined by the data
   * in the defined column. Date object
   */
  getTime: function() {
    return this.stepToTime(this.key);
  },

  /**
   * set the cartocss for the current renderer
   */
  setCartoCSS: function(cartocss) {
    var shader = new carto.RendererJS().render(cartocss);
    this.shader = shader;
    if (this.renderer) {
      this.renderer.setShader(shader);
    }

    // provider options
    var options = torque.common.TorqueLayer.optionsFromLayer(shader.findLayer({ name: 'Map' }));
    this.provider.setCartoCSS && this.provider.setCartoCSS(cartocss);
    if(this.provider && this.provider.setOptions(options)) {
      this._reloadTiles();
    }
    _.extend(this.options, options);

    // animator options
    if (options.animationDuration) {
      this.animator.duration(options.animationDuration);
    }

    this.redraw();
    return this;
  },

  redraw: function() {
    this.scheduleUpdate();
  },

  onRemove: function() {
    CanvasLayer.prototype.onRemove.call(this);
    this.animator.stop();
    this._removeTileLoader();
    google.maps.event.removeListener(this._cacheListener);
  }

});

function GMapsTiledTorqueLayer(options) {
  this.options = _.extend({}, options);
  CanvasTileLayer.call(this, this._loadTile.bind(this), this.drawTile.bind(this));
  this.initialize(options);
}

GMapsTiledTorqueLayer.prototype = _.extend({}, CanvasTileLayer.prototype, {

  providers: {
    'sql_api': torque.providers.json,
    'url_template': torque.providers.JsonArray
  },

  renderers: {
    'point': torque.renderer.Point,
    'pixel': torque.renderer.Rectangle
  },

  initialize: function(options) {
    var self = this;
    this.key = 0;

    this.options.renderer = this.options.renderer || 'pixel';
    this.options.provider = this.options.provider || 'sql_api';

    this.provider = new this.providers[this.options.provider](options);
    this.renderer = new this.renderers[this.options.renderer](null, options);

  },

  _tileLoaded: function(tile, tileData) {
    tile.data = tileData;
    this.drawTile(tile);
  },

  _loadTile: function(tile, coord, zoom) {
    var self = this;
    var limit = 1 << zoom;
    // wrap tile
    var wrappedCoord = {
      x: ((coord.x % limit) + limit) % limit,
      y: coord.y
    };

    this.provider.getTileData(wrappedCoord, zoom, function(tileData) {
      self._tileLoaded(tile, tileData);
    });
  },

  drawTile: function (tile) {
    var canvas = tile.canvas;
    if(!tile.data) return;
    canvas.width = canvas.width;

    this.renderer.setCanvas(canvas);

    var accum = this.renderer.accumulate(tile.data, this.key);
    this.renderer.renderTileAccum(accum, 0, 0);
  },

  setKey: function(key) {
    this.key = key;
    this.redraw();
  },

  /**
   * set the cartocss for the current renderer
   */
  setCartoCSS: function(cartocss) {
    if (!this.renderer) throw new Error('renderer is not valid');
    return this.renderer.setCartoCSS(cartocss);
  }

});

exports.torque.GMapsTiledTorqueLayer = GMapsTiledTorqueLayer;
exports.torque.GMapsTorqueLayer = GMapsTorqueLayer;

})(typeof exports === "undefined" ? this : exports);
<commit_msg>check provider gives setCartoCSS<commit_after>(function(exports) {

if(typeof(google) === 'undefined' || typeof(google.maps) === 'undefined') return;

function GMapsTorqueLayer(options) {
  var self = this;
  if (!torque.isBrowserSupported()) {
    throw new Error("browser is not supported by torque");
  }
  this.key = 0;
  this.shader = null;
  this.ready = false;
  this.options = _.extend({}, options);
  _.defaults(this.options, {
    provider: 'windshaft',
    renderer: 'point',
    resolution: 2,
    steps: 100,
    visible: true
  });
  if (options.cartocss) {
    _.extend(this.options,
        torque.common.TorqueLayer.optionsFromCartoCSS(options.cartocss));
  }

  this.hidden = !this.options.visible;

  this.animator = new torque.Animator(function(time) {
    var k = time | 0;
    if(self.key !== k) {
      self.setKey(k);
    }
  }, this.options);

  this.play = this.animator.start.bind(this.animator);
  this.stop = this.animator.stop.bind(this.animator);
  this.pause = this.animator.pause.bind(this.animator);
  this.toggle = this.animator.toggle.bind(this.animator);
  this.setDuration = this.animator.duration.bind(this.animator);
  this.isRunning = this.animator.isRunning.bind(this.animator);

  CanvasLayer.call(this, {
    map: this.options.map,
    //resizeHandler: this.redraw,
    animate: false,
    updateHandler: this.render,
    readyHandler: this.initialize
  });

}

/**
 * torque layer
 */
GMapsTorqueLayer.prototype = _.extend({},
  CanvasLayer.prototype,
  torque.GMapsTileLoader.prototype,
  torque.Event,
  {

  providers: {
    'sql_api': torque.providers.json,
    'url_template': torque.providers.jsonarray,
    'windshaft': torque.providers.windshaft
  },

  renderers: {
    'point': torque.renderer.Point,
    'pixel': torque.renderer.Rectangle
  },

  initialize: function() {
    var self = this;

    this.onTileAdded = this.onTileAdded.bind(this);

    this.options.ready = function() {
      self.fire("change:bounds", {
        bounds: self.provider.getBounds()
      });
      self.animator.steps(self.provider.getSteps());
      self.animator.rescale();
      self.fire('change:steps', {
        steps: self.provider.getSteps()
      });
      self.setKey(self.key);
    };

    this.provider = new this.providers[this.options.provider](this.options);
    this.renderer = new this.renderers[this.options.renderer](this.getCanvas(), this.options);

    // this listener should be before tile loader
    this._cacheListener = google.maps.event.addListener(this.options.map, 'zoom_changed', function() {
      self.renderer && self.renderer.clearSpriteCache();
    });

    this._initTileLoader(this.options.map, this.getProjection());

    if (this.shader) {
      this.renderer.setShader(this.shader);
    }

  },

  hide: function() {
    if(this.hidden) return this;
    this.pause();
    this.clear();
    this.hidden = true;
    return this;
  },

  show: function() {
    if(!this.hidden) return this;
    this.hidden = false;
    this.play();
    return this;
  },

  setSQL: function(sql) {
    if (!this.provider || !this.provider.setSQL) {
      throw new Error("this provider does not support SQL");
    }
    this.provider.setSQL(sql);
    this._reloadTiles();
    return this;
  },

  setBlendMode: function(_) {
    this.renderer && this.renderer.setBlendMode(_);
    this.redraw();
  },

  setSteps: function(steps) {
    this.provider && this.provider.setSteps(steps);
    this.animator && this.animator.steps(steps);
    this._reloadTiles();
  },

  setColumn: function(column, isTime) {
    this.provider && this.provider.setColumn(column, isTime);
    this._reloadTiles();
  },

  getTimeBounds: function() {
    return this.provider && this.provider.getKeySpan();
  },

  getCanvas: function() {
    return this.canvas;
  },

    // for each tile shown on the map request the data
  onTileAdded: function(t) {
    var self = this;
    this.provider.getTileData(t, t.zoom, function(tileData) {
      // don't load tiles that are not being shown
      if (t.zoom !== self.options.map.getZoom()) return;
      self._tileLoaded(t, tileData);
      if (tileData) {
        self.redraw();
      }
    });
  },

  clear: function() {
    var canvas = this.canvas;
    canvas.width = canvas.width;
  },

  /**
   * render the selectef key
   * don't call this function directly, it's called by
   * requestAnimationFrame. Use redraw to refresh it
   */
  render: function() {
    if(this.hidden) return;
    var t, tile, pos;
    var canvas = this.canvas;
    canvas.width = canvas.width;
    var ctx = canvas.getContext('2d');

    // renders only a "frame"
    for(t in this._tiles) {
      tile = this._tiles[t];
      if (tile) {
        pos = this.getTilePos(tile.coord);
        ctx.setTransform(1, 0, 0, 1, pos.x, pos.y);
        this.renderer.renderTile(tile, this.key, pos.x, pos.y);
      }
    }
  },

  /**
   * set key to be shown. If it's a single value
   * it renders directly, if it's an array it renders
   * accumulated
   */
  setKey: function(key) {
    this.key = key;
    this.animator.step(key);
    this.redraw();
    this.fire('change:time', { time: this.getTime(), step: this.key });
  },

  /**
   * helper function, does the same than ``setKey`` but only
   * accepts scalars.
   */
  setStep: function(time) {
    if(time === undefined || time.length !== undefined) {
      throw new Error("setTime only accept scalars");
    }
    this.setKey(time);
  },

  /**
   * transform from animation step to Date object
   * that contains the animation time
   *
   * ``step`` should be between 0 and ``steps - 1``
   */
  stepToTime: function(step) {
    if (!this.provider) return 0;
    var times = this.provider.getKeySpan();
    var time = times.start + (times.end - times.start)*(step/this.provider.getSteps());
    return new Date(time);
  },

  getStep: function() {
    return this.key;
  },

  /**
   * returns the animation time defined by the data
   * in the defined column. Date object
   */
  getTime: function() {
    return this.stepToTime(this.key);
  },

  /**
   * set the cartocss for the current renderer
   */
  setCartoCSS: function(cartocss) {
    var shader = new carto.RendererJS().render(cartocss);
    this.shader = shader;
    if (this.renderer) {
      this.renderer.setShader(shader);
    }

    // provider options
    var options = torque.common.TorqueLayer.optionsFromLayer(shader.findLayer({ name: 'Map' }));
    this.provider && this.provider.setCartoCSS && this.provider.setCartoCSS(cartocss);
    if(this.provider && this.provider.setOptions(options)) {
      this._reloadTiles();
    }
    _.extend(this.options, options);

    // animator options
    if (options.animationDuration) {
      this.animator.duration(options.animationDuration);
    }

    this.redraw();
    return this;
  },

  redraw: function() {
    this.scheduleUpdate();
  },

  onRemove: function() {
    CanvasLayer.prototype.onRemove.call(this);
    this.animator.stop();
    this._removeTileLoader();
    google.maps.event.removeListener(this._cacheListener);
  }

});

function GMapsTiledTorqueLayer(options) {
  this.options = _.extend({}, options);
  CanvasTileLayer.call(this, this._loadTile.bind(this), this.drawTile.bind(this));
  this.initialize(options);
}

GMapsTiledTorqueLayer.prototype = _.extend({}, CanvasTileLayer.prototype, {

  providers: {
    'sql_api': torque.providers.json,
    'url_template': torque.providers.JsonArray
  },

  renderers: {
    'point': torque.renderer.Point,
    'pixel': torque.renderer.Rectangle
  },

  initialize: function(options) {
    var self = this;
    this.key = 0;

    this.options.renderer = this.options.renderer || 'pixel';
    this.options.provider = this.options.provider || 'sql_api';

    this.provider = new this.providers[this.options.provider](options);
    this.renderer = new this.renderers[this.options.renderer](null, options);

  },

  _tileLoaded: function(tile, tileData) {
    tile.data = tileData;
    this.drawTile(tile);
  },

  _loadTile: function(tile, coord, zoom) {
    var self = this;
    var limit = 1 << zoom;
    // wrap tile
    var wrappedCoord = {
      x: ((coord.x % limit) + limit) % limit,
      y: coord.y
    };

    this.provider.getTileData(wrappedCoord, zoom, function(tileData) {
      self._tileLoaded(tile, tileData);
    });
  },

  drawTile: function (tile) {
    var canvas = tile.canvas;
    if(!tile.data) return;
    canvas.width = canvas.width;

    this.renderer.setCanvas(canvas);

    var accum = this.renderer.accumulate(tile.data, this.key);
    this.renderer.renderTileAccum(accum, 0, 0);
  },

  setKey: function(key) {
    this.key = key;
    this.redraw();
  },

  /**
   * set the cartocss for the current renderer
   */
  setCartoCSS: function(cartocss) {
    if (!this.renderer) throw new Error('renderer is not valid');
    return this.renderer.setCartoCSS(cartocss);
  }

});

exports.torque.GMapsTiledTorqueLayer = GMapsTiledTorqueLayer;
exports.torque.GMapsTorqueLayer = GMapsTorqueLayer;

})(typeof exports === "undefined" ? this : exports);
<|endoftext|>


<commit_before>/**
 * Super class for every transport.
 */
var logger = require('../logger')
function Transport(config, messageFormatter){
	this.config = config;
	this.messageFormater = messageFormatter;
}

Transport.prototype.start = function(){
	logger.error('Transport', 'Abstract method start() is not implemented')
}
module.exports = Transport;<commit_msg>add comments<commit_after>/**
 * Super class for every transport.
 */
var logger = require('../logger')

/**
 * constructor for the parent object
 * @param config
 * @param messageFormatter
 * @returns
 */
function Transport(config, messageFormatter){
	this.config = config;
	this.messageFormater = messageFormatter;
}

/**
 * abstract method to start the transport
 */
Transport.prototype.start = function(){
	logger.error('Transport', 'Abstract method start() is not implemented')
}
module.exports = Transport;<|endoftext|>


<commit_before>/*
	Custom input
*/
"use strict";

var calc = require('../utils/calc.js'),
	utils = require('../utils/utils.js'),
	History = require('../bobs/history.js'),
	Input = function () {
		this.current = {};
		this.history = new History();
		this.offset = {};
		this.update(arguments[0], arguments[1]);
	};

Input.prototype = {

	// Allow input to be inactive for this many frames before declared not moving
	maxInactiveFrames: 2,

	// Number of frames input hasn't moved
	inactiveFrames: 0,

	/*
		Get latest input values
	*/
	get: function () {
		return this.history.get();
	},

	/*
		Update the input values

		Syntax
			input.update({ prop: val });
			input.update('prop', val);

		@param [string || object]:
		@param [number] (optional): If
	*/
	update: function () {
		var values = {};

		if (utils.isNum(arguments[1])) {
			values[arguments[0]] = arguments[1];
		} else {
			values = arguments[0];
		}

		this.history.add(utils.merge(this.current, values));
	},

	/*
		Check for input movement and update pointer object's properties

		@param [number]: Timestamp of frame
	*/
	onFrame: function (timestamp) {
		var latest, hasChanged;

		// Check provided timestamp against lastFrame timestamp and return input has already been updated
		if (timestamp === this.lastFrame) {
		console.log(timestamp);
			return;
		}

		latest = this.history.get();
		hasChanged = utils.hasChanged(this.current, latest);

		// If input has changed between frames
		if (hasChanged) {
			this.velocity = calc.offset(this.current, latest);
			this.current = latest;
			this.inactiveFrames = 0;

		// Or it hasn't moved and our frame limit has been reached
		} else if (this.inactiveFrames >= this.maxInactiveFrames) {
			this.velocity = calc.offset(this.current, this.current);

		// Or input hasn't changed
		} else {
			this.inactiveFrames++;
		}

		this.lastFrame = timestamp;
	}

};

module.exports = Input;<commit_msg>adding ability to get() specific input val<commit_after>/*
	Custom input
*/
"use strict";

var calc = require('../utils/calc.js'),
	utils = require('../utils/utils.js'),
	History = require('../bobs/history.js'),
	Input = function () {
		this.current = {};
		this.history = new History();
		this.offset = {};
		this.update(arguments[0], arguments[1]);
	};

Input.prototype = {

	// Allow input to be inactive for this many frames before declared not moving
	maxInactiveFrames: 2,

	// Number of frames input hasn't moved
	inactiveFrames: 0,

	/*
		Get latest input values

		@param [string] (optional): Name of specific property to return
		@return [object || number]: Latest input values or, if specified, single value
	*/
	get: function (prop) {
		var latest = this.history.get(),
			val = (prop !== undefined) ? latest[prop] : latest;

		return val;
	},

	/*
		Update the input values

		Syntax
			input.update({ prop: val });
			input.update('prop', val);

		@param [string || object]:
		@param [number] (optional): If
	*/
	update: function () {
		var values = {};

		if (utils.isNum(arguments[1])) {
			values[arguments[0]] = arguments[1];
		} else {
			values = arguments[0];
		}

		this.history.add(utils.merge(this.current, values));
	},

	/*
		Check for input movement and update pointer object's properties

		@param [number]: Timestamp of frame
	*/
	onFrame: function (timestamp) {
		var latest, hasChanged;

		// Check provided timestamp against lastFrame timestamp and return input has already been updated
		if (timestamp === this.lastFrame) {
			return;
		}

		latest = this.history.get();
		hasChanged = utils.hasChanged(this.current, latest);

		// If input has changed between frames
		if (hasChanged) {
			this.velocity = calc.offset(this.current, latest);
			this.current = latest;
			this.inactiveFrames = 0;

		// Or it hasn't moved and our frame limit has been reached
		} else if (this.inactiveFrames >= this.maxInactiveFrames) {
			this.velocity = calc.offset(this.current, this.current);

		// Or input hasn't changed
		} else {
			this.inactiveFrames++;
		}

		this.lastFrame = timestamp;
	}

};

module.exports = Input;<|endoftext|>