<commit_before>var archiver = require("archiver");

var redis = require("redis");
var uuid = require('node-uuid');
var crypto = require('crypto');
var tar = require('tar-stream');
var async = require("async");

var client = require("redis").createClient();
var lock = require("redis-lock")(client);

var fs = require("fs");
var p = require("path");
var mkdirp = require("mkdirp");

var color = require("colors");

var store = "."; // default store

function createBucket(bucket, options, cb) {
	// Check if options replicate is true or false, nothing else
	var emptyMetaData = {
		name: bucket,
		replicate: options.replicate || false,
		files: {}
	};

	var exactFilePath = p.join(store, bucket);
	fs.stat(exactFilePath, function(err, stat) {
		if (err) {
			mkdirp(exactFilePath, function(err, stat) {
				var metaJSONString = JSON.stringify(emptyMetaData);
				var metaJSONPath = p.join(exactFilePath, "meta.json");
				fs.writeFile(metaJSONPath, metaJSONString, function(err) {
					cb(err, true);
				});
			});
		} else {
			cb(false);
		}
	});
}

/*
putFile("mustafa", "bigfile", fs.createReadStream("bigfile"), function(){
	client.end();
});
*/

/*
getFile("mustafa", "file1", 0, function(err, stream) {
	stream.on("data", function(data) {
		console.log(data.toString());
	});
	console.log("Error", err);
});
*/

function readMeta(bucket, cb) {
	var metaPath = p.join(store, bucket, "meta.json");
	fs.readFile(metaPath, function(err, data) {
		if (err) {
			cb(false);
		} else {
			var meta = JSON.parse(data);
			cb(meta);
		}
	});
}

function saveMeta(bucket, meta, cb) {
	var metaPath = p.join(store, bucket, "meta.json");
	var metaJSON = JSON.stringify(meta);

	fs.writeFile(metaPath, metaJSON, function(err) {
		cb(err);
	});
}

function getFile(bucket, path, timestamp, cb) {
	// Filter path for path traversal attacks
	// if 0 return latest
	var metaPath = p.join(store, bucket, "meta.json");
	fs.readFile(metaPath, function(err, data) {
		if (err) {
			cb("Meta data cannot be read");
		} else {
			var meta = JSON.parse(data);
			var files = meta.files;
			var file = meta.files[path];
			if (file) {
				var version = null;
				if (timestamp == 0) {
					var newest = 0;
					for (var time in file) {
						if (time > newest) {
							newest = time;
						}
					}
					version = file[newest];
				} else {
					version = file[timestamp];
				}
				if (version) {
					var streamPath = p.join(store, bucket, version.name);
					var stream = fs.createReadStream(streamPath);
					// Check if file exists here!
					cb(null, stream);
				} else {
					cb("File with given timestamp not found");
				}
			} else {
				cb("File not found");
			}
		}
	});
	// 1. Check if folder exists from disk
	// 2. If not exists, ask all peers by broadcasting (for one time checks, check key first to reduce network)
	// 3. If no one has data, return 404
	// 4. If data exists, stream from disk or network
}

function putFile(bucket, path, fileReadStream, putFileCallback) {
	lock("pagsfs-" + bucket, 10000, function(done) {
		readMeta(bucket, function(meta) {
			if (!meta) {
				putFileCallback(new Error("Metadata not found for: " + bucket));
			} else {

				// EMPTY FILE STREAM ERRORS!!!
				var files = meta.files;
				var file = meta.files[path];

				if (!file) {
					meta.files[path] = {}
				}

				// Check for replication status
				// Delete old copies if needed
				var objectName = uuid.v4();

				var objectPath = p.join(store, bucket, objectName);
				var fileWriteStream = fs.createWriteStream(objectPath);

				var hash = crypto.createHash('sha1');
				hash.setEncoding('hex');

				fileReadStream.on("error", function() {
					done();
					putFileCallback(new Error("Cannot read from stream" + bucket + ", " + path));
				});

				fileReadStream.on('end', function() {
					hash.end();
					var computedHash = hash.read();
					var time = (new Date()).getTime();
					meta.files[path][time] = {
						hash: computedHash,
						name: objectName,
					}

					saveMeta(bucket, meta, function(err) {
						putFileCallback(err);
						done();
					});
					// Sync!!
				});

				fileReadStream.pipe(hash);
				fileReadStream.pipe(fileWriteStream);
			}
		});
	});
	// 0. Lock folder
	// 1. Check if folder & file exists
	// 2. If file exists, version the old one and notify peers
	// 3. Stream the file to disk and other peers
	// Possible enhancement: Remove the old tar.gz
}

function oldestObjectInFile(file) {
	var newest = 0;
	for (var time in file) {
		if (time > newest) {
			newest = time;
		}
	}
	return file[newest];
}

function getBucket(bucket, getBucketCallback) {
	readMeta(bucket, function(meta) {
		if (!meta) {
			getBucketCallback(new Error("Bucket not found"));
		} else {
			var files = meta.files;
			var archive = archiver("tar");
			for (var filename in files) {
				var latest = oldestObjectInFile(files[filename]);
				if (!latest) {
					getBucketCallback(new Error("Internal error, file not found"));
					// empty file/non existent file
				} else {
					var objectPath = p.join(store, bucket, latest.name);
					archive.append(fs.createReadStream(objectPath), {
						name: filename
					});
				}
			}
			archive.finalize();
			getBucketCallback(null, archive);
		}
	});
	// 1. Check if folder exists from disk
	// 2. If folder does not exist, ask peers
	// 3. IF no one has data, return 404
	// 4. If data exists, stream tar
	// Possible enhancement: Determimne file date & cache .tar.gz
}

function putBucket(bucket, tarStream, putBucketCallback) {
	// Load all meta
	// Get the file list
	// Prepare a new meta by using old meta
	// Delete other contents
	lock("pagsfs-" + bucket, 10000, function(done) {
		readMeta(bucket, function(meta) {
			if (!meta) {
				putBucketCallback(new Error("no meta man wtf"));
			} else {
				// Unlink old files
				var toUnlink = [];
				for (var filename in meta.files) {
					var file = meta.files[filename];
					for (var timestamp in file) {
						toUnlink.push(file[timestamp].name);
					}
				}

				// Unlink files
				async.each(toUnlink, function(file, callback) {
					var filePath = p.join(store, bucket, file);
					fs.unlink(filePath, callback);
				}, function(err) {

					meta.files = {};

					var extract = tar.extract();

					extract.on('entry', function(header, entryStream, entryCallback) {
						var hash = crypto.createHash('sha1');
						hash.setEncoding('hex');

						var objectName = uuid.v4();
						var filePath = header.name;
						var destinationPath = p.join(store, bucket, objectName);
						var destinationStream = fs.createWriteStream(destinationPath);

						entryStream.on("error", function() {
							putBucketCallback(new Error("file read error"));
						});

						entryStream.on('end', function() {
							hash.end();
							var computedHash = hash.read();
							var time = (new Date()).getTime();

							meta.files[filePath] = {};
							meta.files[filePath][time] = {
								hash: computedHash,
								name: objectName,
							}
							entryCallback();
						});

						entryStream.pipe(hash);
						entryStream.pipe(destinationStream);
					});
					tarStream.pipe(extract);

					extract.on('finish', function(){
						saveMeta(bucket, meta, function(err) {
							putBucketCallback(err);
							done();
						});
					});
				});
			}
		});
	});
}

module.exports.setStore = function(givenStore){
	store = givenStore;
}

module.exports.getFile = getFile;
module.exports.putFile = putFile;
module.exports.getBucket = getBucket;
module.exports.putBucket = putBucket;<commit_msg>Removed Error object creation<commit_after>var archiver = require("archiver");

var redis = require("redis");
var uuid = require('node-uuid');
var crypto = require('crypto');
var tar = require('tar-stream');
var async = require("async");

var client = require("redis").createClient();
var lock = require("redis-lock")(client);

var fs = require("fs");
var p = require("path");
var mkdirp = require("mkdirp");

var color = require("colors");

var store = "."; // default store

function createBucket(bucket, options, cb) {
	// Check if options replicate is true or false, nothing else
	var emptyMetaData = {
		name: bucket,
		replicate: options.replicate || false,
		files: {}
	};

	var exactFilePath = p.join(store, bucket);
	fs.stat(exactFilePath, function(err, stat) {
		if (err) {
			mkdirp(exactFilePath, function(err, stat) {
				var metaJSONString = JSON.stringify(emptyMetaData);
				var metaJSONPath = p.join(exactFilePath, "meta.json");
				fs.writeFile(metaJSONPath, metaJSONString, function(err) {
					cb(err, true);
				});
			});
		} else {
			cb(false);
		}
	});
}

/*
putFile("mustafa", "bigfile", fs.createReadStream("bigfile"), function(){
	client.end();
});
*/

/*
getFile("mustafa", "file1", 0, function(err, stream) {
	stream.on("data", function(data) {
		console.log(data.toString());
	});
	console.log("Error", err);
});
*/

function readMeta(bucket, cb) {
	var metaPath = p.join(store, bucket, "meta.json");
	fs.readFile(metaPath, function(err, data) {
		if (err) {
			cb(false);
		} else {
			var meta = JSON.parse(data);
			cb(meta);
		}
	});
}

function saveMeta(bucket, meta, cb) {
	var metaPath = p.join(store, bucket, "meta.json");
	var metaJSON = JSON.stringify(meta);

	fs.writeFile(metaPath, metaJSON, function(err) {
		cb(err);
	});
}

function getFile(bucket, path, timestamp, cb) {
	// Filter path for path traversal attacks
	// if 0 return latest
	var metaPath = p.join(store, bucket, "meta.json");
	fs.readFile(metaPath, function(err, data) {
		if (err) {
			cb("Meta data cannot be read");
		} else {
			var meta = JSON.parse(data);
			var files = meta.files;
			var file = meta.files[path];
			if (file) {
				var version = null;
				if (timestamp == 0) {
					var newest = 0;
					for (var time in file) {
						if (time > newest) {
							newest = time;
						}
					}
					version = file[newest];
				} else {
					version = file[timestamp];
				}
				if (version) {
					var streamPath = p.join(store, bucket, version.name);
					var stream = fs.createReadStream(streamPath);
					// Check if file exists here!
					cb(null, stream);
				} else {
					cb("File with given timestamp not found");
				}
			} else {
				cb("File not found");
			}
		}
	});
	// 1. Check if folder exists from disk
	// 2. If not exists, ask all peers by broadcasting (for one time checks, check key first to reduce network)
	// 3. If no one has data, return 404
	// 4. If data exists, stream from disk or network
}

function putFile(bucket, path, fileReadStream, putFileCallback) {
	lock("pagsfs-" + bucket, 10000, function(done) {
		readMeta(bucket, function(meta) {
			if (!meta) {
				putFileCallback("Metadata not found for: " + bucket);
			} else {

				// EMPTY FILE STREAM ERRORS!!!
				var files = meta.files;
				var file = meta.files[path];

				if (!file) {
					meta.files[path] = {}
				}

				// Check for replication status
				// Delete old copies if needed
				var objectName = uuid.v4();

				var objectPath = p.join(store, bucket, objectName);
				var fileWriteStream = fs.createWriteStream(objectPath);

				var hash = crypto.createHash('sha1');
				hash.setEncoding('hex');

				fileReadStream.on("error", function() {
					done();
					putFileCallback("Cannot read from stream" + bucket + ", " + path);
				});

				fileReadStream.on('end', function() {
					hash.end();
					var computedHash = hash.read();
					var time = (new Date()).getTime();
					meta.files[path][time] = {
						hash: computedHash,
						name: objectName,
					}

					saveMeta(bucket, meta, function(err) {
						putFileCallback(err);
						done();
					});
					// Sync!!
				});

				fileReadStream.pipe(hash);
				fileReadStream.pipe(fileWriteStream);
			}
		});
	});
	// 0. Lock folder
	// 1. Check if folder & file exists
	// 2. If file exists, version the old one and notify peers
	// 3. Stream the file to disk and other peers
	// Possible enhancement: Remove the old tar.gz
}

function oldestObjectInFile(file) {
	var newest = 0;
	for (var time in file) {
		if (time > newest) {
			newest = time;
		}
	}
	return file[newest];
}

function getBucket(bucket, getBucketCallback) {
	readMeta(bucket, function(meta) {
		if (!meta) {
			getBucketCallback("Bucket not found");
		} else {
			var files = meta.files;
			var archive = archiver("tar");
			for (var filename in files) {
				var latest = oldestObjectInFile(files[filename]);
				if (!latest) {
					getBucketCallback("Internal error, file not found");
					// empty file/non existent file
				} else {
					var objectPath = p.join(store, bucket, latest.name);
					archive.append(fs.createReadStream(objectPath), {
						name: filename
					});
				}
			}
			archive.finalize();
			getBucketCallback(null, archive);
		}
	});
	// 1. Check if folder exists from disk
	// 2. If folder does not exist, ask peers
	// 3. IF no one has data, return 404
	// 4. If data exists, stream tar
	// Possible enhancement: Determimne file date & cache .tar.gz
}

function putBucket(bucket, tarStream, putBucketCallback) {
	// Load all meta
	// Get the file list
	// Prepare a new meta by using old meta
	// Delete other contents
	lock("pagsfs-" + bucket, 10000, function(done) {
		readMeta(bucket, function(meta) {
			if (!meta) {
				putBucketCallback("Meta not found");
			} else {
				// Unlink old files
				var toUnlink = [];
				for (var filename in meta.files) {
					var file = meta.files[filename];
					for (var timestamp in file) {
						toUnlink.push(file[timestamp].name);
					}
				}

				// Unlink files
				async.each(toUnlink, function(file, callback) {
					var filePath = p.join(store, bucket, file);
					fs.unlink(filePath, callback);
				}, function(err) {

					meta.files = {};

					var extract = tar.extract();

					extract.on('entry', function(header, entryStream, entryCallback) {
						var hash = crypto.createHash('sha1');
						hash.setEncoding('hex');

						var objectName = uuid.v4();
						var filePath = header.name;
						var destinationPath = p.join(store, bucket, objectName);
						var destinationStream = fs.createWriteStream(destinationPath);

						entryStream.on("error", function() {
							putBucketCallback("File cannot be read..");
						});

						entryStream.on('end', function() {
							hash.end();
							var computedHash = hash.read();
							var time = (new Date()).getTime();

							meta.files[filePath] = {};
							meta.files[filePath][time] = {
								hash: computedHash,
								name: objectName,
							}
							entryCallback();
						});

						entryStream.pipe(hash);
						entryStream.pipe(destinationStream);
					});
					tarStream.pipe(extract);

					extract.on('finish', function(){
						saveMeta(bucket, meta, function(err) {
							putBucketCallback(err);
							done();
						});
					});
				});
			}
		});
	});
}

module.exports.setStore = function(givenStore){
	store = givenStore;
}

module.exports.getFile = getFile;
module.exports.putFile = putFile;
module.exports.getBucket = getBucket;
module.exports.putBucket = putBucket;<|endoftext|>


<commit_before>exports.gcd = function(list) {
    if (list.length == 0) return 1

    var gcdInner = function(a, b) {
        if (!b) return a
        return gcdInner(b, a % b)
    }
    return gcdInner(list[0], exports.gcd(list.slice(1)))
}

exports.offsetToLinePos = function(offset, input) {
    var lines = input.split('\n').map(function(x) { return x + '\n' })

    var navigate = function(pos, step) {
        var line = pos[0], char = pos[1]

        if (char + step >= 0 && char + step < lines[line].length) {
            return [line, char + step]
        } else if (char + step < 0 && line > 0) {
            return navigate([line - 1, lines[line - 1].length - 1], char + step + 1)
        } else if (char + step >= lines[line].length && line + 1 < lines.length) {
            return navigate([line + 1, 0], char + step - lines[line].length)
        } else {
            return [lines.length - 1, lines[lines.length - 1].length - 1]
        }
    }

    var pos = navigate([0, 0], offset, lines)
    pos[0]++
    pos[1]++
    return pos
}

exports.getIndent = function(input) {
    var useTabs = null
    var indents = input.filter(function(x) {
        return x.trim() != ''
    }).map(function(x, i) {
        var whitespace = /^\s*/.exec(x)[0]

        if (whitespace.length != 0) {
            var tabs = whitespace.indexOf('\t') != -1
            if (useTabs === null) useTabs = tabs
            else if (useTabs != tabs) throw { line: i }
        }

        return whitespace.length
    })

    var indentDiffs = []

    for (var i = 1; i < indents.length; i++)
        indentDiffs.push(Math.abs(indents[i] - indents[i - 1]))

    return exports.gcd(indentDiffs)
}

exports.removeStringComments = function(input) {
    var commentsRemoved = ''
    var pureCode = ''
    var comments = []
    var offset = 0
    var residue = input
    var lineCounter = 1

    var rules = {
        doublestring: /^"("|.*?[^\\]"|.*?\\\\")/,
        singlestring: /^'('|.*?[^\\]'|.*?\\\\')/,
        singlecomment: /^\/\/.*/,
        blockcomment: /^\/\*[^]*?\*\//,
        purecode: /^([^"'\/]+|\/[^\/\*][^"'\/]*)+/
    }

    while (residue.length > 0) {
        var type = ''
        var value = ' '
        var length = 1

        for (var t in rules) {
            var matches = rules[t].exec(residue)
            if (!matches) continue

            type = t
            value = matches[0]
            length = value.length
            break
        }

        if (type.indexOf('comment') != -1) {
            // Add comment to comments
            comments.push([value, lineCounter])
        }

        for (var i = 0; i < value.length; i++) {
            var space = ' '
            if (value[i] == '\n') {
                space = '\n'
                lineCounter++
            }

            if (type.indexOf('comment') != -1) commentsRemoved += space
            else commentsRemoved += value[i]

            if (type == 'purecode') pureCode += value[i]
            else pureCode += space
        }

        residue = residue.substr(length)
        offset += length
    }

    return [commentsRemoved, pureCode, comments]
}

exports.indentifizer = function(input, pureCode) {
    input = input.split('\n')
    pureCode = pureCode.split('\n')

    var indentLength = exports.getIndent(input)
    var depth = 0
    var lastIndex = 0
    var indentDepths = []

    for (var i = 0; i < input.length; i++) {
        if (pureCode[i].trim() == '') continue
        var linedepth = /^\s*/.exec(input[i])[0].length / indentLength

        if (i != 0) {
            if (linedepth > depth) {
                var trimmed = pureCode[lastIndex].trim()

                if (trimmed[trimmed.length - 1] == ':') {
                    input[lastIndex] += ' #INDENT'
                    indentDepths.push(depth)
                }
            }

            for (var j = 0; j < depth - linedepth; j++) {
                if (indentDepths[indentDepths.length - 1] == depth - j - 1) {
                    input[lastIndex] += ' #DEINDENT'
                    indentDepths.splice(indentDepths.length - 1, 1)
                }
            }
        }

        depth = linedepth
        lastIndex = i
    }

    for (var i = 0; i < indentDepths.length; i++)
         input[lastIndex] += ' #DEINDENT'

    input = input.join('\n').replace(/\s*$/, '')
    return input
}

exports.commentator = function(input, src, comments) {
    var r = exports.removeStringComments(input)
    var pureCode = r[1]
    var lastReportedLine = -5

    pureCode = pureCode.split('\n')
    lines = input.split('\n')

    for (var i = 0; i < lines.length; i++) {
        var index = pureCode[i].search(/#OFFSET\d+$/)
        if (index == -1) continue

        var offset = parseInt(pureCode[i].substr(index + 7))
        var indent = pureCode[i].match(/^\s*/)[0]
        r = exports.offsetToLinePos(offset, src)

        var row = r[0], col = r[1]
        lines[i] = null

        if (comments.length > 0 && comments[0][1] <= row) {
            lines[i] = '\n' + indent + comments[0][0]
            comments.splice(0, 1)
        } else if (i - lastReportedLine >= 5) {
            lines[i] = indent + '/*@' + row + ':' + col + '*/'
            lastReportedLine = i
        }
    }

    return lines.filter(function(x) {
        return x !== null
    }).join('\n')
}
<commit_msg>Remove regex in preprocessing<commit_after>exports.gcd = function(list) {
    if (list.length == 0) return 1

    var gcdInner = function(a, b) {
        if (!b) return a
        return gcdInner(b, a % b)
    }
    return gcdInner(list[0], exports.gcd(list.slice(1)))
}

exports.offsetToLinePos = function(offset, input) {
    var lines = input.split('\n').map(function(x) { return x + '\n' })

    var navigate = function(pos, step) {
        var line = pos[0], char = pos[1]

        if (char + step >= 0 && char + step < lines[line].length) {
            return [line, char + step]
        } else if (char + step < 0 && line > 0) {
            return navigate([line - 1, lines[line - 1].length - 1], char + step + 1)
        } else if (char + step >= lines[line].length && line + 1 < lines.length) {
            return navigate([line + 1, 0], char + step - lines[line].length)
        } else {
            return [lines.length - 1, lines[lines.length - 1].length - 1]
        }
    }

    var pos = navigate([0, 0], offset, lines)
    pos[0]++
    pos[1]++
    return pos
}

exports.getIndent = function(input) {
    var useTabs = null
    var indents = input.filter(function(x) {
        return x.trim() != ''
    }).map(function(x, i) {
        var whitespace = /^\s*/.exec(x)[0]

        if (whitespace.length != 0) {
            var tabs = whitespace.indexOf('\t') != -1
            if (useTabs === null) useTabs = tabs
            else if (useTabs != tabs) throw { line: i }
        }

        return whitespace.length
    })

    var indentDiffs = []

    for (var i = 1; i < indents.length; i++)
        indentDiffs.push(Math.abs(indents[i] - indents[i - 1]))

    return exports.gcd(indentDiffs)
}

exports.removeStringComments = function(input) {
    var commentsRemoved = ''
    var pureCode = ''
    var comments = []
    var offset = 0
    var residue = input
    var lineCounter = 1

    var rules = {
        doublestring: /^"("|[^]*?[^\\]"|[^]*?\\\\")/,
        singlestring: /^'('|[^]*?[^\\]'|[^]*?\\\\')/,
        regexstring: /^\/(.*?[^\\]\/|.*?\\\\\/)[gim]*/,
        singlecomment: /^\/\/.*/,
        blockcomment: /^\/\*[^]*?\*\//,
        purecode: /^[^"'\/]+/
    }

    while (residue.length > 0) {
        var type = 'purecode'
        var value = residue[0]
        var length = 1

        for (var t in rules) {
            var matches = rules[t].exec(residue)
            if (!matches) continue

            type = t
            value = matches[0]
            length = value.length
            break
        }

        if (type.indexOf('comment') != -1) {
            // Add comment to comments
            comments.push([value, lineCounter])
        }

        for (var i = 0; i < value.length; i++) {
            var space = ' '
            if (value[i] == '\n') {
                space = '\n'
                lineCounter++
            }

            if (type.indexOf('comment') != -1) commentsRemoved += space
            else commentsRemoved += value[i]

            if (type == 'purecode') pureCode += value[i]
            else pureCode += space
        }

        residue = residue.substr(length)
        offset += length
    }

    return [commentsRemoved, pureCode, comments]
}

exports.indentifizer = function(input, pureCode) {
    input = input.split('\n')
    pureCode = pureCode.split('\n')

    var indentLength = exports.getIndent(input)
    var depth = 0
    var lastIndex = 0
    var indentDepths = []

    for (var i = 0; i < input.length; i++) {
        if (pureCode[i].trim() == '') continue
        var linedepth = /^\s*/.exec(input[i])[0].length / indentLength

        if (i != 0) {
            if (linedepth > depth) {
                var trimmed = pureCode[lastIndex].trim()

                if (trimmed[trimmed.length - 1] == ':') {
                    input[lastIndex] += ' #INDENT'
                    indentDepths.push(depth)
                }
            }

            for (var j = 0; j < depth - linedepth; j++) {
                if (indentDepths[indentDepths.length - 1] == depth - j - 1) {
                    input[lastIndex] += ' #DEINDENT'
                    indentDepths.splice(indentDepths.length - 1, 1)
                }
            }
        }

        depth = linedepth
        lastIndex = i
    }

    for (var i = 0; i < indentDepths.length; i++)
         input[lastIndex] += ' #DEINDENT'

    input = input.join('\n').replace(/\s*$/, '')
    return input
}

exports.commentator = function(input, src, comments) {
    var r = exports.removeStringComments(input)
    var pureCode = r[1]
    var lastReportedLine = -5

    pureCode = pureCode.split('\n')
    lines = input.split('\n')

    for (var i = 0; i < lines.length; i++) {
        var index = pureCode[i].search(/#OFFSET\d+$/)
        if (index == -1) continue

        var offset = parseInt(pureCode[i].substr(index + 7))
        var indent = pureCode[i].match(/^\s*/)[0]
        r = exports.offsetToLinePos(offset, src)

        var row = r[0], col = r[1]
        lines[i] = null

        if (comments.length > 0 && comments[0][1] <= row) {
            lines[i] = '\n' + indent + comments[0][0]
            comments.splice(0, 1)
        } else if (i - lastReportedLine >= 5) {
            lines[i] = indent + '/*@' + row + ':' + col + '*/'
            lastReportedLine = i
        }
    }

    return lines.filter(function(x) {
        return x !== null
    }).join('\n')
}
<|endoftext|>


<commit_before>
NGApp.factory('ViewListService', function($location, $timeout, $interval) {

	var service = {};

	service.view = function(params) {
		var scope = params.scope;
		var query = $location.search();
		var defaultLimit = query.limit || (App.isMobile() ? 5 : 20);

		scope.query = {
			limit: defaultLimit,
			page: query.page || 1
		};
		scope.query.page = parseInt(scope.query.page);

		var timer = undefined;
		var last_search = null;

		var watch = function() {
			var new_search = JSON.stringify( scope.query );
			if( new_search == last_search ){
				return;
			}
			last_search = new_search;
			$location.search(scope.query);
			if( angular.isDefined( timer ) ) {
				$interval.cancel( timer );
				timer = undefined;
				console.log('cancelingggg');
			}
			timer = $interval(function(){
				$interval.cancel( timer );
				timer = undefined;
				update();
				console.log('updaring');
			}, 1500 );
		};

		// @todo: this breaks linking to pages
		var inputWatch = function() {
			if (scope.query.page != 1) {
				scope.query.page = 1;
			} else {
				watch();
			}
		};

		scope.watch = function(vars) {
			for (var x in vars) {
				scope.query[x] = query[x] || vars[x];
				if( x ){
					scope.$watch('query.' + x, inputWatch);
				}
			}
		};

		scope.count = 0;
		scope.pages = 0;

		scope.allowAll = params.allowAll ? true : false;

		scope.$watch('query.limit', inputWatch);
		scope.$watch('query.page', watch);

		scope.setPage = function(page) {
			scope.query.page = page;
			App.scrollTop(0);
		};

		scope.viewAll = function() {
			if (!scope.allowAll) {
				return;
			}
			scope.query.page = 1;
			scope.query.limit = 'none';
		};

		scope.viewLess = function() {
			if (!scope.allowAll) {
				return;
			}
			scope.query.page = 1;
			scope.query.limit = defaultLimit;
		};

		scope.sort = function(by) {
			if (scope.query.sort == by) {
				scope.query.sort = '-' + by;
			} else {
				scope.query.sort = by;
			}
		};

		var updater = function(){};

		scope.update = function(fn) {
			if (fn) {
				updater = fn;
			} else {
				update();
			}
		};

		scope.loader = false;

		scope.complete = function(d) {
			scope.count = d.count;
			scope.pages = d.pages;

			if (scope.loader) {
				clearTimeout(scope.loader);
				scope.loader = setTimeout(function() {
					scope.scope.$apply(function() {
						scope.loading = false;
					});
				},100);
			} else {
				scope.loading = false;
			}
		};

		var update = function() {
			timer = undefined;
			scope.loading = true;
			updater();
		};

		if (!App.isPhoneGap) {
			scope.focus('#search');
		}

		scope.watch(params.watch);
		scope.update(params.update);
	}

	return service;
});
<commit_msg>Allow search on Settlement Drivers list #5453<commit_after>
NGApp.factory('ViewListService', function($location, $timeout, $interval) {

	var service = {};

	service.view = function(params) {
		var scope = params.scope;
		var query = $location.search();
		var defaultLimit = query.limit || (App.isMobile() ? 5 : 20);

		scope.query = {
			limit: defaultLimit,
			page: query.page || 1
		};
		scope.query.page = parseInt(scope.query.page);

		var timer = undefined;
		var last_search = null;

		var watch = function() {
			var new_search = JSON.stringify( scope.query );
			if( new_search == last_search ){
				return;
			}
			last_search = new_search;
			$location.search(scope.query);
			if( angular.isDefined( timer ) ) {
				$interval.cancel( timer );
				timer = undefined;
			}
			timer = $interval(function(){
				$interval.cancel( timer );
				timer = undefined;
				update();
			}, 1000 );
		};

		// @todo: this breaks linking to pages
		var inputWatch = function() {
			if (scope.query.page != 1) {
				scope.query.page = 1;
			} else {
				watch();
			}
		};

		scope.watch = function(vars) {
			for (var x in vars) {
				scope.query[x] = query[x] || vars[x];
				if( x ){
					scope.$watch('query.' + x, inputWatch);
				}
			}
		};

		scope.count = 0;
		scope.pages = 0;

		scope.allowAll = params.allowAll ? true : false;

		scope.$watch('query.limit', inputWatch);
		scope.$watch('query.page', watch);

		scope.setPage = function(page) {
			scope.query.page = page;
			App.scrollTop(0);
		};

		scope.viewAll = function() {
			if (!scope.allowAll) {
				return;
			}
			scope.query.page = 1;
			scope.query.limit = 'none';
		};

		scope.viewLess = function() {
			if (!scope.allowAll) {
				return;
			}
			scope.query.page = 1;
			scope.query.limit = defaultLimit;
		};

		scope.sort = function(by) {
			if (scope.query.sort == by) {
				scope.query.sort = '-' + by;
			} else {
				scope.query.sort = by;
			}
		};

		var updater = function(){};

		scope.update = function(fn) {
			if (fn) {
				updater = fn;
			} else {
				update();
			}
		};

		scope.loader = false;

		scope.complete = function(d) {
			scope.count = d.count;
			scope.pages = d.pages;

			if (scope.loader) {
				clearTimeout(scope.loader);
				scope.loader = setTimeout(function() {
					scope.scope.$apply(function() {
						scope.loading = false;
					});
				},100);
			} else {
				scope.loading = false;
			}
		};

		var update = function() {
			timer = undefined;
			scope.loading = true;
			updater();
		};

		if (!App.isPhoneGap) {
			scope.focus('#search');
		}

		scope.watch(params.watch);
		scope.update(params.update);
	}

	return service;
});
<|endoftext|>


<commit_before>/*global define document canvas*/
define(['../Renderer/TextureAtlas',
        '../Core/Color',
        '../Scene/BillboardCollection'],
function(TextureAtlas,
         Color,
         BillboardCollection) {
    "use strict";

    function DynamicPointVisualizer(scene) {
        this._scene = scene;
        this._unusedIndexes = [];

        var billboardCollection = this._billboardCollection = new BillboardCollection();
        scene.getPrimitives().add(billboardCollection);

        var atlas = new TextureAtlas(scene.getContext());
        this._textureAtlas = atlas;
        billboardCollection.setTextureAtlas(atlas);
    }

    DynamicPointVisualizer.prototype.update = function(time, czmlObjects) {
        for ( var i = 0, len = czmlObjects.length; i < len; i++) {
            this.updateObject(time, czmlObjects[i]);
        }
    };

    DynamicPointVisualizer.prototype.updateObject = function(time, czmlObject) {
        var dynamicPoint = czmlObject.point;
        if (typeof dynamicPoint === 'undefined') {
            return;
        }

        var positionProperty = czmlObject.position;
        if (typeof positionProperty === 'undefined') {
            return;
        }

        var billboard;
        var objectId = czmlObject.id;
        var showProperty = dynamicPoint.show;
        var pointVisualizerIndex = czmlObject.pointVisualizerIndex;
        var show = typeof showProperty === 'undefined' || showProperty.getValue(time);

        if (!show) {
            //don't bother creating or updating anything else
            if (typeof pointVisualizerIndex !== 'undefined') {
                billboard = this._billboardCollection.get(pointVisualizerIndex);
                billboard.setShow(false);
                billboard.point_color = undefined;
                billboard.point_outlineColor = undefined;
                billboard.point_outlineWidth = undefined;
                billboard.point_pixelSize = undefined;
                czmlObject.pointVisualizerIndex = undefined;
                this._unusedIndexes.push(pointVisualizerIndex);
            }
            return;
        }

        var needRedraw = false;
        if (typeof pointVisualizerIndex === 'undefined') {
            needRedraw = true;
            var unusedIndexes = this._unusedIndexes;
            var length = unusedIndexes.length;
            if (length > 0) {
                pointVisualizerIndex = unusedIndexes.pop();
                billboard = this._billboardCollection.get(pointVisualizerIndex);
            } else {
                pointVisualizerIndex = this._billboardCollection.getLength();
                billboard = this._billboardCollection.add();
            }
            czmlObject.pointVisualizerIndex = pointVisualizerIndex;
            billboard.id = objectId;
        } else {
            billboard = this._billboardCollection.get(pointVisualizerIndex);
        }

        billboard.setShow(true);

        var position = positionProperty.getValueCartesian(time);
        if (position !== 'undefined') {
            billboard.setPosition(position);
        }

        var color;
        var property = dynamicPoint.color;
        if (typeof property !== 'undefined') {
            color = property.getValue(time);
            if (billboard.point_color !== color) {
                billboard.point_color = color;
                needRedraw = true;
            }
        }

        var outlineColor;
        property = dynamicPoint.outlineColor;
        if (typeof property !== 'undefined') {
            outlineColor = property.getValue(time);
            if (billboard.point_outlineColor !== outlineColor) {
                billboard.point_outlineColor = outlineColor;
                needRedraw = true;
            }
        }

        var outlineWidth;
        property = dynamicPoint.outlineWidth;
        if (typeof property !== 'undefined') {
            outlineWidth = property.getValue(time);
            if (billboard.point_outlineWidth !== outlineWidth) {
                billboard.point_outlineWidth = outlineWidth;
                needRedraw = true;
            }
        }

        var pixelSize;
        property = dynamicPoint.pixelSize;
        if (typeof property !== 'undefined') {
            pixelSize = property.getValue(time);
            if (billboard.point_pixelSize !== pixelSize) {
                billboard.point_pixelSize = pixelSize;
                needRedraw = true;
            }
        }

        if (needRedraw) {
            var cssColor = color ? color.toCSSColor() : "#FFFFFF";
            var cssOutlineColor = outlineColor ? outlineColor.toCSSColor() : "#000000";
            pixelSize = pixelSize || 3;
            outlineWidth = outlineWidth || 2;

            var textureId = JSON.stringify({
                color : cssColor,
                pixelSize : pixelSize,
                outlineColor : cssOutlineColor,
                outlineWidth : outlineWidth
            });

            this._textureAtlas.addTextureFromFunction(textureId, function(loadedCallback) {
                var canvas = document.createElement("canvas");

                var length = pixelSize + (2 * outlineWidth);
                canvas.height = canvas.width = length;

                var context2D = canvas.getContext("2d");
                context2D.clearRect(0, 0, length, length);

                if (outlineWidth) {
                    context2D.beginPath();
                    context2D.arc(length / 2, length / 2, length / 2, 0, 2 * Math.PI, true);
                    context2D.closePath();
                    context2D.fillStyle = cssOutlineColor;
                    context2D.fill();
                }

                context2D.beginPath();
                context2D.arc(length / 2, length / 2, pixelSize / 2, 0, 2 * Math.PI, true);
                context2D.closePath();
                context2D.fillStyle = cssColor;
                context2D.fill();

                var imageData = context2D.getImageData(0, 0, canvas.width, canvas.height);
                var pixels = imageData.data;
                var limit = canvas.width * canvas.height * 4;
                for ( var i = 3; i < limit; i += 4) {
                    if (pixels[i] < 200) {
                        pixels[i] = 0;
                    }
                }

                loadedCallback(imageData);
            }, function(imageIndex) {
                billboard.setImageIndex(imageIndex);
            });
        }
    };

    DynamicPointVisualizer.prototype.removeAll = function(czmlObjects) {
        this._unusedIndexes = [];
        this._billboardCollection.removeAll();

        for ( var i = 0, len = czmlObjects.length; i < len; i++) {
            czmlObjects.pointVisualizerIndex = undefined;
        }
    };

    return DynamicPointVisualizer;
});<commit_msg>Fix DynamicPointVisualizer after last merge.<commit_after>/*global define document canvas*/
define(['../Renderer/TextureAtlas',
        '../Core/Color',
        '../Scene/BillboardCollection'],
function(TextureAtlas,
         Color,
         BillboardCollection) {
    "use strict";

    function DynamicPointVisualizer(scene) {
        this._scene = scene;
        this._unusedIndexes = [];

        var billboardCollection = this._billboardCollection = new BillboardCollection();
        scene.getPrimitives().add(billboardCollection);

        var atlas = new TextureAtlas(scene.getContext());
        this._textureAtlas = atlas;
        billboardCollection.setTextureAtlas(atlas);
    }

    DynamicPointVisualizer.prototype.update = function(time, czmlObjects) {
        for ( var i = 0, len = czmlObjects.length; i < len; i++) {
            this.updateObject(time, czmlObjects[i]);
        }
    };

    DynamicPointVisualizer.prototype.updateObject = function(time, czmlObject) {
        var dynamicPoint = czmlObject.point;
        if (typeof dynamicPoint === 'undefined') {
            return;
        }

        var positionProperty = czmlObject.position;
        if (typeof positionProperty === 'undefined') {
            return;
        }

        var billboard;
        var objectId = czmlObject.id;
        var showProperty = dynamicPoint.show;
        var pointVisualizerIndex = czmlObject.pointVisualizerIndex;
        var show = typeof showProperty === 'undefined' || showProperty.getValue(time);

        if (!show) {
            //don't bother creating or updating anything else
            if (typeof pointVisualizerIndex !== 'undefined') {
                billboard = this._billboardCollection.get(pointVisualizerIndex);
                billboard.setShow(false);
                billboard.point_color = undefined;
                billboard.point_outlineColor = undefined;
                billboard.point_outlineWidth = undefined;
                billboard.point_pixelSize = undefined;
                czmlObject.pointVisualizerIndex = undefined;
                this._unusedIndexes.push(pointVisualizerIndex);
            }
            return;
        }

        var needRedraw = false;
        if (typeof pointVisualizerIndex === 'undefined') {
            needRedraw = true;
            var unusedIndexes = this._unusedIndexes;
            var length = unusedIndexes.length;
            if (length > 0) {
                pointVisualizerIndex = unusedIndexes.pop();
                billboard = this._billboardCollection.get(pointVisualizerIndex);
            } else {
                pointVisualizerIndex = this._billboardCollection.getLength();
                billboard = this._billboardCollection.add();
            }
            czmlObject.pointVisualizerIndex = pointVisualizerIndex;
            billboard.id = objectId;
        } else {
            billboard = this._billboardCollection.get(pointVisualizerIndex);
        }

        billboard.setShow(true);

        var position = positionProperty.getValueCartesian(time);
        if (position !== 'undefined') {
            billboard.setPosition(position);
        }

        var color;
        var property = dynamicPoint.color;
        if (typeof property !== 'undefined') {
            color = property.getValue(time);
            if (billboard.point_color !== color) {
                billboard.point_color = color;
                needRedraw = true;
            }
        }

        var outlineColor;
        property = dynamicPoint.outlineColor;
        if (typeof property !== 'undefined') {
            outlineColor = property.getValue(time);
            if (billboard.point_outlineColor !== outlineColor) {
                billboard.point_outlineColor = outlineColor;
                needRedraw = true;
            }
        }

        var outlineWidth;
        property = dynamicPoint.outlineWidth;
        if (typeof property !== 'undefined') {
            outlineWidth = property.getValue(time);
            if (billboard.point_outlineWidth !== outlineWidth) {
                billboard.point_outlineWidth = outlineWidth;
                needRedraw = true;
            }
        }

        var pixelSize;
        property = dynamicPoint.pixelSize;
        if (typeof property !== 'undefined') {
            pixelSize = property.getValue(time);
            if (billboard.point_pixelSize !== pixelSize) {
                billboard.point_pixelSize = pixelSize;
                needRedraw = true;
            }
        }

        if (needRedraw) {
            var cssColor = color ? color.toCSSColor() : "#FFFFFF";
            var cssOutlineColor = outlineColor ? outlineColor.toCSSColor() : "#000000";
            pixelSize = pixelSize || 3;
            outlineWidth = outlineWidth || 2;

            var textureId = JSON.stringify({
                color : cssColor,
                pixelSize : pixelSize,
                outlineColor : cssOutlineColor,
                outlineWidth : outlineWidth
            });

            this._textureAtlas.addTextureFromFunction(textureId, function(id, loadedCallback) {
                var canvas = document.createElement("canvas");

                var length = pixelSize + (2 * outlineWidth);
                canvas.height = canvas.width = length;

                var context2D = canvas.getContext("2d");
                context2D.clearRect(0, 0, length, length);

                if (outlineWidth) {
                    context2D.beginPath();
                    context2D.arc(length / 2, length / 2, length / 2, 0, 2 * Math.PI, true);
                    context2D.closePath();
                    context2D.fillStyle = cssOutlineColor;
                    context2D.fill();
                }

                context2D.beginPath();
                context2D.arc(length / 2, length / 2, pixelSize / 2, 0, 2 * Math.PI, true);
                context2D.closePath();
                context2D.fillStyle = cssColor;
                context2D.fill();

                var imageData = context2D.getImageData(0, 0, canvas.width, canvas.height);
                var pixels = imageData.data;
                var limit = canvas.width * canvas.height * 4;
                for ( var i = 3; i < limit; i += 4) {
                    if (pixels[i] < 200) {
                        pixels[i] = 0;
                    }
                }

                loadedCallback(imageData);
            }, function(imageIndex) {
                billboard.setImageIndex(imageIndex);
            });
        }
    };

    DynamicPointVisualizer.prototype.removeAll = function(czmlObjects) {
        this._unusedIndexes = [];
        this._billboardCollection.removeAll();

        for ( var i = 0, len = czmlObjects.length; i < len; i++) {
            czmlObjects.pointVisualizerIndex = undefined;
        }
    };

    return DynamicPointVisualizer;
});<|endoftext|>


<commit_before>define(['./indexOf'], function (indexOf) {

    /**
     * Inserts item to array if not already present.
     * @author André Cruz
     * @version 0.1.0 (2012/01/28)
     */
    function include(arr, val) {
        if (indexOf(arr, val) === -1) {
            arr.push(val);
            return true;
        } else {
            return false;
        }
    }
    return include;
});
<commit_msg>Fix another typo.<commit_after>define(['./indexOf'], function (indexOf) {

    /**
     * Insert item into array if not already present.
     * @author André Cruz
     * @version 0.1.0 (2012/01/28)
     */
    function include(arr, val) {
        if (indexOf(arr, val) === -1) {
            arr.push(val);
            return true;
        } else {
            return false;
        }
    }
    return include;
});
<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/defaultValue',
        '../Core/jsonp',
        '../Core/loadImage',
        '../Core/getImagePixels',
        '../Core/writeTextToCanvas',
        '../Core/DeveloperError',
        '../Core/Math',
        '../Core/BoundingSphere',
        '../Core/Cartesian2',
        '../Core/Cartesian3',
        '../Core/Cartographic',
        '../Core/Extent',
        '../Core/TaskProcessor',
        './Projections',
        './TileState',
        './TerrainProvider',
        './GeographicTilingScheme',
        './WebMercatorTilingScheme',
        '../ThirdParty/when'
    ], function(
        defaultValue,
        jsonp,
        loadImage,
        getImagePixels,
        writeTextToCanvas,
        DeveloperError,
        CesiumMath,
        BoundingSphere,
        Cartesian2,
        Cartesian3,
        Cartographic,
        Extent,
        TaskProcessor,
        Projections,
        TileState,
        TerrainProvider,
        GeographicTilingScheme,
        WebMercatorTilingScheme,
        when) {
    "use strict";

    /**
     * A {@link TerrainProvider} that produces geometry by tessellating height maps
     * retrieved from a Tile Map Service (TMS) server.
     *
     * @alias TileMapServiceTerrainProvider
     * @constructor
     *
     * @param {String} description.url The URL of the TMS service.
     * @param {Object} [description.proxy] A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL, if needed.
     *
     * @see TerrainProvider
     */
    function TileMapServiceTerrainProvider(description) {
        description = defaultValue(description, {});

        if (typeof description.url === 'undefined') {
            throw new DeveloperError('description.url is required.');
        }

        /**
         * The URL of the ArcGIS ImageServer.
         * @type {String}
         */
        this.url = description.url;

        /**
         * The tiling scheme used to tile the surface.
         *
         * @type TilingScheme
         */
        this.tilingScheme = new GeographicTilingScheme({
            numberOfLevelZeroTilesX : 2,
            numberOfLevelZeroTilesY : 1
        });
        this.maxLevel = 11;
        this.heightmapWidth = 64;
        this.levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(this.tilingScheme.ellipsoid, this.heightmapWidth, this.tilingScheme.numberOfLevelZeroTilesX);

        this._proxy = description.proxy;

        this.ready = true;
    }

    /**
     * Gets the maximum geometric error allowed in a tile at a given level.
     *
     * @param {Number} level The tile level for which to get the maximum geometric error.
     * @returns {Number} The maximum geometric error.
     */
    TileMapServiceTerrainProvider.prototype.getLevelMaximumGeometricError = TerrainProvider.prototype.getLevelMaximumGeometricError;

    var requestsInFlight = 0;
    // Creating the geometry will require a request to the ImageServer, which will complete
    // asynchronously.  The question is, what do we do in the meantime?  The best thing to do is
    // to use terrain associated with the parent tile.  Ideally, we would be able to render
    // high-res imagery attached to low-res terrain.  In some ways, this is similar to the need
    // described in TerrainProvider of creating geometry for tiles at a higher level than
    // the terrain source actually provides.

    // In the short term, for simplicity:
    // 1. If a tile has geometry available but it has not yet been loaded, don't render the tile until
    //    the geometry has been loaded.
    // 2. If a tile does not have geometry available at all, do not render it or its siblings.
    // Longer term, #1 may be acceptable, but #2 won't be for the reasons described above.
    // To address #2, we can subdivide a mesh into its four children.  This will be fairly CPU
    // intensive, though, which is why we probably won't want to do it while waiting for the
    // actual data to load.  We could also potentially add fractal detail when subdividing.

    /**
     * Request the tile geometry from the remote server.  Once complete, the
     * tile state should be set to RECEIVED.  Alternatively, tile state can be set to
     * UNLOADED to indicate that the request should be attempted again next update, if the tile
     * is still needed.
     *
     * @param {Tile} The tile to request geometry for.
     */
    TileMapServiceTerrainProvider.prototype.requestTileGeometry = function(tile) {
        if (requestsInFlight > 6) {
            tile.state = TileState.UNLOADED;
            return;
        }

        ++requestsInFlight;

        var yTiles = this.tilingScheme.numberOfLevelZeroTilesY << tile.level;

        var url = this.url + '/' + tile.level + '/' + tile.x + '/' + (yTiles - tile.y - 1) + '.png';

        if (typeof this._proxy !== 'undefined') {
            url = this._proxy.getURL(url);
        }

        when(loadImage(url, true), function(image) {
            tile.geometry = image;
            tile.state = TileState.RECEIVED;
            --requestsInFlight;
        }, function(e) {
            /*global console*/
            console.error('failed to load tile geometry: ' + e);
            tile.state = TileState.FAILED;
            --requestsInFlight;
        });
    };

    var taskProcessor = new TaskProcessor('createVerticesFromHeightmap');

    /**
     * Transform the tile geometry from the format requested from the remote server
     * into a format suitable for resource creation.  Once complete, the tile
     * state should be set to TRANSFORMED.  Alternatively, tile state can be set to
     * RECEIVED to indicate that the transformation should be attempted again next update, if the tile
     * is still needed.
     *
     * @param {Context} context The context to use to create resources.
     * @param {Tile} tile The tile to transform geometry for.
     */
    TileMapServiceTerrainProvider.prototype.transformGeometry = function(context, tile) {
        // Get the height data from the image by copying it to a canvas.
        var image = tile.geometry;
        var width = image.width;
        var height = image.height;
        var pixels = getImagePixels(image);

        var tilingScheme = this.tilingScheme;
        var ellipsoid = tilingScheme.ellipsoid;
        var extent = this.tilingScheme.tileXYToNativeExtent(tile.x, tile.y, tile.level);

        tile.center = ellipsoid.cartographicToCartesian(tile.extent.getCenter());

        var verticesPromise = taskProcessor.scheduleTask({
            heightmap : pixels,
            heightScale : 1000.0,
            heightOffset : 1000.0,
            bytesPerHeight : 3,
            stride : 4,
            width : width,
            height : height,
            extent : extent,
            relativeToCenter : tile.center,
            radiiSquared : ellipsoid.getRadiiSquared(),
            oneOverCentralBodySemimajorAxis : ellipsoid.getOneOverRadii().x,
            skirtHeight : Math.min(this.getLevelMaximumGeometricError(tile.level) * 10.0, 1000.0),
            isGeographic : true
        }, [pixels.buffer]);

        if (typeof verticesPromise === 'undefined') {
            //postponed
            tile.state = TileState.RECEIVED;
            return;
        }

        when(verticesPromise, function(result) {
            tile.geometry = undefined;
            tile.transformedGeometry = {
                vertices : result.vertices,
                statistics : result.statistics,
                indices : TerrainProvider.getRegularGridIndices(width + 2, height + 2)
            };
            tile.state = TileState.TRANSFORMED;
        }, function(e) {
            /*global console*/
            console.error('failed to transform geometry: ' + e);
            tile.state = TileState.FAILED;
        });
    };

    var scratch = new Cartesian3();

    /**
     * Create WebGL resources for the tile using whatever data the transformGeometry step produced.
     * Once complete, the tile state should be set to READY.  Alternatively, tile state can be set to
     * TRANSFORMED to indicate that resource creation should be attempted again next update, if the tile
     * is still needed.
     *
     * @param {Context} context The context to use to create resources.
     * @param {Tile} tile The tile to create resources for.
     */
    TileMapServiceTerrainProvider.prototype.createResources = function(context, tile) {
        var buffers = tile.transformedGeometry;
        tile.transformedGeometry = undefined;

        TerrainProvider.createTileEllipsoidGeometryFromBuffers(context, tile, buffers);
        tile.maxHeight = buffers.statistics.maxHeight;
        tile.boundingSphere3D = BoundingSphere.fromFlatArray(buffers.vertices, tile.center, 5);

        var ellipsoid = this.tilingScheme.ellipsoid;
        var extent = tile.extent;
        tile.southwestCornerCartesian = ellipsoid.cartographicToCartesian(extent.getSouthwest());
        tile.southeastCornerCartesian = ellipsoid.cartographicToCartesian(extent.getSoutheast());
        tile.northeastCornerCartesian = ellipsoid.cartographicToCartesian(extent.getNortheast());
        tile.northwestCornerCartesian = ellipsoid.cartographicToCartesian(extent.getNorthwest());

        tile.westNormal = Cartesian3.UNIT_Z.cross(tile.southwestCornerCartesian.negate(scratch), scratch).normalize();
        tile.eastNormal = tile.northeastCornerCartesian.negate(scratch).cross(Cartesian3.UNIT_Z, scratch).normalize();
        tile.southNormal = ellipsoid.geodeticSurfaceNormal(tile.southeastCornerCartesian).cross(tile.southwestCornerCartesian.subtract(tile.southeastCornerCartesian, scratch)).normalize();
        tile.northNormal = ellipsoid.geodeticSurfaceNormal(tile.northwestCornerCartesian).cross(tile.northeastCornerCartesian.subtract(tile.northwestCornerCartesian, scratch)).normalize();

        tile.state = TileState.READY;
    };

    /**
     * Populates a {@link Tile} with plane-mapped surface geometry from this
     * tile provider.
     *
     * @memberof ArcGisImageServerTerrainProvider
     *
     * @param {Context} context The rendered context to use to create renderer resources.
     * @param {Tile} tile The tile to populate with surface geometry.
     * @param {Projection} projection The map projection to use.
     * @returns {Boolean|Promise} A boolean value indicating whether the tile was successfully
     * populated with geometry, or a promise for such a value in the future.
     */
    TileMapServiceTerrainProvider.prototype.createTilePlaneGeometry = function(context, tile, projection) {
        throw new DeveloperError('Not supported yet.');
    };

    /**
     * DOC_TBA
     * @memberof ArcGisImageServerTerrainProvider
     */
    TileMapServiceTerrainProvider.prototype.getLogo = function() {
        return this._logo;
    };

    return TileMapServiceTerrainProvider;
});<commit_msg>cleanup.<commit_after>/*global define*/
define([
        '../Core/defaultValue',
        '../Core/jsonp',
        '../Core/loadImage',
        '../Core/getImagePixels',
        '../Core/writeTextToCanvas',
        '../Core/DeveloperError',
        '../Core/Math',
        '../Core/BoundingSphere',
        '../Core/Cartesian2',
        '../Core/Cartesian3',
        '../Core/Cartographic',
        '../Core/Extent',
        '../Core/TaskProcessor',
        './Projections',
        './TileState',
        './TerrainProvider',
        './GeographicTilingScheme',
        './WebMercatorTilingScheme',
        '../ThirdParty/when'
    ], function(
        defaultValue,
        jsonp,
        loadImage,
        getImagePixels,
        writeTextToCanvas,
        DeveloperError,
        CesiumMath,
        BoundingSphere,
        Cartesian2,
        Cartesian3,
        Cartographic,
        Extent,
        TaskProcessor,
        Projections,
        TileState,
        TerrainProvider,
        GeographicTilingScheme,
        WebMercatorTilingScheme,
        when) {
    "use strict";

    /**
     * A {@link TerrainProvider} that produces geometry by tessellating height maps
     * retrieved from a Tile Map Service (TMS) server.
     *
     * @alias TileMapServiceTerrainProvider
     * @constructor
     *
     * @param {String} description.url The URL of the TMS service.
     * @param {Object} [description.proxy] A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL, if needed.
     *
     * @see TerrainProvider
     */
    function TileMapServiceTerrainProvider(description) {
        description = defaultValue(description, {});

        if (typeof description.url === 'undefined') {
            throw new DeveloperError('description.url is required.');
        }

        /**
         * The URL of the ArcGIS ImageServer.
         * @type {String}
         */
        this.url = description.url;

        /**
         * The tiling scheme used to tile the surface.
         *
         * @type TilingScheme
         */
        this.tilingScheme = new GeographicTilingScheme({
            numberOfLevelZeroTilesX : 2,
            numberOfLevelZeroTilesY : 1
        });
        this.maxLevel = 11;
        this.heightmapWidth = 64;
        this.levelZeroMaximumGeometricError = TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap(this.tilingScheme.ellipsoid, this.heightmapWidth, this.tilingScheme.numberOfLevelZeroTilesX);

        this._proxy = description.proxy;

        this.ready = true;
    }

    /**
     * Gets the maximum geometric error allowed in a tile at a given level.
     *
     * @param {Number} level The tile level for which to get the maximum geometric error.
     * @returns {Number} The maximum geometric error.
     */
    TileMapServiceTerrainProvider.prototype.getLevelMaximumGeometricError = TerrainProvider.prototype.getLevelMaximumGeometricError;

    var requestsInFlight = 0;
    // Creating the geometry will require a request to the ImageServer, which will complete
    // asynchronously.  The question is, what do we do in the meantime?  The best thing to do is
    // to use terrain associated with the parent tile.  Ideally, we would be able to render
    // high-res imagery attached to low-res terrain.  In some ways, this is similar to the need
    // described in TerrainProvider of creating geometry for tiles at a higher level than
    // the terrain source actually provides.

    // In the short term, for simplicity:
    // 1. If a tile has geometry available but it has not yet been loaded, don't render the tile until
    //    the geometry has been loaded.
    // 2. If a tile does not have geometry available at all, do not render it or its siblings.
    // Longer term, #1 may be acceptable, but #2 won't be for the reasons described above.
    // To address #2, we can subdivide a mesh into its four children.  This will be fairly CPU
    // intensive, though, which is why we probably won't want to do it while waiting for the
    // actual data to load.  We could also potentially add fractal detail when subdividing.

    /**
     * Request the tile geometry from the remote server.  Once complete, the
     * tile state should be set to RECEIVED.  Alternatively, tile state can be set to
     * UNLOADED to indicate that the request should be attempted again next update, if the tile
     * is still needed.
     *
     * @param {Tile} The tile to request geometry for.
     */
    TileMapServiceTerrainProvider.prototype.requestTileGeometry = function(tile) {
        if (requestsInFlight > 6) {
            tile.state = TileState.UNLOADED;
            return;
        }

        ++requestsInFlight;

        var yTiles = this.tilingScheme.numberOfLevelZeroTilesY << tile.level;

        var url = this.url + '/' + tile.level + '/' + tile.x + '/' + (yTiles - tile.y - 1) + '.png';

        if (typeof this._proxy !== 'undefined') {
            url = this._proxy.getURL(url);
        }

        when(loadImage(url, true), function(image) {
            tile.geometry = image;
            tile.state = TileState.RECEIVED;
            --requestsInFlight;
        }, function(e) {
            /*global console*/
            console.error('failed to load tile geometry: ' + e);
            tile.state = TileState.FAILED;
            --requestsInFlight;
        });
    };

    var taskProcessor = new TaskProcessor('createVerticesFromHeightmap');

    /**
     * Transform the tile geometry from the format requested from the remote server
     * into a format suitable for resource creation.  Once complete, the tile
     * state should be set to TRANSFORMED.  Alternatively, tile state can be set to
     * RECEIVED to indicate that the transformation should be attempted again next update, if the tile
     * is still needed.
     *
     * @param {Context} context The context to use to create resources.
     * @param {Tile} tile The tile to transform geometry for.
     */
    TileMapServiceTerrainProvider.prototype.transformGeometry = function(context, tile) {
        // Get the height data from the image by copying it to a canvas.
        var image = tile.geometry;
        var width = image.width;
        var height = image.height;
        var pixels = getImagePixels(image);

        var tilingScheme = this.tilingScheme;
        var ellipsoid = tilingScheme.ellipsoid;
        var extent = tilingScheme.tileXYToNativeExtent(tile.x, tile.y, tile.level);

        tile.center = ellipsoid.cartographicToCartesian(tile.extent.getCenter());

        var verticesPromise = taskProcessor.scheduleTask({
            heightmap : pixels,
            heightScale : 1000.0,
            heightOffset : 1000.0,
            bytesPerHeight : 3,
            stride : 4,
            width : width,
            height : height,
            extent : extent,
            relativeToCenter : tile.center,
            radiiSquared : ellipsoid.getRadiiSquared(),
            oneOverCentralBodySemimajorAxis : ellipsoid.getOneOverRadii().x,
            skirtHeight : Math.min(this.getLevelMaximumGeometricError(tile.level) * 10.0, 1000.0),
            isGeographic : true
        }, [pixels.buffer]);

        if (typeof verticesPromise === 'undefined') {
            //postponed
            tile.state = TileState.RECEIVED;
            return;
        }

        when(verticesPromise, function(result) {
            tile.geometry = undefined;
            tile.transformedGeometry = {
                vertices : result.vertices,
                statistics : result.statistics,
                indices : TerrainProvider.getRegularGridIndices(width + 2, height + 2)
            };
            tile.state = TileState.TRANSFORMED;
        }, function(e) {
            /*global console*/
            console.error('failed to transform geometry: ' + e);
            tile.state = TileState.FAILED;
        });
    };

    var scratch = new Cartesian3();

    /**
     * Create WebGL resources for the tile using whatever data the transformGeometry step produced.
     * Once complete, the tile state should be set to READY.  Alternatively, tile state can be set to
     * TRANSFORMED to indicate that resource creation should be attempted again next update, if the tile
     * is still needed.
     *
     * @param {Context} context The context to use to create resources.
     * @param {Tile} tile The tile to create resources for.
     */
    TileMapServiceTerrainProvider.prototype.createResources = function(context, tile) {
        var buffers = tile.transformedGeometry;
        tile.transformedGeometry = undefined;

        TerrainProvider.createTileEllipsoidGeometryFromBuffers(context, tile, buffers);
        tile.maxHeight = buffers.statistics.maxHeight;
        tile.boundingSphere3D = BoundingSphere.fromFlatArray(buffers.vertices, tile.center, 5);

        var ellipsoid = this.tilingScheme.ellipsoid;
        var extent = tile.extent;
        tile.southwestCornerCartesian = ellipsoid.cartographicToCartesian(extent.getSouthwest());
        tile.southeastCornerCartesian = ellipsoid.cartographicToCartesian(extent.getSoutheast());
        tile.northeastCornerCartesian = ellipsoid.cartographicToCartesian(extent.getNortheast());
        tile.northwestCornerCartesian = ellipsoid.cartographicToCartesian(extent.getNorthwest());

        tile.westNormal = Cartesian3.UNIT_Z.cross(tile.southwestCornerCartesian.negate(scratch), scratch).normalize();
        tile.eastNormal = tile.northeastCornerCartesian.negate(scratch).cross(Cartesian3.UNIT_Z, scratch).normalize();
        tile.southNormal = ellipsoid.geodeticSurfaceNormal(tile.southeastCornerCartesian).cross(tile.southwestCornerCartesian.subtract(tile.southeastCornerCartesian, scratch)).normalize();
        tile.northNormal = ellipsoid.geodeticSurfaceNormal(tile.northwestCornerCartesian).cross(tile.northeastCornerCartesian.subtract(tile.northwestCornerCartesian, scratch)).normalize();

        tile.state = TileState.READY;
    };

    /**
     * Populates a {@link Tile} with plane-mapped surface geometry from this
     * tile provider.
     *
     * @memberof ArcGisImageServerTerrainProvider
     *
     * @param {Context} context The rendered context to use to create renderer resources.
     * @param {Tile} tile The tile to populate with surface geometry.
     * @param {Projection} projection The map projection to use.
     * @returns {Boolean|Promise} A boolean value indicating whether the tile was successfully
     * populated with geometry, or a promise for such a value in the future.
     */
    TileMapServiceTerrainProvider.prototype.createTilePlaneGeometry = function(context, tile, projection) {
        throw new DeveloperError('Not supported yet.');
    };

    /**
     * DOC_TBA
     * @memberof ArcGisImageServerTerrainProvider
     */
    TileMapServiceTerrainProvider.prototype.getLogo = function() {
        return this._logo;
    };

    return TileMapServiceTerrainProvider;
});<|endoftext|>


<commit_before>var socket = io();

socket.on('news', function (data) {
	alert (data.width+"x"+data.height)
});

socket.on('liveStream', function(url) {
  $('#stream').attr('src', url);
});

window.addEventListener("load", function(){
  var StartStreamButton = document.getElementById('StartStreamButton');
  StartStreamButton.addEventListener('click', function() {
    var sW = document.getElementById("streamcontainer").offsetWidth
    var sH = document.getElementById("streamcontainer").offsetHeight
    socket.emit('start-stream', { width : sW, height : sH });
  });

  var StopStreamButton = document.getElementById('StopStreamButton');
  StopStreamButton.addEventListener('click', function() {
    socket.emit('stop-stream');
  });

});
<commit_msg>changing how we acquire stream element on dashboard<commit_after>var socket = io();

socket.on('news', function (data) {
	alert (data.width+"x"+data.height)
});

socket.on('liveStream', function(url) {
  var stream = document.getElementById('stream');
  stream.attr('src', url);
});

window.addEventListener("load", function(){
  var StartStreamButton = document.getElementById('StartStreamButton');
  StartStreamButton.addEventListener('click', function() {
    var sW = document.getElementById("streamcontainer").offsetWidth
    var sH = document.getElementById("streamcontainer").offsetHeight
    socket.emit('start-stream', { width : sW, height : sH });
  });

  var StopStreamButton = document.getElementById('StopStreamButton');
  StopStreamButton.addEventListener('click', function() {
    socket.emit('stop-stream');
  });

});
<|endoftext|>


<commit_before>/**
 * Resources
 *
 * https://gist.github.com/2489540
 *
 */

/*global config:true, task:true*/
module.exports = function( grunt ) {

	// readOptionalJSON
	// by Ben Alman
	// https://gist.github.com/2876125
	function readOptionalJSON( filepath ) {
		var data = {};
		try {
			data = grunt.file.readJSON(filepath);
			grunt.log.write( "Reading data from " + filepath + "..." ).ok();
		} catch(e) {}
		return data;
	}

	var task = grunt.task;
	var file = grunt.file;
	var utils = grunt.utils;
	var log = grunt.log;
	var verbose = grunt.verbose;
	var fail = grunt.fail;
	var option = grunt.option;
	var config = grunt.config;
	var template = grunt.template;
	var distpaths = [
		"dist/jquery.js",
		"dist/jquery.min.js"
	];

	grunt.initConfig({
		pkg: "<json:package.json>",
		dst: readOptionalJSON("dist/.destination.json"),
		meta: {
			banner: "/*! jQuery v@<%= pkg.version %> jquery.com | jquery.org/license */"
		},
		compare_size: {
			files: distpaths
		},
		selector: {
			"src/selector.js": [
				"src/sizzle-jquery.js",
				"src/sizzle/sizzle.js"
			]
		},
		build: {
			"dist/jquery.js": [
				"src/intro.js",
				"src/core.js",
				"src/callbacks.js",
				"src/deferred.js",
				"src/support.js",
				"src/data.js",
				"src/queue.js",
				"src/attributes.js",
				"src/event.js",
				"src/selector.js",
				"src/traversing.js",
				"src/manipulation.js",
				"src/css.js",
				"src/ajax.js",
				"src/ajax/jsonp.js",
				"src/ajax/script.js",
				"src/ajax/xhr.js",
				{ flag: "effects", src: "src/effects.js" },
				{ flag: "offset", src: "src/offset.js" },
				{ flag: "dimensions", src: "src/dimensions.js" },
				"src/exports.js",
				"src/outro.js"
			]
		},
		min: {
			"dist/jquery.min.js": [ "<banner>", "dist/jquery.js" ]
		},
		lint: {
			files: [ "grunt.js", "dist/jquery.js" ]
		},
		qunit: {
			files: "test/index.html"
		},
		watch: {
			files: [ "<config:lint.files>", "src/**/*.js" ],
			tasks: "dev"
		},
		jshint: {
			options: {
				evil: true,
				browser: true,
				wsh: true,
				eqnull: true,
				expr: true,
				curly: true,
				trailing: true,
				undef: true,
				smarttabs: true,
				predef: [
					"define",
					"DOMParser",
					"__dirname"
				],
				maxerr: 100
			},
			globals: {
				jQuery: true,
				global: true,
				module: true,
				exports: true,
				require: true,
				file: true,
				log: true,
				console: true
			}
		},
		uglify: {}
	});

	// Default grunt.
	grunt.registerTask( "default", "submodules selector build:*:* dist:* lint min compare_size" );

	// Short list as a high frequency watch task
	grunt.registerTask( "dev", "selector build:*:* lint" );

	// Load the "compare_size" task from NPM packages
	grunt.loadNpmTasks("grunt-compare-size");

	grunt.registerTask( "testswarm", function( commit, configFile ) {
		var testswarm = require( "testswarm" ),
			testUrls = [];
		var tests = "ajax attributes callbacks core css data deferred dimensions effects event manipulation offset queue selector support traversing".split( " " );
		tests.forEach(function( test ) {
			testUrls.push( "http://swarm.jquery.org/git/jquery/" + commit + "/test/index.html?filter=" + test );
		});
		testswarm({
			url: "http://swarm.jquery.org/",
			pollInterval: 10000,
			timeout: 1000 * 60 * 30,
			done: this.async()
		}, {
			authUsername: "jquery",
			authToken: grunt.file.readJSON( configFile ).jquery.authToken,
			jobName: 'jQuery commit #' + commit.substr( 0, 10 ) + '',
			runMax: 4,
			"runNames[]": tests,
			"runUrls[]": testUrls,
			"browserSets[]": ["popular"]
		});
	});

	// Build src/selector.js
	grunt.registerMultiTask( "selector", "Build src/selector.js", function() {

		var name = this.file.dest,
				files = this.file.src,
				sizzle = {
					api: file.read( files[0] ),
					src: file.read( files[1] )
				},
				compiled;

		// sizzle-jquery.js -> sizzle after "EXPOSE", replace window.Sizzle
		compiled = sizzle.src.replace( "window.Sizzle = Sizzle;", sizzle.api );
		verbose.write("Injected sizzle-jquery.js into sizzle.js");

		// Write concatenated source to file
		file.write( name, compiled );

		// Fail task if errors were logged.
		if ( this.errorCount ) {
			return false;
		}

		// Otherwise, print a success message.
		log.writeln( "File '" + name + "' created." );
	});

	// Special concat/build task to handle various jQuery build requirements
	grunt.registerMultiTask(
		"build",
		"Concatenate source (include/exclude modules with +/- flags), embed date/version",
		function() {
			// Concat specified files.
			var compiled = "",
					modules = this.flags,
					optIn = !modules["*"],
					name = this.file.dest;

			this.file.src.forEach(function( filepath ) {
				// Include optional modules per build flags; exclusion trumps inclusion
				var flag = filepath.flag;
				if ( flag ) {
					if ( modules[ "-" + flag ] ||
						optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {

						log.writeln( "Excluding " + filepath.flag + ": '" + filepath.src + "'." );
						return;
					}
					log.writeln( "Including " + filepath.flag + ": '" + filepath.src + "'." );
					filepath = filepath.src;
				}

				// Unwrap redundant IIFEs
				compiled += file.read( filepath );
				//.replace( /^\(function\( jQuery \) \{|\}\)\( jQuery \);\s*$/g, "" );
			});

			// Embed Date
			// Embed Version
			compiled = compiled.replace( "@DATE", new Date() )
				.replace( "@VERSION", config("pkg.version") );

			// Write concatenated source to file
			file.write( name, compiled );

			// Fail task if errors were logged.
			if ( this.errorCount ) {
				return false;
			}

			// Otherwise, print a success message.
			log.writeln( "File '" + name + "' created." );
		});

	grunt.registerTask( "submodules", function() {
		var done = this.async();

		grunt.verbose.write( "Updating submodules..." );

		// TODO: migrate remaining `make` to grunt tasks
		//
		grunt.utils.spawn({
			cmd: "make"
		}, function( err, result ) {
			if ( err ) {
				grunt.verbose.error();
				done( err );
				return;
			}

			grunt.log.writeln( result );

			done();
		});
	});

	// Allow custom dist file locations
	grunt.registerTask( "dist", function() {
		var flags, paths, stored;

		// Check for stored destination paths
		// ( set in dist/.destination.json )
		stored = Object.keys( config("dst") );

		// Allow command line input as well
		flags = Object.keys( this.flags );

		// Combine all output target paths
		paths = [].concat( stored, flags ).filter(function( path ) {
			return path !== "*";
		});

		// Proceed only if there are actual
		// paths to write to
		if ( paths.length ) {

			// 'distpaths' is declared at the top of the
			// module.exports function scope. It is an array
			// of default files that jQuery creates
			distpaths.forEach(function( filename ) {
				paths.forEach(function( path ) {
					var created;

					if ( !/\/$/.test( path ) ) {
						path += "/";
					}

					created = path + filename.replace( "dist/", "" );

					if ( !/^\//.test( path ) ) {
						log.error( "File '" + created + "' was NOT created." );
						return;
					}

					file.write( created, file.read(filename) );

					log.writeln( "File '" + created + "' created." );
				});
			});
		}
	});
};
<commit_msg>Grunt: Update testswarm task to use more config properties. Already deployed on Jenkins server<commit_after>/**
 * Resources
 *
 * https://gist.github.com/2489540
 *
 */

/*global config:true, task:true*/
module.exports = function( grunt ) {

	// readOptionalJSON
	// by Ben Alman
	// https://gist.github.com/2876125
	function readOptionalJSON( filepath ) {
		var data = {};
		try {
			data = grunt.file.readJSON(filepath);
			grunt.log.write( "Reading data from " + filepath + "..." ).ok();
		} catch(e) {}
		return data;
	}

	var task = grunt.task;
	var file = grunt.file;
	var utils = grunt.utils;
	var log = grunt.log;
	var verbose = grunt.verbose;
	var fail = grunt.fail;
	var option = grunt.option;
	var config = grunt.config;
	var template = grunt.template;
	var distpaths = [
		"dist/jquery.js",
		"dist/jquery.min.js"
	];

	grunt.initConfig({
		pkg: "<json:package.json>",
		dst: readOptionalJSON("dist/.destination.json"),
		meta: {
			banner: "/*! jQuery v@<%= pkg.version %> jquery.com | jquery.org/license */"
		},
		compare_size: {
			files: distpaths
		},
		selector: {
			"src/selector.js": [
				"src/sizzle-jquery.js",
				"src/sizzle/sizzle.js"
			]
		},
		build: {
			"dist/jquery.js": [
				"src/intro.js",
				"src/core.js",
				"src/callbacks.js",
				"src/deferred.js",
				"src/support.js",
				"src/data.js",
				"src/queue.js",
				"src/attributes.js",
				"src/event.js",
				"src/selector.js",
				"src/traversing.js",
				"src/manipulation.js",
				"src/css.js",
				"src/ajax.js",
				"src/ajax/jsonp.js",
				"src/ajax/script.js",
				"src/ajax/xhr.js",
				{ flag: "effects", src: "src/effects.js" },
				{ flag: "offset", src: "src/offset.js" },
				{ flag: "dimensions", src: "src/dimensions.js" },
				"src/exports.js",
				"src/outro.js"
			]
		},
		min: {
			"dist/jquery.min.js": [ "<banner>", "dist/jquery.js" ]
		},
		lint: {
			files: [ "grunt.js", "dist/jquery.js" ]
		},
		qunit: {
			files: "test/index.html"
		},
		watch: {
			files: [ "<config:lint.files>", "src/**/*.js" ],
			tasks: "dev"
		},
		jshint: {
			options: {
				evil: true,
				browser: true,
				wsh: true,
				eqnull: true,
				expr: true,
				curly: true,
				trailing: true,
				undef: true,
				smarttabs: true,
				predef: [
					"define",
					"DOMParser",
					"__dirname"
				],
				maxerr: 100
			},
			globals: {
				jQuery: true,
				global: true,
				module: true,
				exports: true,
				require: true,
				file: true,
				log: true,
				console: true
			}
		},
		uglify: {}
	});

	// Default grunt.
	grunt.registerTask( "default", "submodules selector build:*:* dist:* lint min compare_size" );

	// Short list as a high frequency watch task
	grunt.registerTask( "dev", "selector build:*:* lint" );

	// Load the "compare_size" task from NPM packages
	grunt.loadNpmTasks("grunt-compare-size");

	grunt.registerTask( "testswarm", function( commit, configFile ) {
		var testswarm = require( "testswarm" ),
			testUrls = [],
			config = grunt.file.readJSON( configFile ).jquery;
		var tests = "ajax attributes callbacks core css data deferred dimensions effects event manipulation offset queue selector support traversing".split( " " );
		tests.forEach(function( test ) {
			testUrls.push( config.testUrl + commit + "/test/index.html?filter=" + test );
		});
		testswarm({
			url: config.swarmUrl,
			pollInterval: 10000,
			timeout: 1000 * 60 * 30,
			done: this.async()
		}, {
			authUsername: config.authUsername,
			authToken: config.authToken,
			jobName: 'jQuery commit #' + commit.substr( 0, 10 ) + '',
			runMax: 4,
			"runNames[]": tests,
			"runUrls[]": testUrls,
			"browserSets[]": ["popular"]
		});
	});

	// Build src/selector.js
	grunt.registerMultiTask( "selector", "Build src/selector.js", function() {

		var name = this.file.dest,
				files = this.file.src,
				sizzle = {
					api: file.read( files[0] ),
					src: file.read( files[1] )
				},
				compiled;

		// sizzle-jquery.js -> sizzle after "EXPOSE", replace window.Sizzle
		compiled = sizzle.src.replace( "window.Sizzle = Sizzle;", sizzle.api );
		verbose.write("Injected sizzle-jquery.js into sizzle.js");

		// Write concatenated source to file
		file.write( name, compiled );

		// Fail task if errors were logged.
		if ( this.errorCount ) {
			return false;
		}

		// Otherwise, print a success message.
		log.writeln( "File '" + name + "' created." );
	});

	// Special concat/build task to handle various jQuery build requirements
	grunt.registerMultiTask(
		"build",
		"Concatenate source (include/exclude modules with +/- flags), embed date/version",
		function() {
			// Concat specified files.
			var compiled = "",
					modules = this.flags,
					optIn = !modules["*"],
					name = this.file.dest;

			this.file.src.forEach(function( filepath ) {
				// Include optional modules per build flags; exclusion trumps inclusion
				var flag = filepath.flag;
				if ( flag ) {
					if ( modules[ "-" + flag ] ||
						optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {

						log.writeln( "Excluding " + filepath.flag + ": '" + filepath.src + "'." );
						return;
					}
					log.writeln( "Including " + filepath.flag + ": '" + filepath.src + "'." );
					filepath = filepath.src;
				}

				// Unwrap redundant IIFEs
				compiled += file.read( filepath );
				//.replace( /^\(function\( jQuery \) \{|\}\)\( jQuery \);\s*$/g, "" );
			});

			// Embed Date
			// Embed Version
			compiled = compiled.replace( "@DATE", new Date() )
				.replace( "@VERSION", config("pkg.version") );

			// Write concatenated source to file
			file.write( name, compiled );

			// Fail task if errors were logged.
			if ( this.errorCount ) {
				return false;
			}

			// Otherwise, print a success message.
			log.writeln( "File '" + name + "' created." );
		});

	grunt.registerTask( "submodules", function() {
		var done = this.async();

		grunt.verbose.write( "Updating submodules..." );

		// TODO: migrate remaining `make` to grunt tasks
		//
		grunt.utils.spawn({
			cmd: "make"
		}, function( err, result ) {
			if ( err ) {
				grunt.verbose.error();
				done( err );
				return;
			}

			grunt.log.writeln( result );

			done();
		});
	});

	// Allow custom dist file locations
	grunt.registerTask( "dist", function() {
		var flags, paths, stored;

		// Check for stored destination paths
		// ( set in dist/.destination.json )
		stored = Object.keys( config("dst") );

		// Allow command line input as well
		flags = Object.keys( this.flags );

		// Combine all output target paths
		paths = [].concat( stored, flags ).filter(function( path ) {
			return path !== "*";
		});

		// Proceed only if there are actual
		// paths to write to
		if ( paths.length ) {

			// 'distpaths' is declared at the top of the
			// module.exports function scope. It is an array
			// of default files that jQuery creates
			distpaths.forEach(function( filename ) {
				paths.forEach(function( path ) {
					var created;

					if ( !/\/$/.test( path ) ) {
						path += "/";
					}

					created = path + filename.replace( "dist/", "" );

					if ( !/^\//.test( path ) ) {
						log.error( "File '" + created + "' was NOT created." );
						return;
					}

					file.write( created, file.read(filename) );

					log.writeln( "File '" + created + "' created." );
				});
			});
		}
	});
};
<|endoftext|>


<commit_before>module.exports = function (grunt) {

  grunt.initConfig({
    pkg: '<json:package.json>',
    lint: {
      files: ['grunt.js', 'lib/comment.js', 'lib/template/js/*.js']
    },
    stylus: {
      compile: {
        files: {
          'lib/template/css/*.css': ['lib/template/css/styl/comment.styl', 'lib/template/css/styl/src.styl']
        }
      }
    },
    watch: {
      files: ['<config:lint.files>', 'lib/template/css/styl/comment.styl', 'lib/template/css/styl/src.styl'],
      tasks: 'lint stylus'
    },
    jshint: {
      options: {
        curly: true,
        immed: true,
        latedef: true,
        noarg: true,
        sub: true,
        undef: true,
        eqnull: true,
        node: true
      },
      globals: {
        window: true
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-stylus');

  grunt.registerTask('default', 'lint stylus');

};<commit_msg>update grunt paths and added cssmin<commit_after>module.exports = function (grunt) {

  grunt.initConfig({
    pkg: '<json:package.json>',
    lint: {
      files: ['grunt.js', 'lib/comment.js', 'lib/template/src/js/tocfilter.js']
    },
    stylus: {
      compile: {
        files: {
          'lib/template/src/css/docs.css': ['lib/template/src/css/styl/docs.styl']
        }
      }
    },
    min: {
      dist: {
        src: ['lib/template/src/js/prettify.js', 'lib/template/src/js/tocfilter.js'],
        dest: 'lib/template/js/docs.min.js'
      }
    },
    mincss: {
      dist: {
        src: ['lib/template/src/css/docs.css'],
        dest: 'lib/template/css/docs.min.css'
      }
    },
    watch: {
      files: ['<config:lint.files>', 'lib/template/css/styl/comment.styl', 'lib/template/css/styl/src.styl'],
      tasks: 'lint min stylus mincss'
    },
    jshint: {
      options: {
        curly: true,
        immed: true,
        latedef: true,
        noarg: true,
        sub: true,
        undef: true,
        eqnull: true,
        node: true
      },
      globals: {
        window: true
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-stylus');
  grunt.loadNpmTasks('grunt-contrib-mincss');

  grunt.registerTask('default', 'lint min stylus mincss');

};<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>*/'
    },
    concat: {
      dist: {
        src: ['<banner:meta.banner>',
              'src/bucefalo.namespace.js',
              'src/architecture/publisherSubscriber/pubsub.js'
        ],
        dest: 'dist/<%= pkg.name %>.js'
      },
      module: {
        src: ['<config:concat.dist.dest>', 'src/bucefalo.module.js'],
        dest: 'dist/<%= pkg.name %>.module.js'
      }
    },
    min: {
      dist: {
        src: ['<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      },
      module: {
        src: ['<config:concat.module.dest>'],
        dest: 'dist/<%= pkg.name %>.module.min.js'
      }
    },
    lint: {
      files: ['grunt.js', 'src/**/*.js']//, 'test/**/*.js']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint qunit'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true,
        plusplus: false,
        smarttabs:true
      },
      globals: {
        bucefalo: true,
        console: true,
        module: true
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'lint concat min');

};
<commit_msg>Update Grunt<commit_after>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>*/'
    },
    concat: {
      dist: {
        src: ['<banner:meta.banner>',
              'src/bucefalo.namespace.js',
              'src/architecture/publisherSubscriber/*.js'
        ],
        dest: 'dist/<%= pkg.name %>.js'
      },
      test: {
        src : ['test/**/**/*.js'],
        dest: 'test/<%= pkg.name %>.test.js'
      }
    },
    min: {
      dist: {
        src: ['<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    lint: {
      files: ['grunt.js', 'src/**/*.js']//, 'test/**/*.js']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint qunit'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true,
        plusplus: false,
        smarttabs:true
      },
      globals: {
        bucefalo: true,
        console: true,
        module: true
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'lint concat min');

};
<|endoftext|>


<commit_before>'use strict';

(function($){
  var changeMergeButtonState = function() {
    var $container = $('#js-repo-pjax-container');
    var issueTitle = $container.find('#js-discussion-header .js-issue-title').text();
    var caution = /(\[wip\]|\[do\s*not\s*merge\])/i.test(issueTitle);
    var $buttonMerge = $container.find('#js-pull-merging button.merge-branch-action.js-details-target');
    var buttonText = caution ? 'WIP! You can\'t merge!' : 'Merge pull request';
    $buttonMerge.attr('disabled', caution);
    $buttonMerge.text(buttonText);
  };
  setInterval(changeMergeButtonState, 1000);
})(jQuery);
<commit_msg>Tweak octicon in button<commit_after>'use strict';

(function($){
  var changeMergeButtonState = function() {
    var $container = $('#js-repo-pjax-container');
    var issueTitle = $container.find('#js-discussion-header .js-issue-title').text();
    var caution = /(\[wip\]|\[do\s*not\s*merge\])/i.test(issueTitle);
    var $buttonMerge = $container.find('#js-pull-merging button.merge-branch-action.js-details-target');
    var buttonText = caution ? 'WIP! You can\'t merge!' : ' Merge pull request';
    $buttonMerge.attr('disabled', caution);
    $buttonMerge.html(buttonText);
  };
  setInterval(changeMergeButtonState, 1000);
})(jQuery);
<|endoftext|>


<commit_before>/* global google */

const icons = {
  user: 'mosque',
  church: 'curch',
  bank: 'bank',
  'call-shop': 'call-shop',
  supermarket: 'supermarket',
  culture: 'culture',
  pharmacy: 'pharmacy',
  laundry: 'laundry',
  playground: 'playground',
  football: 'football',
  basketball: 'basketball',
  'table-tennis': 'table-tennis',
  skateboard: 'skateboard',
  library: 'library',
  'public-restroom': 'public-restroom'
};

/**
 * Get the marker icon
 * @param {String} category The category of the location
 * @return {GoogleIconObject} icon The marker icon
 */
/* eslint-disable complexity */
export default function(category) {
  const iconName = icons[category];

  if (iconName) {
    return create({url: `assets/${iconName}.png`});
  }

  if (category === 'user') {
    return getUserIcon();
  }

  return create({url: 'assets/marker-24@2x.png'});
}
/* eslint-enable complexity */

/**
 * Get the user icon
 * @return {GoogleIconObject} icon The marker icon
 */
function getUserIcon() {
  return create({
    url: 'assets/red-marker.png',
    width: 25,
    height: 40,
    anchorX: 12,
    anchorY: 40
  });
}

/**
 * Create the google icon object
 * @param {String} url The icon URL
 * @param {Integer} width The icon width
 * @param {Integer} height The icon height
 * @param {Integer} anchorX The x anchor value
 * @param {Integer} anchorY The y anchor value
 * @return {GoogleIconObject} icon The marker icon
 */
function create({url, width = 30, height = 30, anchorX = 15, anchorY = 15}) {
  return {
    url: url,
    size: new google.maps.Size(width, height),
    origin: new google.maps.Point(0, 0),
    anchor: new google.maps.Point(anchorX, anchorY),
    scaledSize: new google.maps.Size(width, height)
  };
}
<commit_msg>fix(get-icon): fix mosque icon<commit_after>/* global google */

const icons = {
  mosque: 'mosque',
  church: 'curch',
  bank: 'bank',
  'call-shop': 'call-shop',
  supermarket: 'supermarket',
  culture: 'culture',
  pharmacy: 'pharmacy',
  laundry: 'laundry',
  playground: 'playground',
  football: 'football',
  basketball: 'basketball',
  'table-tennis': 'table-tennis',
  skateboard: 'skateboard',
  library: 'library',
  'public-restroom': 'public-restroom'
};

/**
 * Get the marker icon
 * @param {String} category The category of the location
 * @return {GoogleIconObject} icon The marker icon
 */
/* eslint-disable complexity */
export default function(category) {
  const iconName = icons[category];

  if (iconName) {
    return create({url: `assets/${iconName}.png`});
  }

  if (category === 'user') {
    return getUserIcon();
  }

  return create({url: 'assets/marker-24@2x.png'});
}
/* eslint-enable complexity */

/**
 * Get the user icon
 * @return {GoogleIconObject} icon The marker icon
 */
function getUserIcon() {
  return create({
    url: 'assets/red-marker.png',
    width: 25,
    height: 40,
    anchorX: 12,
    anchorY: 40
  });
}

/**
 * Create the google icon object
 * @param {String} url The icon URL
 * @param {Integer} width The icon width
 * @param {Integer} height The icon height
 * @param {Integer} anchorX The x anchor value
 * @param {Integer} anchorY The y anchor value
 * @return {GoogleIconObject} icon The marker icon
 */
function create({url, width = 30, height = 30, anchorX = 15, anchorY = 15}) {
  return {
    url: url,
    size: new google.maps.Size(width, height),
    origin: new google.maps.Point(0, 0),
    anchor: new google.maps.Point(anchorX, anchorY),
    scaledSize: new google.maps.Size(width, height)
  };
}
<|endoftext|>


<commit_before>
define(['plugins/greet'], function () {
        return {
                    name: 'greet',
                    reply:

    function(args) {
        if (args.rawInput.matches(/^My name is (.*)$/)) {
           args.persistentStorage["global.userName"] = $1;
           return [1, "Hi "+$1];
        } else {
            return [0, "Sorry, no name there"];
        }
    }
        }
});
<commit_msg>She knows my name<commit_after>
define(['plugins/greet'], function () {
        return {
                    name: 'greet',
                    reply:

    function(args) {
        if (result = args.rawInput.match(/^(My name is|I'm called|Call me) (.*)$/i)) {
           args.persistentStorage["global.userName"] = result[2];
           return [1, "Hi "+result[2]];
        } else if (result = args.rawInput.match(/^(What's my name|What am I called|Who am I)/)) {
            return[1, "You're "+args.persistentStorage["global.userName"]];

        } else {
            return [0, "Sorry, no name there"];
        }
        }
}});
<|endoftext|>


<commit_before>"use strict";
const webpack = require("webpack");

module.exports = {
    entry: {
        OpenSEE: "./Scripts/TSX/openSEE.tsx"
    },
    output: {
        filename: "./Scripts/[name].js"
    },
    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".css"]
    },
    module: {
        loaders: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
            { test: /\.tsx?$/, loader: "ts-loader" },
            {
                test: /\.css$/,
                include: /node_modules/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.js$/,
                enforce: "pre",
                loader: "source-map-loader"
            },
            { test: /\.(woff|woff2|ttf|eot|svg|png|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=100000" }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
          $: 'jquery',
          jQuery: 'jquery',
          Map: 'core-js/es6/map',
          Set: 'core-js/es6/set',
          //requestAnimationFrame: 'raf/polyfill'
        }),
        //new webpack.DefinePlugin({
        //    'process.env.NODE_ENV': JSON.stringify('production')
        //}),
        //new webpack.optimize.UglifyJsPlugin()
    ]
};<commit_msg>Restored and fixed polyfills for requestAnimationFrame and cancelAnimationFrame in webpack.config.js ProvidePlugin.<commit_after>"use strict";
const webpack = require("webpack");

module.exports = {
    entry: {
        OpenSEE: "./Scripts/TSX/openSEE.tsx"
    },
    output: {
        filename: "./Scripts/[name].js"
    },
    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".css"]
    },
    module: {
        loaders: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
            { test: /\.tsx?$/, loader: "ts-loader" },
            {
                test: /\.css$/,
                include: /node_modules/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.js$/,
                enforce: "pre",
                loader: "source-map-loader"
            },
            { test: /\.(woff|woff2|ttf|eot|svg|png|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=100000" }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
          $: 'jquery',
          jQuery: 'jquery',
          Map: 'core-js/es6/map',
          Set: 'core-js/es6/set',
          requestAnimationFrame: 'raf',
          cancelAnimationFrame: ['raf', 'cancel']
        }),
        //new webpack.DefinePlugin({
        //    'process.env.NODE_ENV': JSON.stringify('production')
        //}),
        //new webpack.optimize.UglifyJsPlugin()
    ]
};<|endoftext|>