<commit_before>define([
    'ports'
], function(ports) {
    var _ = codebox.require("hr/utils");
    var commands = codebox.require("core/commands/toolbar");
    var operations = codebox.require("core/operations");
    var box = codebox.require("core/box");
    var dialogs = codebox.require("utils/dialogs");
    var alerts = codebox.require("utils/alerts");
    var Command = codebox.require("models/command");

    // Currently running terminal
    var runningTerm = undefined;

    // Map type -> icon
    var typeIcons = {
        'run': "fa-play",
        'build': "fa-cog fa-spin",
        'clean': "fa-eraser"
    };

    // Run command
    var runCommand = commands.register("project.run", {
        category: "Project",
        title: "Run",
        icons: {
            'default': "play",
        },
        offline: false,
        position: 1,
        shortcuts: [
            "alt+r"
        ]
    }, function(options) {
        options = options || {};

        if (runningTerm !== undefined) {
            if (runningTerm != null) runningTerm.closeTab();
            return;
        }

        setRunTerminal(null);

        // Run
        return box.run(options)
        .then(function(runInfo) {
            var op = operations.start("project.run."+runInfo.shellId, null, {
                'title': runInfo.name+" running on port "+runInfo.port,
                'icons': {
                    'default': typeIcons[runInfo.type] || "play",
                },
                'action': function() {
                    // Open the url
                    window.open(runInfo.url);

                    // Check that port is still active
                    ports.update().then(function(ports) {
                        var _port = _.find(ports, function(proc) {
                            return proc.port == runInfo.port;
                        });
                        if (!_port) {
                            op.destroy();
                        }
                    });
                }
            });

            // Stop
            op.on("destroy", function() {
                setRunTerminal(undefined);
            });

            // Terminal is close: finish the operation
            runInfo.terminal.on("tab:close", function() {
                op.destroy();
            });

            // Set active runningterminal
            setRunTerminal(runInfo.terminal);

            // Update list of ports
            ports.update();
        }, function(err) {
            dialogs.alert("Error running this project", "An error occurred when trying to run this project: "+(err.message || err));
        });
    });

    var setRunTerminal = function(st) {
        runningTerm = st;
        if (runningTerm != null) {
            runCommand.set({
                'title': "Stop",
                'icons': {
                    'default': "stop"
                }
            });
        } else {
            runCommand.set({
                'title': "Run",
                'icons': {
                    'default': "play"
                }
            });
        }
    };

    setRunTerminal(undefined);

    return {
        'command': runCommand
    }
});<commit_msg>Run 'stop' process when clicking the stop button<commit_after>define([
    'ports'
], function(ports) {
    var _ = codebox.require("hr/utils");
    var commands = codebox.require("core/commands/toolbar");
    var operations = codebox.require("core/operations");
    var box = codebox.require("core/box");
    var dialogs = codebox.require("utils/dialogs");
    var alerts = codebox.require("utils/alerts");
    var Command = codebox.require("models/command");

    // Currently running terminal
    // undefined -> nothing is running
    // null -> preparing the run
    // {...} _> running
    var runningTerm = undefined;

    // Map type -> icon
    var typeIcons = {
        'run': "fa-play",
        'build': "fa-cog fa-spin",
        'clean': "fa-eraser"
    };

    // Run command
    var runCommand = commands.register("project.run", {
        category: "Project",
        title: "Run",
        icons: {
            'default': "play",
        },
        offline: false,
        position: 1,
        shortcuts: [
            "alt+r"
        ]
    }, function(options) {
        options = _.defaults(options || {}, {
            'ignoreErrors': false
        });

        if (runningTerm !== undefined) {
            // For stopping: Close terminal
            if (runningTerm != null) {
                runningTerm.terminal.closeTab();
            }

            return;
        }

        setRunTerminal(null);

        // Run
        return box.run({
            'type': options.type
        })
        .then(function(runInfo) {
            var op = operations.start("project.run."+runInfo.shellId, null, {
                'title': runInfo.name+" running on port "+runInfo.port,
                'icons': {
                    'default': typeIcons[runInfo.type] || "play",
                },
                'action': function() {
                    // Open the url
                    window.open(runInfo.url);

                    // Check that port is still active
                    ports.update().then(function(ports) {
                        var _port = _.find(ports, function(proc) {
                            return proc.port == runInfo.port;
                        });
                        if (!_port) {
                            op.destroy();
                        }
                    });
                }
            });

            // Stop
            op.on("destroy", function() {
                setRunTerminal(undefined);
            });

            // Terminal is close: finish the operation
            runInfo.terminal.on("tab:close", function() {
                op.destroy();
            });

            // Set active runningterminal
            setRunTerminal(runInfo);

            // Update list of ports
            ports.update();
        }, function(err) {
            setRunTerminal(undefined);

            if (!options.ignoreErrors) dialogs.alert("Error running this project", "An error occurred when trying to run this project: "+(err.message || err));
        });
    });

    var setRunTerminal = function(st) {
        var previous = runningTerm;
        runningTerm = st;

        // Change command state
        if (runningTerm != null) {
            runCommand.set({
                'title': "Stop",
                'icons': {
                    'default': "stop"
                }
            });
        } else {
            runCommand.set({
                'title': "Run",
                'icons': {
                    'default': "play"
                }
            });
        }

        if (previous
        && previous.type == "run"
        && runningTerm === undefined) {
            // Run stop command
            return runCommand.run({
                'type': "stop",
                'ignoreErrors': true
            });
        }
    };

    setRunTerminal(undefined);

    return {
        'command': runCommand
    }
});<|endoftext|>


<commit_before>var fs = require('fs');
var Steam = require('steam');
var SteamTrade = require('steam-trade');
var Coinbase = require('coinbase');
var doge = require('../node_modules/dogeapi.js/src/index.js') // I know this is dumb, but the DogeAPI.js module is awful and this appears to be the only way to import it
var config = require('../config')
var http = require('http');
var https = require('https');
var url = require('url');
var util = require('util');
var redis = require('redis');

//Redis Test
console.log("Connecting to Redis...");
rclient = redis.createClient();
<commit_msg>dogeapi.js is so weird<commit_after>var fs = require('fs');
var Steam = require('steam');
var SteamTrade = require('steam-trade');
var Coinbase = require('coinbase');
//var doge = require('../node_modules/dogeapi.js/src/index.js') // I know this is dumb, but the DogeAPI.js module is awful and this appears to be the only way to import it
var config = require('../config')
var http = require('http');
var https = require('https');
var url = require('url');
var util = require('util');
var redis = require('redis');

//Redis Test
console.log("Connecting to Redis...");
rclient = redis.createClient();
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var _ = require('lodash');

exports.restoreDefaultsPlugin = function restoreDefaultsPlugin(Model) {
    Model.attributes._changes = {type: Model.sequelize.Sequelize.JSONB};

    Model.Instance.prototype.restoreDefaults = function restoreDefaults() {
        // nothing to restore
        if (!this._changes && !this._changes.original) return this.sequelize.Promise.resolve(this);

        var update = _.reduce(this._changes.original, function (acc, value, key) {
            acc[key] = value;
            return acc;
        }, {_changes: null});

        return this.Model.update(update, {where: {id: this.id}, returning: true, validate: false})
            .spread(function (affected, rows) {
                return rows[0];
            });
    };

    Model.applyLatestChanges = function applyLatestChanges(options) {
        var self = this;

        var attrs = _.reduce(this.attributes, function (acc, attr, name) {
            if (!self._isVirtualAttribute(attr) && name !== '_changes' && !attr.primaryKey) {
                acc.push(attr);
            }
            return acc;
        }, []);

        var updateExprs = attrs.map(function (attr) {
            var field = self.sequelize.queryInterface.quoteIdentifier(attr.field);
            return util.format('%s = COALESCE(c.%s, m.%s)', field, field, field);
        }).join(', ');

        var castExprs = attrs.map(function (attr) {
            return [
                self.sequelize.queryInterface.quoteIdentifier(attr.field),
                attr.type.toString()
            ].join(' ');
        }).join(', ');

        var withQuery = util.format('WITH changes as (select id, c.* from %s, jsonb_to_record(_changes -> \'current\') as c(%s))',
            this.options.tableName,
            castExprs);

        var update = util.format('UPDATE %s m SET %s', this.options.tableName, updateExprs);

        var query = util.format('%s %s FROM changes c WHERE m.id = c.id and m._changes is not null', withQuery, update);
        return this.sequelize.query(query, _.merge(options, {raw: true}));
    };

    Model.options.setterMethods = Model.options.setterMethods || {};

    Model.options.setterMethods._changes = function (value) {
        if (value) {
            //noinspection JSPotentiallyInvalidUsageOfThis
            this.setDataValue('_changes', value);
            _.forEach(value.current, function (change, key) {
                this[key] = change;
            }, this);
        } else {
            var previous = this.previous('_changes') || {};
            _.forEach(previous.original, function (change, key) {
                this[key] = change;
            }, this);
            //noinspection JSPotentiallyInvalidUsageOfThis
            this.setDataValue('_changes', null);
        }
    };

    Model.hook('beforeUpdate', function (model) {
        // restoring defaults
        if (model.changed('_changes')) return;

        var fieldsToTrack = _.difference(model.changed(), ['_changes']);

        if (fieldsToTrack.length === 0) return;

        var changes = _.assign({}, model._changes);
        changes.current = changes.current || {};
        changes.original = changes.original || {};

        fieldsToTrack.forEach(function (field) {
            changes.original[field] = changes.original.hasOwnProperty(field) ? changes.original[field] : model.previous(field);
            changes.current[field] = model[field];
            if(_.isEqual(changes.original[field], changes.current[field])) {
                delete changes.original[field];
                delete changes.current[field];
            }
        });

        model.setDataValue('_changes', Object.keys(changes.current).length > 0 || Object.keys(changes.original).length > 0 ? changes : null);
    });

    Model.refreshAttributes();

    return Model;
};<commit_msg>fixed problem with bulk upsert where no id field exists<commit_after>'use strict';

var util = require('util');
var _ = require('lodash');

exports.restoreDefaultsPlugin = function restoreDefaultsPlugin(Model) {
    Model.attributes._changes = {type: Model.sequelize.Sequelize.JSONB};
    const idColumn = _(Model.attributes).filter({ primaryKey: true }).pluck('fieldName').first() || 'id';

    Model.Instance.prototype.restoreDefaults = function restoreDefaults() {
        // nothing to restore
        if (!this._changes && !this._changes.original) return this.sequelize.Promise.resolve(this);

        var update = _.reduce(this._changes.original, function (acc, value, key) {
            acc[key] = value;
            return acc;
        }, {_changes: null});

        return this.Model.update(update, {where: {[idColumn]: this[idColumn]}, returning: true, validate: false})
            .spread(function (affected, rows) {
                return rows[0];
            });
    };

    Model.applyLatestChanges = function applyLatestChanges(options) {
        var self = this;

        var attrs = _.reduce(this.attributes, function (acc, attr, name) {
            if (!self._isVirtualAttribute(attr) && name !== '_changes' && !attr.primaryKey) {
                acc.push(attr);
            }
            return acc;
        }, []);

        var updateExprs = attrs.map(function (attr) {
            var field = self.sequelize.queryInterface.quoteIdentifier(attr.field);
            return util.format('%s = COALESCE(c.%s, m.%s)', field, field, field);
        }).join(', ');

        var castExprs = attrs.map(function (attr) {
            return [
                self.sequelize.queryInterface.quoteIdentifier(attr.field),
                attr.type.toString()
            ].join(' ');
        }).join(', ');

        var withQuery = util.format(`WITH changes as (select "%s", c.* from "%s", jsonb_to_record(_changes -> \'current\') as c(%s))`,
            idColumn,
            this.options.tableName,
            castExprs);

        var update = util.format('UPDATE "%s" m SET %s', this.options.tableName, updateExprs);

        var query = util.format(`%s %s FROM changes c WHERE m."%s" = c."%s" and m._changes is not null`, withQuery, update, idColumn, idColumn);
        return this.sequelize.query(query, _.merge(options, {raw: true}));
    };

    Model.options.setterMethods = Model.options.setterMethods || {};

    Model.options.setterMethods._changes = function (value) {
        if (value) {
            //noinspection JSPotentiallyInvalidUsageOfThis
            this.setDataValue('_changes', value);
            _.forEach(value.current, function (change, key) {
                this[key] = change;
            }, this);
        } else {
            var previous = this.previous('_changes') || {};
            _.forEach(previous.original, function (change, key) {
                this[key] = change;
            }, this);
            //noinspection JSPotentiallyInvalidUsageOfThis
            this.setDataValue('_changes', null);
        }
    };

    Model.hook('beforeUpdate', function (model) {
        // restoring defaults
        if (model.changed('_changes')) return;

        var fieldsToTrack = _.difference(model.changed(), ['_changes']);

        if (fieldsToTrack.length === 0) return;

        var changes = _.assign({}, model._changes);
        changes.current = changes.current || {};
        changes.original = changes.original || {};

        fieldsToTrack.forEach(function (field) {
            changes.original[field] = changes.original.hasOwnProperty(field) ? changes.original[field] : model.previous(field);
            changes.current[field] = model[field];
            if(_.isEqual(changes.original[field], changes.current[field])) {
                delete changes.original[field];
                delete changes.current[field];
            }
        });

        model.setDataValue('_changes', Object.keys(changes.current).length > 0 || Object.keys(changes.original).length > 0 ? changes : null);
    });

    Model.refreshAttributes();

    return Model;
};<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(FILL_ME_IN);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe(FILL_ME_IN);
    expect(overrideMessage()).toBe(FILL_ME_IN);
    expect(message).toBe(FILL_ME_IN);
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>"Almost finished with functions"<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe('Outer');
    expect(overrideMessage()).toBe('Inner');
    expect(message).toBe('Outer');
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe('local');
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

import { Cache } from './Cache';
import { DefaultLoadingManager } from './LoadingManager';

function FileLoader( manager ) {

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

}

Object.assign( FileLoader.prototype, {

	load: function ( url, onLoad, onProgress, onError ) {

		if ( url === undefined ) url = '';

		if ( this.path !== undefined ) url = this.path + url;

		var scope = this;

		var cached = Cache.get( url );

		if ( cached !== undefined ) {

			scope.manager.itemStart( url );

			setTimeout( function () {

				if ( onLoad ) onLoad( cached );

				scope.manager.itemEnd( url );

			}, 0 );

			return cached;

		}

		// Check for data: URI
		var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
		var dataUriRegexResult = url.match( dataUriRegex );

		// Safari can not handle Data URIs through XMLHttpRequest so process manually
		if ( dataUriRegexResult ) {

			var mimeType = dataUriRegexResult[ 1 ];
			var isBase64 = !! dataUriRegexResult[ 2 ];
			var data = dataUriRegexResult[ 3 ];

			data = window.decodeURIComponent( data );

			if ( isBase64 ) data = window.atob( data );

			try {

				var response;
				var responseType = ( this.responseType || '' ).toLowerCase();

				switch ( responseType ) {

					case 'arraybuffer':
					case 'blob':

					 	response = new ArrayBuffer( data.length );

						var view = new Uint8Array( response );

						for ( var i = 0; i < data.length; i ++ ) {

							view[ i ] = data.charCodeAt( i );

						}

						if ( responseType === 'blob' ) {

							response = new Blob( [ response ], { type: mimeType } );

						}

						break;

					case 'document':

						var parser = new DOMParser();
						response = parser.parseFromString( data, mimeType );

						break;

					case 'json':

						response = JSON.parse( data );

						break;

					default: // 'text' or other

						response = data;

						break;

				}

				// Wait for next browser tick
				window.setTimeout( function () {

					if ( onLoad ) onLoad( response );

					scope.manager.itemEnd( url );

				}, 0 );

			} catch ( error ) {

				// Wait for next browser tick
				window.setTimeout( function () {

					if ( onError ) onError( error );

					scope.manager.itemEnd( url );
					scope.manager.itemError( url );

				}, 0 );

			}

		} else {

			var request = new XMLHttpRequest();
			request.open( 'GET', url, true );

			request.addEventListener( 'load', function ( event ) {

				var response = event.target.response;

				Cache.add( url, response );

				if ( this.status === 200 ) {

					if ( onLoad ) onLoad( response );

					scope.manager.itemEnd( url );

				} else if ( this.status === 0 ) {

					// Some browsers return HTTP Status 0 when using non-http protocol
					// e.g. 'file://' or 'data://'. Handle as success.

					console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );

					if ( onLoad ) onLoad( response );

					scope.manager.itemEnd( url );

				} else {

					if ( onError ) onError( event );

					scope.manager.itemEnd( url );
					scope.manager.itemError( url );

				}

			}, false );

			if ( onProgress !== undefined ) {

				request.addEventListener( 'progress', function ( event ) {

					onProgress( event );

				}, false );

			}

			request.addEventListener( 'error', function ( event ) {

				if ( onError ) onError( event );

				scope.manager.itemEnd( url );
				scope.manager.itemError( url );

			}, false );

			if ( this.responseType !== undefined ) request.responseType = this.responseType;
			if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;

			if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );

			for ( var header in this.requestHeader ) {

				request.setRequestHeader( header, this.requestHeader[ header ] );

			}

			request.send( null );

		}

		scope.manager.itemStart( url );

		return request;

	},

	setPath: function ( value ) {

		this.path = value;
		return this;

	},

	setResponseType: function ( value ) {

		this.responseType = value;
		return this;

	},

	setWithCredentials: function ( value ) {

		this.withCredentials = value;
		return this;

	},

	setMimeType: function ( value ) {

		this.mimeType = value;
		return this;

	},

	setRequestHeader: function ( value ) {

		this.requestHeader = value;
		return this;

	}

} );

export { FileLoader };
<commit_msg>have fileloader merge multiple concurrent requests for the same url (fixes #10644)<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

import { Cache } from './Cache';
import { DefaultLoadingManager } from './LoadingManager';

function FileLoader( manager ) {

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

}

Object.assign( FileLoader.prototype, {

	load: function ( url, onLoad, onProgress, onError ) {

		if ( url === undefined ) url = '';

		if ( this.path !== undefined ) url = this.path + url;

		var scope = this;

		var cached = Cache.get( url );

		if ( cached !== undefined && ! cached.loaderSubscriptions ) {

			scope.manager.itemStart( url );

			setTimeout( function () {

				if ( onLoad ) onLoad( cached );

				scope.manager.itemEnd( url );

			}, 0 );

			return cached;

		}

		// If file is already in process of loading, wait for it to load.
		if ( cached !== undefined && cached.loaderSubscriptions ) {

			cached.loaderSubscriptions.push( function () {

				scope.load( url, onLoad, onProgress, onError );

			} );

			return;

		}

		// Check for data: URI
		var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
		var dataUriRegexResult = url.match( dataUriRegex );

		// Safari can not handle Data URIs through XMLHttpRequest so process manually
		if ( dataUriRegexResult ) {

			var mimeType = dataUriRegexResult[ 1 ];
			var isBase64 = !! dataUriRegexResult[ 2 ];
			var data = dataUriRegexResult[ 3 ];

			data = window.decodeURIComponent( data );

			if ( isBase64 ) data = window.atob( data );

			try {

				var response;
				var responseType = ( this.responseType || '' ).toLowerCase();

				switch ( responseType ) {

					case 'arraybuffer':
					case 'blob':

					 	response = new ArrayBuffer( data.length );

						var view = new Uint8Array( response );

						for ( var i = 0; i < data.length; i ++ ) {

							view[ i ] = data.charCodeAt( i );

						}

						if ( responseType === 'blob' ) {

							response = new Blob( [ response ], { type: mimeType } );

						}

						break;

					case 'document':

						var parser = new DOMParser();
						response = parser.parseFromString( data, mimeType );

						break;

					case 'json':

						response = JSON.parse( data );

						break;

					default: // 'text' or other

						response = data;

						break;

				}

				// Wait for next browser tick
				window.setTimeout( function () {

					if ( onLoad ) onLoad( response );

					scope.manager.itemEnd( url );

				}, 0 );

			} catch ( error ) {

				// Wait for next browser tick
				window.setTimeout( function () {

					if ( onError ) onError( error );

					scope.manager.itemEnd( url );
					scope.manager.itemError( url );

				}, 0 );

			}

		} else {

			var loaderSubscriptions = [];
			var request = new XMLHttpRequest();

			// Allow other file loaders to wait and subscribe on this request.
			Cache.add( url, { loaderSubscriptions: loaderSubscriptions } );

			request.open( 'GET', url, true );

			request.addEventListener( 'load', function ( event ) {

				var response = event.target.response;

				Cache.add( url, response );

				if ( this.status === 200 ) {

					if ( onLoad ) onLoad( response );

					scope.manager.itemEnd( url );

				} else if ( this.status === 0 ) {

					// Some browsers return HTTP Status 0 when using non-http protocol
					// e.g. 'file://' or 'data://'. Handle as success.

					console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );

					if ( onLoad ) onLoad( response );

					scope.manager.itemEnd( url );

				} else {

					if ( onError ) onError( event );

					scope.manager.itemEnd( url );
					scope.manager.itemError( url );

				}

				// Tell other requests for the same file that the file has finished loading.
				for ( var i = 0; i < loaderSubscriptions.length; i ++ ) {

					loaderSubscriptions[ i ]( response );

				}

			}, false );

			if ( onProgress !== undefined ) {

				request.addEventListener( 'progress', function ( event ) {

					onProgress( event );

				}, false );

			}

			request.addEventListener( 'error', function ( event ) {

				if ( onError ) onError( event );

				scope.manager.itemEnd( url );
				scope.manager.itemError( url );

			}, false );

			if ( this.responseType !== undefined ) request.responseType = this.responseType;
			if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;

			if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );

			for ( var header in this.requestHeader ) {

				request.setRequestHeader( header, this.requestHeader[ header ] );

			}

			request.send( null );

		}

		scope.manager.itemStart( url );

		return request;

	},

	setPath: function ( value ) {

		this.path = value;
		return this;

	},

	setResponseType: function ( value ) {

		this.responseType = value;
		return this;

	},

	setWithCredentials: function ( value ) {

		this.withCredentials = value;
		return this;

	},

	setMimeType: function ( value ) {

		this.mimeType = value;
		return this;

	},

	setRequestHeader: function ( value ) {

		this.requestHeader = value;
		return this;

	}

} );

export { FileLoader };
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(FILL_ME_IN);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe(FILL_ME_IN);
    expect(overrideMessage()).toBe(FILL_ME_IN);
    expect(message).toBe(FILL_ME_IN);
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Completed AboutFunctions.js<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe("John rules!");

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(3);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe("function (a, b) {\n      //An internal comment\n      return a * b;\n    }");
  });
});
<|endoftext|>


<commit_before>import co from "co"
import { readFile as read } from "mz/fs"
import { test } from "tape"
import Fly from "../src/fly"
import { join } from "path"
import touch from "touch"

test("✈  fly", (t) => {
  t.ok(Fly !== undefined, "is defined")
  Array.prototype.concat([
    "source",
    "filter",
    "watch",
    "unwrap",
    "exec",
    "start",
    "write",
    "clear",
    "concat",
    "target",
    "emit"
  ]).forEach((method) => t.ok(method !== undefined,
    method + " is defined"))
  t.end()
})

test("✈  fly.constructor", (t) => {
  const fly = new Fly({
    file: join(__dirname, "fixtures", "flyfile.js"),
    host: {
      task() {
        t.equal(fly, this, "bind tasks to fly instance")
      }
    }
  })
  t.ok(fly !== undefined, "create fly instance")
  t.ok(fly.tasks.task !== undefined, "load task from host")
  fly.tasks.task()
  t.deepEqual(fly.plugins, [], "no default plugins")
  t.equal(process.cwd(), join(__dirname, "fixtures"),
    "switch current working directory")
  t.equal(fly.file, join(__dirname, "fixtures", "flyfile.js"),
    "set file to path specified in the constructor")
  t.end()
})

test("✈  fly.source", (t) => {
  const fly = new Fly()
  fly.source([[[[["*.a", ["*.b"]]], ["*.c"]]]])
  t.deepEqual(fly._.globs, ["*.a", "*.b", "*.c"], "flatten globs")
  t.deepEqual(fly._.filters, [], "init empty filter list")
  t.end()
})

test("✈  fly.filter", (t) => {
  const fly = new Fly()
  fly.filter((src) => src.toLowerCase())

  t.equal(fly._.filters.length, 1, "add filter to filter collection")
  t.equal(fly._.filters[0].cb("FLY"), "fly",
    "add transform cb for anonymous filters")

  fly.filter("myFilter", (data) => {
    return {
      code: data.toString().toUpperCase(),
      ext: ".foo"
    }
  })

  t.ok(fly.myFilter instanceof Function,
    "add transform cb to fly instance for named filters")

  fly.myFilter({ secret: 42 })
  t.equal(fly._.filters[1].cb("fly").code, "FLY",
    "create transform cb function for named filter")
  t.equal(fly._.filters[1].cb("fly").ext, ".foo", "read extension from filter")
  t.equal(fly._.filters[1].options.secret, 42, "read options from filter")

  try { fly.filter("myFilter")
  } catch (e) { t.ok(true, "throw an error if filter already exists") }

  fly.source("")
  t.deepEqual(fly._.filters, [], "reset filter each time source is called")

  t.end()
})

test("✈  fly.watch", (t) => {
  t.plan(6)
  const glob = "flyfile.js"
  const path = join(__dirname, "fixtures", "flyfile.js")
  const fly = new Fly({
    file: path,
    host: {
      *default(data) {
        t.ok(true, "run tasks at least once")
        t.equal(data, 42, "pass options into task via start")
      }
    }
  })
  fly.emit = (event) => {
    if (event === "fly_watch") t.ok(true, "notify watch event to observers")
    return fly
  }
  fly.watch(glob, "default", { value: 42 }).then((watcher) => {
    t.ok(watcher.unwatch !== undefined, "watch promise resolves to a watcher")
    setTimeout(() =>{
    // hijack the task to test the watcher runs default when the glob changes
      fly.host.default = function* (data) {
        watcher.unwatch(glob)
        t.ok(true, "run given tasks when glob changes")
        t.equal(data, 42, "pass options into task via start on change")
      }
      touch(path)
    }, 100)
  })
})

test("✈  fly.unwrap", (t) => {
  t.plan(4)
  const files_x = ["a.x", "b.x", "c.x"]
  const files_y = ["a.y", "b.y", "c.y"]
  const files = files_x.concat(files_y)
  const paths = files.map((file) => {
    const path = join(__dirname, "fixtures", file)
    touch(path)
    return path
  })
  const fly = new Fly()
  co(function* () {
    yield fly.source("*.x").unwrap((f) => {
      t.deepEqual(f, files_x, "unwrap source globs with single entry point")
    })
    yield fly.source(["*.y"]).unwrap((f) => {
      t.deepEqual(f, files_y, "unwrap source globs with single entry point in array")
    })
    const result = yield fly.source(["*.x", "*.y"]).unwrap((f) => {
      t.deepEqual(f, files, "unwrap source globs with multiple entry points")
      return 42
    })
    t.equal(result, 42, "result is the return value from fulfilled handler")
    yield fly.clear(files)
  })
})

test("✈  fly.*exec", (t) => {
  t.plan(4)
  const fly = new Fly({
    host: {
      *task(data) {
        t.ok(true, "run a task")
        t.equal(data, "rosebud", "pass an initial value to task")
      }
    }
  })
  fly.emit = (event, options) => {
    if (event === "task_start")
      t.ok(true, "notify start event to observers")
    if (event === "task_complete")
      t.ok(true, "notify complete event to observers")
    return fly
  }
  co(fly.exec.bind(fly), "task", "rosebud")
})

test("✈  fly.start", (t) => {
  t.plan(3)
  const value = 42
  const fly = new Fly({
    host: {
      *a(data) {
        return data + 1
      },
      *b(data) {
        return data + 1
      },
      *c(data) {
        t.ok(true, "run a given list of tasks")
        t.equal(data, value + 2, "cascade return values")
        return data + 1
      }
    }
  })
  co(function* () {
    const result = yield fly.start(["a", "b", "c"], { value: value })
    t.equal(result, value + 3, "return last task value")
  })
})

test("✈  fly.start (order)", (t, state) => {
  t.plan(2)
  state = 0
  const fly = new Fly({
    host: {
    // when running in a sequence both b and c wait while a blocks.
    // when running in parallel, b and c run while a blocks. state
    // can only be 3 when each task runs in order.
      *a() {
        yield block()
        if (state === 0) state++
      },
      *b() { state++ },
      *c() { state++ }
    }
  })
  co(function* () {
    yield fly.start(["a", "b", "c"], { parallel: false })
    t.ok(state === 3, "run tasks in sequence")
    state = 0 // reset
    yield fly.start(["a", "b", "c"], { parallel: true })
    t.ok(state !== 3, "run tasks in parallel")
  })
  function block () {
    return new Promise((resolve) => setTimeout(() => resolve(), 200))
  }
})

test("✈  fly.clear", (t) => {
  t.plan(1)
  const paths = Array.prototype.concat(["tmp1", "tmp2", "tmp3"])
  .map((file) => {
    const path = join(__dirname, "fixtures", file)
    touch(path)
    return path
  })
  const fly = new Fly()
  co(function* () {
    yield fly.clear(paths)
    t.ok(true, "clear files from a given list of paths")
  })
})

test("✈  fly.concat", (t) => {
  const fly = new Fly()
  fly.concat("f")
  t.equal(fly._.cat.base, "f", "add concat writer")
  t.end()
})

test("✈  fly.target", (t) => {
  t.plan(1)
  co(function* () {
    process.chdir(join(__dirname, "fixtures"))
    const fly = new Fly()
    yield fly
      .source("*.txt")
      .filter((data) => data.toString().toUpperCase())
      .target(".")

    yield fly
      .source("*.txt")
      .filter((data) => {
        t.ok(data.toString() === "FOO BAR\n", "resolve source, filters and writers")
        return data.toString().toLowerCase()
      })
      .target(".")
  })
})
<commit_msg>setup tests' structure for target-flattening<commit_after>import co from "co"
import { readFile as read } from "mz/fs"
import { test } from "tape"
import Fly from "../src/fly"
import { join } from "path"
import touch from "touch"

test("✈  fly", (t) => {
  t.ok(Fly !== undefined, "is defined")
  Array.prototype.concat([
    "source",
    "filter",
    "watch",
    "unwrap",
    "exec",
    "start",
    "write",
    "clear",
    "concat",
    "target",
    "emit"
  ]).forEach((method) => t.ok(method !== undefined,
    method + " is defined"))
  t.end()
})

test("✈  fly.constructor", (t) => {
  const fly = new Fly({
    file: join(__dirname, "fixtures", "flyfile.js"),
    host: {
      task() {
        t.equal(fly, this, "bind tasks to fly instance")
      }
    }
  })
  t.ok(fly !== undefined, "create fly instance")
  t.ok(fly.tasks.task !== undefined, "load task from host")
  fly.tasks.task()
  t.deepEqual(fly.plugins, [], "no default plugins")
  t.equal(process.cwd(), join(__dirname, "fixtures"),
    "switch current working directory")
  t.equal(fly.file, join(__dirname, "fixtures", "flyfile.js"),
    "set file to path specified in the constructor")
  t.end()
})

test("✈  fly.source", (t) => {
  const fly = new Fly()
  fly.source([[[[["*.a", ["*.b"]]], ["*.c"]]]])
  t.deepEqual(fly._.globs, ["*.a", "*.b", "*.c"], "flatten globs")
  t.deepEqual(fly._.filters, [], "init empty filter list")
  t.end()
})

test("✈  fly.filter", (t) => {
  const fly = new Fly()
  fly.filter((src) => src.toLowerCase())

  t.equal(fly._.filters.length, 1, "add filter to filter collection")
  t.equal(fly._.filters[0].cb("FLY"), "fly",
    "add transform cb for anonymous filters")

  fly.filter("myFilter", (data) => {
    return {
      code: data.toString().toUpperCase(),
      ext: ".foo"
    }
  })

  t.ok(fly.myFilter instanceof Function,
    "add transform cb to fly instance for named filters")

  fly.myFilter({ secret: 42 })
  t.equal(fly._.filters[1].cb("fly").code, "FLY",
    "create transform cb function for named filter")
  t.equal(fly._.filters[1].cb("fly").ext, ".foo", "read extension from filter")
  t.equal(fly._.filters[1].options.secret, 42, "read options from filter")

  try { fly.filter("myFilter")
  } catch (e) { t.ok(true, "throw an error if filter already exists") }

  fly.source("")
  t.deepEqual(fly._.filters, [], "reset filter each time source is called")

  t.end()
})

test("✈  fly.watch", (t) => {
  t.plan(6)
  const glob = "flyfile.js"
  const path = join(__dirname, "fixtures", "flyfile.js")
  const fly = new Fly({
    file: path,
    host: {
      *default(data) {
        t.ok(true, "run tasks at least once")
        t.equal(data, 42, "pass options into task via start")
      }
    }
  })
  fly.emit = (event) => {
    if (event === "fly_watch") t.ok(true, "notify watch event to observers")
    return fly
  }
  fly.watch(glob, "default", { value: 42 }).then((watcher) => {
    t.ok(watcher.unwatch !== undefined, "watch promise resolves to a watcher")
    setTimeout(() =>{
    // hijack the task to test the watcher runs default when the glob changes
      fly.host.default = function* (data) {
        watcher.unwatch(glob)
        t.ok(true, "run given tasks when glob changes")
        t.equal(data, 42, "pass options into task via start on change")
      }
      touch(path)
    }, 100)
  })
})

test("✈  fly.unwrap", (t) => {
  t.plan(4)
  const files_x = ["a.x", "b.x", "c.x"]
  const files_y = ["a.y", "b.y", "c.y"]
  const files = files_x.concat(files_y)
  const paths = files.map((file) => {
    const path = join(__dirname, "fixtures", file)
    touch(path)
    return path
  })
  const fly = new Fly()
  co(function* () {
    yield fly.source("*.x").unwrap((f) => {
      t.deepEqual(f, files_x, "unwrap source globs with single entry point")
    })
    yield fly.source(["*.y"]).unwrap((f) => {
      t.deepEqual(f, files_y, "unwrap source globs with single entry point in array")
    })
    const result = yield fly.source(["*.x", "*.y"]).unwrap((f) => {
      t.deepEqual(f, files, "unwrap source globs with multiple entry points")
      return 42
    })
    t.equal(result, 42, "result is the return value from fulfilled handler")
    yield fly.clear(files)
  })
})

test("✈  fly.*exec", (t) => {
  t.plan(4)
  const fly = new Fly({
    host: {
      *task(data) {
        t.ok(true, "run a task")
        t.equal(data, "rosebud", "pass an initial value to task")
      }
    }
  })
  fly.emit = (event, options) => {
    if (event === "task_start")
      t.ok(true, "notify start event to observers")
    if (event === "task_complete")
      t.ok(true, "notify complete event to observers")
    return fly
  }
  co(fly.exec.bind(fly), "task", "rosebud")
})

test("✈  fly.start", (t) => {
  t.plan(3)
  const value = 42
  const fly = new Fly({
    host: {
      *a(data) {
        return data + 1
      },
      *b(data) {
        return data + 1
      },
      *c(data) {
        t.ok(true, "run a given list of tasks")
        t.equal(data, value + 2, "cascade return values")
        return data + 1
      }
    }
  })
  co(function* () {
    const result = yield fly.start(["a", "b", "c"], { value: value })
    t.equal(result, value + 3, "return last task value")
  })
})

test("✈  fly.start (order)", (t, state) => {
  t.plan(2)
  state = 0
  const fly = new Fly({
    host: {
    // when running in a sequence both b and c wait while a blocks.
    // when running in parallel, b and c run while a blocks. state
    // can only be 3 when each task runs in order.
      *a() {
        yield block()
        if (state === 0) state++
      },
      *b() { state++ },
      *c() { state++ }
    }
  })
  co(function* () {
    yield fly.start(["a", "b", "c"], { parallel: false })
    t.ok(state === 3, "run tasks in sequence")
    state = 0 // reset
    yield fly.start(["a", "b", "c"], { parallel: true })
    t.ok(state !== 3, "run tasks in parallel")
  })
  function block () {
    return new Promise((resolve) => setTimeout(() => resolve(), 200))
  }
})

test("✈  fly.clear", (t) => {
  t.plan(1)
  const paths = Array.prototype.concat(["tmp1", "tmp2", "tmp3"])
  .map((file) => {
    const path = join(__dirname, "fixtures", file)
    touch(path)
    return path
  })
  const fly = new Fly()
  co(function* () {
    yield fly.clear(paths)
    t.ok(true, "clear files from a given list of paths")
  })
})

test("✈  fly.concat", (t) => {
  const fly = new Fly()
  fly.concat("f")
  t.equal(fly._.cat.base, "f", "add concat writer")
  t.end()
})

test("✈  fly.flatten", (t) => {
  t.plan(4)
  const fly = new Fly()
  const src = join(__dirname, "fixtures", "**/*.md")
  const dest = join(__dirname, "fixtures", "dest")

  co(function* () {
    yield fly.source(src).target(dest)
    t.ok(true, "retain normal pathing if desired depth not specified")
    yield fly.clear(dest)
  })

  co(function* () {
    yield fly.source(src).target(dest, {depth: 0})
    t.ok(true, "move all files to same directory, no parents")
    yield fly.clear(dest)
  })

  co(function* () {
    yield fly.source(src).target(dest, {depth: 1})
    t.ok(true, "keep one parent directory per file")
    yield fly.clear(dest)
  })

  co(function* () {
    yield fly.source(src).target(dest, {depth: 5})
    t.ok(true, 'retain full path if desired depth exceeds path depth')
    yield fly.clear(dest)
  })
})

test("✈  fly.target", (t) => {
  t.plan(1)
  co(function* () {
    process.chdir(join(__dirname, "fixtures"))
    const fly = new Fly()
    yield fly
      .source("*.txt")
      .filter((data) => data.toString().toUpperCase())
      .target(".")

    yield fly
      .source("*.txt")
      .filter((data) => {
        t.ok(data.toString() === "FOO BAR\n", "resolve source, filters and writers")
        return data.toString().toLowerCase()
      })
      .target(".")
  })
})
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe();

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe("John rules!");

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(3);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe("function (a, b) {\n//An internal comment\nreturn a * b;\n}");
  });
});
<commit_msg>Completed all require parts.<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe();

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe("John rules!");

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(3);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe("function (a, b) {\n      //An internal comment\n      return a * b;\n    }");
  });
});
<|endoftext|>


<commit_before>javascript: (async () => {

    let api = new mw.Api();
    let titles = [];
    let result = '';

    await api.get({
        'action': 'query',
        'format': 'json',
        'prop': 'redirects',
        'titles': mw.config.get('wgPageName'),
        'rdlimit': 'max',
    }).then(async data => {
        let pageids = mw.config.get('wgArticleId') + '|' + $.map(data.query.pages[mw.config.get('wgArticleId')].redirects, redirect => redirect.pageid).join('|');
        pageids = pageids.replace(/\|$/, '');

        await api.get({
            'action': 'query',
            'format': 'json',
            'prop': 'info',
            'pageids': pageids,
            'inprop': 'varianttitles'
        }).then(data => {
            for (const pageid in data.query.pages) {
                const page = data.query.pages[pageid];
                for (const variant in page.varianttitles) {
                    const title = page.varianttitles[variant].replace(/^[^:]+?:/, '');
                    if (titles.indexOf(title) === -1) {
                        titles.push(title);
                        result += title + '
';
                    }
                }
            }
        });
    });

    let regex = '(' + $.map(titles, title => {
        if (title.match(/^[A-Z]/)) {
            title = '[' + title[0] + title[0].toLowerCase() + ']' + title.substr(1);
        }
        title = title.replace(/ /, '[ _]');
        return title;
    }).join('|') + ')';

    let regexcilist = [];
    let checkdup = [];
    titles.forEach(title => {
        if (checkdup.indexOf(title.toLowerCase()) !== -1) {
            return;
        }
        checkdup.push(title.toLowerCase());
        regexcilist.push(title.replace(/ /, '[ _]'));
    });

    let regexci = '(' + regexcilist.join('|') + ')';

    result += '
Regex:
' + regex;
    result += '
Regex (case insensitive):
' + regexci;

    var win = window.open('');
    win.document.body.innerHTML = result;

}
)();
<commit_msg>Space can be one or more<commit_after>javascript: (async () => {

    let api = new mw.Api();
    let titles = [];
    let result = '';

    await api.get({
        'action': 'query',
        'format': 'json',
        'prop': 'redirects',
        'titles': mw.config.get('wgPageName'),
        'rdlimit': 'max',
    }).then(async data => {
        let pageids = mw.config.get('wgArticleId') + '|' + $.map(data.query.pages[mw.config.get('wgArticleId')].redirects, redirect => redirect.pageid).join('|');
        pageids = pageids.replace(/\|$/, '');

        await api.get({
            'action': 'query',
            'format': 'json',
            'prop': 'info',
            'pageids': pageids,
            'inprop': 'varianttitles'
        }).then(data => {
            for (const pageid in data.query.pages) {
                const page = data.query.pages[pageid];
                for (const variant in page.varianttitles) {
                    const title = page.varianttitles[variant].replace(/^[^:]+?:/, '');
                    if (titles.indexOf(title) === -1) {
                        titles.push(title);
                        result += title + '
';
                    }
                }
            }
        });
    });

    let regex = '(' + $.map(titles, title => {
        if (title.match(/^[A-Z]/)) {
            title = '[' + title[0] + title[0].toLowerCase() + ']' + title.substr(1);
        }
        title = title.replace(/ /, '[ _]+');
        return title;
    }).join('|') + ')';

    let regexcilist = [];
    let checkdup = [];
    titles.forEach(title => {
        if (checkdup.indexOf(title.toLowerCase()) !== -1) {
            return;
        }
        checkdup.push(title.toLowerCase());
        regexcilist.push(title.replace(/ /, '[ _]+'));
    });

    let regexci = '(' + regexcilist.join('|') + ')';

    result += '
Regex:
' + regex;
    result += '
Regex (case insensitive):
' + regexci;

    var win = window.open('');
    win.document.body.innerHTML = result;

}
)();
<|endoftext|>


<commit_before>// SotD
//  must link to mailing list, include its name, link to archive
//  below:

// If you wish to make comments regarding this document, please send them to
// public-html@w3.org
// (subscribe,
// archives).

const self = {
    name: 'sotd.mailing-list'
};

exports.check = function (sr, done) {
    var $sotd = sr.getSotDSection();
    if (!$sotd || !$sotd.length) {
        sr.error(self, "no-sotd");
        return done();
    }
    var foundML = false
    ,   foundSub = false
    ,   foundArch = false
    ;
    $sotd.find("a[href]").each(function () {
        var $a = sr.$(this)
        ,   href = $a.attr("href")
        ,   text = sr.norm($a.text())
        ;
        if (/^mailto:.+@w3\.org(?:\?subject=.*)?$/i.test(href) &&
            !/.+-request@/.test(href)) {
            foundML = true;
            return;
        }
        if (/^mailto:.+?-request@w3\.org\?subject=subscribe$/i.test(href) && text === "subscribe") {
            foundSub = true;
            return;
        }
        if (/^http:\/\/lists\.w3\.org\/Archives\//.test(href) && /archive/i.test(text)) {
            foundArch = true;
            return;
        }
    });
    if (!foundML) sr.error(self, "no-list");
    if (!foundSub) sr.warning(self, "no-sub");
    if (!foundArch) sr.error(self, "no-arch");
    done();
};
<commit_msg>mailing list archive: also check https<commit_after>// SotD
//  must link to mailing list, include its name, link to archive
//  below:

// If you wish to make comments regarding this document, please send them to
// public-html@w3.org
// (subscribe,
// archives).

const self = {
    name: 'sotd.mailing-list'
};

exports.check = function (sr, done) {
    var $sotd = sr.getSotDSection();
    if (!$sotd || !$sotd.length) {
        sr.error(self, "no-sotd");
        return done();
    }
    var foundML = false
    ,   foundSub = false
    ,   foundArch = false
    ;
    $sotd.find("a[href]").each(function () {
        var $a = sr.$(this)
        ,   href = $a.attr("href")
        ,   text = sr.norm($a.text())
        ;
        if (/^mailto:.+@w3\.org(?:\?subject=.*)?$/i.test(href) &&
            !/.+-request@/.test(href)) {
            foundML = true;
            return;
        }
        if (/^mailto:.+?-request@w3\.org\?subject=subscribe$/i.test(href) && text === "subscribe") {
            foundSub = true;
            return;
        }
        if (/^https?:\/\/lists\.w3\.org\/Archives\//.test(href) && /archive/i.test(text)) {
            foundArch = true;
            return;
        }
    });
    if (!foundML) sr.error(self, "no-list");
    if (!foundSub) sr.warning(self, "no-sub");
    if (!foundArch) sr.error(self, "no-arch");
    done();
};
<|endoftext|>


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

describe('non-player character', function() {
	describe('reaction', function() {
		it("must have a reaction level")
	});

	describe('hostile NPC', function() {
		it("must have a hostile reaction level")
	});

	describe('undecided NPC', function() {
		it("must have a hostile reaction level")
	});

	describe('friendly NPC', function() {
		it("must have a hostile reaction level")
	});
});<commit_msg>updated pending NPC tests<commit_after>var ultralite = require('../lib/ultralite.js');

describe('non-player character', function() {
	describe('reaction', function() {
		it("must have a reaction level")
	});

	describe('hostile NPC', function() {
		it("must have a hostile reaction level")
	});

	describe('undecided NPC', function() {
		it("must have an undecided reaction level")
	});

	describe('friendly NPC', function() {
		it("must have a friendly reaction level")
	});
});<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
 *
 * lib/endpoints/server/images.js: SAPI endpoints to manage images
 */

var restify = require('restify');

function Images() {}

Images.download = function (req, res, next) {
	var model = this.model;
	var log = model.log;

	/*
	 * Node's default HTTP timeout is two minutes, and this DownloadImage
	 * request can take longer than that to complete.  Set this connection's
	 * timeout to an hour to avoid an abrupt close after two minutes.
	 */
	req.connection.setTimeout(60 * 60 * 1000);

	var opts = {};
	if (req.params.skipOwnerCheck)
		opts.skipOwnerCheck = true;

	model.downloadImage(req.params.uuid, opts, function (err) {
		if (err) {
			log.error(err, 'failed to download image');
			return (next(err));
		}

		res.send(204);
		return (next());

	});

	return (null);
};

Images.search = function (req, res, next) {
	var model = this.model;
	var log = model.log;

	var name = req.params.name;

	if (!name) {
		log.error('missing "name" parameter');
		return (next(new restify.MissingParameterError()));
	}

	var search_opts = {};
	search_opts.name = name;
	if (req.params.version)
		search_opts.version = req.params.version;

	model.searchImages(search_opts, function (err, images) {
		if (err)
			return (next(err));

		res.send(images);
		return (next());
	});

	return (null);
};

function attachTo(sapi, model) {
	var toModel = {
		model: model
	};

	// Download an image
	sapi.post({ path: '/images/:uuid', name: 'DownloadImage' },
		Images.download.bind(toModel));

	// Search for images
	sapi.get({ path: '/images', name: 'SearchImages' },
		Images.search.bind(toModel));
}

exports.attachTo = attachTo;
<commit_msg>MANTA-1969: manta deployment: stop needing an external on SAPI (logging image requests)<commit_after>/*
 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
 *
 * lib/endpoints/server/images.js: SAPI endpoints to manage images
 */

var restify = require('restify');

function Images() {}

Images.download = function (req, res, next) {
	var model = this.model;
	var log = model.log;

	log.info({ req: req });

	/*
	 * Node's default HTTP timeout is two minutes, and this DownloadImage
	 * request can take longer than that to complete.  Set this connection's
	 * timeout to an hour to avoid an abrupt close after two minutes.
	 */
	req.connection.setTimeout(60 * 60 * 1000);

	var opts = {};
	if (req.params.skipOwnerCheck)
		opts.skipOwnerCheck = true;

	model.downloadImage(req.params.uuid, opts, function (err) {
		if (err) {
			log.error(err, 'failed to download image');
			return (next(err));
		}

		res.send(204);
		return (next());

	});

	return (null);
};

Images.search = function (req, res, next) {
	var model = this.model;
	var log = model.log;

	log.info({ req: req });

	var name = req.params.name;

	if (!name) {
		log.error('missing "name" parameter');
		return (next(new restify.MissingParameterError()));
	}

	var search_opts = {};
	search_opts.name = name;
	if (req.params.version)
		search_opts.version = req.params.version;

	model.searchImages(search_opts, function (err, images) {
		if (err)
			return (next(err));

		res.send(images);
		return (next());
	});

	return (null);
};

function attachTo(sapi, model) {
	var toModel = {
		model: model
	};

	// Download an image
	sapi.post({ path: '/images/:uuid', name: 'DownloadImage' },
		Images.download.bind(toModel));

	// Search for images
	sapi.get({ path: '/images', name: 'SearchImages' },
		Images.search.bind(toModel));
}

exports.attachTo = attachTo;
<|endoftext|>


<commit_before>var mdeps = require('../');
var test = require('tap').test;
var path = require('path');
var fs = require('fs');

var dirname = path.join(__dirname, '/pkg');

test('pkg', function (t) {
    t.plan(4);

    var d = mdeps();
    d.on('package', function (pkg_) {
        var pkg = JSON.parse(fs.readFileSync(dirname + pkg_.dir + '/package.json'));
        pkg.__dirname = dirname + pkg_.dir;

        t.deepEqual(pkg_, pkg);
    });
    d.end(path.join(__dirname, '/pkg/main.js'));
    d.resume();
});
<commit_msg>Windows compatability for test/pkg.js<commit_after>var mdeps = require('../');
var test = require('tap').test;
var path = require('path');
var fs = require('fs');

var dirname = path.join(__dirname, '/pkg');

test('pkg', function (t) {
    t.plan(4);

    var d = mdeps();
    d.on('package', function (pkg_) {
        var pkg = JSON.parse(fs.readFileSync(dirname + pkg_.dir + '/package.json'));
        pkg.__dirname = path.join(dirname, pkg_.dir);

        t.deepEqual(pkg_, pkg);
    });
    d.end(path.join(__dirname, '/pkg/main.js'));
    d.resume();
});
<|endoftext|>


<commit_before>'use strict';

const Region = require('../constant/region.js');

const Service = require('../service.js');

/**
 * @class
 * @alias module:LeagueWrapper/service~LolStaticDataService
 * @extends Service
 */
class LolStaticDataService extends Service {
  constructor(api) {
    super(api);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getChampions
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~ChampionListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {boolean} [query.dataById]
   * @param {ChampData[]|ChampData} [query.champData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getChampions} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~ChampionListDto>}
   */
  getChampions(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/champion',
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getChampionById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~ChampionDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {boolean} [query.dataById]
   * @param {ChampData[]|ChampData} [query.champData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getChampionById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~ChampionDto>}
   */
  getChampionById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/champion/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getItems
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~ItemListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {ItemData[]|ItemData} [query.itemListData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getItems} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~ItemListDto>}
   */
  getItems(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/item',
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getItemById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~ItemDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {ItemData[]|ItemData} [query.itemData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getItemById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~ItemDto>}
   */
  getItemById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/item/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getLanguageStrings
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~LanguageStringsDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getLanguageStrings} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~LanguageStringsDto>}
   */
  getLanguageStrings(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/language-strings',
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getLanguages
   * @param {?Error} error
   * @param {Array.<string>} [data]
   */
  /**
   * @todo example
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getLanguages} [callback]
   *
   * @return {Promise.<Array.<string>>}
   */
  getLanguages(options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/languages',
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getMap
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~MapDataDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getMap} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~MapDataDto>}
   */
  getMap(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/languages',
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getMasteries
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~MasteryListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {MasteryData} [query.masteryListData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getMasteries} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~MasteryListDto>}
   */
  getMasteries(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/mastery',
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getMasteryById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~MasteryDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {MasteryData} [query.masteryData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getMasteryById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~MasteryDto>}
   */
  getMasteryById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/mastery/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getRealm
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~RealmDto} [data]
   */
  /**
   * @todo example
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getRealm} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~RealmDto>}
   */
  getRealm(options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/realm',
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getRunes
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~RuneListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {RuneData} [query.runeListData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getRunes} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~RuneListDto>}
   */
  getRunes(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/rune/',
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getRuneById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~RuneDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {RuneData} [query.runeData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getRuneById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~RuneDto>}
   */
  getRuneById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/rune/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getSummonerSpells
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~SummonerSpellListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {boolean} [query.dataById]
   * @param {SpellData} [query.spellData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getSummonerSpells} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~SummonerSpellListDto>}
   */
  getSummonerSpells(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/summoner-spell',
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getSummonerSpellById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~SummonerSpellDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {boolean} [query.dataById]
   * @param {SpellData} [query.spellData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getSummonerSpellById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~SummonerSpellDto>}
   */
  getSummonerSpellById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/summoner-spell/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getVersions
   * @param {?Error} error
   * @param {Array.<string>} [data]
   */
  /**
   * @todo example
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getVersions} [callback]
   *
   * @return {Promise.<Array.<string>>}
   */
  getVersions(options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/versions',
      host: Region.GLOBAL.getHostUrl()
    }, options);

    return super.request(options).execute(callback);
  }
}

exports = module.exports = LolStaticDataService;

<commit_msg>Add returnType to LolStaticDataService<commit_after>'use strict';

const ChampionDto = require('../dto/lol-static-data/champion-dto.js');
const ChampionListDto = require('../dto/lol-static-data/champion-list-dto.js');
const ItemDto = require('../dto/lol-static-data/item-dto.js');
const ItemListDto = require('../dto/lol-static-data/item-list-dto.js');
const LanguageStringsDto = require('../dto/lol-static-data/language-strings-dto.js');
const MapDataDto = require('../dto/lol-static-data/map-data-dto.js');
const MasteryDto = require('../dto/lol-static-data/mastery-dto.js');
const MasteryListDto = require('../dto/lol-static-data/mastery-list-dto.js');
const RealmDto = require('../dto/lol-static-data/realm-dto.js');
const RuneDto = require('../dto/lol-static-data/rune-dto.js');
const RuneListDto = require('../dto/lol-static-data/rune-list-dto.js');
const SummonerSpellDto = require('../dto/lol-static-data/summoner-spell-dto.js');
const SummonerSpellListDto = require('../dto/lol-static-data/summoner-spell-list-dto.js');

const Region = require('../constant/region.js');

const Service = require('../service.js');

/**
 * @class
 * @alias module:LeagueWrapper/service~LolStaticDataService
 * @extends Service
 */
class LolStaticDataService extends Service {
  constructor(api) {
    super(api);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getChampions
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~ChampionListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {boolean} [query.dataById]
   * @param {ChampData[]|ChampData} [query.champData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getChampions} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~ChampionListDto>}
   */
  getChampions(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/champion',
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: ChampionListDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getChampionById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~ChampionDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {boolean} [query.dataById]
   * @param {ChampData[]|ChampData} [query.champData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getChampionById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~ChampionDto>}
   */
  getChampionById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/champion/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: ChampionDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getItems
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~ItemListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {ItemData[]|ItemData} [query.itemListData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getItems} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~ItemListDto>}
   */
  getItems(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/item',
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: ItemListDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getItemById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~ItemDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {ItemData[]|ItemData} [query.itemData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getItemById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~ItemDto>}
   */
  getItemById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/item/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: ItemDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getLanguageStrings
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~LanguageStringsDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getLanguageStrings} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~LanguageStringsDto>}
   */
  getLanguageStrings(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/language-strings',
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: LanguageStringsDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getLanguages
   * @param {?Error} error
   * @param {Array.<string>} [data]
   */
  /**
   * @todo example
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getLanguages} [callback]
   *
   * @return {Promise.<Array.<string>>}
   */
  getLanguages(options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/languages',
      host: Region.GLOBAL.getHostUrl(),
      returnType: [String]
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getMap
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~MapDataDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getMap} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~MapDataDto>}
   */
  getMap(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/languages',
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: MapDataDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getMasteries
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~MasteryListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {MasteryData} [query.masteryListData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getMasteries} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~MasteryListDto>}
   */
  getMasteries(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/mastery',
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: MasteryListDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getMasteryById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~MasteryDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {MasteryData} [query.masteryData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getMasteryById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~MasteryDto>}
   */
  getMasteryById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/mastery/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: MasteryDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getRealm
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~RealmDto} [data]
   */
  /**
   * @todo example
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getRealm} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~RealmDto>}
   */
  getRealm(options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/realm',
      host: Region.GLOBAL.getHostUrl(),
      returnType: RealmDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getRunes
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~RuneListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {RuneData} [query.runeListData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getRunes} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~RuneListDto>}
   */
  getRunes(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/rune/',
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: RuneListDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getRuneById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~RuneDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {RuneData} [query.runeData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getRuneById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~RuneDto>}
   */
  getRuneById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/rune/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: RuneDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getSummonerSpells
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~SummonerSpellListDto} [data]
   */
  /**
   * @todo example
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {boolean} [query.dataById]
   * @param {SpellData} [query.spellData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getSummonerSpells} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~SummonerSpellListDto>}
   */
  getSummonerSpells(query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/summoner-spell',
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: SummonerSpellListDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getSummonerSpellById
   * @param {?Error} error
   * @param {module:LeagueWrapper/dto/lolStaticData~SummonerSpellDto} [data]
   */
  /**
   * @todo example
   * @param {number} id
   * @param {Object} [query]
   * @param {string} [query.locale] // @todo: enum
   * @param {string} [query.version]
   * @param {boolean} [query.dataById]
   * @param {SpellData} [query.spellData]
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getSummonerSpellById} [callback]
   *
   * @return {Promise.<module:LeagueWrapper/dto/lolStaticData~SummonerSpellDto>}
   */
  getSummonerSpellById(id, query, options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/summoner-spell/${id}',
      params: {
        id: id
      },
      query: query,
      host: Region.GLOBAL.getHostUrl(),
      returnType: SummonerSpellDto
    }, options);

    return super.request(options).execute(callback);
  }

  /**
   * @callback module:LeagueWrapper/service~LolStaticDataService~getVersions
   * @param {?Error} error
   * @param {Array.<string>} [data]
   */
  /**
   * @todo example
   * @param {?module:LeagueWrapper/options~RequestOptions} [options]
   * @param {module:LeagueWrapper/service~LolStaticDataService~getVersions} [callback]
   *
   * @return {Promise.<Array.<string>>}
   */
  getVersions(options, callback) {
    options = Object.assign({
      path: '/api/lol/static-data/${region}/v1.2/versions',
      host: Region.GLOBAL.getHostUrl(),
      returnType: [String]
    }, options);

    return super.request(options).execute(callback);
  }
}

exports = module.exports = LolStaticDataService;

<|endoftext|>