<commit_before>SirTrevor.Blocks.Video = (function(){

  var video_regexes = {
    'vimeo': /(?:http[s]?:\/\/)?(?:www.)?vimeo.com\/(.*)/,
    'youtube': /(?:http[s]?:\/\/)?(?:www.)?(?:youtu(?:be)?.(?:be|com)\/(?:watch\?v=)?([^&]*)(?:&(?:.))?)/,
    'vine': /(?:http[s]?:\/\/)?(?:www.)?vine.co\/v\/([^\W]*)/,
    'dailymotion': /(?:http[s]?:\/\/)?(?:www.)?dai(?:.ly|lymotion.com\/video)\/([^\W_]*)/
  };

  var embed_strings = {
    'youtube': "",
    'vimeo': "",
    'vine': "",
    'dailymotion': ""
  };

  return SirTrevor.Block.extend({

    type: 'video',
    title: function() { return i18n.t('blocks:video:title'); },

    droppable: true,
    pastable: true,

    icon_name: 'video',

    loadData: function(data){
      if (data.source === 'vine') {
        this.$editor.addClass('st-block__editor--with-square-media');
      } else {
        this.$editor.addClass('st-block__editor--with-sixteen-by-nine-media');
      }

      var embed_string = embed_strings[data.source]
        .replace('{{protocol}}', window.location.protocol)
        .replace('{{remote_id}}', data.remote_id)
        .replace('{{width}}', this.$editor.width()); // for videos that can't resize automatically like vine

      this.$editor.html(embed_string);
    },

    onContentPasted: function(event){
      // Content pasted. Delegate to the drop parse method
      var input = $(event.target),
          val = input.val();

      // Pass this to the same handler as onDrop
      this.handleDropPaste(val);
    },

    handleDropPaste: function(url){

      if(_.isURI(url))
      {
        _.each(video_regexes, function(element, index) {
          var match = element.exec(url);

          if(match !== null && match[1] !== undefined) {
            var data = {};
            data.source = index;
            data.remote_id = match[1];
            // save the data
            this.setAndLoadData(data);
          }
        }.bind(this));
      }

    },

    onDrop: function(transferData){
      var url = transferData.getData('text/plain');
      this.handleDropPaste(url);
    }
  });

})();
<commit_msg>* Allow user to use setBlockOptions to overload video providers * move video_regexes and embed_strings into one object<commit_after>SirTrevor.Blocks.Video = (function(){

  return SirTrevor.Block.extend({

    // more providers at https://gist.github.com/jeffling/a9629ae28e076785a14f
    providers: {
      vimeo: {
        regex: /(?:http[s]?:\/\/)?(?:www.)?vimeo.com\/(.*)/,
        html: ""
      },
      youtube: {
        regex: /(?:http[s]?:\/\/)?(?:www.)?(?:youtu(?:be)?.(?:be|com)\/(?:watch\?v=)?([^&]*)(?:&(?:.))?)/,
        html: ""
      }
    },

    type: 'video',
    title: function() { return i18n.t('blocks:video:title'); },

    droppable: true,
    pastable: true,

    icon_name: 'video',

    loadData: function(data){
      if (this.providers[data.source].square) {
        this.$editor.addClass('st-block__editor--with-square-media');
      } else {
        this.$editor.addClass('st-block__editor--with-sixteen-by-nine-media');
      }

      var embed_string = this.providers[data.source].html
        .replace('{{protocol}}', window.location.protocol)
        .replace('{{remote_id}}', data.remote_id)
        .replace('{{width}}', this.$editor.width()); // for videos that can't resize automatically like vine

      this.$editor.html(embed_string);
    },

    onContentPasted: function(event){
      // Content pasted. Delegate to the drop parse method
      var input = $(event.target),
          val = input.val();

      // Pass this to the same handler as onDrop
      this.handleDropPaste(val);
    },

    handleDropPaste: function(url){
      if(_.isURI(url))
      {
        _.each(this.providers, function(provider, index) {
          var match = provider.regex.exec(url);

          if(match !== null && match[1] !== undefined) {
            var data = {};
            data.source = index;
            data.remote_id = match[1];
            // save the data
            this.setAndLoadData(data);
          }
        }.bind(this));
      }

    },

    onDrop: function(transferData){
      var url = transferData.getData('text/plain');
      this.handleDropPaste(url);
    }
  });

})();
<|endoftext|>


<commit_before>/*
--------------------------------
isMobile
--------------------------------
+ https://github.com/pinceladasdaweb/isMobile
+ Detect Mobile Browsers with pure JavaScript
+ version 2.0
+ Copyright 2013 Pedro Rogerio
+ Licensed under the MIT license
*/

;var isMobile = (function (userAgent) {
  'use strict';

  return !!userAgent.match(/android|webos|ip(hone|ad|od)|opera (mini|mobi|tablet)|iemobile|windows.+(phone|touch)|mobile|fennec|kindle (Fire)|Silk|maemo|blackberry|playbook|bb10\; (touch|kbd)/i);
}(navigator.userAgent));<commit_msg>Update userAgent match<commit_after>/*
--------------------------------
isMobile
--------------------------------
+ https://github.com/pinceladasdaweb/isMobile
+ Detect Mobile Browsers with pure JavaScript
+ version 2.0
+ Copyright 2013 Pedro Rogerio
+ Licensed under the MIT license
*/

;var isMobile = (function (userAgent) {
  'use strict';

  return !!userAgent.match(/android|webos|ip(hone|ad|od)|opera (mini|mobi|tablet)|iemobile|windows.+(phone|touch)|mobile|fennec|kindle (Fire)|Silk|maemo|blackberry|playbook|bb10\; (touch|kbd)|Symbian(OS)|Ubuntu Touch/i);
}(navigator.userAgent));
<|endoftext|>


<commit_before>var FilterESCompiler = require('./filter-es-compiler');
var juttle_utils = require('juttle/lib/runtime').utils;
var elastic = require('./elastic');
var Juttle = require('juttle/lib/runtime').Juttle;

var Read = Juttle.proc.base.extend({
    procName: 'elastic_read',
    sourceType: 'batch',

    initialize: function(options, params) {
        this.id = options.id;
        this._setup_time_filter(options);
        var filter_ast = params.filter_ast;
        if (filter_ast) {
            var filter_es_compiler = new FilterESCompiler();
            var result = filter_es_compiler.compile(filter_ast);
            this.es_filter = result.filter;
        }

        var optimization_info = params && params.optimization_info || {};

        this.es_opts = {
            limit: optimization_info.limit,
            aggregations: optimization_info.aggregations
        };

        if (options.fetch_size) {
            this.es_opts.fetch_size = options.fetch_size;
        }

        if (options.deep_paging_limit) {
            this.es_opts.deep_paging_limit = options.deep_paging_limit;
        }
    },

    _setup_time_filter: function(options) {
        this.now = this.program.now;

        if (options.from && options.to) {
            this.from = options.from;
            this.to = options.to;
        } else if (options.last) {
            this.to = this.now;
            this.from = this.to.subtract(options.last);
        } else {
            throw new Error('-from/-to or -last time filter required');
        }
    },

    start: function() {
        var self = this;
        return elastic.fetcher(this.id, this.es_filter, this.from, this.to, this.es_opts)
            .then(function(fetcher) {
                function loop() {
                    return fetcher()
                        .then(function(result) {
                            if (result.points.length > 0) {
                                self.emit(juttle_utils.toNative(result.points));
                            }
                            if (result.eof) {
                                return self.emit_eof();
                            } else {
                                return loop();
                            }
                        });
                }

                return loop();
            })
            .catch(function(err) {
                self.trigger('error', err);
                self.emit_eof();
            });
    }
});

module.exports = Read;
<commit_msg>Read inherits from source proc<commit_after>var FilterESCompiler = require('./filter-es-compiler');
var juttle_utils = require('juttle/lib/runtime').utils;
var elastic = require('./elastic');
var Juttle = require('juttle/lib/runtime').Juttle;

var Read = Juttle.proc.source.extend({
    procName: 'elastic_read',
    sourceType: 'batch',

    initialize: function(options, params) {
        this.id = options.id;
        this._setup_time_filter(options);
        var filter_ast = params.filter_ast;
        if (filter_ast) {
            var filter_es_compiler = new FilterESCompiler();
            var result = filter_es_compiler.compile(filter_ast);
            this.es_filter = result.filter;
        }

        var optimization_info = params && params.optimization_info || {};

        this.es_opts = {
            limit: optimization_info.limit,
            aggregations: optimization_info.aggregations
        };

        if (options.fetch_size) {
            this.es_opts.fetch_size = options.fetch_size;
        }

        if (options.deep_paging_limit) {
            this.es_opts.deep_paging_limit = options.deep_paging_limit;
        }
    },

    _setup_time_filter: function(options) {
        this.now = this.program.now;

        if (options.from && options.to) {
            this.from = options.from;
            this.to = options.to;
        } else if (options.last) {
            this.to = this.now;
            this.from = this.to.subtract(options.last);
        } else {
            throw new Error('-from/-to or -last time filter required');
        }
    },

    start: function() {
        var self = this;
        return elastic.fetcher(this.id, this.es_filter, this.from, this.to, this.es_opts)
            .then(function(fetcher) {
                function loop() {
                    return fetcher()
                        .then(function(result) {
                            if (result.points.length > 0) {
                                self.emit(juttle_utils.toNative(result.points));
                            }
                            if (result.eof) {
                                return self.emit_eof();
                            } else {
                                return loop();
                            }
                        });
                }

                return loop();
            })
            .catch(function(err) {
                self.trigger('error', err);
                self.emit_eof();
            });
    }
});

module.exports = Read;
<|endoftext|>


<commit_before>requirejs.config({
	baseUrl: 'js/lib',
	waitSeconds: 30,

	paths: {
		app: '../app',
		model: '../app/models',
		route: '../app/routes',
		template: '../../templates',
		widget: '../app/widgets',
		worker: '../app/workers',
		root: '../..',

		// requirejs plugins
		text: 'requirejs-plugins/text',
		tpl: 'requirejs-plugins/template',
		image: 'requirejs-plugins/image'
	},
	shim: {

	}
});

require(['route/home'], function() {
	Path.rescue(function() {
		// TODO - Redirect to 404 page
	});

	Path.root("#!/home");

	Path.listen();
});
<commit_msg>Change path to 'templates' folder in requirejs config<commit_after>requirejs.config({
	baseUrl: 'js/lib',
	waitSeconds: 30,

	paths: {
		app: '../app',
		model: '../app/models',
		route: '../app/routes',
		template: '../app/templates',
		widget: '../app/widgets',
		worker: '../app/workers',
		root: '../..',

		// requirejs plugins
		text: 'requirejs-plugins/text',
		tpl: 'requirejs-plugins/template',
		image: 'requirejs-plugins/image'
	},
	shim: {

	}
});

require(['route/home'], function() {
	Path.rescue(function() {
		// TODO - Redirect to 404 page
	});

	Path.root("#!/home");

	Path.listen();
});
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const Hash = require("./Hash");

const BULK_SIZE = 2000;

// We are using an object instead of a Map as this will stay static during the runtime
// so access to it can be optimized by v8
const digestCaches = {};

class BulkUpdateDecorator extends Hash {
	/**
	 * @param {Hash | function(): Hash} hashOrFactory function to create a hash
	 * @param {string=} hashKey key for caching
	 */
	constructor(hashOrFactory, hashKey) {
		super();
		this.hashKey = hashKey;
		if (typeof hashOrFactory === "function") {
			this.hashFactory = hashOrFactory;
			this.hash = undefined;
		} else {
			this.hashFactory = undefined;
			this.hash = hashOrFactory;
		}
		this.buffer = "";
	}

	/**
	 * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
	 * @param {string|Buffer} data data
	 * @param {string=} inputEncoding data encoding
	 * @returns {this} updated hash
	 */
	update(data, inputEncoding) {
		if (
			inputEncoding !== undefined ||
			typeof data !== "string" ||
			data.length > BULK_SIZE
		) {
			if (this.hash === undefined) this.hash = this.hashFactory();
			if (this.buffer.length > 0) {
				this.hash.update(this.buffer);
				this.buffer = "";
			}
			this.hash.update(data, inputEncoding);
		} else {
			this.buffer += data;
			if (this.buffer.length > BULK_SIZE) {
				if (this.hash === undefined) this.hash = this.hashFactory();
				this.hash.update(this.buffer);
				this.buffer = "";
			}
		}
		return this;
	}

	/**
	 * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
	 * @param {string=} encoding encoding of the return value
	 * @returns {string|Buffer} digest
	 */
	digest(encoding) {
		let digestCache;
		if (this.hash === undefined) {
			// short data for hash, we can use caching
			const cacheKey = `${this.hashKey}-${encoding}`;
			digestCache = digestCaches[cacheKey];
			if (digestCache === undefined) {
				digestCache = digestCaches[cacheKey] = new Map();
			}
			const cacheEntry = digestCache.get(this.buffer);
			if (cacheEntry !== undefined) return cacheEntry;
			this.hash = this.hashFactory();
		}
		if (this.buffer.length > 0) {
			this.hash.update(this.buffer);
		}
		const digestResult = this.hash.digest(encoding);
		const result =
			typeof digestResult === "string" ? digestResult : digestResult.toString();
		if (digestCache !== undefined) {
			digestCache.set(this.buffer, result);
		}
		return result;
	}
}

/* istanbul ignore next */
class DebugHash extends Hash {
	constructor() {
		super();
		this.string = "";
	}

	/**
	 * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
	 * @param {string|Buffer} data data
	 * @param {string=} inputEncoding data encoding
	 * @returns {this} updated hash
	 */
	update(data, inputEncoding) {
		if (typeof data !== "string") data = data.toString("utf-8");
		if (data.startsWith("debug-digest-")) {
			data = Buffer.from(data.slice("debug-digest-".length), "hex").toString();
		}
		this.string += `[${data}](${new Error().stack.split("\n", 3)[2]})\n`;
		return this;
	}

	/**
	 * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
	 * @param {string=} encoding encoding of the return value
	 * @returns {string|Buffer} digest
	 */
	digest(encoding) {
		return "debug-digest-" + Buffer.from(this.string).toString("hex");
	}
}

let crypto = undefined;

/**
 * Creates a hash by name or function
 * @param {string | typeof Hash} algorithm the algorithm name or a constructor creating a hash
 * @returns {Hash} the hash
 */
module.exports = algorithm => {
	if (typeof algorithm === "function") {
		return new BulkUpdateDecorator(() => new algorithm());
	}
	switch (algorithm) {
		// TODO add non-cryptographic algorithm here
		case "debug":
			return new DebugHash();
		default:
			if (crypto === undefined) crypto = require("crypto");
			return new BulkUpdateDecorator(
				() => crypto.createHash(algorithm),
				algorithm
			);
	}
};
<commit_msg>cache buffer in local var<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const Hash = require("./Hash");

const BULK_SIZE = 2000;

// We are using an object instead of a Map as this will stay static during the runtime
// so access to it can be optimized by v8
const digestCaches = {};

class BulkUpdateDecorator extends Hash {
	/**
	 * @param {Hash | function(): Hash} hashOrFactory function to create a hash
	 * @param {string=} hashKey key for caching
	 */
	constructor(hashOrFactory, hashKey) {
		super();
		this.hashKey = hashKey;
		if (typeof hashOrFactory === "function") {
			this.hashFactory = hashOrFactory;
			this.hash = undefined;
		} else {
			this.hashFactory = undefined;
			this.hash = hashOrFactory;
		}
		this.buffer = "";
	}

	/**
	 * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
	 * @param {string|Buffer} data data
	 * @param {string=} inputEncoding data encoding
	 * @returns {this} updated hash
	 */
	update(data, inputEncoding) {
		if (
			inputEncoding !== undefined ||
			typeof data !== "string" ||
			data.length > BULK_SIZE
		) {
			if (this.hash === undefined) this.hash = this.hashFactory();
			if (this.buffer.length > 0) {
				this.hash.update(this.buffer);
				this.buffer = "";
			}
			this.hash.update(data, inputEncoding);
		} else {
			this.buffer += data;
			if (this.buffer.length > BULK_SIZE) {
				if (this.hash === undefined) this.hash = this.hashFactory();
				this.hash.update(this.buffer);
				this.buffer = "";
			}
		}
		return this;
	}

	/**
	 * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
	 * @param {string=} encoding encoding of the return value
	 * @returns {string|Buffer} digest
	 */
	digest(encoding) {
		let digestCache;
		const buffer = this.buffer;
		if (this.hash === undefined) {
			// short data for hash, we can use caching
			const cacheKey = `${this.hashKey}-${encoding}`;
			digestCache = digestCaches[cacheKey];
			if (digestCache === undefined) {
				digestCache = digestCaches[cacheKey] = new Map();
			}
			const cacheEntry = digestCache.get(buffer);
			if (cacheEntry !== undefined) return cacheEntry;
			this.hash = this.hashFactory();
		}
		if (buffer.length > 0) {
			this.hash.update(buffer);
		}
		const digestResult = this.hash.digest(encoding);
		const result =
			typeof digestResult === "string" ? digestResult : digestResult.toString();
		if (digestCache !== undefined) {
			digestCache.set(buffer, result);
		}
		return result;
	}
}

/* istanbul ignore next */
class DebugHash extends Hash {
	constructor() {
		super();
		this.string = "";
	}

	/**
	 * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
	 * @param {string|Buffer} data data
	 * @param {string=} inputEncoding data encoding
	 * @returns {this} updated hash
	 */
	update(data, inputEncoding) {
		if (typeof data !== "string") data = data.toString("utf-8");
		if (data.startsWith("debug-digest-")) {
			data = Buffer.from(data.slice("debug-digest-".length), "hex").toString();
		}
		this.string += `[${data}](${new Error().stack.split("\n", 3)[2]})\n`;
		return this;
	}

	/**
	 * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
	 * @param {string=} encoding encoding of the return value
	 * @returns {string|Buffer} digest
	 */
	digest(encoding) {
		return "debug-digest-" + Buffer.from(this.string).toString("hex");
	}
}

let crypto = undefined;

/**
 * Creates a hash by name or function
 * @param {string | typeof Hash} algorithm the algorithm name or a constructor creating a hash
 * @returns {Hash} the hash
 */
module.exports = algorithm => {
	if (typeof algorithm === "function") {
		return new BulkUpdateDecorator(() => new algorithm());
	}
	switch (algorithm) {
		// TODO add non-cryptographic algorithm here
		case "debug":
			return new DebugHash();
		default:
			if (crypto === undefined) crypto = require("crypto");
			return new BulkUpdateDecorator(
				() => crypto.createHash(algorithm),
				algorithm
			);
	}
};
<|endoftext|>


<commit_before>'use strict';

/**
 * 가로or세로형 드래그&드롭 슬라이더.
 *
 * @class Slider
 */
export default class Slider {

	/**
	 * Creates an instance of Slider.
	 *
	 * @param {Object} [{
	 * 		el, 			- 슬라이더 적용 대상 엘리먼트
	 * 		onDrag, 		- 드래그 콜백 함수
	 * 		axis='x' 		- 드래그 방향
	 * 	}={}]
	 */
	constructor({ el, onDrag, axis='x' } = {}) {
		/**
		 * 슬라이더 엘리먼트
		 * @type {Element}
		 */
		this.range = el;

		/**
		 * 드래그 버튼 엘리먼트
		 * @type {Element}
		 */
		this.dragger = this.range.children[0];

		/**
		 * 드래그 콜백 함수
		 * @type {Function}
		 */
		this.onDrag = onDrag;

		/**
		 * x 방향이면 true
		 * @type {Boolean}
		 */
		this.isX = axis === 'x';

		/**
		 * mousedown 상태이면 true
		 * @type {Boolean}
		 */
		this.isDown = false;

		this.range.addEventListener("mousedown", this.mousedown.bind(this));
		document.addEventListener("mousemove", this.update.bind(this));
		document.addEventListener("mouseup", this.mouseup.bind(this));
		this.range.addEventListener("touchstart", this.mousedown.bind(this));
		document.addEventListener("touchmove", this.update.bind(this));
		document.addEventListener("touchend", this.mouseup.bind(this));

		return this;
	}

	/**
	 * 드래그 시작
	 * @param {Event} e
	 */
	mousedown(e) {
		e.preventDefault();
		e.stopPropagation();
		this.isDown = true;
		this.update(e);
	}

	/**
	 * 드래그 움직임
	 * @param {Event} e
	 */
	update(e) {
		let eventPos = this.isX ? e.pageX || e.touches[0].pageX : e.pageY || e.touches[0].pageY,
			offsetPos = this.offsetPos,
			isOver = eventPos >= offsetPos && eventPos <= (offsetPos + this.rangeSize),
			gap = eventPos - this.offsetPos,
			to = 0;

		if (this.isDown && isOver) {
			if(this.isX) {
				to = Math.round(gap / this.rangeSize * 100);
			} else {
				to = Math.round((this.rangeSize -gap) / this.rangeSize * 100);
			}

			this.position = to;

			if (typeof this.onDrag === "function") {
				this.onDrag.call(this, this.position);
			}
		}
	}

	/**
	 * 드래그 종료
	 */
	mouseup() {
		this.isDown = false;
	}

	/**
	 * 현재 위치 백분율 값 리턴
	 * @type {Number}
	 */
	get position() {
		let prop = this.isX ? 'width' : 'height';
		return Math.round(parseInt(this.dragger.style[prop]));
	}

	/**
	 * 슬라이더 위치 적용(백분율 값)
	 * @type {Number}
	 */
	set position(val) {
		let prop = this.isX ? 'width' : 'height';
		this.dragger.style[prop] = val + '%';
	}

	/**
	 * 슬라이더 사이즈 리턴. width or height
	 * @type {Number}
	 * @readonly
	 */
	get rangeSize() {
		return this.isX ? this.range.offsetWidth : this.range.offsetHeight;
	}

	/**
	 * 슬라이더 위치 리턴. left or top
	 * @type {Number}
	 * @readonly
	 */
	get offsetPos() {
		let obj = this.range,
			pos = 0;

		if (obj && obj.offsetParent) {
			do {
				if(this.isX) {
					pos += obj.offsetLeft;
				} else {
					pos += obj.offsetTop;
				}
			} while (obj = obj.offsetParent);
		}

		return pos;
	}
}<commit_msg>offsetPos() 문법경고 수정<commit_after>'use strict';

/**
 * 가로or세로형 드래그&드롭 슬라이더.
 *
 * @class Slider
 */
export default class Slider {

	/**
	 * Creates an instance of Slider.
	 *
	 * @param {Object} [{
	 * 		el, 			- 슬라이더 적용 대상 엘리먼트
	 * 		onDrag, 		- 드래그 콜백 함수
	 * 		axis='x' 		- 드래그 방향
	 * 	}={}]
	 */
	constructor({ el, onDrag, axis='x' } = {}) {
		/**
		 * 슬라이더 엘리먼트
		 * @type {Element}
		 */
		this.range = el;

		/**
		 * 드래그 버튼 엘리먼트
		 * @type {Element}
		 */
		this.dragger = this.range.children[0];

		/**
		 * 드래그 콜백 함수
		 * @type {Function}
		 */
		this.onDrag = onDrag;

		/**
		 * x 방향이면 true
		 * @type {Boolean}
		 */
		this.isX = axis === 'x';

		/**
		 * mousedown 상태이면 true
		 * @type {Boolean}
		 */
		this.isDown = false;

		this.range.addEventListener("mousedown", this.mousedown.bind(this));
		document.addEventListener("mousemove", this.update.bind(this));
		document.addEventListener("mouseup", this.mouseup.bind(this));
		this.range.addEventListener("touchstart", this.mousedown.bind(this));
		document.addEventListener("touchmove", this.update.bind(this));
		document.addEventListener("touchend", this.mouseup.bind(this));

		return this;
	}

	/**
	 * 드래그 시작
	 * @param {Event} e
	 */
	mousedown(e) {
		e.preventDefault();
		e.stopPropagation();
		this.isDown = true;
		this.update(e);
	}

	/**
	 * 드래그 움직임
	 * @param {Event} e
	 */
	update(e) {
		let eventPos = this.isX ? e.pageX || e.touches[0].pageX : e.pageY || e.touches[0].pageY,
			offsetPos = this.offsetPos,
			isOver = eventPos >= offsetPos && eventPos <= (offsetPos + this.rangeSize),
			gap = eventPos - this.offsetPos,
			to = 0;

		if (this.isDown && isOver) {
			if(this.isX) {
				to = Math.round(gap / this.rangeSize * 100);
			} else {
				to = Math.round((this.rangeSize -gap) / this.rangeSize * 100);
			}

			this.position = to;

			if (typeof this.onDrag === "function") {
				this.onDrag.call(this, this.position);
			}
		}
	}

	/**
	 * 드래그 종료
	 */
	mouseup() {
		this.isDown = false;
	}

	/**
	 * 현재 위치 백분율 값 리턴
	 * @type {Number}
	 */
	get position() {
		let prop = this.isX ? 'width' : 'height';
		return Math.round(parseInt(this.dragger.style[prop]));
	}

	/**
	 * 슬라이더 위치 적용(백분율 값)
	 * @type {Number}
	 */
	set position(val) {
		let prop = this.isX ? 'width' : 'height';
		this.dragger.style[prop] = val + '%';
	}

	/**
	 * 슬라이더 사이즈 리턴. width or height
	 * @type {Number}
	 * @readonly
	 */
	get rangeSize() {
		return this.isX ? this.range.offsetWidth : this.range.offsetHeight;
	}

	/**
	 * 슬라이더 위치 리턴. left or top
	 * @type {Number}
	 * @readonly
	 */
	get offsetPos() {
		let obj = this.range,
			pos = 0;

		if (obj && obj.offsetParent) {
			while (obj) {
				if(this.isX) {
					pos += obj.offsetLeft;
				} else {
					pos += obj.offsetTop;
				}
				obj = obj.offsetParent;
			}
		}

		return pos;
	}
}<|endoftext|>


<commit_before>// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-constructor
it('should throw if being used via `new`', function() {
	var test = function () {
		return new Symbol();
	}
	expect(test).to.throwError();
});

it('should have Symbol as the constructor property on the prototype', function() {
	expect(Object.getPrototypeOf(Symbol()).constructor).to.be(Symbol)
});

it('should silently fail when assigning new properties', function (){
	const a = Symbol("1");
	a.b = '1';
	expect(a.b).to.be.undefined;
});

it('should have Symbol.prototype as the prototype of an instance', function() {
	expect(Object.getPrototypeOf(Symbol())).to.be(Symbol.prototype);
});

it('should return "[object Symbol]" when called with Object.prototype.toString()', function() {
	expect(Object.prototype.toString.call(Symbol())).to.be('[object Symbol]');
});

it('should silently fail when overwriting properties', function() {
	var sym = Symbol("2");
	sym.toString = 0;
	expect(sym.toString).to.be.a(Function)
	sym.valueOf = 0;
	expect(sym.valueOf).to.be.a(Function)
});

it('should create unique symbols', function() {
	expect(Symbol("3")).to.not.equal(Symbol("3"))
});

it('has for, and keyFor static methods', function() {
	expect(Symbol.for).to.be.a(Function);
	expect(Symbol.keyFor).to.be.a(Function);
});

it('Symbol.keyFor should throw if not given a symbol', function() {
	var stringKeyFor = function() {
		return Symbol.keyFor('a');
	}
	var numberKeyFor = function() {
		return Symbol.keyFor(1);
	}
	var arrayKeyFor = function() {
		return Symbol.keyFor([]);
	}
	var objectKeyFor = function() {
		return Symbol.keyFor({});
	}
	var boolKeyFor = function() {
		return Symbol.keyFor(true);
	}
	var undefinedKeyFor = function() {
		return Symbol.keyFor(undefined);
	}
	var symbolKeyFor = function() {
		return Symbol.keyFor(Symbol("4"));
	}

	expect(stringKeyFor).to.throwError();
	expect(numberKeyFor).to.throwError();
	expect(arrayKeyFor).to.throwError();
	expect(objectKeyFor).to.throwError();
	expect(boolKeyFor).to.throwError();
	expect(undefinedKeyFor).to.throwError();
	expect(symbolKeyFor).to.not.throwError();
});

it('Symbol.keyFor should return undefined if can not find symbol in global registry', function() {
	expect(Symbol.keyFor(Symbol("5"))).to.be.undefined;
});

it('Symbol() should not add the symbol to the global registry', function() {
	var sym = Symbol("6");
	expect(Symbol.keyFor(sym)).to.be.undefined;
});

it('Symbol.for should create new symbol if can not find symbol in global registry', function() {
	var sym1 = Symbol("7");
	var sym2 = Symbol.for("7");
	expect(sym1).to.not.equal(sym2);
});

it('Symbol.for should return symbol if can find symbol in global registry', function() {
	var sym = Symbol.for("8");
	expect(sym).to.equal(Symbol.for("8"));
});

it('Symbol.keyFor should return key of symbol if can find symbol in global registry', function() {
	var key = "9"
	var sym = Symbol.for(key);
	expect(Symbol.keyFor(sym)).to.be(key);
});

it('has toString and valueOf instance methods', function() {
	expect(Symbol.prototype['toString']).to.be.a(Function);
	expect(Symbol.prototype['valueOf']).to.be.a(Function);
});

it('has the well known symbol hasInstance as static properties on Symbol', function() {
	expect(Symbol.hasInstance).to.be.a('symbol');
});

it('has the well known symbol isConcatSpreadable as static properties on Symbol', function() {
	expect(Symbol.isConcatSpreadable).to.be.a('symbol');
});

it('has the well known symbol iterator as static properties on Symbol', function() {
	expect(Symbol.iterator).to.be.a('symbol');
});

it('has the well known symbol match as static properties on Symbol', function() {
	expect(Symbol.match).to.be.a('symbol');
});

it('has the well known symbol replace as static properties on Symbol', function() {
	expect(Symbol.replace).to.be.a('symbol');
});

it('has the well known symbol search as static properties on Symbol', function() {
	expect(Symbol.search).to.be.a('symbol');
});

it('has the well known symbol species as static properties on Symbol', function() {
	expect(Symbol.species).to.be.a('symbol');
});

it('has the well known symbol split as static properties on Symbol', function() {
	expect(Symbol.split).to.be.a('symbol');
});

it('has the well known symbol toPrimitive as static properties on Symbol', function() {
	expect(Symbol.toPrimitive).to.be.a('symbol');
});

it('has the well known symbol toStringTag as static properties on Symbol', function() {
	expect(Symbol.toStringTag).to.be.a('symbol');
});

it('has the well known symbol unscopables as static properties on Symbol', function() {
	expect(Symbol.unscopables).to.be.a('symbol');
});

// https://kangax.github.io/compat-table/es6/#Symbol_symbol_keys_are_hidden_to_pre-ES6_code
it('should make symbols non-enumerable', function() {
	var object = {};
	var symbol = Symbol();
	object[symbol] = 1;

	for (var x in object){}
	var passed = !x;

	expect(passed).to.be.true;
	expect(Object.keys(object).length).to.be(0);
	expect(Object.getOwnPropertyNames(object).length).to.be(0);
});

it('should perform correctly with toString operations', function() {
	expect(String(Symbol('10'))).to.be('Symbol(10)');
	expect(Symbol('10').toString()).to.be('Symbol(10)');
	expect(Object(Symbol('10')).toString()).to.be('Symbol(10)');
	expect(Symbol.prototype.toString.call(Symbol('10'))).to.be('Symbol(10)');
});

it('should not allow implicit string coercion', function() {
	var implicitStringCoercion = function() {
		return Symbol('10') + '';
	}
	expect(implicitStringCoercion).to.throwError();
})
<commit_msg>Switch to existence checks<commit_after>// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-constructor
it('should throw if being used via `new`', function() {
	var test = function () {
		return new Symbol();
	}
	expect(test).to.throwError();
});

it('should have Symbol as the constructor property on the prototype', function() {
	expect(Object.getPrototypeOf(Symbol()).constructor).to.be(Symbol)
});

it('should silently fail when assigning new properties', function (){
	const a = Symbol("1");
	a.b = '1';
	expect(a.b).to.be.undefined;
});

it('should have Symbol.prototype as the prototype of an instance', function() {
	expect(Object.getPrototypeOf(Symbol())).to.be(Symbol.prototype);
});

it('should return "[object Symbol]" when called with Object.prototype.toString()', function() {
	expect(Object.prototype.toString.call(Symbol())).to.be('[object Symbol]');
});

it('should silently fail when overwriting properties', function() {
	var sym = Symbol("2");
	sym.toString = 0;
	expect(sym.toString).to.be.a(Function)
	sym.valueOf = 0;
	expect(sym.valueOf).to.be.a(Function)
});

it('should create unique symbols', function() {
	expect(Symbol("3")).to.not.equal(Symbol("3"))
});

it('has for, and keyFor static methods', function() {
	expect(Symbol.for).to.be.a(Function);
	expect(Symbol.keyFor).to.be.a(Function);
});

it('Symbol.keyFor should throw if not given a symbol', function() {
	var stringKeyFor = function() {
		return Symbol.keyFor('a');
	}
	var numberKeyFor = function() {
		return Symbol.keyFor(1);
	}
	var arrayKeyFor = function() {
		return Symbol.keyFor([]);
	}
	var objectKeyFor = function() {
		return Symbol.keyFor({});
	}
	var boolKeyFor = function() {
		return Symbol.keyFor(true);
	}
	var undefinedKeyFor = function() {
		return Symbol.keyFor(undefined);
	}
	var symbolKeyFor = function() {
		return Symbol.keyFor(Symbol("4"));
	}

	expect(stringKeyFor).to.throwError();
	expect(numberKeyFor).to.throwError();
	expect(arrayKeyFor).to.throwError();
	expect(objectKeyFor).to.throwError();
	expect(boolKeyFor).to.throwError();
	expect(undefinedKeyFor).to.throwError();
	expect(symbolKeyFor).to.not.throwError();
});

it('Symbol.keyFor should return undefined if can not find symbol in global registry', function() {
	expect(Symbol.keyFor(Symbol("5"))).to.be.undefined;
});

it('Symbol() should not add the symbol to the global registry', function() {
	var sym = Symbol("6");
	expect(Symbol.keyFor(sym)).to.be.undefined;
});

it('Symbol.for should create new symbol if can not find symbol in global registry', function() {
	var sym1 = Symbol("7");
	var sym2 = Symbol.for("7");
	expect(sym1).to.not.equal(sym2);
});

it('Symbol.for should return symbol if can find symbol in global registry', function() {
	var sym = Symbol.for("8");
	expect(sym).to.equal(Symbol.for("8"));
});

it('Symbol.keyFor should return key of symbol if can find symbol in global registry', function() {
	var key = "9"
	var sym = Symbol.for(key);
	expect(Symbol.keyFor(sym)).to.be(key);
});

it('has toString and valueOf instance methods', function() {
	expect(Symbol.prototype['toString']).to.be.a(Function);
	expect(Symbol.prototype['valueOf']).to.be.a(Function);
});

it('has the well known symbol hasInstance as static properties on Symbol', function() {
	expect(Symbol.hasInstance).to.not.be.undefined;
});

it('has the well known symbol isConcatSpreadable as static properties on Symbol', function() {
	expect(Symbol.isConcatSpreadable).to.not.be.undefined;
});

it('has the well known symbol iterator as static properties on Symbol', function() {
	expect(Symbol.iterator).to.not.be.undefined;
});

it('has the well known symbol match as static properties on Symbol', function() {
	expect(Symbol.match).to.not.be.undefined;
});

it('has the well known symbol replace as static properties on Symbol', function() {
	expect(Symbol.replace).to.not.be.undefined;
});

it('has the well known symbol search as static properties on Symbol', function() {
	expect(Symbol.search).to.not.be.undefined;
});

it('has the well known symbol species as static properties on Symbol', function() {
	expect(Symbol.species).to.not.be.undefined;
});

it('has the well known symbol split as static properties on Symbol', function() {
	expect(Symbol.split).to.not.be.undefined;
});

it('has the well known symbol toPrimitive as static properties on Symbol', function() {
	expect(Symbol.toPrimitive).to.not.be.undefined;
});

it('has the well known symbol toStringTag as static properties on Symbol', function() {
	expect(Symbol.toStringTag).to.not.be.undefined;
});

it('has the well known symbol unscopables as static properties on Symbol', function() {
	expect(Symbol.unscopables).to.not.be.undefined;
});

// https://kangax.github.io/compat-table/es6/#Symbol_symbol_keys_are_hidden_to_pre-ES6_code
it('should make symbols non-enumerable', function() {
	var object = {};
	var symbol = Symbol();
	object[symbol] = 1;

	for (var x in object){}
	var passed = !x;

	expect(passed).to.be.true;
	expect(Object.keys(object).length).to.be(0);
	expect(Object.getOwnPropertyNames(object).length).to.be(0);
});

it('should perform correctly with toString operations', function() {
	expect(String(Symbol('10'))).to.be('Symbol(10)');
	expect(Symbol('10').toString()).to.be('Symbol(10)');
	expect(Object(Symbol('10')).toString()).to.be('Symbol(10)');
	expect(Symbol.prototype.toString.call(Symbol('10'))).to.be('Symbol(10)');
});

it('should not allow implicit string coercion', function() {
	var implicitStringCoercion = function() {
		return Symbol('10') + '';
	}
	expect(implicitStringCoercion).to.throwError();
})
<|endoftext|>


<commit_before>/* These functions require the jquery.formrestrict.js functions to work!
 *
 * These functions can be used to replace the functionality of the jQuery
 * AlphaNumeric plugin. The usage of this plugin is almost identical to that of
 * the AlphaNumeric plugin.
 */

(function ($) {
    jQuery.fn.alphanumeric = function(r) {
        alphanumericHelper(this, r, true, true);
    };
    jQuery.fn.numeric = function(r) {
        alphanumericHelper(this, r, false, true);
    };
    jQuery.fn.alpha = function(r) {
        alphanumericHelper(this, r, true, false);
    };
    var alphanumericHelper = function(obj, restraints, alpha, numeric) {
        var regex = "";
        if (numeric)
            regex += "0-9";
        if (alpha) {
            if (restraints == undefined || !restraints.allcaps)
                regex += "a-z";
            if (restraints == undefined || !restraints.nocaps)
                regex += "A-Z";
        }
        if (restraints != undefined && restraints.allow != undefined)
            regex += RegExp.escape(restraints.allow);

        $(obj).regexRestrict(RegExp("[^"+regex+"]", "g"))
    };
})(jQuery);

/*
 * Function created by Colin Snover in response to an article by Simon Willison
 * on Regular Expression escaping in JavaScript:
 * http://simonwillison.net/2006/Jan/20/escape/
 */
RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
<commit_msg>Allow spaces in each method<commit_after>/* These functions require the jquery.formrestrict.js functions to work!
 *
 * These functions can be used to replace the functionality of the jQuery
 * AlphaNumeric plugin. The usage of this plugin is almost identical to that of
 * the AlphaNumeric plugin.
 */

(function ($) {
    jQuery.fn.alphanumeric = function(r) {
        alphanumericHelper(this, r, true, true, false);
    };
    jQuery.fn.numeric = function(r) {
        alphanumericHelper(this, r, false, true, false);
    };
    jQuery.fn.alpha = function(r) {
        alphanumericHelper(this, r, true, false, false);
    };
    jQuery.fn.alphanumericSpaces = function(r) {
        alphanumericHelper(this, r, true, true, true);
    };
    jQuery.fn.numericSpaces = function(r) {
        alphanumericHelper(this, r, false, true, true);
    };
    jQuery.fn.alphaSpaces = function(r) {
        alphanumericHelper(this, r, true, false, true);
    };
    var alphanumericHelper = function(obj, restraints, alpha, numeric, spaces) {
        var regex = "";
        if (spaces)
            regex += " ";
        if (numeric)
            regex += "0-9";
        if (alpha) {
            if (restraints == undefined || !restraints.allcaps)
                regex += "a-z";
            if (restraints == undefined || !restraints.nocaps)
                regex += "A-Z";
        }
        if (restraints != undefined && restraints.allow != undefined)
            regex += RegExp.escape(restraints.allow);

        $(obj).regexRestrict(RegExp("[^"+regex+"]", "g"))
    };
})(jQuery);

/*
 * Function created by Colin Snover in response to an article by Simon Willison
 * on Regular Expression escaping in JavaScript:
 * http://simonwillison.net/2006/Jan/20/escape/
 */
RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');
var url = require('url');
var Promise = require('bluebird');
var JuttleMoment = require('juttle/lib/runtime/types/juttle-moment');
var AdapterRead = require('juttle/lib/runtime/adapter-read');
var errors = require('juttle/lib/errors');

var Config = require('./config');
var Serializer = require('./serializer');
var QueryBuilder = require('./query');

var request = Promise.promisifyAll(require('request'));
request.async = Promise.promisify(request);

class ReadInflux extends AdapterRead {
    constructor(options, params) {
        super(options, params);

        if (options.raw) {
            if (params.filter_ast !== null) {
                throw errors.compileError('INVALID-OPTION-COMBINATION', {
                    option: 'raw',
                    rule: 'empty filter'
                });
            }

            if (this.options.from || this.options.to) {
                throw errors.compileError('OPTION-FROM-TO-ERROR', {
                    option: 'raw'
                });
            }

            this.from = undefined;
            this.to = undefined;
        } else {
            if (!this.options.from && !this.options.to) {
                throw errors.compileError('MISSING-TIME-RANGE');
            }

            this.from = this.options.from || params.now;
            this.to = this.options.to || params.now;
        }

        this.nameField = options.nameField || 'name';
        this.serializer = new Serializer();

        this.url = this.setUrl(Config.get().url);
        this.db = options.db;

        this.queryBuilder = new QueryBuilder();
        this.queryOptimization = params.optimization_info;

        this.queryOptions = _.defaults(
            _.pick(options, 'offset', 'limit', 'fields', 'raw'),
            this.queryOptimization.options || {},
            {
                nameField: this.nameField,
                limit: 1000,
            }
        );

        this.queryFilter  = params;
    }

    static allowedOptions() {
        return AdapterRead.commonOptions().concat(['db', 'optimize', 'limit', 'offset', 'raw', 'nameField', 'fields']);
    }

    static requiredOptions() {
        return ['db'];
    }

    setUrl(urlStr) {
        var urlObj = {};

        try {
            urlObj = url.parse(urlStr);
        } catch (e) {
            throw errors.compileError('INVALID-URL-ERROR', { url: urlStr });
        }

        if (!urlObj.host) {
            throw errors.compileError('INVALID-URL-ERROR', { url: urlStr });
        }

        return urlObj;
    }

    toNative(s) {
        var self = this;
        if (_.contains(s.columns, this.nameField)) {
            self.trigger('warning', errors.runtimeError('INTERNAL-ERROR', {
                error: `Points contain ${this.nameField} field, use nameField option to make the field accessible.`
            }));
        }
        return _.map(s.values,
            (row) => this.serializer.toJuttle(s.name, s.columns, row, this.nameField)
        );
    }

    _sort(t1, t2) {
        return JuttleMoment.compare(t1.time, t2.time);
    }

    parse(data) {
        var e  = _.find(data.results, 'error');

        if (e && e.error) {
            throw errors.runtimeError('INTERNAL-ERROR', { error: e.error });
        }

        var results = _.find(data.results, 'series') || {};

        if (!results.series) {
            return [];
        } else {
            return _.chain(results.series)
                .map(this.toNative.bind(this))
                .flatten()
                .sort(this._sort)
                .value();
        }
    }

    defaultTimeRange() {
        return {
            from: this.from,
            to: this.to
        };
    }

    periodicLiveRead() {
        return this.queryOptions.raw === undefined;
    }

    read(from, to, limit, state) {
        var self = this;

        var parsedUrl = _.clone(this.url);
        var reqUrl = null;

        var queryOptions = _.extend({ to, from }, this.queryOptions);
        var query = this.queryBuilder.build(queryOptions, this.queryFilter);

        this.logger.debug(`Running query: ${query}`);

        _.extend(parsedUrl, { pathname: '/query', query: { 'q': query, 'db': this.db, 'epoch' : 'ms' } });

        return request.async({
            url: url.format(parsedUrl),
            method: 'GET'
        }).then((response) => {
            if (response.statusCode < 200 || response.statusCode >= 300) {
                throw errors.runtimeError('INTERNAL-ERROR', {
                    error: `${response.statusCode}: ${response.body} for ${reqUrl}`
                });
            }

            return {
                points: self.parse(JSON.parse(response.body)),
                readEnd: to || new JuttleMoment(Infinity)
            };
        }).catch((e) => {
            throw e;
        });
    }
}

module.exports = ReadInflux;
<commit_msg>Update to defaultTimeRange -> defaultTimeOptions rename<commit_after>'use strict';

var _ = require('underscore');
var url = require('url');
var Promise = require('bluebird');
var JuttleMoment = require('juttle/lib/runtime/types/juttle-moment');
var AdapterRead = require('juttle/lib/runtime/adapter-read');
var errors = require('juttle/lib/errors');

var Config = require('./config');
var Serializer = require('./serializer');
var QueryBuilder = require('./query');

var request = Promise.promisifyAll(require('request'));
request.async = Promise.promisify(request);

class ReadInflux extends AdapterRead {
    constructor(options, params) {
        super(options, params);

        if (options.raw) {
            if (params.filter_ast !== null) {
                throw errors.compileError('INVALID-OPTION-COMBINATION', {
                    option: 'raw',
                    rule: 'empty filter'
                });
            }

            if (this.options.from || this.options.to) {
                throw errors.compileError('OPTION-FROM-TO-ERROR', {
                    option: 'raw'
                });
            }

            this.from = undefined;
            this.to = undefined;
        } else {
            if (!this.options.from && !this.options.to) {
                throw errors.compileError('MISSING-TIME-RANGE');
            }

            this.from = this.options.from || params.now;
            this.to = this.options.to || params.now;
        }

        this.nameField = options.nameField || 'name';
        this.serializer = new Serializer();

        this.url = this.setUrl(Config.get().url);
        this.db = options.db;

        this.queryBuilder = new QueryBuilder();
        this.queryOptimization = params.optimization_info;

        this.queryOptions = _.defaults(
            _.pick(options, 'offset', 'limit', 'fields', 'raw'),
            this.queryOptimization.options || {},
            {
                nameField: this.nameField,
                limit: 1000,
            }
        );

        this.queryFilter  = params;
    }

    static allowedOptions() {
        return AdapterRead.commonOptions().concat(['db', 'optimize', 'limit', 'offset', 'raw', 'nameField', 'fields']);
    }

    static requiredOptions() {
        return ['db'];
    }

    setUrl(urlStr) {
        var urlObj = {};

        try {
            urlObj = url.parse(urlStr);
        } catch (e) {
            throw errors.compileError('INVALID-URL-ERROR', { url: urlStr });
        }

        if (!urlObj.host) {
            throw errors.compileError('INVALID-URL-ERROR', { url: urlStr });
        }

        return urlObj;
    }

    toNative(s) {
        var self = this;
        if (_.contains(s.columns, this.nameField)) {
            self.trigger('warning', errors.runtimeError('INTERNAL-ERROR', {
                error: `Points contain ${this.nameField} field, use nameField option to make the field accessible.`
            }));
        }
        return _.map(s.values,
            (row) => this.serializer.toJuttle(s.name, s.columns, row, this.nameField)
        );
    }

    _sort(t1, t2) {
        return JuttleMoment.compare(t1.time, t2.time);
    }

    parse(data) {
        var e  = _.find(data.results, 'error');

        if (e && e.error) {
            throw errors.runtimeError('INTERNAL-ERROR', { error: e.error });
        }

        var results = _.find(data.results, 'series') || {};

        if (!results.series) {
            return [];
        } else {
            return _.chain(results.series)
                .map(this.toNative.bind(this))
                .flatten()
                .sort(this._sort)
                .value();
        }
    }

    defaultTimeOptions() {
        return {
            from: this.from,
            to: this.to
        };
    }

    periodicLiveRead() {
        return this.queryOptions.raw === undefined;
    }

    read(from, to, limit, state) {
        var self = this;

        var parsedUrl = _.clone(this.url);
        var reqUrl = null;

        var queryOptions = _.extend({ to, from }, this.queryOptions);
        var query = this.queryBuilder.build(queryOptions, this.queryFilter);

        this.logger.debug(`Running query: ${query}`);

        _.extend(parsedUrl, { pathname: '/query', query: { 'q': query, 'db': this.db, 'epoch' : 'ms' } });

        return request.async({
            url: url.format(parsedUrl),
            method: 'GET'
        }).then((response) => {
            if (response.statusCode < 200 || response.statusCode >= 300) {
                throw errors.runtimeError('INTERNAL-ERROR', {
                    error: `${response.statusCode}: ${response.body} for ${reqUrl}`
                });
            }

            return {
                points: self.parse(JSON.parse(response.body)),
                readEnd: to || new JuttleMoment(Infinity)
            };
        }).catch((e) => {
            throw e;
        });
    }
}

module.exports = ReadInflux;
<|endoftext|>


<commit_before>/* Normalized hide address bar for iOS & Android (c) Scott Jehl, scottjehl.com MIT License */
(function(a){var b=a.document;if(!location.hash&&a.addEventListener){window.scrollTo(0,1);var c=1,d=function(){return a.pageYOffset||b.compatMode==="CSS1Compat"&&b.documentElement.scrollTop||b.body.scrollTop||0},e=setInterval(function(){if(b.body){clearInterval(e);c=d();a.scrollTo(0,c===1?0:1)}},15);a.addEventListener("load",function(){setTimeout(function(){if(d()<20){a.scrollTo(0,c===1?0:1)}},0)})}})(this);

/*! A fix for the iOS orientationchange zoom bug. Script by @scottjehl, rebound by @wilto.MIT License.*/
(function(m){var l=m.document;if(!l.querySelector){return}var n=l.querySelector("meta[name=viewport]"),a=n&&n.getAttribute("content"),k=a+",maximum-scale=1",d=a+",maximum-scale=10",g=true,j,i,h,c;if(!n){return}function f(){n.setAttribute("content",d);g=true}function b(){n.setAttribute("content",k);g=false}function e(o){c=o.accelerationIncludingGravity;j=Math.abs(c.x);i=Math.abs(c.y);h=Math.abs(c.z);if(!m.orientation&&(j>7||((h>6&&i<8||h<8&&i>6)&&j>5))){if(g){b()}}else{if(!g){f()}}}m.addEventListener("orientationchange",f,false);m.addEventListener("devicemotion",e,false)})(this);

(function(w){
	var sw = document.body.clientWidth,
		sh = document.body.clientHeight,
		breakpoint = 650,
		speed = 800,
		mobile = true;

	$(document).ready(function() {
		checkMobile();
		setNav();
		setImg();
	});

	$(w).resize(function(){ //Update dimensions on resize
		sw = document.body.clientWidth;
		sh = document.body.clientHeight;
		checkMobile();
	});

	//Check if Mobile
	function checkMobile() {
		mobile = (sw > breakpoint) ? false : true;
		if (!mobile) { //If Not Mobile
			loadAux();
			$('.aux header a').addClass('disabled').addClass('open');
			$('[role="tabpanel"],#nav,#search').show(); //Show full navigation and search
		} else { //Hide
			if(!$('#nav-anchors a').hasClass('active')) {
				$('#nav,#search').hide();
			}
		}
	}

	//Toggle navigation for small screens
	function setNav() {
		var $anchorLinks = $('#nav-anchors').find('a');
		$anchorLinks.click(function(e){
			e.preventDefault();
			var $this = $(this),
				thisHref = $this.attr('href');
			$('.reveal').hide();
			if($this.hasClass('active')) {
				$this.removeClass('active');
				$(thisHref).hide();
			} else {
				$anchorLinks.removeClass('active');
				$this.addClass('active');
				$(thisHref).show();
			}
		});
	}

	//Set up Image Carousel
	function setImg() {
		var container = $('#img-container'),
			nav = $('#product-img').find('nav'),
			imgList = Object,
			current = 0,
			swipeEnabled = false;

		function buildGallery() {
			container.html('

');
			imgList = $('#img-list');
			nav.find('li:first').addClass('active');

			var arr = '';<commit_msg>Added for each navigation link block<commit_after>/* Normalized hide address bar for iOS & Android (c) Scott Jehl, scottjehl.com MIT License */
(function(a){var b=a.document;if(!location.hash&&a.addEventListener){window.scrollTo(0,1);var c=1,d=function(){return a.pageYOffset||b.compatMode==="CSS1Compat"&&b.documentElement.scrollTop||b.body.scrollTop||0},e=setInterval(function(){if(b.body){clearInterval(e);c=d();a.scrollTo(0,c===1?0:1)}},15);a.addEventListener("load",function(){setTimeout(function(){if(d()<20){a.scrollTo(0,c===1?0:1)}},0)})}})(this);

/*! A fix for the iOS orientationchange zoom bug. Script by @scottjehl, rebound by @wilto.MIT License.*/
(function(m){var l=m.document;if(!l.querySelector){return}var n=l.querySelector("meta[name=viewport]"),a=n&&n.getAttribute("content"),k=a+",maximum-scale=1",d=a+",maximum-scale=10",g=true,j,i,h,c;if(!n){return}function f(){n.setAttribute("content",d);g=true}function b(){n.setAttribute("content",k);g=false}function e(o){c=o.accelerationIncludingGravity;j=Math.abs(c.x);i=Math.abs(c.y);h=Math.abs(c.z);if(!m.orientation&&(j>7||((h>6&&i<8||h<8&&i>6)&&j>5))){if(g){b()}}else{if(!g){f()}}}m.addEventListener("orientationchange",f,false);m.addEventListener("devicemotion",e,false)})(this);

(function(w){
	var sw = document.body.clientWidth,
		sh = document.body.clientHeight,
		breakpoint = 650,
		speed = 800,
		mobile = true;

	$(document).ready(function() {
		checkMobile();
		setNav();
		setImg();
	});

	$(w).resize(function(){ //Update dimensions on resize
		sw = document.body.clientWidth;
		sh = document.body.clientHeight;
		checkMobile();
	});

	//Check if Mobile
	function checkMobile() {
		mobile = (sw > breakpoint) ? false : true;
		if (!mobile) { //If Not Mobile
			loadAux();
			$('.aux header a').addClass('disabled').addClass('open');
			$('[role="tabpanel"],#nav,#search').show(); //Show full navigation and search
		} else { //Hide
			if(!$('#nav-anchors a').hasClass('active')) {
				$('#nav,#search').hide();
			}
		}
	}

	//Toggle navigation for small screens
	function setNav() {
		var $anchorLinks = $('#nav-anchors').find('a');
		$anchorLinks.click(function(e){
			e.preventDefault();
			var $this = $(this),
				thisHref = $this.attr('href');
			$('.reveal').hide();
			if($this.hasClass('active')) {
				$this.removeClass('active');
				$(thisHref).hide();
			} else {
				$anchorLinks.removeClass('active');
				$this.addClass('active');
				$(thisHref).show();
			}
		});
	}

	//Set up Image Carousel
	function setImg() {
		var container = $('#img-container'),
			nav = $('#product-img').find('nav'),
			imgList = Object,
			current = 0,
			swipeEnabled = false;

		function buildGallery() {
			container.html('

');
			imgList = $('#img-list');
			nav.find('li:first').addClass('active');

			var arr = '';

			//For Each Navigation Link
			nav.find('a').each(function() {
				var $this = $(this),
					href = $this.attr('href');<|endoftext|>


<commit_before>/**
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @fileoverview A utility to simplify the creation of fake events.
 */

goog.provide('shaka.util.FakeEvent');

goog.require('shaka.asserts');

/**
 * @namespace shaka.util.FakeEvent
 * @summary A utility to simplify the creation of fake events.
 */

/**
 * Return an Event object based on the dictionary.
 * The event should contain all of the same properties from the dict.
 * @param {!Object} dict
 * @return {!Event}
 */
shaka.util.FakeEvent.create = function(dict) {
  var event = new CustomEvent(dict.type, {
    detail: dict.detail,
    bubbles: !!dict.bubbles
  });
  // NOTE: In strict mode, we can't overwrite existing properties, so we only
  // set properties on "event" which don't exist yet.  If a property does exist
  // on "event", we assert that it has the correct value already.
  for (var key in dict) {
    if (key in event) {
      shaka.asserts.assert(event[key] == dict[key]);
    } else {
      event[key] = dict[key];
    }
  }
  return event;
};

/**
 * Return an 'error' Event object based on an Error object.
 * @param {!Error} error
 * @return {!Event}
 */
shaka.util.FakeEvent.createErrorEvent = function(error) {
  var event = new CustomEvent('error', {
    detail: error,
    bubbles: true
  });
  return event;
};

<commit_msg>Enhance FakeEvent assert output<commit_after>/**
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @fileoverview A utility to simplify the creation of fake events.
 */

goog.provide('shaka.util.FakeEvent');

goog.require('shaka.asserts');

/**
 * @namespace shaka.util.FakeEvent
 * @summary A utility to simplify the creation of fake events.
 */

/**
 * Return an Event object based on the dictionary.
 * The event should contain all of the same properties from the dict.
 * @param {!Object} dict
 * @return {!Event}
 */
shaka.util.FakeEvent.create = function(dict) {
  var event = new CustomEvent(dict.type, {
    detail: dict.detail,
    bubbles: !!dict.bubbles
  });
  // NOTE: In strict mode, we can't overwrite existing properties, so we only
  // set properties on "event" which don't exist yet.  If a property does exist
  // on "event", we assert that it has the correct value already.
  for (var key in dict) {
    if (key in event) {
      shaka.asserts.assert(event[key] == dict[key], 'key = ' + key);
    } else {
      event[key] = dict[key];
    }
  }
  return event;
};

/**
 * Return an 'error' Event object based on an Error object.
 * @param {!Error} error
 * @return {!Event}
 */
shaka.util.FakeEvent.createErrorEvent = function(error) {
  var event = new CustomEvent('error', {
    detail: error,
    bubbles: true
  });
  return event;
};

<|endoftext|>


<commit_before>/* Plugin for jQuery for working with colors.
 *
 * Version 1.1.
 *
 * Inspiration from jQuery color animation plugin by John Resig.
 *
 * Released under the MIT license by Ole Laursen, October 2009.
 *
 * Examples:
 *
 *   $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
 *   var c = $.color.extract($("#mydiv"), 'background-color');
 *   console.log(c.r, c.g, c.b, c.a);
 *   $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
 *
 * Note that .scale() and .add() return the same modified object
 * instead of making a new one.
 *
 * V. 1.1: Fix error handling so e.g. parsing an empty string does
 * produce a color rather than just crashing.
 */

(function($) {
    $.color = {};

    // construct color object with some convenient chainable helpers
    $.color.make = function (r, g, b, a) {
        var o = {};
        o.r = r || 0;
        o.g = g || 0;
        o.b = b || 0;
        o.a = a != null ? a : 1;

        o.add = function (c, d) {
            for (var i = 0; i < c.length; ++i)
                o[c.charAt(i)] += d;
            return o.normalize();
        };

        o.scale = function (c, f) {
            for (var i = 0; i < c.length; ++i)
                o[c.charAt(i)] *= f;
            return o.normalize();
        };

        o.toString = function () {
            if (o.a >= 1.0) {
                return "rgb("+[o.r, o.g, o.b].join(",")+")";
            } else {
                return "rgba("+[o.r, o.g, o.b, o.a].join(",")+")";
            }
        };

        o.normalize = function () {
            function clamp(min, value, max) {
                return value < min ? min: (value > max ? max: value);
            }

            o.r = clamp(0, parseInt(o.r), 255);
            o.g = clamp(0, parseInt(o.g), 255);
            o.b = clamp(0, parseInt(o.b), 255);
            o.a = clamp(0, o.a, 1);
            return o;
        };

        o.clone = function () {
            return $.color.make(o.r, o.b, o.g, o.a);
        };

        return o.normalize();
    }

    // extract CSS color property from element, going up in the DOM
    // if it's "transparent"
    $.color.extract = function (elem, css) {
        var c;
        var parentElm;
        do {
            c = elem.css(css).toLowerCase();
            // keep going until we find an element that has color, or
            // we hit the body or root (have no parent)
            if (c != '' && c != 'transparent')
                break;
            parentElm = elem.parent();
            if (null == parentElm.get(0)) {
                break;
            }
            elem = parentElm;
        } while (!$.nodeName(elem.get(0), "body"));

        // catch Safari's way of signalling transparent
        if (c == "rgba(0, 0, 0, 0)")
            c = "transparent";

        return $.color.parse(c);
    }

    // parse CSS color string (like "rgb(10, 32, 43)" or "#fff"),
    // returns color object, if parsing failed, you get black (0, 0,
    // 0) out
    $.color.parse = function (str) {
        var res, m = $.color.make;

        // Look for rgb(num,num,num)
        if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))
            return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10));

        // Look for rgba(num,num,num,num)
        if (res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
            return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4]));

        // Look for rgb(num%,num%,num%)
        if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))
            return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55);

        // Look for rgba(num%,num%,num%,num)
        if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
            return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55, parseFloat(res[4]));

        // Look for #a0b1c2
        if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))
            return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16));

        // Look for #fff
        if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))
            return m(parseInt(res[1]+res[1], 16), parseInt(res[2]+res[2], 16), parseInt(res[3]+res[3], 16));

        // Otherwise, we're most likely dealing with a named color
        var name = $.trim(str).toLowerCase();
        if (name == "transparent")
            return m(255, 255, 255, 0);
        else {
            // default to black
            res = lookupColors[name] || [0, 0, 0];
            return m(res[0], res[1], res[2]);
        }
    }

    var lookupColors = {
        aqua:[0,255,255],
        azure:[240,255,255],
        beige:[245,245,220],
        black:[0,0,0],
        blue:[0,0,255],
        brown:[165,42,42],
        cyan:[0,255,255],
        darkblue:[0,0,139],
        darkcyan:[0,139,139],
        darkgrey:[169,169,169],
        darkgreen:[0,100,0],
        darkkhaki:[189,183,107],
        darkmagenta:[139,0,139],
        darkolivegreen:[85,107,47],
        darkorange:[255,140,0],
        darkorchid:[153,50,204],
        darkred:[139,0,0],
        darksalmon:[233,150,122],
        darkviolet:[148,0,211],
        fuchsia:[255,0,255],
        gold:[255,215,0],
        green:[0,128,0],
        indigo:[75,0,130],
        khaki:[240,230,140],
        lightblue:[173,216,230],
        lightcyan:[224,255,255],
        lightgreen:[144,238,144],
        lightgrey:[211,211,211],
        lightpink:[255,182,193],
        lightyellow:[255,255,224],
        lime:[0,255,0],
        magenta:[255,0,255],
        maroon:[128,0,0],
        navy:[0,0,128],
        olive:[128,128,0],
        orange:[255,165,0],
        pink:[255,192,203],
        purple:[128,0,128],
        violet:[128,0,128],
        red:[255,0,0],
        silver:[192,192,192],
        white:[255,255,255],
        yellow:[255,255,0]
    };
})(jQuery);
<commit_msg>Slight cleanup / optimization for #1084.<commit_after>/* Plugin for jQuery for working with colors.
 *
 * Version 1.1.
 *
 * Inspiration from jQuery color animation plugin by John Resig.
 *
 * Released under the MIT license by Ole Laursen, October 2009.
 *
 * Examples:
 *
 *   $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
 *   var c = $.color.extract($("#mydiv"), 'background-color');
 *   console.log(c.r, c.g, c.b, c.a);
 *   $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
 *
 * Note that .scale() and .add() return the same modified object
 * instead of making a new one.
 *
 * V. 1.1: Fix error handling so e.g. parsing an empty string does
 * produce a color rather than just crashing.
 */

(function($) {
    $.color = {};

    // construct color object with some convenient chainable helpers
    $.color.make = function (r, g, b, a) {
        var o = {};
        o.r = r || 0;
        o.g = g || 0;
        o.b = b || 0;
        o.a = a != null ? a : 1;

        o.add = function (c, d) {
            for (var i = 0; i < c.length; ++i)
                o[c.charAt(i)] += d;
            return o.normalize();
        };

        o.scale = function (c, f) {
            for (var i = 0; i < c.length; ++i)
                o[c.charAt(i)] *= f;
            return o.normalize();
        };

        o.toString = function () {
            if (o.a >= 1.0) {
                return "rgb("+[o.r, o.g, o.b].join(",")+")";
            } else {
                return "rgba("+[o.r, o.g, o.b, o.a].join(",")+")";
            }
        };

        o.normalize = function () {
            function clamp(min, value, max) {
                return value < min ? min: (value > max ? max: value);
            }

            o.r = clamp(0, parseInt(o.r), 255);
            o.g = clamp(0, parseInt(o.g), 255);
            o.b = clamp(0, parseInt(o.b), 255);
            o.a = clamp(0, o.a, 1);
            return o;
        };

        o.clone = function () {
            return $.color.make(o.r, o.b, o.g, o.a);
        };

        return o.normalize();
    }

    // extract CSS color property from element, going up in the DOM
    // if it's "transparent"
    $.color.extract = function (elem, css) {
        var c;

        do {
            c = elem.css(css).toLowerCase();
            // keep going until we find an element that has color, or
            // we hit the body or root (have no parent)
            if (c != '' && c != 'transparent')
                break;
            elem = elem.parent();
        } while (elem.length && !$.nodeName(elem.get(0), "body"));

        // catch Safari's way of signalling transparent
        if (c == "rgba(0, 0, 0, 0)")
            c = "transparent";

        return $.color.parse(c);
    }

    // parse CSS color string (like "rgb(10, 32, 43)" or "#fff"),
    // returns color object, if parsing failed, you get black (0, 0,
    // 0) out
    $.color.parse = function (str) {
        var res, m = $.color.make;

        // Look for rgb(num,num,num)
        if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))
            return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10));

        // Look for rgba(num,num,num,num)
        if (res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
            return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4]));

        // Look for rgb(num%,num%,num%)
        if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))
            return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55);

        // Look for rgba(num%,num%,num%,num)
        if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
            return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55, parseFloat(res[4]));

        // Look for #a0b1c2
        if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))
            return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16));

        // Look for #fff
        if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))
            return m(parseInt(res[1]+res[1], 16), parseInt(res[2]+res[2], 16), parseInt(res[3]+res[3], 16));

        // Otherwise, we're most likely dealing with a named color
        var name = $.trim(str).toLowerCase();
        if (name == "transparent")
            return m(255, 255, 255, 0);
        else {
            // default to black
            res = lookupColors[name] || [0, 0, 0];
            return m(res[0], res[1], res[2]);
        }
    }

    var lookupColors = {
        aqua:[0,255,255],
        azure:[240,255,255],
        beige:[245,245,220],
        black:[0,0,0],
        blue:[0,0,255],
        brown:[165,42,42],
        cyan:[0,255,255],
        darkblue:[0,0,139],
        darkcyan:[0,139,139],
        darkgrey:[169,169,169],
        darkgreen:[0,100,0],
        darkkhaki:[189,183,107],
        darkmagenta:[139,0,139],
        darkolivegreen:[85,107,47],
        darkorange:[255,140,0],
        darkorchid:[153,50,204],
        darkred:[139,0,0],
        darksalmon:[233,150,122],
        darkviolet:[148,0,211],
        fuchsia:[255,0,255],
        gold:[255,215,0],
        green:[0,128,0],
        indigo:[75,0,130],
        khaki:[240,230,140],
        lightblue:[173,216,230],
        lightcyan:[224,255,255],
        lightgreen:[144,238,144],
        lightgrey:[211,211,211],
        lightpink:[255,182,193],
        lightyellow:[255,255,224],
        lime:[0,255,0],
        magenta:[255,0,255],
        maroon:[128,0,0],
        navy:[0,0,128],
        olive:[128,128,0],
        orange:[255,165,0],
        pink:[255,192,203],
        purple:[128,0,128],
        violet:[128,0,128],
        red:[255,0,0],
        silver:[192,192,192],
        white:[255,255,255],
        yellow:[255,255,0]
    };
})(jQuery);
<|endoftext|>


<commit_before>"use strict";

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return unescape(pair[1]);
    }
  }
}

$(window).load(function() {
  jQuery.loadErrors("slowparse/spec/", ["base", "forbidjs"], function() {
    var codeMirror = ParsingCodeMirror($("#source")[0], {
      mode: "text/html",
      theme: "jsbin",
      tabMode: "indent",
      lineWrapping: true,
      lineNumbers: true,
      parse: function(html) {
        return Slowparse.HTML(document, html, [TreeInspectors.forbidJS]);
      }
    });
    var cursorHelp = ContextSensitiveHelp({
      codeMirror: codeMirror,
      helpIndex: Help.Index(),
      template: _.template($("#help-template").text()),
      helpArea: $(".help")
    });
    var errorHelp = ErrorHelp({
      codeMirror: codeMirror,
      template: _.template($("#error-template").text()),
      errorArea: $(".error")
    });
    var preview = LivePreview({
      codeMirror: codeMirror,
      ignoreErrors: true,
      previewArea: $("#preview")
    });
    var publishUI = PublishUI({
      codeMirror: codeMirror,
      publisher: Publisher($("meta[name='publish-url']").attr("content")),
      dialog: $("#publish-dialog")
    });
    var historyUI = HistoryUI({
      codeMirror: codeMirror,
      undo: $("#undo_button"),
      redo: $("#redo_button")
    });
    var shareUI = ShareUI({
       codeMirror: codeMirror,
       dialog: $('#share-dialog')
    });
    var socialMedia = SocialMedia({
        jQuery: jQuery,
        getURL: function() {
          return $("#share-container .link-to-this a.view")[0].href;
        },
        container: $("#share-container")
    });
    var pageToLoad = getQueryVariable('p') || "default";
    var parachute = Parachute(window, codeMirror, pageToLoad, lscache);

    $("#save_button").click(function() { publishUI.saveCode(); });
    $("#share_button").click(function() { shareUI.shareCode(); });

    function doneLoading() {
      $("#editor").removeClass("loading");
      codeMirror.clearHistory();
      historyUI.refresh();
      if (parachute.restore()) {
        // Display a non-modal message telling the user that their
        // previous data has been restored, and that they can click 'undo'
        // to go back to the original version of the editor content.
        // This is just a temporary workaround to avoid confusion until
        // we figure out a better solution; see this issue for more
        // discussion:
        //
        // https://github.com/mozilla/webpagemaker/issues/53
        $("#undo_button").tipsy({
          gravity: 'n',
          fade: true,
          trigger: 'manual',
          title: 'data-restore-help'
        }).tipsy("show");
        setTimeout(function() { $("#undo_button").tipsy("hide"); }, 6000);
      } else {
        // Only save data on page unload if it's different from
        // the URL we just (hopefully) loaded.
        parachute.refresh();
      }
      codeMirror.reparse();
      codeMirror.focus();
    }

    if (pageToLoad == "default") {
      codeMirror.setValue($("#initial-html").text().trim());
      doneLoading();
    } else
      publishUI.loadCode(pageToLoad, doneLoading);

    // We're only exposing these as globals so we can debug via
    // the console. Other parts of our code should never reference them.
    window._codeMirror = codeMirror;
    window._parachute = parachute;
  });
});
<commit_msg>fixed bug in my last commit.<commit_after>"use strict";

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return unescape(pair[1]);
    }
  }
}

$(window).load(function() {
  jQuery.loadErrors("slowparse/spec/", ["base", "forbidjs"], function() {
    var codeMirror = ParsingCodeMirror($("#source")[0], {
      mode: "text/html",
      theme: "jsbin",
      tabMode: "indent",
      lineWrapping: true,
      lineNumbers: true,
      parse: function(html) {
        return Slowparse.HTML(document, html, [TreeInspectors.forbidJS]);
      }
    });
    var cursorHelp = ContextSensitiveHelp({
      codeMirror: codeMirror,
      helpIndex: Help.Index(),
      template: _.template($("#help-template").text()),
      helpArea: $(".help")
    });
    var errorHelp = ErrorHelp({
      codeMirror: codeMirror,
      template: _.template($("#error-template").text()),
      errorArea: $(".error")
    });
    var preview = LivePreview({
      codeMirror: codeMirror,
      ignoreErrors: true,
      previewArea: $("#preview")
    });
    var publisher = Publisher($("meta[name='publish-url']").attr("content"));
    var publishUI = PublishUI({
      codeMirror: codeMirror,
      publisher: publisher,
      dialog: $("#publish-dialog")
    });
    var historyUI = HistoryUI({
      codeMirror: codeMirror,
      undo: $("#undo_button"),
      redo: $("#redo_button")
    });
    var shareUI = ShareUI({
       codeMirror: codeMirror,
       dialog: $('#share-dialog'),
       publisher: publisher
    });
    var socialMedia = SocialMedia({
        jQuery: jQuery,
        getURL: function() {
          return $("#share-container .link-to-this a.view")[0].href;
        },
        container: $("#share-container")
    });
    var pageToLoad = getQueryVariable('p') || "default";
    var parachute = Parachute(window, codeMirror, pageToLoad, lscache);

    $("#save_button").click(function() { publishUI.saveCode(); });
    $("#share_button").click(function() { shareUI.shareCode(); });

    function doneLoading() {
      $("#editor").removeClass("loading");
      codeMirror.clearHistory();
      historyUI.refresh();
      if (parachute.restore()) {
        // Display a non-modal message telling the user that their
        // previous data has been restored, and that they can click 'undo'
        // to go back to the original version of the editor content.
        // This is just a temporary workaround to avoid confusion until
        // we figure out a better solution; see this issue for more
        // discussion:
        //
        // https://github.com/mozilla/webpagemaker/issues/53
        $("#undo_button").tipsy({
          gravity: 'n',
          fade: true,
          trigger: 'manual',
          title: 'data-restore-help'
        }).tipsy("show");
        setTimeout(function() { $("#undo_button").tipsy("hide"); }, 6000);
      } else {
        // Only save data on page unload if it's different from
        // the URL we just (hopefully) loaded.
        parachute.refresh();
      }
      codeMirror.reparse();
      codeMirror.focus();
    }

    if (pageToLoad == "default") {
      codeMirror.setValue($("#initial-html").text().trim());
      doneLoading();
    } else
      publishUI.loadCode(pageToLoad, doneLoading);

    // We're only exposing these as globals so we can debug via
    // the console. Other parts of our code should never reference them.
    window._codeMirror = codeMirror;
    window._parachute = parachute;
  });
});
<|endoftext|>


<commit_before>/* global complete, desc, directory, fail, jake, task */
"use strict";

desc("Full build.");
task("default", ["check node version", "lint", "test"]);

directory("build");

desc("Runs JSLint (to catch common JavaScript errors).");
task("lint", /* jshint latedef: false */ function() {
  var lint_runner = require("./src/build/lint/lint_runner.js");

  var allJavaScriptSources = new jake.FileList();
  allJavaScriptSources.include("**/*.js");
  allJavaScriptSources.exclude("node_modules");  // assuming these are properly linted, already.
  var passesLint = lint_runner.validateFileList(allJavaScriptSources, getJSHintOptions());

  if(!passesLint) { fail("Task 'lint' failed (see above)."); }
});

desc("Runs unit tests.");
task("test", ["build"], function() {
  var reporter = require('nodeunit').reporters.default;
  reporter.run(['src/specs/server'], null, function(failureOccurred) {
      if(failureOccurred) { fail("Task 'test' failed (see above)."); }
      complete();
    });
}, {async: true});

desc("Integration");
task("integrate", ["default"], function() {
  console.log("Steps for the commit tango...");
  console.log("1. Verify the build on the master branch, locally.\n   yourbox$ ./jake.sh\n");
  console.log("2. Pull to the Integation Station and verify the build there.\n   integration$ git pull && ./jake.sh\n");
  console.log("3. If all good, merge changes into 'last-known-good'\n   yourbox$ merge-to-integration.sh\n");
});

function getJSHintOptions() {
  return {
    bitwise: false,
    curly: true,
    eqeqeq: true,
    forin: true,
    immed: true,
    latedef: true,
    newcap: true,
    noarg: true,
    nonew: true,
    undef: true,
    unused: true,
    strict: true,
    trailing: true,
    maxstatements: 15,
    maxcomplexity: 10,
    node: true
  };
}

task("check node version", function() {
  var expectedNodeVersion = "v0.10.8";
  var actualNodeVersion = process.version;

  // since node.js is changes quite frequently, making this an exact match, for now.
  if(actualNodeVersion !== expectedNodeVersion) {
    fail(actualNodeVersion + " is an unsupported version of node.js.  Must be " + expectedNodeVersion);
  }
});

<commit_msg>Build script can create and purge the build directory.<commit_after>/* global complete, desc, directory, fail, jake, task */
"use strict";

var BUILD_DIR = "build";

desc("Full build.");
task("default", ["check node version", "clean", "lint", "test"]);

directory(BUILD_DIR);

desc("Purges the build output directory (i.e. " + BUILD_DIR + ").");
task("clean", function() {
  jake.rmRf(BUILD_DIR);
});

desc("Runs JSLint (to catch common JavaScript errors).");
task("lint", /* jshint latedef: false */ function() {
  var lint_runner = require("./src/build/lint/lint_runner.js");

  var allJavaScriptSources = new jake.FileList();
  allJavaScriptSources.include("**/*.js");
  allJavaScriptSources.exclude("node_modules");  // assuming these are properly linted, already.
  var passesLint = lint_runner.validateFileList(allJavaScriptSources, getJSHintOptions());

  if(!passesLint) { fail("Task 'lint' failed (see above)."); }
});

desc("Runs unit tests.");
task("test", [BUILD_DIR], function() {
  var reporter = require('nodeunit').reporters.default;
  reporter.run(['src/specs/server'], null, function(failureOccurred) {
      if(failureOccurred) { fail("Task 'test' failed (see above)."); }
      complete();
    });
}, {async: true});

desc("Integration");
task("integrate", ["default"], function() {
  console.log("Steps for the commit tango...");
  console.log("1. Verify the build on the master branch, locally.\n   yourbox$ ./jake.sh\n");
  console.log("2. Pull to the Integation Station and verify the build there.\n   integration$ git pull && ./jake.sh\n");
  console.log("3. If all good, merge changes into 'last-known-good'\n   yourbox$ merge-to-integration.sh\n");
});

function getJSHintOptions() {
  return {
    bitwise: false,
    curly: true,
    eqeqeq: true,
    forin: true,
    immed: true,
    latedef: true,
    newcap: true,
    noarg: true,
    nonew: true,
    undef: true,
    unused: true,
    strict: true,
    trailing: true,
    maxstatements: 15,
    maxcomplexity: 10,
    node: true
  };
}

task("check node version", function() {
  var expectedNodeVersion = "v0.10.8";
  var actualNodeVersion = process.version;

  // since node.js is changes quite frequently, making this an exact match, for now.
  if(actualNodeVersion !== expectedNodeVersion) {
    fail(actualNodeVersion + " is an unsupported version of node.js.  Must be " + expectedNodeVersion);
  }
});

<|endoftext|>


<commit_before>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("./log")
  , exec = require("./exec")
  , npm = require("../../npm")
  , path = require("path")
  , readJson = require("./read-json")
  , fs = require("fs")

function lifecycle (pkg, stage, cb) {
  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))
  if (!pkg.scripts || !(stage in pkg.scripts)) return cb()

  // run package lifecycle scripts in the package root, or the nearest parent.
  var d = path.join(npm.dir, pkg.name, pkg.version, "package")
  while (d) {
    try {
      process.chdir(d)
      break
    } catch (ex) {
      d = path.dirname(d)
    }
  }
  log(pkg._id, stage)

  // set the env variables, then run the script as a child process.
  // NOTE: The env vars won't work until node supports env hashes for child procs
  var env = makeEnv(pkg)
  env.npm_lifecycle_event = stage
  env.npm_lifecycle_script = pkg.scripts[stage]
  exec("sh", ["-c", env.npm_lifecycle_script], env, function (er) {
    if (er) {
      log("Failed to exec "+stage+" script", pkg._id)
      er.message = pkg._id + " " + stage + ": `" + env.npm_lifecycle_script+"`\n"
                 + er.message
      return cb(er)
    }
    // check for a hook script
    var hook = path.join(npm.dir, ".hooks", stage)
    fs.stat(hook, function (er) {
      if (er) return cb()
      exec(hook, env, function (er) {
        if (er) log("Failed to exec "+stage+" hook script", pkg._id)
        cb(er)
      })
    })
  })
}

function makeEnv (data, prefix, env) {
  if (data._lifecycleEnv) return data._lifecycleEnv
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) env[i] = process.env[i]
  } else {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    if (data[i] && typeof(data[i]) === "object") {
      env[prefix+i] = JSON.stringify(data[i])
      makeEnv(data[i], prefix+i+"_", env)
    } else {
      env[prefix+i] = String(data[i])
    }
  }
  if (prefix !== "npm_package_") return env
  prefix = "npm_config_"
  var conf = npm.config.get()
  for (var i in conf) if (i.charAt(0) !== "_") {
    env[prefix+i] = String(conf[i])
  }
  return env
}

function cmd (stage, req) { return function (args, cb) {
  var pkg = args[0]
    , ver = pkg.indexOf("/") !== -1 ? "" : (args[1] || "active")
    , json = path.join(npm.dir, pkg, ver, "package/package.json")
  readJson(json, function (er, data) {
    data.version = ver
    if (er) return log.er(cb, "Couldn't find "+path.join(pkg, ver))(er)
    if ( !data.scripts
        || !(stage in data.scripts)
        && !("pre"+stage in data.scripts)) {
      log("Nothing to do", stage)
      return cb(req ? new Error("Nothing to do") : null)
    }
    lifecycle(data, "pre"+stage, function (er) {
      if (er) return log.er(cb, "Failed pre"+stage)(er)
      lifecycle(data, stage, cb)
    })
  })
}}
<commit_msg>Update the lifecycle commands to follow the "name@version" convention, and also support multiple args<commit_after>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("./log")
  , exec = require("./exec")
  , npm = require("../../npm")
  , path = require("path")
  , readJson = require("./read-json")
  , fs = require("fs")

function lifecycle (pkg, stage, cb) {
  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))
  if (!pkg.scripts || !(stage in pkg.scripts)) return cb()

  // run package lifecycle scripts in the package root, or the nearest parent.
  var d = path.join(npm.dir, pkg.name, pkg.version, "package")
  while (d) {
    try {
      process.chdir(d)
      break
    } catch (ex) {
      d = path.dirname(d)
    }
  }
  log(pkg._id, stage)

  // set the env variables, then run the script as a child process.
  // NOTE: The env vars won't work until node supports env hashes for child procs
  var env = makeEnv(pkg)
  env.npm_lifecycle_event = stage
  env.npm_lifecycle_script = pkg.scripts[stage]
  exec("sh", ["-c", env.npm_lifecycle_script], env, function (er) {
    if (er) {
      log("Failed to exec "+stage+" script", pkg._id)
      er.message = pkg._id + " " + stage + ": `" + env.npm_lifecycle_script+"`\n"
                 + er.message
      return cb(er)
    }
    // check for a hook script
    var hook = path.join(npm.dir, ".hooks", stage)
    fs.stat(hook, function (er) {
      if (er) return cb()
      exec(hook, env, function (er) {
        if (er) log("Failed to exec "+stage+" hook script", pkg._id)
        cb(er)
      })
    })
  })
}

function makeEnv (data, prefix, env) {
  if (data._lifecycleEnv) return data._lifecycleEnv
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) env[i] = process.env[i]
  } else {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    if (data[i] && typeof(data[i]) === "object") {
      env[prefix+i] = JSON.stringify(data[i])
      makeEnv(data[i], prefix+i+"_", env)
    } else {
      env[prefix+i] = String(data[i])
    }
  }
  if (prefix !== "npm_package_") return env
  prefix = "npm_config_"
  var conf = npm.config.get()
  for (var i in conf) if (i.charAt(0) !== "_") {
    env[prefix+i] = String(conf[i])
  }
  return env
}

function cmd (stage, req) { return function (args, cb_) {
  var d = args.length
  function cb (er) {
    if (er) return cb_(er)
    if (-- d === 0) return cb_()
  }
  args.forEach(function (arg) {
    var pkg = arg.split("@")
      , name = pkg.shift()
      , ver = pkg.join("@")
      , json = path.join(npm.dir, name, ver || "active", "package/package.json")
    readJson(json, function (er, data) {
      if (er) return log.er(cb, "Couldn't find "+name + "@" + ver)(er)
      if (ver && ver !== data.version) {
        data.version = ver
        data._id = data.name+"-"+ver
      }
      if ( !data.scripts
          || !(stage in data.scripts)
          && !("pre"+stage in data.scripts)) {
        log("Nothing to do", stage)
        return cb(req ? new Error("Nothing to do") : null)
      }
      lifecycle(data, "pre"+stage, function (er) {
        if (er) return log.er(cb, "Failed pre"+stage)(er)
        lifecycle(data, stage, cb)
      })
    })
  })
}}
<|endoftext|>