<commit_before>var fs = require('fs'),
    path = require('path'),
    program = require('commander'),
    http = require('http'),
    ProgressBar = require('progress'),
    tarball = require('tarball-extract');

var outputDirectory = path.normalize(process.env.PWD),
    downloadQueries = [],
    downloadPatterns = [],
    argsIndex = [],
    argsValues = [],
    argsNames = [],
    dataDescriptor = null,
    progress = null;

function processFile(url, destFile, extractedDir, doneCallback) {
    fs.exists(extractedDir, function(exists) {
        if(exists) {
            console.log(" |  $ ArcticViewer -d " + extractedDir);
            doneCallback();
        } else {
            tarball.extractTarballDownload(
                url,
                destFile, path.dirname(destFile),
                {},
                function(err, result) {
                    if(!err) {
                        console.log(" |  $ ArcticViewer -d " + extractedDir);
                    } else {
                        console.log(' | oups something wrong happened while downloading ' + url);
                    }
                    doneCallback();
                }
            );
        }
    });
}

// Process data descriptor and start download
function buildDownloadStructure() {
    // Handle args dimension
    for(var key in dataDescriptor.arguments) {
        argsNames.push(key);
        argsIndex.push(0);
        argsValues.push(dataDescriptor.arguments[key].values);
    }

    // Handle data pattern
    var array = dataDescriptor.data,
        count = array.length;
    while(count--) {
       downloadPatterns.push(array[count].pattern);
    }

    while(next()) {
        downloadQueries.push(getQuery());
    }
    progress = new ProgressBar('downloading [:bar] :percent | :current/:total | :etas', {
        complete: '=',
        incomplete: ' ',
        width: 50,
        total: downloadQueries.length * downloadPatterns.length });

    downloadNextFile();
}

function next(idx) {
    if(idx === undefined) {
        idx = argsIndex.length - 1;
    }

    if(idx < 0) {
        return false;
    }

    if(argsIndex[idx] + 1 < argsValues[idx].length) {
        argsIndex[idx]++;
        return true;
    } else {
        if(next(idx - 1)) {
            argsIndex[idx] = 0;
            return true;
        }
        return false;
    }
}

function getQuery() {
    var query = {},
        count = argsNames.length;

    while(count--) {
        query[argsNames[count]] = argsValues[count][argsIndex[count]];
    }

    return query;
}

function toUrl(pattern, query) {
    var result = '/' + pattern,
        keyPattern = ['{', '}'];

    for(var opt in query) {
        result = result.replace(keyPattern.join(opt), query[opt]);
    }

    return result;
}

function downloadNextFile() {
    if(downloadQueries.length === 0) {
        console.log("\nAll download are completed\n");
        return;
    }
    var query = downloadQueries.pop(),
        count = downloadPatterns.length;
    while(count--) {
        downloadFile(toUrl(downloadPatterns[count], query));
    }
}

function mkdirp(dirPath, done) {
    var parent = path.dirname(dirPath);
    fs.exists(dirPath, function(exists) {
        if(exists) {
            done();
        } else {
            mkdirp(parent, function(){
                fs.mkdirSync(dirPath);
                done();
            });
        }
    });
}

function downloadFile(url) {
    // Create content directory if need be
    var destFile = path.join(outputDirectory, url),
        destDirectory = path.dirname(destFile);

    fs.exists(destFile, function(exists) {
        if(exists) {
            progress.tick(1);
            downloadNextFile();
        } else {
            mkdirp(destDirectory, function(){
                // Download file
                http.get(program.download + url, function(res) {
                    res.on('data', function (chunk) {
                        fs.appendFile(destFile,
                                    chunk,
                                    function (err) { if (err) throw err; }
                        );
                    });
                    res.on('end', function () {
                        progress.tick(1);
                        downloadNextFile();
                    });

                }).on('error', function(e) {
                    console.log("Got error: " + e.message);
                });
            });
        }
    });
}

module.exports = {
    downloadSampleData: function() {
        console.log("\n | Downloading sample data (~100MB) into directory " + outputDirectory);
        var baseURL = 'http://www.kitware.com/in-situ-data/tonic-sample-data/',
            files = ['mpas-probe-flat-earth.tgz', 'hydra-image-fluid-velocity.tgz'],
            doneCount = 0;

        function done() {
            doneCount++;

            if(doneCount === files.length) {
                console.log(" |\n | Thank you for trying this out...\n");
            }
        }

        mkdirp(outputDirectory, function(){
            console.log(" |\n | => Once the data will be downloaded, you will be able to try the ArcticViewer with the following commands:\n |");
            for(var i = 0; i < files.length; i++) {
                var url = baseURL + files[i],
                    destFile = path.join(outputDirectory, files[i]),
                    extractedDir = destFile.substring(0, destFile.length - 4);

                processFile(url, destFile, extractedDir, done);
            }
        });
    },

    downloadData: function(url) {
        http.get(url + '/index.json', function(res) {
            var buffer = [];
            res.on('data', function (chunk) {
                buffer.push(chunk);
            });
            res.on('end', function () {
                fs.writeFile(path.join(outputDirectory, 'index.json'),
                            buffer.join(''),
                            function (err) {
                                if (err) throw err;
                            }
                );
                dataDescriptor = JSON.parse(buffer.join(''));
                buildDownloadStructure();
            });

        }).on('error', function(e) {
            console.log("Got error: " + e.message);
        });
    }
};
<commit_msg>fix(SampleDownload): Improve the UI to control sample dataset to download<commit_after>var fs = require('fs'),
    path = require('path'),
    program = require('commander'),
    http = require('http'),
    ProgressBar = require('progress'),
    tarball = require('tarball-extract');

var outputDirectory = path.normalize(process.env.PWD),
    downloadQueries = [],
    downloadPatterns = [],
    argsIndex = [],
    argsValues = [],
    argsNames = [],
    dataDescriptor = null,
    progress = null;

require('shelljs/global');

var availableData = {
    'diskout-composite': {
        url: 'http://tonic.kitware.com/arctic-viewer/diskout-composite.tgz',
        size: ' 40.0 MB'
    },
    'ensemble': {
        url: 'http://tonic.kitware.com/arctic-viewer/ensemble.tgz',
        size: ' 94.2 MB'
    },
    'garfield': {
        url: 'http://tonic.kitware.com/arctic-viewer/garfield.tgz',
        size: '  292 KB'
    },
    'head_ct_3_features': {
        url: 'http://tonic.kitware.com/arctic-viewer/head_ct_3_features.tgz',
        size: ' 13.7 MB'
    },
    'head_ct_4_features': {
        url: 'http://tonic.kitware.com/arctic-viewer/head_ct_4_features.tgz',
        size: ' 13.1 MB'
    },
    'hydra-image-fluid-velocity': {
        url: 'http://tonic.kitware.com/arctic-viewer/hydra-image-fluid-velocity.tgz',
        size: ' 50.8 MB'
    },
    'mpas-composite-earth': {
        url: 'http://tonic.kitware.com/arctic-viewer/mpas-composite-earth.tgz',
        size: '162.3 MB'
    },
    'mpas-flat-earth-prober': {
        url: 'http://tonic.kitware.com/arctic-viewer/mpas-flat-earth-prober.tgz',
        size: ' 37.5 MB'
    },
    'mpas-hd-500-7t': {
        url: 'http://tonic.kitware.com/arctic-viewer/mpas-hd-500-7t.tgz',
        size: '552.5 MB'
    }
};

function processFile(url, destFile, extractedDir, doneCallback) {
    fs.exists(extractedDir, function(exists) {
        if(exists) {
            console.log(" |  $ ArcticViewer -d " + extractedDir);
            doneCallback();
        } else {
            tarball.extractTarballDownload(
                url,
                destFile, path.dirname(destFile),
                {},
                function(err, result) {
                    if(!err) {
                        console.log(" |  $ ArcticViewer -d " + extractedDir);
                        rm(destFile);
                    } else {
                        console.log(' | oups something wrong happened while downloading ' + url);
                    }
                    doneCallback();
                }
            );
        }
    });
}

// Process data descriptor and start download
function buildDownloadStructure() {
    // Handle args dimension
    for(var key in dataDescriptor.arguments) {
        argsNames.push(key);
        argsIndex.push(0);
        argsValues.push(dataDescriptor.arguments[key].values);
    }

    // Handle data pattern
    var array = dataDescriptor.data,
        count = array.length;
    while(count--) {
       downloadPatterns.push(array[count].pattern);
    }

    while(next()) {
        downloadQueries.push(getQuery());
    }
    progress = new ProgressBar('downloading [:bar] :percent | :current/:total | :etas', {
        complete: '=',
        incomplete: ' ',
        width: 50,
        total: downloadQueries.length * downloadPatterns.length });

    downloadNextFile();
}

function next(idx) {
    if(idx === undefined) {
        idx = argsIndex.length - 1;
    }

    if(idx < 0) {
        return false;
    }

    if(argsIndex[idx] + 1 < argsValues[idx].length) {
        argsIndex[idx]++;
        return true;
    } else {
        if(next(idx - 1)) {
            argsIndex[idx] = 0;
            return true;
        }
        return false;
    }
}

function getQuery() {
    var query = {},
        count = argsNames.length;

    while(count--) {
        query[argsNames[count]] = argsValues[count][argsIndex[count]];
    }

    return query;
}

function toUrl(pattern, query) {
    var result = '/' + pattern,
        keyPattern = ['{', '}'];

    for(var opt in query) {
        result = result.replace(keyPattern.join(opt), query[opt]);
    }

    return result;
}

function downloadNextFile() {
    if(downloadQueries.length === 0) {
        console.log("\nAll download are completed\n");
        return;
    }
    var query = downloadQueries.pop(),
        count = downloadPatterns.length;
    while(count--) {
        downloadFile(toUrl(downloadPatterns[count], query));
    }
}

function mkdirp(dirPath, done) {
    var parent = path.dirname(dirPath);
    fs.exists(dirPath, function(exists) {
        if(exists) {
            done();
        } else {
            mkdirp(parent, function(){
                fs.mkdirSync(dirPath);
                done();
            });
        }
    });
}

function downloadFile(url) {
    // Create content directory if need be
    var destFile = path.join(outputDirectory, url),
        destDirectory = path.dirname(destFile);

    fs.exists(destFile, function(exists) {
        if(exists) {
            progress.tick(1);
            downloadNextFile();
        } else {
            mkdirp(destDirectory, function(){
                // Download file
                http.get(program.download + url, function(res) {
                    res.on('data', function (chunk) {
                        fs.appendFile(destFile,
                                    chunk,
                                    function (err) { if (err) throw err; }
                        );
                    });
                    res.on('end', function () {
                        progress.tick(1);
                        downloadNextFile();
                    });

                }).on('error', function(e) {
                    console.log("Got error: " + e.message);
                });
            });
        }
    });
}

function downloadAvailableDatasets(list) {
    var downloadCount = 0,
        doneCount = 0;

    console.log(" |\n | => Once the data will be downloaded, you will be able to try the ArcticViewer with the following commands:\n |");

    function done() {
        doneCount++;
        if(downloadCount === doneCount) {
            console.log(" |\n | Thank you for trying this out...\n");
        }
    }

    while(list.length) {
        var dsIdx = list.pop();
        var idx = 0;
        for(var name in availableData) {
            idx++;
            if(idx === dsIdx) {
                downloadCount++;
                var url = availableData[name].url,
                    destFile = path.join(outputDirectory, name + '.tgz'),
                    extractedDir = destFile.substring(0, destFile.length - 4);
                processFile(url, destFile, extractedDir, done);
            }
        }
    }
}

module.exports = {
    downloadSampleData: function() {
        console.log("\n | Available datasets for download (path: " + outputDirectory + ')');

        var idx = 1;
        for(var name in availableData) {
            console.log(" |   ("+ (idx++)+ ')', availableData[name].size, ' - ' , name);
        }
        console.log(' | ')

        var message = ' | Press Enter to quit or the dataset number to download: ',
            listToDownload = [];

        process.stdin.resume();
        process.stdin.setEncoding('utf8');
        process.stdout.write(message);
        process.stdin.on('data', function (text) {
            var n = Number(text);
            listToDownload.push(n);
            if(text === '\n') {
                process.stdin.pause();
                downloadAvailableDatasets(listToDownload);
            } else {
                process.stdout.write(message);
            }
        });
    },

    downloadData: function(url) {
        http.get(url + '/index.json', function(res) {
            var buffer = [];
            res.on('data', function (chunk) {
                buffer.push(chunk);
            });
            res.on('end', function () {
                fs.writeFile(path.join(outputDirectory, 'index.json'),
                            buffer.join(''),
                            function (err) {
                                if (err) throw err;
                            }
                );
                dataDescriptor = JSON.parse(buffer.join(''));
                buildDownloadStructure();
            });

        }).on('error', function(e) {
            console.log("Got error: " + e.message);
        });
    }
};
<|endoftext|>


<commit_before>angular.module('app.controllers.search', ['app.services.config']).controller('SearchController', ['$state', '$scope', '$rootScope', '$timeout', 'Config',
    function SearchController($state, $scope, $rootScope, $timeout, Config) {
		console.log('[SearchController] Init');
/*
$timeout(function() {
	console.log("Men nå da?");
			$scope.$broadcast('angucomplete-alt:changeInput', 'search', 'Hello!');
}, 0);*/

/*
		$rootScope.$on('$stateNotFound',
function(event, unfoundState, fromState, fromParams){
	console.log("state not found");
    console.log(unfoundState.to); // "lazy.state"
    console.log(unfoundState.toParams); // {a:1, b:2}
    console.log(unfoundState.options); // {inherit:false} + default options
});

$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
  console.log('state change');
  console.log(toState);
    // transitionTo() promise will be rejected with
    // a 'transition prevented' error
});

$rootScope.$on('$stateChangeError',
function(event, toState, toParams, fromState, fromParams){
  console.log('state change error');
  console.log(toState);
    // transitionTo() promise will be rejected with
    // a 'transition prevented' error
});

$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){
  console.log('state change success');
  console.log(toState);
    // transitionTo() promise will be rejected with
    // a 'transition prevented' error
})

/*
http://data.ub.uio.no/yasqe/?query=PREFIX+skos%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2004%2F02%2Fskos%2Fcore%23%3E%0ASELECT+%3Flabel%0AFROM+%3Chttp%3A%2F%2Fdata.ub.uio.no%2Frt%3E%0AWHERE%0A%7B%0A++%3Fconcept+(skos%3AprefLabel%7Cskos%3AaltLabel)+%3Flabel+.%0A+++FILTER+langMatches(+lang(%3Flabel)%2C+%22nn%22+)%0A%7D

PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?label1 ?label2 ?label3
FROM <http://data.ub.uio.no/rt>
WHERE
{
  ?concept (skos:prefLabel) ?label1 , ?label2, ?label3
   FILTER langMatches( lang(?label1), "nn" )
   FILTER langMatches( lang(?label2), "nb" )
   FILTER langMatches( lang(?label3), "en" )
}

*/

		this.searchUrl = Config.skosmos.searchUrl;

		this.formatRequest = function(str) {

			var lang = $state.params.lang || Config.defaultLanguage;

			var vocab = $state.params.vocab;

			var query = (str.length == 2) ? str : '*' + str + '*';

			return {
				query: query,
				labellang: lang,
				vocab: vocab
			};
		};

		this.formatResult = function(response) {

			return response.results.map(function(result) {
				result.description = result.matchedPrefLabel ? ' (' +result.matchedPrefLabel + ')' : '';
				return result;
			});

		};

		function shortIdFromUri(uri) {
			var s = uri.split('/'),
				id = s.pop(),
				vocab = s.pop();
			return vocab + ':' + id;
		}

		this.selectSubject = function(item) {
			if (item) {
				var subjects = shortIdFromUri(item.originalObject.uri);
				console.log('[SearchController] Selecting subject(s): ' + subjects);

				$state.go('home.subject', {
					lang:		item.originalObject.lang,
					subjects:   subjects
				});
			}
		};
    }
]);<commit_msg>SearchController: slight code cleanup<commit_after>angular.module('app.controllers.search', ['app.services.config']).controller('SearchController', ['$state', '$scope', '$rootScope', '$timeout', 'Config',
    function SearchController($state, $scope, $rootScope, $timeout, Config) {
		console.log('[SearchController] Init');
/*
$timeout(function() {
	console.log("Men nå da?");
			$scope.$broadcast('angucomplete-alt:changeInput', 'search', 'Hello!');
}, 0);*/

/*
		$rootScope.$on('$stateNotFound',
function(event, unfoundState, fromState, fromParams){
	console.log("state not found");
    console.log(unfoundState.to); // "lazy.state"
    console.log(unfoundState.toParams); // {a:1, b:2}
    console.log(unfoundState.options); // {inherit:false} + default options
});

$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
  console.log('state change');
  console.log(toState);
    // transitionTo() promise will be rejected with
    // a 'transition prevented' error
});

$rootScope.$on('$stateChangeError',
function(event, toState, toParams, fromState, fromParams){
  console.log('state change error');
  console.log(toState);
    // transitionTo() promise will be rejected with
    // a 'transition prevented' error
});

$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){
  console.log('state change success');
  console.log(toState);
    // transitionTo() promise will be rejected with
    // a 'transition prevented' error
})

/*
http://data.ub.uio.no/yasqe/?query=PREFIX+skos%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2004%2F02%2Fskos%2Fcore%23%3E%0ASELECT+%3Flabel%0AFROM+%3Chttp%3A%2F%2Fdata.ub.uio.no%2Frt%3E%0AWHERE%0A%7B%0A++%3Fconcept+(skos%3AprefLabel%7Cskos%3AaltLabel)+%3Flabel+.%0A+++FILTER+langMatches(+lang(%3Flabel)%2C+%22nn%22+)%0A%7D

PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?label1 ?label2 ?label3
FROM <http://data.ub.uio.no/rt>
WHERE
{
  ?concept (skos:prefLabel) ?label1 , ?label2, ?label3
   FILTER langMatches( lang(?label1), "nn" )
   FILTER langMatches( lang(?label2), "nb" )
   FILTER langMatches( lang(?label3), "en" )
}

*/

		this.searchUrl = Config.skosmos.searchUrl;
		this.lang = $state.params.lang || Config.defaultLanguage;
		this.vocab = $state.params.vocab;

		this.formatRequest = angular.bind(this, function(str) {

			var query = (str.length == 2) ? str : '*' + str + '*';

			return {
				query: query,
				labellang: this.lang,
				vocab: this.vocab
			};
		});

		this.formatResult = function(response) {

			return response.results.map(function(result) {
				result.description = result.matchedPrefLabel ? ' (' +result.matchedPrefLabel + ')' : '';
				return result;
			});

		};

		function shortIdFromUri(uri) {
			var s = uri.split('/'),
				id = s.pop(),
				vocab = s.pop();
			return vocab + ':' + id;
		}

		this.selectSubject = function(item) {
			if (item) {
				var subjects = shortIdFromUri(item.originalObject.uri);
				console.log('[SearchController] Selecting subject(s): ' + subjects);

				$state.go('home.subject', {
					lang:		item.originalObject.lang,
					subjects:   subjects
				});
			}
		};
    }
]);<|endoftext|>


<commit_before>var formats = require('./formats.js');

function Validator(schema) {
	this.schema = schema;
}

Validator.prototype = {
	setFormattingLibrary : function() {},
	validate : function(data, schema) {

		var schema = schema || this.schema;

		var self = this,
			success = true,
			errors = [],
			fieldResults = {},
			testResults = Object.keys(schema).reduce(function(results, field) {
				var fieldConfigs = (schema[field] instanceof Array)
					? schema[field]
					: (schema[field] ? [schema[field]] : []);

				var verdict = fieldConfigs.some(function(fieldConfig) {

					var localSuccess = true;

					results[field] = Object.keys(fieldConfig)
						.reduce(function(init, funcName) {

							var v = !!self.validators[funcName].call(self, fieldConfig[funcName], data[field]);
							localSuccess &= v;
							init[funcName] = v;

							if(!v) {
								// errors.push("'"+field+"' failed on '"+funcName+"'");
								errors.push({ field : field, validator : funcName });
							}

							return init;
						}, {});

					return localSuccess;
				});

				fieldResults[field] = verdict;
				success &= verdict;

				return results;
			}, {});

		return {
			results : testResults,
			success : success,
			fieldResults : fieldResults,
			errors : errors
		};

	},

	validators : {
		type : function(target, value) {

			if(value === undefined || value === null) { return true; }
			return (typeof(target) == 'string')
				? (target == typeof value)
				: (value.constructor === target);
		},
		required : function(target, value) {
			return target ? (value !== undefined) : true;
		},
		pattern : function(target, value) {
			if(!(target instanceof RegExp)) {
				throw new Error('Validator pattern must be a regex!');
			}
			return target.test(value);
		},
		format : function(target, value) {
			var formatValidator = formats[target];
			if(!formatValidator) {
				throw new Error("'" + target + "' is not a defined formatting validator");
			}

			return !!formatValidator(value);
		},
		notNull : function(target, value) {
			return target
				? ((value !== null) && (value !== undefined))
				: true;
		},
		max : function(target, value) { return value.length <= target; },
		min : function(target, value) { return value.length >= target; },
		boolean : function(target, value) { return !target || (!!value === value); },
		enum : function(target, value) {
			if(!(target instanceof Array)) {
				throw new Error("Enum value must be an array");
			}
			return !!~target.indexOf(value);
		},
		validator : function(target, value) {
			return target.call(this, value);
		},
		schema : function(target, value) {
			return this.validate(value, target).success;
		}
	}
};

Validator.validate = function(schema, data) {
	var v = new Validator(schema);
	return v.validate(data);
};

module.exports = Validator;<commit_msg>Separated out some files<commit_after>var formats = require('./formats.js');

function Validator(schema) {
	this.schema = schema;
}

Validator.prototype = {
	setFormattingLibrary : function() {},
	validate : function(data, schema) {

		var schema = schema || this.schema;

		var self = this,
			success = true,
			errors = [],
			fieldResults = {},
			testResults = Object.keys(schema).reduce(function(results, field) {
				var fieldConfigs = (schema[field] instanceof Array)
					? schema[field]
					: (schema[field] ? [schema[field]] : []);

				var verdict = fieldConfigs.some(function(fieldConfig) {

					var localSuccess = true;

					results[field] = Object.keys(fieldConfig)
						.reduce(function(init, funcName) {

							var v = !!self.validators[funcName].call(self, fieldConfig[funcName], data[field]);
							localSuccess &= v;
							init[funcName] = v;

							if(!v) {
								// errors.push("'"+field+"' failed on '"+funcName+"'");
								errors.push({ field : field, validator : funcName });
							}

							return init;
						}, {});

					return localSuccess;
				});

				fieldResults[field] = verdict;
				success &= verdict;

				return results;
			}, {});

		return {
			results : testResults,
			success : success,
			fieldResults : fieldResults,
			errors : errors
		};

	},

	validators : {
		type : function(target, value) {

			if(value === undefined || value === null) { return true; }
			return (typeof(target) == 'string')
				? (target == typeof value)
				: (value.constructor === target);
		},
		required : function(target, value) {
			return target ? (value !== undefined) : true;
		},
		pattern : function(target, value) {
			if(!(target instanceof RegExp)) {
				throw new Error('Validator pattern must be a regex!');
			}
			return target.test(value);
		},
		format : function(target, value) {
			var formatValidator = formats[target];
			if(!formatValidator) {
				throw new Error("'" + target + "' is not a defined formatting validator");
			}

			return !!formatValidator(value);
		},
		notNull : function(target, value) {
			return target
				? ((value !== null) && (value !== undefined))
				: true;
		},
		max : function(target, value) { return value.length <= target; },
		min : function(target, value) { return value.length >= target; },
		boolean : function(target, value) { return !target || (!!value === value); },
		unique : function(target, value) {
			if(value instanceof Array) {
				var obj = value.reduce(function(init, v) {
					init[v] = true;
					return init;
				}, {});

				return Object.keys(obj).length == value.length;
			}
			return true;
		},
		enum : function(target, value) {
			if(!(target instanceof Array)) {
				throw new Error("Enum value must be an array");
			}
			return !!~target.indexOf(value);
		},
		validator : function(target, value) {
			return target.call(this, value);
		},
		schema : function(target, value) {
			return this.validate(value, target).success;
		}
	}
};

Validator.validate = function(schema, data) {
	var v = new Validator(schema);
	return v.validate(data);
};

module.exports = Validator;<|endoftext|>


<commit_before>var dragDrop = require('drag-drop/buffer')
var magnet = require('magnet-uri')
var path = require('path')
var prettysize = require('prettysize')
var querystring = require('querystring')
var thunky = require('thunky')
var toBuffer = require('typedarray-to-buffer')
var upload = require('upload-element')
var WebTorrent = require('webtorrent')
var xhr = require('xhr')

var hash = window.location.hash.replace('#', '')

var log = document.querySelector('.log')
var media = document.querySelector('.media')

var getClient = thunky(function (cb) {
  xhr('/rtcConfig', function (err, res) {
    if (err) return cb(err)
    var rtcConfig
    try {
      rtcConfig = JSON.parse(res.body)
    } catch (err) {
      return cb(new Error('Expected JSON response from /rtcConfig: ' + res.body))
    }
    cb(null, new WebTorrent({ rtcConfig: rtcConfig }))
  })
})

getClient(function (err, client) {
  if (err) return error(err)
  window.client = client
})

function download (infoHash) {
  getClient(function (err, client) {
    if (err) return error(err)
    var magnetUri = magnet.encode({
      infoHash: infoHash,
      announce: [ 'wss://tracker.webtorrent.io' ]
    })
    logAppend('using magnet uri: ' + magnetUri)
    client.add(magnetUri, onTorrent)
  })
}

function seed (files) {
  // Store files for 24 hours (if user requests it)
  files.forEach(function (file) {
    xhr({
      url: '/upload?' + querystring.stringify({ name: file.name }),
      method: 'POST',
      headers: {
        'Content-Type': file.type
      },
      body: file
    }, function (err) {
      if (err) return error(err)
      // TODO: add message that file was stored
    })
  })

  // Seed from WebTorrent
  getClient(function (err, client) {
    if (err) return error(err)
    client.seed(files, onTorrent)
  })
}

upload(document.querySelector('input[name=upload]'), { type: 'array' }, onFile)

function onFile (err, results) {
  if (err) return error(err)
  var files = results.map(function (r) {
    var buf = toBuffer(r.target.result)
    buf.name = r.file.name
    buf.size = r.file.size
    buf.lastModifiedDate = r.file.lastModifiedDate
    buf.type = r.file.type
    return buf
  })
  logAppend('Creating .torrent file...
')
  seed(files)
}

dragDrop('body', function (files) {
  logAppend('Creating .torrent file...
')
  seed(files)
})

document.querySelector('form').addEventListener('submit', function (e) {
  e.preventDefault()
  download(document.querySelector('form input[name=infoHash]').value)
})

if (/^[a-f0-9]+$/i.test(hash)) {
  download(hash)
}

function onTorrent (torrent) {
  logAppend('Torrent info hash: ' + torrent.infoHash + ' (link)
')
  logAppend('Downloading from ' + torrent.swarm.wires.length + ' peers
')
  logAppend('progress: starting...')

  torrent.swarm.on('download', function () {
    var progress = (100 * torrent.downloaded / torrent.parsedTorrent.length).toFixed(1)
    logReplace('progress: ' + progress + '% -- download speed: ' + prettysize(torrent.swarm.downloadSpeed()) + '/s
')
  })

  torrent.swarm.on('upload', function () {
    logReplace('upload speed:' + prettysize(torrent.swarm.uploadSpeed()) + '/s
')
  })

  torrent.files.forEach(function (file) {
    var extname = path.extname(file.name)
    if (extname === '.mp4' || extname === '.webm') {
      var video = document.createElement('video')
      video.controls = true
      media.appendChild(video)
      file.createReadStream().pipe(video)
    } else if (extname === '.mp3') {
      var audio = document.createElement('audio')
      audio.controls = true
      media.appendChild(audio)
      file.createReadStream().pipe(audio)
    } else {
      file.getBlobURL(function (err, url) {
        if (err) throw err
        var a = document.createElement('a')
        a.download = file.name
        a.href = url
        a.textContent = 'Download ' + file.name
        log.innerHTML += a.outerHTML + '
'
      })
    }
  })
}

// append a P to the log
function logAppend (str) {
  var p = document.createElement('p')
  p.innerHTML = str
  log.appendChild(p)
}

// replace the last P in the log
function logReplace (str) {
  log.lastChild.innerHTML = str
}

function error (err) {
  console.error(err.stack || err.message || err)
  window.alert(err.message || err)
}
<commit_msg>only use MediaSource if it's available<commit_after>var dragDrop = require('drag-drop/buffer')
var magnet = require('magnet-uri')
var path = require('path')
var prettysize = require('prettysize')
var querystring = require('querystring')
var thunky = require('thunky')
var toBuffer = require('typedarray-to-buffer')
var upload = require('upload-element')
var WebTorrent = require('webtorrent')
var xhr = require('xhr')

var hash = window.location.hash.replace('#', '')

var log = document.querySelector('.log')
var media = document.querySelector('.media')

var getClient = thunky(function (cb) {
  xhr('/rtcConfig', function (err, res) {
    if (err) return cb(err)
    var rtcConfig
    try {
      rtcConfig = JSON.parse(res.body)
    } catch (err) {
      return cb(new Error('Expected JSON response from /rtcConfig: ' + res.body))
    }
    cb(null, new WebTorrent({ rtcConfig: rtcConfig }))
  })
})

getClient(function (err, client) {
  if (err) return error(err)
  window.client = client
})

function download (infoHash) {
  getClient(function (err, client) {
    if (err) return error(err)
    var magnetUri = magnet.encode({
      infoHash: infoHash,
      announce: [ 'wss://tracker.webtorrent.io' ]
    })
    logAppend('using magnet uri: ' + magnetUri)
    client.add(magnetUri, onTorrent)
  })
}

function seed (files) {
  // Store files for 24 hours (if user requests it)
  files.forEach(function (file) {
    xhr({
      url: '/upload?' + querystring.stringify({ name: file.name }),
      method: 'POST',
      headers: {
        'Content-Type': file.type
      },
      body: file
    }, function (err) {
      if (err) return error(err)
      // TODO: add message that file was stored
    })
  })

  // Seed from WebTorrent
  getClient(function (err, client) {
    if (err) return error(err)
    client.seed(files, onTorrent)
  })
}

upload(document.querySelector('input[name=upload]'), { type: 'array' }, onFile)

function onFile (err, results) {
  if (err) return error(err)
  var files = results.map(function (r) {
    var buf = toBuffer(r.target.result)
    buf.name = r.file.name
    buf.size = r.file.size
    buf.lastModifiedDate = r.file.lastModifiedDate
    buf.type = r.file.type
    return buf
  })
  logAppend('Creating .torrent file...
')
  seed(files)
}

dragDrop('body', function (files) {
  logAppend('Creating .torrent file...
')
  seed(files)
})

document.querySelector('form').addEventListener('submit', function (e) {
  e.preventDefault()
  download(document.querySelector('form input[name=infoHash]').value)
})

if (/^[a-f0-9]+$/i.test(hash)) {
  download(hash)
}

function onTorrent (torrent) {
  logAppend('Torrent info hash: ' + torrent.infoHash + ' (link)
')
  logAppend('Downloading from ' + torrent.swarm.wires.length + ' peers
')
  logAppend('progress: starting...')

  torrent.swarm.on('download', function () {
    var progress = (100 * torrent.downloaded / torrent.parsedTorrent.length).toFixed(1)
    logReplace('progress: ' + progress + '% -- download speed: ' + prettysize(torrent.swarm.downloadSpeed()) + '/s
')
  })

  torrent.swarm.on('upload', function () {
    logReplace('upload speed:' + prettysize(torrent.swarm.uploadSpeed()) + '/s
')
  })

  torrent.files.forEach(function (file) {
    var extname = path.extname(file.name)
    if (window.MediaSource && extname === '.mp4' || extname === '.webm') {
      var video = document.createElement('video')
      video.controls = true
      media.appendChild(video)
      file.createReadStream().pipe(video)
    } else if (window.MediaSource && extname === '.mp3') {
      var audio = document.createElement('audio')
      audio.controls = true
      media.appendChild(audio)
      file.createReadStream().pipe(audio)
    } else {
      file.getBlobURL(function (err, url) {
        if (err) throw err
        var a = document.createElement('a')
        a.download = file.name
        a.href = url
        a.textContent = 'Download ' + file.name
        log.innerHTML += a.outerHTML + '
'
      })
    }
  })
}

// append a P to the log
function logAppend (str) {
  var p = document.createElement('p')
  p.innerHTML = str
  log.appendChild(p)
}

// replace the last P in the log
function logReplace (str) {
  log.lastChild.innerHTML = str
}

function error (err) {
  console.error(err.stack || err.message || err)
  window.alert(err.message || err) //eslint-disable-line
}
<|endoftext|>


<commit_before>// UI for the Navigation Bar in the sidebar

NavigationBar = {
  detectSelectedSection: function() {
    // Direct match
		var link = $$('.nav_links a').select(function(e) {
			return e.getAttribute('href') == window.location.pathname
		}).last()
		if (link) link.up('.el').addClassName('selected')
		// Close enough
		if (link == undefined) {
			var link = $$('.nav_links a').sortBy(function(e) {
				return e.getAttribute('href').length
				}).select(function(e) {
					return (window.location.pathname.search(e.getAttribute('href')) > -1 && e.getAttribute('href') != '/')
			}).last()
			if (link) link.up('.el').addClassName('children-selected')
		}

    if(link) return link.up('.el')
  },

  showContainers: function(current) {
    var container = current.up('.contained')
    if (container) {
      container.show().previous('.el').addClassName('expanded')
      while (container = container.up('.contained')) {
				container.show().previous('.el').addClassName('expanded')
			}
    }
  },

  scroll: function() {
    var sidebar = $('column')
    if (document.viewport.getHeight() > sidebar.getHeight() && document.viewport.getScrollOffsets()[1] >= NavigationBar.initial_offest) {
      sidebar.style.position = 'fixed'
      sidebar.style.top = 0
    }
    else
    {
      sidebar.style.position = 'absolute'
      sidebar.style.top = 'auto'
    }
  },

  scrollToTopIfNeeded: function() {
    var sidebar = $('column')
    if (document.viewport.getHeight() < sidebar.getHeight()) {
      NavigationBar.scroll()
      Effect.ScrollTo('container', { duration: '0.4' })
    }
  },

  toggleElement: function(el, effect) {
    var contained = el.next()
    // if next element is an expanded area..
    if (contained && contained.hasClassName('contained')) {
      if (el.hasClassName('expanded')) {
        // contract it if it's open
        el.removeClassName('expanded')
        contained.setStyle({height: ''})
        contained.blindUp({ duration: 0.2 })
      } else {
        // contract others if open
        var visible_containers = el.up().select('.contained').select( function(e) { return e.visible() })
        effect ? visible_containers.invoke("blindUp", { duration: 0.2 }) : visible_containers.invoke('hide')
        el.up().select('.el').invoke('removeClassName', 'expanded')
        // expand the selected one
        el.addClassName('expanded')

        contained.setStyle({height: ''})
        effect ? contained.blindDown({ duration: 0.2 }) : contained.show()
        setTimeout(function() { NavigationBar.scrollToTopIfNeeded() }, 100)
      }
      // Stop the event and don't follow the link
      return true
    }
    // Stop the event if it's selected (don't follow the link)
    return el.hasClassName('selected')
  },

  selectElement: function(el) {
    $$('.nav_links .el.selected').invoke('removeClassName', 'selected').invoke('removeClassName', 'children-selected')
    el.addClassName('selected')
  }
}

document.on("dom:loaded", function() {
  $$('.nav_links .contained').invoke('hide')
  NavigationBar.initial_offest = window.$('column').viewportOffset().top

  // Select and expand the current element
  var current = NavigationBar.detectSelectedSection()
  if (current) {
    // If it's hidden in the "Show more" options
    if(!current.visible()) {
      $('show_more').insert({before: current})
      current.show()
    }
    NavigationBar.toggleElement(current)
    NavigationBar.showContainers(current)
  }
  // If we're on All Projects, then expand the recent projects list
  var elements = $$('.nav_links .el')
  if (elements[0] && elements[0].hasClassName('selected')) {
    NavigationBar.toggleElement(elements[1])
  }
})

document.on('click', '.nav_links .el', function(e,el) {
  if (e.isMiddleClick()) return
  var clicked = Event.element(e)
  if (clicked.id == 'open_my_tasks') {
    window.location = clicked.readAttribute("href")
    e.stop()
  } else {
    NavigationBar.toggleElement(el, true) && e.stop()
  }
})

document.on('click', '.nav_links .el#show_all_projects', function(e,el) {
  if (e.isMiddleClick()) return
  e.stop()
  Projects.showAllProjects()
})

document.on('click', '.nav_links .el .show_more', function(e,el) {
  e.stop()
  $$('.el#show_more').invoke('hide')
  $$('.el.extra').invoke('show')
})

document.on('click', '.nav_links .el .show_less', function(e,el) {
  e.stop()
  $$('.el#show_more').invoke('show')
  $$('.el.extra').invoke('hide')
})

window.onscroll = function() { NavigationBar.scroll() }

<commit_msg>Fixed typo<commit_after>// UI for the Navigation Bar in the sidebar

NavigationBar = {
  detectSelectedSection: function() {
    // Direct match
		var link = $$('.nav_links a').select(function(e) {
			return e.getAttribute('href') == window.location.pathname
		}).last()
		if (link) link.up('.el').addClassName('selected')
		// Close enough
		if (link == undefined) {
			var link = $$('.nav_links a').sortBy(function(e) {
				return e.getAttribute('href').length
				}).select(function(e) {
					return (window.location.pathname.search(e.getAttribute('href')) > -1 && e.getAttribute('href') != '/')
			}).last()
			if (link) link.up('.el').addClassName('children-selected')
		}

    if(link) return link.up('.el')
  },

  showContainers: function(current) {
    var container = current.up('.contained')
    if (container) {
      container.show().previous('.el').addClassName('expanded')
      while (container = container.up('.contained')) {
				container.show().previous('.el').addClassName('expanded')
			}
    }
  },

  scroll: function() {
    var sidebar = $('column')
    if (document.viewport.getHeight() > sidebar.getHeight() && document.viewport.getScrollOffsets()[1] >= NavigationBar.initial_offset) {
      sidebar.style.position = 'fixed'
      sidebar.style.top = 0
    }
    else
    {
      sidebar.style.position = 'absolute'
      sidebar.style.top = 'auto'
    }
  },

  scrollToTopIfNeeded: function() {
    var sidebar = $('column')
    if (document.viewport.getHeight() < sidebar.getHeight()) {
      NavigationBar.scroll()
      Effect.ScrollTo('container', { duration: '0.4' })
    }
  },

  toggleElement: function(el, effect) {
    var contained = el.next()
    // if next element is an expanded area..
    if (contained && contained.hasClassName('contained')) {
      if (el.hasClassName('expanded')) {
        // contract it if it's open
        el.removeClassName('expanded')
        contained.setStyle({height: ''})
        contained.blindUp({ duration: 0.2 })
      } else {
        // contract others if open
        var visible_containers = el.up().select('.contained').select( function(e) { return e.visible() })
        effect ? visible_containers.invoke("blindUp", { duration: 0.2 }) : visible_containers.invoke('hide')
        el.up().select('.el').invoke('removeClassName', 'expanded')
        // expand the selected one
        el.addClassName('expanded')

        contained.setStyle({height: ''})
        effect ? contained.blindDown({ duration: 0.2 }) : contained.show()
        setTimeout(function() { NavigationBar.scrollToTopIfNeeded() }, 100)
      }
      // Stop the event and don't follow the link
      return true
    }
    // Stop the event if it's selected (don't follow the link)
    return el.hasClassName('selected')
  },

  selectElement: function(el) {
    $$('.nav_links .el.selected').invoke('removeClassName', 'selected').invoke('removeClassName', 'children-selected')
    el.addClassName('selected')
  }
}

document.on("dom:loaded", function() {
  $$('.nav_links .contained').invoke('hide')
  NavigationBar.initial_offset = window.$('column').viewportOffset().top

  // Select and expand the current element
  var current = NavigationBar.detectSelectedSection()
  if (current) {
    // If it's hidden in the "Show more" options
    if(!current.visible()) {
      $('show_more').insert({before: current})
      current.show()
    }
    NavigationBar.toggleElement(current)
    NavigationBar.showContainers(current)
  }
  // If we're on All Projects, then expand the recent projects list
  var elements = $$('.nav_links .el')
  if (elements[0] && elements[0].hasClassName('selected')) {
    NavigationBar.toggleElement(elements[1])
  }
})

document.on('click', '.nav_links .el', function(e,el) {
  if (e.isMiddleClick()) return
  var clicked = Event.element(e)
  if (clicked.id == 'open_my_tasks') {
    window.location = clicked.readAttribute("href")
    e.stop()
  } else {
    NavigationBar.toggleElement(el, true) && e.stop()
  }
})

document.on('click', '.nav_links .el#show_all_projects', function(e,el) {
  if (e.isMiddleClick()) return
  e.stop()
  Projects.showAllProjects()
})

document.on('click', '.nav_links .el .show_more', function(e,el) {
  e.stop()
  $$('.el#show_more').invoke('hide')
  $$('.el.extra').invoke('show')
})

document.on('click', '.nav_links .el .show_less', function(e,el) {
  e.stop()
  $$('.el#show_more').invoke('show')
  $$('.el.extra').invoke('hide')
})

window.onscroll = function() { NavigationBar.scroll() }

<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var multer  = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'tmp/uploads')
  },
  filename: function (req, file, cb) {
    //cb(null, file.originalname + '-' + Date.now())
    cb(null, 'fileToConvert.json')
  }
})

var upload = multer({ storage: storage });
var fs = require('fs');
var xml2js = require('xml2js');

var builder = new xml2js.Builder();

var parser = new xml2js.Parser({
    //attrkey : "@",
    //mergeAttrs : true,
    //charkey : "$String",
    //trim : true,
    //normalize : true,
    explicitArray : false
    //explicitRoot : true
});

var request = require('superagent');

// middleware specific to this router
// a middleware with no mount path; gets executed for every request to the app
router.use('/upload', function(req, res, next) {
  // delete existing temporary uploaded file(s)
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send({endpoint: 'Validator home page'});
  console.log('Did not send response, so just go to next');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About the Validator (came from next call)');
});

router.post('/upload', upload.single('fileToValidate'), function (req, res, next) {
  fs.readFile('tmp/uploads/fileToConvert.json', function(err, data) {
          // determine the profile we need to use

       var xml = builder.buildObject(JSON.parse(data));
          // now build XML from the resulting JSON data
        fs.writeFile('public/fileToValidate.xml', xml, function (err) {
          if (err) {
            console.log("Got error writing from JSON back to XML: " + err);
          }
            console.log("File saved as fileToValidate.xml");
          });
        console.log('Now validation should take over');
    });
  //this has multer upload the file and pass it on for further manipulation
  next();
});

router.use('/upload', function(req, res) {
  request
   .get('http://validator.imsglobal.org/validate')
   .query({ source: 'https://lti.learningcomponents.com/fileToValidate.xml' })
   .query({ profile: 'QTIv2p1ASI_Base'})
   .end(function(err, response){
     if (err) {
       console.log('Got an error trying to validate: ' + err);
     }
     res.send(response.text);
   });
  //http://validator.imsglobal.org/validate?source=http://validator.imsglobal.org/test/cartridge.imscc&xsl=http://validator.imsglobal.org/template.xsl&profile=1.1.0
});

module.exports = router;
<commit_msg>Added xsl to get some formatting on the response.  Changed nginx so that is is all http instead of https<commit_after>var express = require('express');
var router = express.Router();
var multer  = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'tmp/uploads')
  },
  filename: function (req, file, cb) {
    //cb(null, file.originalname + '-' + Date.now())
    cb(null, 'fileToConvert.json')
  }
})

var upload = multer({ storage: storage });
var fs = require('fs');
var xml2js = require('xml2js');

var builder = new xml2js.Builder();

var parser = new xml2js.Parser({
    //attrkey : "@",
    //mergeAttrs : true,
    //charkey : "$String",
    //trim : true,
    //normalize : true,
    explicitArray : false
    //explicitRoot : true
});

var request = require('superagent');

// middleware specific to this router
// a middleware with no mount path; gets executed for every request to the app
router.use('/upload', function(req, res, next) {
  // delete existing temporary uploaded file(s)
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send({endpoint: 'Validator home page'});
  console.log('Did not send response, so just go to next');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About the Validator (came from next call)');
});

router.post('/upload', upload.single('fileToValidate'), function (req, res, next) {
  fs.readFile('tmp/uploads/fileToConvert.json', function(err, data) {
          // determine the profile we need to use

       var xml = builder.buildObject(JSON.parse(data));
          // now build XML from the resulting JSON data
        fs.writeFile('public/fileToValidate.xml', xml, function (err) {
          if (err) {
            console.log("Got error writing from JSON back to XML: " + err);
          }
            console.log("File saved as fileToValidate.xml");
          });
        console.log('Now validation should take over');
    });
  //this has multer upload the file and pass it on for further manipulation
  next();
});

router.use('/upload', function(req, res) {
  request
   .get('http://validator.imsglobal.org/validate')
   .query({ source: 'http://lti.learningcomponents.com/fileToValidate.xml' })
   .query({ xsl: 'http://validator.imsglobal.org/template.xsl'})
   .query({ profile: 'QTIv2p1ASI_Base'})
   .end(function(err, response){
     if (err) {
       console.log('Got an error trying to validate: ' + err);
     }
     res.send(response.text);
   });
  //http://validator.imsglobal.org/validate?source=http://validator.imsglobal.org/test/cartridge.imscc&xsl=http://validator.imsglobal.org/template.xsl&profile=1.1.0
});

module.exports = router;
<|endoftext|>


<commit_before>import './style/style.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, hashHistory, IndexRoute } from 'react-router';

import ApolloClient from 'apollo-client';
import { ApolloProvider} from 'react-apollo';

import App from './components/App'
import ProjectList from './components/ProjectList';
import ProjectCreate from './components/ProjectCreate';
import ProjectDetail from './components/ProjectDetail';

const client = new ApolloClient({
  //o = object
  // dataIdFromObject, takes every single piece of data that is fetch on the Apollo Client
  // id = result identifies piece of data
  // mmm tells React when that piece of data (id) is updated, only works when all Id's are uniques
  // always return a Id on a query, if NOT Apollo can do that
  dataIdFromObject: o => o.id
});

const Root = () => {
  return (
    <ApolloProvider client={client}>
      <Router history={hashHistory}>
        <Route path="/" component={App}>
          <IndexRoute component={ProjectList} />
          <Route path="projects/new" component={ProjectCreate} />
          <Route path="projects/:id" component={ProjectDetail} />
        </Route>
      </Router>
    </ApolloProvider>
  )
};

ReactDOM.render(
  <Root />,
  document.querySelector('#mainEstimation')
);
<commit_msg>typo nnaahh<commit_after>import './style/style.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, hashHistory, IndexRoute } from 'react-router';

import ApolloClient from 'apollo-client';
import { ApolloProvider} from 'react-apollo';

import App from './components/App'
import ProjectList from './components/ProjectList';
import ProjectCreate from './components/ProjectCreate';
import ProjectDetail from './components/ProjectDetail';

const client = new ApolloClient({
  //o = object
  // dataIdFromObject, takes every single piece of data that is fetch on the Apollo Client
  // id = result identifies piece of data
  // mmm tells React when that piece of data (id) is updated, only works when all Id's are uniques
  // always return an Id on a query, if NOT Apolo can't do that
  dataIdFromObject: o => o.id
});

const Root = () => {
  return (
    <ApolloProvider client={client}>
      <Router history={hashHistory}>
        <Route path="/" component={App}>
          <IndexRoute component={ProjectList} />
          <Route path="projects/new" component={ProjectCreate} />
          <Route path="projects/:id" component={ProjectDetail} />
        </Route>
      </Router>
    </ApolloProvider>
  )
};

ReactDOM.render(
  <Root />,
  document.querySelector('#mainEstimation')
);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017-present, Viro, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  View,
  StyleSheet,
  PixelRatio,
  TouchableHighlight,
} from 'react-native';

import {
  ViroSceneNavigator,
  ViroARSceneNavigator
} from 'react-viro';

/*
 TODO: Insert your API key below
 */
var sharedProps = {
  apiKey:"API_KEY_HERE",
}

// Sets the default scene you want for AR and VR
var InitialARScene = require('./js/HelloWorldSceneAR');
var InitialVRScene = require('./js/HelloWorldScene');

var UNSET = "UNSET";
var VR_NAVIGATOR_TYPE = "VR";
var AR_NAVIGATOR_TYPE = "AR";

// This determines which type of experience to launch in, or UNSET, if the user should
// be presented with a choice of AR or VR. By default, we offer the user a choice.
var defaultNavigatorType = UNSET;

export default class ViroSample extends Component {
  constructor() {
    super();

    this.state = {
      navigatorType : defaultNavigatorType,
      sharedProps : sharedProps
    }
    this._getExperienceSelector = this._getExperienceSelector.bind(this);
    this._getARNavigator = this._getARNavigator.bind(this);
    this._getVRNavigator = this._getVRNavigator.bind(this);
    this._getExperienceButtonOnPress = this._getExperienceButtonOnPress.bind(this);
    this._exitViro = this._exitViro.bind(this);
  }

  // Replace this function with the contents of _getVRNavigator() or _getARNavigator()
  // if you are building a specific type of experience.
  render() {
    if (this.state.navigatorType == UNSET) {
      return this._getExperienceSelector();
    } else if (this.state.navigatorType == VR_NAVIGATOR_TYPE) {
      return this._getVRNavigator();
    } else if (this.state.navigatorType == AR_NAVIGATOR_TYPE) {
      return this._getARNavigator();
    }
  }

  // Presents the user with a choice of an AR or VR experience
  _getExperienceSelector() {
    return (
      <View style={localStyles.outer} >
        <View style={localStyles.inner} >

          <Text style={localStyles.titleText}>
            Choose your desired experience:
          </Text>

          <TouchableHighlight style={localStyles.buttons}
            onPress={this._getExperienceButtonOnPress(AR_NAVIGATOR_TYPE)}
            underlayColor={'#68a0ff'} >

            <Text style={localStyles.buttonText}>AR</Text>
          </TouchableHighlight>

          <TouchableHighlight style={localStyles.buttons}
            onPress={this._getExperienceButtonOnPress(VR_NAVIGATOR_TYPE)}
            underlayColor={'#68a0ff'} >

            <Text style={localStyles.buttonText}>VR</Text>
          </TouchableHighlight>
        </View>
      </View>
    );
  }

  // Returns the ViroARSceneNavigator which will start the AR experience
  _getARNavigator() {
    return (
      <View style={localStyles.viroContainer} >

        <ViroARSceneNavigator {...this.state.sharedProps}
          initialScene={{scene: InitialARScene}} />

        {/* Add button to "exit" from AR */}
        <View style={{position: 'absolute',  left: 0, right: 0, bottom: 20, alignItems: 'center'}}>
          <TouchableHighlight style={localStyles.buttons}
            onPress={this._exitViro}
            underlayColor={'#00000000'} >
            <Text style={localStyles.buttonText}>Exit</Text>
          </TouchableHighlight>
        </View>
      </View>
    );
  }

  // Returns the ViroSceneNavigator which will start the VR experience
  _getVRNavigator() {
    return (
      <ViroSceneNavigator {...this.state.sharedProps}
        initialScene={{scene: InitialVRScene}} onExitViro={this._exitViro}/>
    );
  }

  // This function returns an anonymous/lambda function to be used
  // by the experience selector buttons
  _getExperienceButtonOnPress(navigatorType) {
    return () => {
      this.setState({
        navigatorType : navigatorType
      })
    }
  }

  // This function "exits" Viro by setting the navigatorType to UNSET.
  _exitViro() {
    this.setState({
      navigatorType : UNSET
    })
  }
}

var localStyles = StyleSheet.create({
  viroContainer :{
    flex : 1,
    backgroundColor: "black",
  },
  outer : {
    flex : 1,
    flexDirection: 'row',
    alignItems:'center',
    backgroundColor: "black",
  },
  inner: {
    flex : 1,
    flexDirection: 'column',
    alignItems:'center',
    backgroundColor: "black",
  },
  titleText: {
    paddingTop: 30,
    paddingBottom: 20,
    color:'#fff',
    textAlign:'center',
    fontSize : 25
  },
  buttonText: {
    color:'#fff',
    textAlign:'center',
    fontSize : 20
  },
  buttons : {
    height: 80,
    width: 150,
    paddingTop:20,
    paddingBottom:20,
    marginTop: 10,
    marginBottom: 10,
    backgroundColor:'#68a0cf',
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#fff',
  },
  exitButton : {
    height: 50,
    width: 100,
    paddingTop:10,
    paddingBottom:10,
    marginTop: 10,
    marginBottom: 10,
    backgroundColor:'#68a0cf',
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#fff',
  }
});

AppRegistry.registerComponent('APP_NAME_HERE', () => ViroSample);

// The below line is necessary for use with the TestBed App
AppRegistry.registerComponent('ViroSample', () => ViroSample);

<commit_msg>Update Hello World JS file<commit_after>/**
 * Copyright (c) 2017-present, Viro, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  View,
  StyleSheet,
  PixelRatio,
  TouchableHighlight,
} from 'react-native';

import {
  ViroSceneNavigator,
  ViroARSceneNavigator
} from 'react-viro';

/*
 TODO: Insert your API key below
 */
var sharedProps = {
  apiKey:"API_KEY_HERE",
}

// Sets the default scene you want for AR and VR
var InitialARScene = require('./js/HelloWorldSceneAR');
var InitialVRScene = require('./js/HelloWorldScene');

var UNSET = "UNSET";
var VR_NAVIGATOR_TYPE = "VR";
var AR_NAVIGATOR_TYPE = "AR";

// This determines which type of experience to launch in, or UNSET, if the user should
// be presented with a choice of AR or VR. By default, we offer the user a choice.
var defaultNavigatorType = UNSET;

export default class ViroSample extends Component {
  constructor() {
    super();

    this.state = {
      navigatorType : defaultNavigatorType,
      sharedProps : sharedProps
    }
    this._getExperienceSelector = this._getExperienceSelector.bind(this);
    this._getARNavigator = this._getARNavigator.bind(this);
    this._getVRNavigator = this._getVRNavigator.bind(this);
    this._getExperienceButtonOnPress = this._getExperienceButtonOnPress.bind(this);
    this._exitViro = this._exitViro.bind(this);
  }

  // Replace this function with the contents of _getVRNavigator() or _getARNavigator()
  // if you are building a specific type of experience.
  render() {
    if (this.state.navigatorType == UNSET) {
      return this._getExperienceSelector();
    } else if (this.state.navigatorType == VR_NAVIGATOR_TYPE) {
      return this._getVRNavigator();
    } else if (this.state.navigatorType == AR_NAVIGATOR_TYPE) {
      return this._getARNavigator();
    }
  }

  // Presents the user with a choice of an AR or VR experience
  _getExperienceSelector() {
    return (
      <View style={localStyles.outer} >
        <View style={localStyles.inner} >

          <Text style={localStyles.titleText}>
            Choose your desired experience:
          </Text>

          <TouchableHighlight style={localStyles.buttons}
            onPress={this._getExperienceButtonOnPress(AR_NAVIGATOR_TYPE)}
            underlayColor={'#68a0ff'} >

            <Text style={localStyles.buttonText}>AR</Text>
          </TouchableHighlight>

          <TouchableHighlight style={localStyles.buttons}
            onPress={this._getExperienceButtonOnPress(VR_NAVIGATOR_TYPE)}
            underlayColor={'#68a0ff'} >

            <Text style={localStyles.buttonText}>VR</Text>
          </TouchableHighlight>
        </View>
      </View>
    );
  }

  // Returns the ViroARSceneNavigator which will start the AR experience
  _getARNavigator() {
    return (
      <View style={localStyles.viroContainer} >

        <ViroARSceneNavigator {...this.state.sharedProps}
          initialScene={{scene: InitialARScene}} />

        {/* Add button to "exit" from AR */}
        <View style={{position: 'absolute',  left: 0, right: 0, bottom: 20, alignItems: 'center'}}>
          <TouchableHighlight style={localStyles.exitButton}
            onPress={this._exitViro}
            underlayColor={'#00000000'} >
            <Text style={localStyles.buttonText}>Exit</Text>
          </TouchableHighlight>
        </View>
      </View>
    );
  }

  // Returns the ViroSceneNavigator which will start the VR experience
  _getVRNavigator() {
    return (
      <ViroSceneNavigator {...this.state.sharedProps}
        initialScene={{scene: InitialVRScene}} onExitViro={this._exitViro}/>
    );
  }

  // This function returns an anonymous/lambda function to be used
  // by the experience selector buttons
  _getExperienceButtonOnPress(navigatorType) {
    return () => {
      this.setState({
        navigatorType : navigatorType
      })
    }
  }

  // This function "exits" Viro by setting the navigatorType to UNSET.
  _exitViro() {
    this.setState({
      navigatorType : UNSET
    })
  }
}

var localStyles = StyleSheet.create({
  viroContainer :{
    flex : 1,
    backgroundColor: "black",
  },
  outer : {
    flex : 1,
    flexDirection: 'row',
    alignItems:'center',
    backgroundColor: "black",
  },
  inner: {
    flex : 1,
    flexDirection: 'column',
    alignItems:'center',
    backgroundColor: "black",
  },
  titleText: {
    paddingTop: 30,
    paddingBottom: 20,
    color:'#fff',
    textAlign:'center',
    fontSize : 25
  },
  buttonText: {
    color:'#fff',
    textAlign:'center',
    fontSize : 20
  },
  buttons : {
    height: 80,
    width: 150,
    paddingTop:20,
    paddingBottom:20,
    marginTop: 10,
    marginBottom: 10,
    backgroundColor:'#68a0cf',
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#fff',
  },
  exitButton : {
    height: 50,
    width: 100,
    paddingTop:10,
    paddingBottom:10,
    marginTop: 10,
    marginBottom: 10,
    backgroundColor:'#68a0cf',
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#fff',
  }
});

AppRegistry.registerComponent('APP_NAME_HERE', () => ViroSample);

// The below line is necessary for use with the TestBed App
AppRegistry.registerComponent('ViroSample', () => ViroSample);

<|endoftext|>


<commit_before>// Copsy, event-driven form validation for jQuery, using `$.Deferred`.
// Version 0.1
// (c) 2011 [Fred Arnoux](mailto:fred@farnoux.com)
// Released under the MIT license

(function ($) {

  //## Copsy object
  function Copsy(element, validators) {
    this.$element = $(element);
    this.validators = validators;
  }

  // Return the validator that didn't pass, `false` otherwise.
  Copsy.prototype.validate = function () {
    if ($.fn.copsy.skip(this.$element)) {
      return false;
    }

    var v, args,
      i = 0,
      l = this.validators.length,
      value = this.$element.val(),
      // Create a [Deferred object](http://api.jquery.com/category/deferred-object/) that wrap the validation result.
      dfd = $.Deferred();

    for (; i < l; i++) {
      v = this.validators[i];
      args = (v.test.length === 2) ? [this.$element, value] : [value];

      //* Deferred is rejected if validation fails.
      if (!v.test.apply(null, args)) {
        dfd.reject(this.$element, v.name);
        break;
      }
    }

    //* Or successfully resolved otherwise.
    if (!dfd.isRejected()) {
      dfd.resolve(this.$element);
    }

    // Finally the [Promise object](http://api.jquery.com/deferred.promise/) of the Deferred is returned.
    return dfd.promise();
  };

  //## Copsy jQuery plugin
  $.fn.copsy = function (options) {
    if (options === true) {
      return get(this);
    }
    if (typeof options === 'string') {
      options = { trigger: options };
    }

    options = $.extend({}, $.fn.copsy.defaults, options);

    function getValidator(element, name) {
      // Is there validators matching this `name` ?
      var test, v = $.fn.copsy.validators[name];
      if (!v) {
        return null;
      }

      // Iterate over validators of type `name`
      $.each(v, function (selector, fn) {
        if (element.is(selector)) {
          test = fn;
          return false; // Break the loop
        }
      });

      return { name: name, test: test };
    }

    function getValidators(element) {
      element = $(element);
      var classnames = element.attr('class');
      if(classnames === undefined) {
        return null;
      }
      return $.map(classnames.split(/\s+/), function (name) {
        return getValidator(element, name) || null;
      });
    }

    // Lazy getter that return the Copsy object corresponding to the element passed.
    function get(ele) {
      var c = $.data(ele, 'copsy');
      if (!c) {
        c = new Copsy(ele, getValidators(ele));
        $.data(ele, 'copsy', c);
      }
      return c;
    }

    function validate() {
      // Get the Copsy object associated to the element.
      // Start validation.
      // Get the returned promise.
      var promise = get(this).validate();

      // Apply validation handlers to the promise object
      $.each($.fn.copsy.handlers, function () {
        this(promise);
      });

      // Return `false` if validation has failed.
      return promise.isRejected();
    }

    //### Event Binding Options

    //* If some specific trigger events have been passed, bind validation to them.
    if (typeof options.trigger === 'string') {
      return this.bind(options.trigger, validate);
    }

    //* Else apply default trigger events corresponding to the selector this element matches.
    for (var i = 0, l = options.trigger.length; i < l; i += 2) {
      if(this.is(options.trigger[i])) {
        this.bind(options.trigger[i+1], validate);
        break;
      }
    }

    return this;
  };

  $.fn.copsy.skip = function (element) {
    if (element.is(':hidden')) {
      return true;
    }
  };

  //### Default options
  $.fn.copsy.defaults = {
    // Different selectors and their corresponding trigger events.
    trigger: [
      ':radio', 'change',
      ':input:not(:radio):not(:submit)', 'blur change keyup'
    ]
  }

  // Array of available validator objects.
  $.fn.copsy.validators = {};

  // Handy helper function to easily register new validators.
  // `id` is the unique id
  // `selector` is a CSS selector
  $.fn.copsy.addValidator = function (id, selector, fn) {
    var v = $.fn.copsy.validators[id];
    if (!v) {
      $.fn.copsy.validators[id] = v = {};
    }
    v[selector] = fn;
  };

  // Array of validation handlers.
  $.fn.copsy.handlers = [];

  // Handy helper function to add new validation handlers.
  // `fn` argument is a handler function that should accept a Promise object as unique argument.
  $.fn.copsy.addHandler = function (fn) {
    if ($.isFunction(fn) && fn.length === 1) {
      $.fn.copsy.handlers.push(fn);
    }
  };

})(jQuery);

//
//## Configuration
//
(function ($) {
  //
  //### Define validators
  //
  $.fn.copsy.addValidator("mandatory", "input.mandatory", function (value) {
    return value.length > 0;
  });

  $.fn.copsy.addValidator("numeric", "input.numeric", function (value) {
    return value.length < 1 || /^\d+$/i.test(value);
  });

  $.fn.copsy.addValidator("email", "input.email", function (value) {
    return value.length < 1 || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
  });

})(jQuery);<commit_msg>Remove the `skip` condition. Not very useful, and not very stylish.<commit_after>// Copsy, event-driven form validation for jQuery, using `$.Deferred`.
// Version 0.1
// (c) 2011 [Fred Arnoux](mailto:fred@farnoux.com)
// Released under the MIT license

(function ($) {

  //## Copsy object
  function Copsy(element, validators) {
    this.$element = $(element);
    this.validators = validators;
  }

  // Return the validator that didn't pass, `false` otherwise.
  Copsy.prototype.validate = function () {
    var v, args,
      i = 0,
      l = this.validators.length,
      value = this.$element.val(),
      // Create a [Deferred object](http://api.jquery.com/category/deferred-object/) that wrap the validation result.
      dfd = $.Deferred();

    for (; i < l; i++) {
      v = this.validators[i];
      args = (v.test.length === 2) ? [this.$element, value] : [value];

      //* Deferred is rejected if validation fails.
      if (!v.test.apply(null, args)) {
        dfd.reject(this.$element, v.name);
        break;
      }
    }

    //* Or successfully resolved otherwise.
    if (!dfd.isRejected()) {
      dfd.resolve(this.$element);
    }

    // Finally the [Promise object](http://api.jquery.com/deferred.promise/) of the Deferred is returned.
    return dfd.promise();
  };

  //## Copsy jQuery plugin
  $.fn.copsy = function (options) {
    if (options === true) {
      return get(this);
    }
    if (typeof options === 'string') {
      options = { trigger: options };
    }

    options = $.extend({}, $.fn.copsy.defaults, options);

    function getValidator(element, name) {
      // Is there validators matching this `name` ?
      var test, v = $.fn.copsy.validators[name];
      if (!v) {
        return null;
      }

      // Iterate over validators of type `name`
      $.each(v, function (selector, fn) {
        if (element.is(selector)) {
          test = fn;
          return false; // Break the loop
        }
      });

      return { name: name, test: test };
    }

    function getValidators(element) {
      element = $(element);
      var classnames = element.attr('class');
      if(classnames === undefined) {
        return null;
      }
      return $.map(classnames.split(/\s+/), function (name) {
        return getValidator(element, name) || null;
      });
    }

    // Lazy getter that return the Copsy object corresponding to the element passed.
    function get(ele) {
      var c = $.data(ele, 'copsy');
      if (!c) {
        c = new Copsy(ele, getValidators(ele));
        $.data(ele, 'copsy', c);
      }
      return c;
    }

    function validate() {
      // Get the Copsy object associated to the element.
      // Start validation.
      // Get the returned promise.
      var promise = get(this).validate();

      // Apply validation handlers to the promise object
      $.each($.fn.copsy.handlers, function () {
        this(promise);
      });

      // Return `false` if validation has failed.
      return promise.isRejected();
    }

    //### Event Binding Options

    //* If some specific trigger events have been passed, bind validation to them.
    if (typeof options.trigger === 'string') {
      return this.bind(options.trigger, validate);
    }

    //* Else apply default trigger events corresponding to the selector this element matches.
    for (var i = 0, l = options.trigger.length; i < l; i += 2) {
      if(this.is(options.trigger[i])) {
        this.bind(options.trigger[i+1], validate);
        break;
      }
    }

    return this;
  };

  //### Default options
  $.fn.copsy.defaults = {
    // Different selectors and their corresponding trigger events.
    trigger: [
      ':radio', 'change',
      ':input:not(:radio):not(:submit)', 'blur change keyup'
    ]
  }

  // Array of available validator objects.
  $.fn.copsy.validators = {};

  // Handy helper function to easily register new validators.
  // `id` is the unique id
  // `selector` is a CSS selector
  $.fn.copsy.addValidator = function (id, selector, fn) {
    var v = $.fn.copsy.validators[id];
    if (!v) {
      $.fn.copsy.validators[id] = v = {};
    }
    v[selector] = fn;
  };

  // Array of validation handlers.
  $.fn.copsy.handlers = [];

  // Handy helper function to add new validation handlers.
  // `fn` argument is a handler function that should accept a Promise object as unique argument.
  $.fn.copsy.addHandler = function (fn) {
    if ($.isFunction(fn) && fn.length === 1) {
      $.fn.copsy.handlers.push(fn);
    }
  };

})(jQuery);

//
//## Configuration
//
(function ($) {
  //
  //### Define validators
  //
  $.fn.copsy.addValidator("mandatory", "input.mandatory", function (value) {
    return value.length > 0;
  });

  $.fn.copsy.addValidator("numeric", "input.numeric", function (value) {
    return value.length < 1 || /^\d+$/i.test(value);
  });

  $.fn.copsy.addValidator("email", "input.email", function (value) {
    return value.length < 1 || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
  });

})(jQuery);<|endoftext|>


<commit_before>/**
 * jQuery Modal
 * Version: 0.1.0
 * URL: http://github.com/emilkaiser/jquery-modal
 * Dependecies: jQuery
 * Author: Emil Kaiser (emilkaiser@gmail.com)
 * License: MIT
 */

;(function ($, undefined) {

  'use strict';

  var template = '

',
  defaults = {
      html: '',
      show: true,
      closeText: 'Stäng',
      className: 'modal',
      bodyClassName: 'jqm-active'
    };

  function Modal (options) {
    this.options = $.extend({}, defaults, options);
    if (this.options.show) {
      this.show();
    }
  }

  Modal.prototype = {
    init: function () {
      if (this.$modal) {
        return;
      }
      this.$modal = $(template).addClass(this.options.className);
      this.$modal.find('.jqm-close').attr('data-close', this.options.closeText);
      this.$modal.find('a').on('click', $.proxy(function (event) {
        event.preventDefault();
        this.hide();
      }, this));
      $('body').append(this.$modal);
      this.update(this.options.html);
    },
    show: function () {
      this.init();
      $('.jqm').removeClass('jqm-active');
      if (this.options.bodyClassName) {
        $('body').addClass(this.options.bodyClassName);
      }
      this.$modal.addClass('jqm-active');
      return this;
    },
    hide: function () {
      this.init();
      if (this.options.bodyClassName) {
        $('body').removeClass(this.options.bodyClassName);
      }
      this.$modal.removeClass('jqm-active');
      return this;
    },
    remove: function () {
      this.init();
      this.$modal.children().off();
      this.$modal.remove();
    },
    ajax: function (url, settings) {
      this.init();
      return $.ajax(url, settings).done($.proxy(function (response) {
        this.update(response);
      }, this));
    },
    update: function (html) {
      this.init();
      this.$modal.find('.jqm-content').html(html);
      return this;
    },
    $: function () {
      return this.$modal;
    }
  };

  $.modal = function (options) {
    return new Modal(options);
  };

})(jQuery);
<commit_msg>promises<commit_after>/**
 * jQuery Modal
 * Version: 0.1.0
 * URL: http://github.com/emilkaiser/jquery-modal
 * Dependecies: jQuery
 * Author: Emil Kaiser (emilkaiser@gmail.com)
 * License: MIT
 */

;(function ($, undefined) {

  'use strict';

  var template = '

',
  defaults = {
      html: false,
      closeText: 'Stäng',
      className: 'modal',
      bodyClassName: 'jqm-active'
    };

  function Modal (options) {
    this.options = $.extend({}, defaults, options);
    this.$modal = $(template).addClass(this.options.className);
    this.$modal.find('.jqm-close').attr('data-close', this.options.closeText);
    this.$modal.find('a').on('click', $.proxy(function (event) {
      event.preventDefault();
      this.hide();
    }, this));
    $('body').append(this.$modal);
    if (this.options.html) {
      this.update(this.options.html);
    }
    this.deferred = $.Deferred();
  }

  Modal.prototype = {
    show: function () {
      this.deferred.done(function () {
        $('.jqm').removeClass('jqm-active');
        if (this.options.bodyClassName) {
          $('body').addClass(this.options.bodyClassName);
        }
        this.$modal.addClass('jqm-active');
      });
    },
    hide: function () {
      if (this.options.bodyClassName) {
        $('body').removeClass(this.options.bodyClassName);
      }
      this.$modal.removeClass('jqm-active');
    },
    remove: function () {
      this.$modal.children().off();
      this.$modal.remove();
    },
    promise: function (promise, show) {
      promise.done($.proxy(function (response) {
        this.update(response);
      }, this));
      return this.deferred.promise();
    },
    update: function (html) {
      this.$modal.find('.jqm-content').html(html);
      this.deferred.resolveWith(this, [this]);
    },
    $: function () {
      return this.$modal;
    }
  };

  $.modal = function (options) {
    return new Modal(options);
  };

})(jQuery);
<|endoftext|>


<commit_before>import EventEmitter from 'events';
import {Buttons, Manager as InputManager} from './game/input';
import {LocalPlayer} from './game/player';
import React from 'react';
import {render} from 'react-dom';
import BABYLON from 'babylonjs';
import {BabylonJS} from './react-babylonjs.js';
import Hero from './game/heroes/baseHero';
import Menu from './menu/Menu';
import mapLoader from './mapLoader.js';

class Game extends EventEmitter {
  constructor() {
    super();
    this.players = [];
    this.heroes = [];
    this.on('playerschanged', () => this.handlePlayersChanged());
  }

  addInput(input) {
    const i = this.players.concat(undefined).indexOf(undefined);
    const player = this.players[i] = new LocalPlayer(`Player ${i}`, input);
    console.log(`Added player ${player.name} (${input.name})`);
    player.on('end', () => {
      this.players[i] = undefined;
      player.destroy();
      this.emit('playerschanged');
    });
    // TODO: Need to decide how to do routing of input when menu is
    // shown. E.g., joystick should control menu and not heroes when
    // menu is shown and switch back. Maybe instead of having heroes
    // bind to the inputs directly we could just have an input router
    // which just forwards the events to whatever is active at the
    // moment. Could even just pass the player a faked out
    // router-controlled input which the router forwards to. But the
    // levels of indirection!
    player.input.on('buttondown', button => {
      console.log(`input emitted ${button}`);
      if (button === Buttons.Menu) {
        this.setState({menu: true,});
      }
    });
    this.emit('playerschanged');
  }

  doRenderLoop() {
    this.scene.render();
  }

  handlePlayersChanged() {
    // For now, create a hero now. In the future, hero creation will
    // be up to the current game mode (no such thing exists yet
    // though).
    for (const i in this.players) {
      const player = this.players[i];
      if (player) {
        // Assert hero.
        if (!this.heroes[i]) {
          const hero = this.heroes[i] = new Hero(this, `${player.name}のヒーロー`);
          hero.setPlayer(player);
        }
      } else { // if (player)
        // Assert no hero.
        const hero = this.heroes[i];
        if (hero) {
          hero.destory();
          this.heroes[i] = undefined;
        }
      }
    }
  }

  setEngine(engine) {
    this.engine = engine;
    engine.runRenderLoop(this.handleRenderLoop = () => this.doRenderLoop());
    this.scene = new BABYLON.Scene(engine);

    // Controllable camera
    var camera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 1, 0.8, 10, new BABYLON.Vector3.Zero(), this.scene);
    camera.setPosition(new BABYLON.Vector3(0, 40, -40));
    camera.attachControl(engine.getRenderingCanvas(), false);

    this.light = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(0, -2, 0), this.scene);
    // Skybox
    BABYLON.Engine.ShadersRepository = "./shaders/";

    var skybox = BABYLON.Mesh.CreateSphere("skyBox", 10, 2500, this.scene);

    const shader = new BABYLON.ShaderMaterial("gradient", this.scene, "gradient", {});
    shader.setFloat("offset", 0);
    shader.setFloat("exponent", 0.6);
    shader.setColor3("topColor", BABYLON.Color3.FromInts(0,119,255));
    shader.setColor3("bottomColor", BABYLON.Color3.FromInts(240,240, 255));
    shader.backFaceCulling = false;
    skybox.material = shader;

    // Fog
    this.scene.fogMode = BABYLON.Scene.FOGMODE_EXP2;
    this.scene.fogDensity = 0.0018;
    this.scene.fogColor = new BABYLON.Color3(240/255, 240/255, 1);

    // Add shadow generator
    this.shadowGenerator = new BABYLON.ShadowGenerator(Math.pow(2,10), this.light);
    this.shadowGenerator.setDarkness(0.5) ;

    this.scene.enablePhysics(
      new BABYLON.Vector3(0, -10, 0),
      new BABYLON.CannonJSPlugin());
    // Add collision groups, groups must be powers of 2: http://schteppe.github.io/cannon.js/demos/collisionFilter.html
    this.collisionGroupNormal = 2;
    this.collisionGroupGround = 1;
    this.collisionGroupFall = 4;

    // Add ground
      /*
    this.ground = BABYLON.Mesh.CreateGround("ground", 2500, 2500, 20, this.scene);
    var material = new BABYLON.StandardMaterial("green", this.scene);
    material.diffuseColor = BABYLON.Color3.FromInts(31, 158, 69);
    this.ground.material = material;
    this.ground.setPhysicsState({ impostor: BABYLON.PhysicsEngine.BoxImpostor, move:false});
    this.ground.physicsImpostor.physicsBody
    BABYLON.Tags.EnableFor(this.ground);
    BABYLON.Tags.AddTagsTo(this.ground, "checkJump");
    this.ground.physicsImpostor.physicsBody.collisionFilterGroup = this.collisionGroupGround;
    this.ground.physicsImpostor.physicsBody.collisionFilterMask = this.collisionGroupNormal | this.collisionGroupGround;
    this.shadowGenerator.getShadowMap().renderList.push(this.scene.meshes[2]);
    this.ground.receiveShadows = true;
    */

    this.mapLoader = new mapLoader('test1', this);

    for (var x in [0,1]) {
      require('../models/heroes/omi.blend').Append(BABYLON.SceneLoader, this.scene, loadedScene => {
        /*onsuccess*/
      //  new BABYLON.PhysicsImpostor(loadedScene.meshes[x], BABYLON.PhysicsImpostor.BoxImpostor, { mass: 1, }, scene);
        loadedScene.beginAnimation(this.scene.skeletons[x], 0, 120, true, 2);
      }, x => {/*onprogress*/}, ex => {/*onerror*/});
    }

    new InputManager(this);
  }

  abandonEngine(engine) {
    this.engine.stopRenderLoop(this.handleRenderLoop);
    this.handleRenderLoop = null;
    this.engine = null;
  }
}

class Ui extends React.Component {
  constructor() {
    super();
    this.state = {
      menu: false,
    };
  }

  handleEngineCreated(engine) {
    this.props.game.setEngine(engine);
  }

  handleEngineAbandoned(engine) {
    this.props.game.abandonEngine(engine);
  }

  render() {
    return

        <BabylonJS onEngineCreated={engine => this.handleEngineCreated(engine)} onEngineAbandoned={engine => this.handleEngineAbandoned(engine)}/>
        {this.state.menu ? <Menu onHide={() => this.setState({menu: false,})}/> : []}

;
  }
}

render(<Ui game={new Game()}/>, document.getElementById("game-container"));
<commit_msg>removed fog temporarily<commit_after>import EventEmitter from 'events';
import {Buttons, Manager as InputManager} from './game/input';
import {LocalPlayer} from './game/player';
import React from 'react';
import {render} from 'react-dom';
import BABYLON from 'babylonjs';
import {BabylonJS} from './react-babylonjs.js';
import Hero from './game/heroes/baseHero';
import Menu from './menu/Menu';
import mapLoader from './mapLoader.js';

class Game extends EventEmitter {
  constructor() {
    super();
    this.players = [];
    this.heroes = [];
    this.on('playerschanged', () => this.handlePlayersChanged());
  }

  addInput(input) {
    const i = this.players.concat(undefined).indexOf(undefined);
    const player = this.players[i] = new LocalPlayer(`Player ${i}`, input);
    console.log(`Added player ${player.name} (${input.name})`);
    player.on('end', () => {
      this.players[i] = undefined;
      player.destroy();
      this.emit('playerschanged');
    });
    // TODO: Need to decide how to do routing of input when menu is
    // shown. E.g., joystick should control menu and not heroes when
    // menu is shown and switch back. Maybe instead of having heroes
    // bind to the inputs directly we could just have an input router
    // which just forwards the events to whatever is active at the
    // moment. Could even just pass the player a faked out
    // router-controlled input which the router forwards to. But the
    // levels of indirection!
    player.input.on('buttondown', button => {
      console.log(`input emitted ${button}`);
      if (button === Buttons.Menu) {
        this.setState({menu: true,});
      }
    });
    this.emit('playerschanged');
  }

  doRenderLoop() {
    this.scene.render();
  }

  handlePlayersChanged() {
    // For now, create a hero now. In the future, hero creation will
    // be up to the current game mode (no such thing exists yet
    // though).
    for (const i in this.players) {
      const player = this.players[i];
      if (player) {
        // Assert hero.
        if (!this.heroes[i]) {
          const hero = this.heroes[i] = new Hero(this, `${player.name}のヒーロー`);
          hero.setPlayer(player);
        }
      } else { // if (player)
        // Assert no hero.
        const hero = this.heroes[i];
        if (hero) {
          hero.destory();
          this.heroes[i] = undefined;
        }
      }
    }
  }

  setEngine(engine) {
    this.engine = engine;
    engine.runRenderLoop(this.handleRenderLoop = () => this.doRenderLoop());
    this.scene = new BABYLON.Scene(engine);

    // Controllable camera
    var camera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 1, 0.8, 10, new BABYLON.Vector3.Zero(), this.scene);
    camera.setPosition(new BABYLON.Vector3(0, 40, -40));
    camera.attachControl(engine.getRenderingCanvas(), false);

    this.light = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(0, -2, 0), this.scene);
    // Skybox
    BABYLON.Engine.ShadersRepository = "./shaders/";

    var skybox = BABYLON.Mesh.CreateSphere("skyBox", 10, 2500, this.scene);

    const shader = new BABYLON.ShaderMaterial("gradient", this.scene, "gradient", {});
    shader.setFloat("offset", 0);
    shader.setFloat("exponent", 0.6);
    shader.setColor3("topColor", BABYLON.Color3.FromInts(0,119,255));
    shader.setColor3("bottomColor", BABYLON.Color3.FromInts(240,240, 255));
    shader.backFaceCulling = false;
    skybox.material = shader;

    /*
    this.scene.fogMode = BABYLON.Scene.FOGMODE_LINEAR;
    this.scene.fogDensity = 0.01;
    this.scene.fogColor = new BABYLON.Color3(240/255, 240/255, 1);
    this.scene.fogStart = 300.0;
    this.scene.fogEnd = 400.0;
    */

    // Add shadow generator
    this.shadowGenerator = new BABYLON.ShadowGenerator(Math.pow(2,10), this.light);
    this.shadowGenerator.setDarkness(0.5) ;

    this.scene.enablePhysics(
      new BABYLON.Vector3(0, -10, 0),
      new BABYLON.CannonJSPlugin());
    // Add collision groups, groups must be powers of 2: http://schteppe.github.io/cannon.js/demos/collisionFilter.html
    this.collisionGroupNormal = 2;
    this.collisionGroupGround = 1;
    this.collisionGroupFall = 4;

    // Add ground
      /*
    this.ground = BABYLON.Mesh.CreateGround("ground", 2500, 2500, 20, this.scene);
    var material = new BABYLON.StandardMaterial("green", this.scene);
    material.diffuseColor = BABYLON.Color3.FromInts(31, 158, 69);
    this.ground.material = material;
    this.ground.setPhysicsState({ impostor: BABYLON.PhysicsEngine.BoxImpostor, move:false});
    this.ground.physicsImpostor.physicsBody
    BABYLON.Tags.EnableFor(this.ground);
    BABYLON.Tags.AddTagsTo(this.ground, "checkJump");
    this.ground.physicsImpostor.physicsBody.collisionFilterGroup = this.collisionGroupGround;
    this.ground.physicsImpostor.physicsBody.collisionFilterMask = this.collisionGroupNormal | this.collisionGroupGround;
    this.shadowGenerator.getShadowMap().renderList.push(this.scene.meshes[2]);
    this.ground.receiveShadows = true;
    */

    this.mapLoader = new mapLoader('test1', this);

    for (var x in [0,1]) {
      require('../models/heroes/omi.blend').Append(BABYLON.SceneLoader, this.scene, loadedScene => {
        /*onsuccess*/
      //  new BABYLON.PhysicsImpostor(loadedScene.meshes[x], BABYLON.PhysicsImpostor.BoxImpostor, { mass: 1, }, scene);
        loadedScene.beginAnimation(this.scene.skeletons[x], 0, 120, true, 2);
      }, x => {/*onprogress*/}, ex => {/*onerror*/});
    }

    new InputManager(this);
  }

  abandonEngine(engine) {
    this.engine.stopRenderLoop(this.handleRenderLoop);
    this.handleRenderLoop = null;
    this.engine = null;
  }
}

class Ui extends React.Component {
  constructor() {
    super();
    this.state = {
      menu: false,
    };
  }

  handleEngineCreated(engine) {
    this.props.game.setEngine(engine);
  }

  handleEngineAbandoned(engine) {
    this.props.game.abandonEngine(engine);
  }

  render() {
    return

        <BabylonJS onEngineCreated={engine => this.handleEngineCreated(engine)} onEngineAbandoned={engine => this.handleEngineAbandoned(engine)}/>
        {this.state.menu ? <Menu onHide={() => this.setState({menu: false,})}/> : []}

;
  }
}

render(<Ui game={new Game()}/>, document.getElementById("game-container"));
<|endoftext|>


<commit_before>/**
 * Loader to add ol.css, ol.js and the example-specific js file to the
 * documents.
 *
 * This loader is used for the hosted examples. It is used in place of the
 * development loader (examples/loader.js).
 *
 * ol.css, ol.js, ol-simple.js, ol-whitespace.js, and ol-deps.js are built
 * by OL3's build.py script. They are located in the ../build/ directory,
 * relatively to this script.
 *
 * The script must be named loader.js.
 *
 * Usage:
 *
 *     <script src="../loader.js?id=my-demo"></script>
 */

(function() {

  var i, pair;

  var href = window.location.href, start, end, paramsString, pairs,
      pageParams = {};
  if (href.indexOf('?') > 0) {
    start = href.indexOf('?') + 1;
    end = href.indexOf('#') > 0 ? href.indexOf('#') : href.length;
    paramsString = href.substring(start, end);
    pairs = paramsString.split(/[&;]/);
    for (i = 0; i < pairs.length; ++i) {
      pair = pairs[i].split('=');
      if (pair[0]) {
          pageParams[decodeURIComponent(pair[0])] =
              decodeURIComponent(pair[1]);
      }
    }
  }

  var scripts = document.getElementsByTagName('script');
  var src, index, search, chunks, scriptParams = {};
  for (i = scripts.length - 1; i >= 0; --i) {
    src = scripts[i].getAttribute('src');
    if (~(index = src.indexOf('loader.js?'))) {
      search = src.substr(index + 10);
      chunks = search ? search.split('&') : [];
      for (i = chunks.length - 1; i >= 0; --i) {
        pair = chunks[i].split('=');
        if (pair[0]) {
          scriptParams[decodeURIComponent(pair[0])] =
              decodeURIComponent(pair[1]);
        }
      }
      break;
    }
  }

  var oljs = 'ol.js', mode;
  if ('mode' in pageParams) {
    mode = pageParams.mode.toLowerCase();
    if (mode == 'debug') {
      mode = 'raw';
    }
    if (mode != 'advanced' && mode != 'raw') {
      oljs = 'ol-' + mode + '.js';
    }
  }

  var scriptId = encodeURIComponent(scriptParams.id);
  document.write('<link rel="stylesheet" href="../build/ol.css" type="text/css">');
  if (mode != 'raw') {
    document.write('<scr' + 'ipt type="text/javascript" src="../build/' + oljs + '"></scr' + 'ipt>');
  } else {
    window.CLOSURE_NO_DEPS = true; // we've got our own deps file
    document.write('<scr' + 'ipt type="text/javascript" src="../closure-library/closure/goog/base.js"></scr' + 'ipt>');
    document.write('<scr' + 'ipt type="text/javascript" src="../build/ol-deps.js"></scr' + 'ipt>');
    document.write('<scr' + 'ipt type="text/javascript" src="' + scriptId + '-require.js"></scr' + 'ipt>');
  }
  document.write('<scr' + 'ipt type="text/javascript" src="' + scriptId + '.js"></scr' + 'ipt>');
}());
<commit_msg>Always set CLOSURE_NO_DEPS to true<commit_after>/**
 * Loader to add ol.css, ol.js and the example-specific js file to the
 * documents.
 *
 * This loader is used for the hosted examples. It is used in place of the
 * development loader (examples/loader.js).
 *
 * ol.css, ol.js, ol-simple.js, ol-whitespace.js, and ol-deps.js are built
 * by OL3's build.py script. They are located in the ../build/ directory,
 * relatively to this script.
 *
 * The script must be named loader.js.
 *
 * Usage:
 *
 *     <script src="../loader.js?id=my-demo"></script>
 */

(function() {

  var i, pair;

  var href = window.location.href, start, end, paramsString, pairs,
      pageParams = {};
  if (href.indexOf('?') > 0) {
    start = href.indexOf('?') + 1;
    end = href.indexOf('#') > 0 ? href.indexOf('#') : href.length;
    paramsString = href.substring(start, end);
    pairs = paramsString.split(/[&;]/);
    for (i = 0; i < pairs.length; ++i) {
      pair = pairs[i].split('=');
      if (pair[0]) {
          pageParams[decodeURIComponent(pair[0])] =
              decodeURIComponent(pair[1]);
      }
    }
  }

  var scripts = document.getElementsByTagName('script');
  var src, index, search, chunks, scriptParams = {};
  for (i = scripts.length - 1; i >= 0; --i) {
    src = scripts[i].getAttribute('src');
    if (~(index = src.indexOf('loader.js?'))) {
      search = src.substr(index + 10);
      chunks = search ? search.split('&') : [];
      for (i = chunks.length - 1; i >= 0; --i) {
        pair = chunks[i].split('=');
        if (pair[0]) {
          scriptParams[decodeURIComponent(pair[0])] =
              decodeURIComponent(pair[1]);
        }
      }
      break;
    }
  }

  var oljs = 'ol.js', mode;
  if ('mode' in pageParams) {
    mode = pageParams.mode.toLowerCase();
    if (mode == 'debug') {
      mode = 'raw';
    }
    if (mode != 'advanced' && mode != 'raw') {
      oljs = 'ol-' + mode + '.js';
    }
  }

  // CLOSURE_NO_DEPS has an effect in "raw" and "whitespace" modes only (i.e.
  // when COMPILED is false). In "raw" mode we use our own deps file
  // (ol-deps.js), so we set CLOSURE_NO_DEPS to true to prevent Google
  // Library's base.js script to load deps.js. In "whitespace" mode
  // no deps file is needed at all, yet base.js will attempt to load deps.js
  // if CLOSURE_NO_DEPS is not set to true.
  window.CLOSURE_NO_DEPS = true;

  var scriptId = encodeURIComponent(scriptParams.id);
  document.write('<link rel="stylesheet" href="../build/ol.css" type="text/css">');
  if (mode != 'raw') {
    document.write('<scr' + 'ipt type="text/javascript" src="../build/' + oljs + '"></scr' + 'ipt>');
  } else {
    document.write('<scr' + 'ipt type="text/javascript" src="../closure-library/closure/goog/base.js"></scr' + 'ipt>');
    document.write('<scr' + 'ipt type="text/javascript" src="../build/ol-deps.js"></scr' + 'ipt>');
    document.write('<scr' + 'ipt type="text/javascript" src="' + scriptId + '-require.js"></scr' + 'ipt>');
  }
  document.write('<scr' + 'ipt type="text/javascript" src="' + scriptId + '.js"></scr' + 'ipt>');
}());
<|endoftext|>