<commit_before>'use strict';

exports.interpreter = function()
{
    var self = this;

    this.builtin_functions =
    {
        '+':
        {
            argc: 2,
            exec: function(a, b) { return a + b; }
        },
        '-':
        {
            argc: 2,
            exec: function(a, b) { return a - b; }
        },
        '*':
        {
            argc: 2,
            exec: function(a, b) { return a * b; }
        },
        '/':
        {
            argc: 2,
            exec: function(a, b) { return a / b; }
        },
        '%':
        {
            argc: 2,
            exec: function(a, b) { return a % b; }
        },
        '**':
        {
            argc: 2,
            exec: function(a, b) { return Math.pow(a, b); }
        },
        '<':
        {
            argc: 2,
            exec: function(a, b) { return a < b; }
        },
        '>':
        {
            argc: 2,
            exec: function(a, b) { return a > b; }
        },
        '<=':
        {
            argc: 2,
            exec: function(a, b) { return a <= b; }
        },
        '>=':
        {
            argc: 2,
            exec: function(a, b) { return a >= b; }
        },
        '==':
        {
            argc: 2,
            exec: function(a, b) { return a == b; }
        },
        '!=':
        {
            argc: 2,
            exec: function(a, b) { return a != b; }
        },
        'print':
        {
            argc: 1,
            exec: function(s) { console.log(s); }
        },
        'inspect':
        {
            argc: 0,
            exec: function()
            {
                process.stdout.write('Stack: ');
                console.log(self.exec_layer.stack);

                process.stdout.write('Variables: ');
                console.log(self.variables);
            }
        },
        'exec':
        {
            argc: 1,
            exec: function(fn)
            {
                if (typeof fn !== 'object')
                {
                    console.error('Error: exec: argument is not a function');
                    return;
                }

                if (fn.type === 'variable')
                {
                    var value = self.variables[fn.name];

                    if (typeof value !== 'object')
                    {
                        console.error('Error: exec: variable argument is not a function');
                        return;
                    }

                    self.exec_layer.exec(value);
                }
                else if (fn.type === 'function')
                {
                    self.exec_layer.exec(fn.value);
                }
                else
                {
                    throw new Error('Unrecognised type ' + fn.type);
                }
            }
        },
        '=':
        {
            argc: 0,
            exec: function()
            {
                // Check the stack can provide the arguments required
                if (self.exec_layer.stack.length < 2)
                {
                    console.error('Error: Not enough arguments for assignment');
                    self.exec_layer.stack.length = 0;
                    return;
                }

                var args = self.exec_layer.stack.splice(self.exec_layer.stack.length - 2, 2);

                if (typeof args[0] !== 'object' || args[0].type !== 'variable')
                {
                    console.error('Error: First argument to assignment is not a variable');
                    return;
                }

                if (typeof args[1] === 'object')
                {
                    if (args[1].type === 'variable')
                    {
                        var value = self.variables[args[1].name];

                        if (value === undefined)
                        {
                            console.error('Error: Cannot assign ' + args[0].name + ' to undefined variable ' + args[1].name);
                            return;
                        }

                        args[1] = value;
                    }
                    else if (args[1].type === 'function')
                    {
                        args[1] = args[1].value;
                    }
                    else
                    {
                        throw new Error('Unrecognised type ' + args[1].type);
                    }
                }

                self.variables[args[0].name] = args[1];
            }
        }
    };

    this.variables = {};

    this.handle_string = function(str)
    {
        for (var i = 0; i != str.length; i++)
        {
            self.comment_layer.handle_char(str[i]);
        }
    }

    this.comment_layer = new (function()
    {
        var layer = this;

        this.next_layer = null;

        this.had_slash = false;
        this.had_star = false;
        this.had_escape = false;

        this.block_depth = 0;
        this.block_has_newline = false;

        this.handle_char = function(c)
        {
            //console.log('comment layer: \'' + c + '\'');
            layer.mode(c);
        }

        this.normal_mode = function(c)
        {
            if (c === '"')
            {
                layer.had_slash = false;
                layer.mode = layer.string_mode;
                layer.next_layer.handle_char(c);
            }
            else if (layer.had_slash)
            {
                layer.had_slash = false;

                if (c === '/')
                {
                    layer.mode = layer.line_comment_mode;
                }
                else if (c === '*')
                {
                    layer.block_depth = 1;
                    layer.mode = layer.block_comment_mode;
                }
                else
                {
                    layer.next_layer.handle_char('/');
                    layer.next_layer.handle_char(c);
                }
            }
            else
            {
                if (c === '/')
                {
                    layer.had_slash = true;
                }
                else
                {
                    layer.next_layer.handle_char(c);
                }
            }
        }

        this.string_mode = function(c)
        {
            if (layer.had_escape)
            {
                layer.had_escape = false;
            }
            else if (c === '\\')
            {
                layer.had_escape = true;
            }
            else if (c === '"')
            {
                layer.mode = layer.normal_mode;
            }

            layer.next_layer.handle_char(c);
        }

        this.line_comment_mode = function(c)
        {
            if (c === '\n')
            {
                layer.mode = layer.normal_mode;
                layer.next_layer.handle_char('\n');
            }
        }

        this.block_comment_mode = function(c)
        {
            if (layer.had_slash)
            {
                layer.had_slash = false;

                if (c === '*')
                {
                    layer.block_depth++;
                    //console.log('incremented block depth to ' + layer.block_depth);
                }
                else if (c === '\n')
                {
                    layer.block_has_newline = true;
                }
            }
            else if (layer.had_star)
            {
                layer.had_star = false;

                if (c === '/')
                {
                    layer.block_depth--;
                    //console.log('decremented block depth to ' + layer.block_depth);

                    if (layer.block_depth === 0)
                    {
                        layer.next_layer.handle_char(layer.block_has_newline ? '\n' : ' ');
                        layer.block_has_newline = false;
                        layer.mode = layer.normal_mode;
                    }
                }
                else if (c === '\n')
                {
                    layer.block_has_newline = true;
                }
            }
            else
            {
                if (c === '/')
                {
                    layer.had_slash = true;
                }
                else if (c === '*')
                {
                    layer.had_star = true;
                }
            }
        }

        this.mode = this.normal_mode;
    })();

    this.word_layer = new (function()
    {
        var layer = this;

        this.next_layer = null;

        this.word = '';

        this.had_escape = false;

        this.handle_char = function(c)
        {
            //console.log('word layer: \'' + c + '\'');
            if (layer.word.length > 0 && layer.word[0] === '"')
            {
                if (layer.had_escape)
                {
                    layer.had_escape = false;
                    layer.word += c;
                }
                else
                {
                    if (c === '\\')
                    {
                        layer.had_escape = true;
                    }
                    else
                    {
                        layer.word += c;

                        if (c === '"')
                        {
                            layer.next_layer.handle_word(layer.word);
                            layer.word = ''; // TODO: this will allow the next word to start without whitespace, e.g. "foo"7 will be two words
                        }
                    }
                }
            }
            else
            {
                if (c === ' ' || c === '\n' || c === '\t' || c === '\r')
                {
                    if (layer.word !== '')
                    {
                        layer.next_layer.handle_word(layer.word);
                        layer.word = '';
                    }
                }
                else
                {
                    layer.word += c;
                }
            }
        }
    })();

    this.comment_layer.next_layer = this.word_layer;

    this.number_regex = new RegExp('^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$');
    this.variable_regex = new RegExp('^[a-zA-Z_][a-zA-Z0-9_]*$');

    this.exec_layer = new (function()
    {
        var layer = this;

        layer.stack = [];

        this.handle_word = function(word)
        {
            if (word[word.length - 1] === '#')
            {
                var sub_word = word.substr(0, word.length - 1);

                if (self.builtin_functions[sub_word])
                {
                    layer.stack.push({type: 'function', value: self.builtin_functions[sub_word]});
                }
                else if (self.variables[sub_word])
                {
                    layer.stack.push({type: 'variable', name: sub_word});
                }
                else
                {
                    console.error('Error: No matching symbol for "' + sub_word + '"');
                }
            }
            else if (self.builtin_functions[word])
            {
                layer.exec(self.builtin_functions[word]);
            }
            else if (self.variables[word])
            {
                var variable = self.variables[word];

                if (typeof variable === 'object')
                {
                    layer.exec(variable);
                }
                else
                {
                    layer.stack.push({type: 'variable', name: word});
                }
            }
            else if (self.number_regex.test(word))
            {
                layer.stack.push(parseFloat(word));
            }
            else if (word.length >= 2 && word[0] === '"' && word[word.length - 1] === '"')
            {
                layer.stack.push(word.substr(1, word.length - 2));
            }
            else if (self.variable_regex.test(word))
            {
                layer.stack.push({type: 'variable', name: word});
            }
            else
            {
                console.error('Error: Cannot parse word "' + word + '"');
            }
        }

        this.exec = function(fn)
        {
            // Check the stack can provide the arguments required
            if (layer.stack.length < fn.argc)
            {
                console.error('Error: Not enough arguments for function');
                layer.stack.length = 0;
                return;
            }

            // Retrieve function arguments from the stack
            var args = layer.stack.splice(layer.stack.length - fn.argc, fn.argc);

            // Replace variables with values
            for (var i in args)
            {
                if (typeof args[i] === 'object' && args[i].type === 'variable')
                {
                    var value = self.variables[args[i].name];

                    if (value === undefined)
                    {
                        console.error('Error: Cannot call function with undefined variable ' + args[i].name);
                        return;
                    }

                    args[i] = value;
                }
            }

            // Call the function
            var ret = fn.exec.apply(null, args);

            // Place the return value on the stack if one is provided
            if (ret !== undefined)
            {
                layer.stack.push(ret);
            }
        }
    })();

    this.word_layer.next_layer = this.exec_layer;
}
<commit_msg>Added constants (true and false for now) and type checking for builtins<commit_after>'use strict';

function check_type_pair(a, b, type)
{
    return (typeof a === type && typeof b === type);
}

exports.interpreter = function()
{
    var self = this;

    this.builtin_functions =
    {
        '+':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number') && !check_type_pair(a, b, 'string'))
                {
                    console.error('Error: +: arguments must be numbers or strings');
                    return;
                }

                return a + b;
            }
        },
        '-':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number'))
                {
                    console.error('Error: -: arguments must be numbers');
                    return;
                }

                return a - b;
            }
        },
        '*':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number'))
                {
                    console.error('Error: *: arguments must be numbers');
                    return;
                }

                return a * b;
            }
        },
        '/':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number'))
                {
                    console.error('Error: /: arguments must be numbers');
                    return;
                }

                return a / b;
            }
        },
        '%':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number'))
                {
                    console.error('Error: /: arguments must be numbers');
                    return;
                }

                return a % b;
            }
        },
        '**':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number'))
                {
                    console.error('Error: **: arguments must be numbers');
                    return;
                }

                return Math.pow(a, b);
            }
        },
        '<':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number') && !check_type_pair(a, b, 'string'))
                {
                    console.error('Error: <: arguments must be numbers or strings');
                    return;
                }

                return a < b;
            }
        },
        '>':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number') && !check_type_pair(a, b, 'string'))
                {
                    console.error('Error: >: arguments must be numbers or strings');
                    return;
                }

                return a > b;
            }
        },
        '<=':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number') && !check_type_pair(a, b, 'string'))
                {
                    console.error('Error: <=: arguments must be numbers or strings');
                    return;
                }

                return a <= b;
            }
        },
        '>=':
        {
            argc: 2,
            exec: function(a, b)
            {
                if (!check_type_pair(a, b, 'number') && !check_type_pair(a, b, 'string'))
                {
                    console.error('Error: >=: arguments must be numbers or strings');
                    return;
                }

                return a >= b;
            }
        },
        '==':
        {
            argc: 2,
            exec: function(a, b) { return a === b; }
        },
        '!=':
        {
            argc: 2,
            exec: function(a, b) { return a !== b; }
        },
        '!':
        {
            argc: 1,
            exec: function(x)
            {
                if (typeof x !== 'boolean')
                {
                    console.error('Error: !: argument must be a boolean');
                }

                return !x;
            }
        },
        'print':
        {
            argc: 1,
            exec: function(s) { console.log(s); }
        },
        'inspect':
        {
            argc: 0,
            exec: function()
            {
                process.stdout.write('Stack: ');
                console.log(self.exec_layer.stack);

                process.stdout.write('Variables: ');
                console.log(self.variables);
            }
        },
        'exec':
        {
            argc: 1,
            exec: function(fn)
            {
                if (typeof fn !== 'object')
                {
                    console.error('Error: exec: argument is not a function');
                    return;
                }

                if (fn.type === 'variable')
                {
                    var value = self.variables[fn.name];

                    if (typeof value !== 'object')
                    {
                        console.error('Error: exec: variable argument is not a function');
                        return;
                    }

                    self.exec_layer.exec(value);
                }
                else if (fn.type === 'function')
                {
                    self.exec_layer.exec(fn.value);
                }
                else
                {
                    throw new Error('Unrecognised type ' + fn.type);
                }
            }
        },
        '=':
        {
            argc: 0,
            exec: function()
            {
                // Check the stack can provide the arguments required
                if (self.exec_layer.stack.length < 2)
                {
                    console.error('Error: Not enough arguments for assignment');
                    self.exec_layer.stack.length = 0;
                    return;
                }

                var args = self.exec_layer.stack.splice(self.exec_layer.stack.length - 2, 2);

                if (typeof args[0] !== 'object' || args[0].type !== 'variable')
                {
                    console.error('Error: First argument to assignment is not a variable');
                    return;
                }

                if (typeof args[1] === 'object')
                {
                    if (args[1].type === 'variable')
                    {
                        var value = self.variables[args[1].name];

                        if (value === undefined)
                        {
                            console.error('Error: Cannot assign ' + args[0].name + ' to undefined variable ' + args[1].name);
                            return;
                        }

                        args[1] = value;
                    }
                    else if (args[1].type === 'function')
                    {
                        args[1] = args[1].value;
                    }
                    else
                    {
                        throw new Error('Unrecognised type ' + args[1].type);
                    }
                }

                self.variables[args[0].name] = args[1];
            }
        }
    };

    this.constants =
    {
        'true': true,
        'false': false
    };

    this.variables = {};

    this.handle_string = function(str)
    {
        for (var i = 0; i != str.length; i++)
        {
            self.comment_layer.handle_char(str[i]);
        }
    }

    this.comment_layer = new (function()
    {
        var layer = this;

        this.next_layer = null;

        this.had_slash = false;
        this.had_star = false;
        this.had_escape = false;

        this.block_depth = 0;
        this.block_has_newline = false;

        this.handle_char = function(c)
        {
            //console.log('comment layer: \'' + c + '\'');
            layer.mode(c);
        }

        this.normal_mode = function(c)
        {
            if (c === '"')
            {
                layer.had_slash = false;
                layer.mode = layer.string_mode;
                layer.next_layer.handle_char(c);
            }
            else if (layer.had_slash)
            {
                layer.had_slash = false;

                if (c === '/')
                {
                    layer.mode = layer.line_comment_mode;
                }
                else if (c === '*')
                {
                    layer.block_depth = 1;
                    layer.mode = layer.block_comment_mode;
                }
                else
                {
                    layer.next_layer.handle_char('/');
                    layer.next_layer.handle_char(c);
                }
            }
            else
            {
                if (c === '/')
                {
                    layer.had_slash = true;
                }
                else
                {
                    layer.next_layer.handle_char(c);
                }
            }
        }

        this.string_mode = function(c)
        {
            if (layer.had_escape)
            {
                layer.had_escape = false;
            }
            else if (c === '\\')
            {
                layer.had_escape = true;
            }
            else if (c === '"')
            {
                layer.mode = layer.normal_mode;
            }

            layer.next_layer.handle_char(c);
        }

        this.line_comment_mode = function(c)
        {
            if (c === '\n')
            {
                layer.mode = layer.normal_mode;
                layer.next_layer.handle_char('\n');
            }
        }

        this.block_comment_mode = function(c)
        {
            if (layer.had_slash)
            {
                layer.had_slash = false;

                if (c === '*')
                {
                    layer.block_depth++;
                    //console.log('incremented block depth to ' + layer.block_depth);
                }
                else if (c === '\n')
                {
                    layer.block_has_newline = true;
                }
            }
            else if (layer.had_star)
            {
                layer.had_star = false;

                if (c === '/')
                {
                    layer.block_depth--;
                    //console.log('decremented block depth to ' + layer.block_depth);

                    if (layer.block_depth === 0)
                    {
                        layer.next_layer.handle_char(layer.block_has_newline ? '\n' : ' ');
                        layer.block_has_newline = false;
                        layer.mode = layer.normal_mode;
                    }
                }
                else if (c === '\n')
                {
                    layer.block_has_newline = true;
                }
            }
            else
            {
                if (c === '/')
                {
                    layer.had_slash = true;
                }
                else if (c === '*')
                {
                    layer.had_star = true;
                }
            }
        }

        this.mode = this.normal_mode;
    })();

    this.word_layer = new (function()
    {
        var layer = this;

        this.next_layer = null;

        this.word = '';

        this.had_escape = false;

        this.handle_char = function(c)
        {
            //console.log('word layer: \'' + c + '\'');
            if (layer.word.length > 0 && layer.word[0] === '"')
            {
                if (layer.had_escape)
                {
                    layer.had_escape = false;
                    layer.word += c;
                }
                else
                {
                    if (c === '\\')
                    {
                        layer.had_escape = true;
                    }
                    else
                    {
                        layer.word += c;

                        if (c === '"')
                        {
                            layer.next_layer.handle_word(layer.word);
                            layer.word = ''; // TODO: this will allow the next word to start without whitespace, e.g. "foo"7 will be two words
                        }
                    }
                }
            }
            else
            {
                if (c === ' ' || c === '\n' || c === '\t' || c === '\r')
                {
                    if (layer.word !== '')
                    {
                        layer.next_layer.handle_word(layer.word);
                        layer.word = '';
                    }
                }
                else
                {
                    layer.word += c;
                }
            }
        }
    })();

    this.comment_layer.next_layer = this.word_layer;

    this.number_regex = new RegExp('^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$');
    this.variable_regex = new RegExp('^[a-zA-Z_][a-zA-Z0-9_]*$');

    this.exec_layer = new (function()
    {
        var layer = this;

        layer.stack = [];

        this.handle_word = function(word)
        {
            if (word[word.length - 1] === '#')
            {
                var sub_word = word.substr(0, word.length - 1);

                if (self.builtin_functions[sub_word])
                {
                    layer.stack.push({type: 'function', value: self.builtin_functions[sub_word]});
                }
                else if (self.variables[sub_word])
                {
                    layer.stack.push({type: 'variable', name: sub_word});
                }
                else
                {
                    console.error('Error: No matching symbol for "' + sub_word + '"');
                }
            }
            else if (self.builtin_functions[word])
            {
                layer.exec(self.builtin_functions[word]);
            }
            else if (self.constants.hasOwnProperty(word))
            {
                layer.stack.push(self.constants[word]);
            }
            else if (self.variables[word])
            {
                var variable = self.variables[word];

                if (typeof variable === 'object')
                {
                    layer.exec(variable);
                }
                else
                {
                    layer.stack.push({type: 'variable', name: word});
                }
            }
            else if (self.number_regex.test(word))
            {
                layer.stack.push(parseFloat(word));
            }
            else if (word.length >= 2 && word[0] === '"' && word[word.length - 1] === '"')
            {
                layer.stack.push(word.substr(1, word.length - 2));
            }
            else if (self.variable_regex.test(word))
            {
                layer.stack.push({type: 'variable', name: word});
            }
            else
            {
                console.error('Error: Cannot parse word "' + word + '"');
            }
        }

        this.exec = function(fn)
        {
            // Check the stack can provide the arguments required
            if (layer.stack.length < fn.argc)
            {
                console.error('Error: Not enough arguments for function');
                layer.stack.length = 0;
                return;
            }

            // Retrieve function arguments from the stack
            var args = layer.stack.splice(layer.stack.length - fn.argc, fn.argc);

            // Replace variables with values
            for (var i in args)
            {
                if (typeof args[i] === 'object' && args[i].type === 'variable')
                {
                    var value = self.variables[args[i].name];

                    if (value === undefined)
                    {
                        console.error('Error: Cannot call function with undefined variable ' + args[i].name);
                        return;
                    }

                    if (typeof value === 'object')
                    {
                        args[i] = {type: 'function', value: value};
                    }
                    else
                    {
                        args[i] = value;
                    }
                }
            }

            // Call the function
            var ret = fn.exec.apply(null, args);

            // Place the return value on the stack if one is provided
            if (ret !== undefined)
            {
                layer.stack.push(ret);
            }
        }
    })();

    this.word_layer.next_layer = this.exec_layer;
}
<|endoftext|>


<commit_before>define([
	'goo/entities/components/Component',
	'goo/entities/SystemBus',
	'goo/scripts/Scripts',
	'goo/util/ObjectUtil',
	'goo/scripts/ScriptRegister'
],
/** @lends */
function (
	Component,
	SystemBus,
	Scripts,
	_
) {
	'use strict';

	/**
	 * @class Contains scripts to be executed each frame when set on an active entity.
	 * @param {object[]|object} [scripts] A script-object or an array of script-objects to attach to the entity.
	 * The script-object needs to define the function run({@link Entity} entity, number tpf).
	 * @extends Component
	 */
	function ScriptComponent(scripts) {
		this.type = 'ScriptComponent';
		this._gooClasses = Scripts.getClasses();

		if (scripts instanceof Array) {
			this.scripts = scripts;
		} else if (scripts) {
			this.scripts = [scripts];
		} else {
			/**
			* Array of scripts tied to this script component. Scripts can be added to the component
			* using the constructor or by manually adding to the array.
			* @type {object[]}
			* @example
			* // Add a script to script component
			* var scriptComponent = new ScriptComponent();
			* var controlScript = new WASDControlScript();
			* scriptComponent.scripts.push(controlScript);
			*/
			this.scripts = [];
		}
	}

	ScriptComponent.prototype = Object.create(Component.prototype);
	ScriptComponent.prototype.constructor = ScriptComponent;

	/**
	 * Runs the .setup method on each script; called when the ScriptComponent is attached to the entity or when the entity is added to the world.
	 * @private
	 * @param entity
	 */
	ScriptComponent.prototype.setup = function (entity) {
		var systemContext = entity._world.getSystem('ScriptSystem').context;
		var componentContext = Object.create(systemContext);
		_.extend(componentContext, {
			entity: entity,
			entityData: {}
		});

		for (var i = 0; i < this.scripts.length; i++) {
			var script = this.scripts[i];
			if (!script.context) {
				script.context = Object.create(componentContext);
				if (script.parameters && script.parameters.enabled !== undefined) {
					script.enabled = script.parameters.enabled;
				} else {
					script.enabled = true;
				}
				if (script.setup) {
					try {
						script.setup(script.parameters, script.context, this._gooClasses);
					} catch (e) {
						script.enabled = false;
						SystemBus.emit('goo.scriptError', {
							message: e.message || e,
							phase: 'setup',
							scriptName: script.name || script.externals.name
						});
					}
				}
			}
		}
	};

	/**
	 * Called when script component is attached to entity.
	 * @private
	 * @type {setup}
	 */
	//ScriptComponent.prototype.attached = ScriptComponent.prototype.setup;

	/**
	 * Runs the update function on every script attached to this entity.
	 * @private
	 * @param entity {Entity}
	 * @param tpf {number}
	 * @param context
	 */
	ScriptComponent.prototype.run = function (entity) {
		for (var i = 0; i < this.scripts.length; i++) {
			var script = this.scripts[i];
			if (script && script.run && (script.enabled === undefined || script.enabled)) {
				try {
					script.run(entity, entity._world.tpf, script.context, script.parameters);
				} catch (e) {}
			} else if (script.update && (script.enabled === undefined || script.enabled)) {
				try {
					script.update(script.parameters, script.context, this._gooClasses);
				} catch (e) {
					script.enabled = false;
					SystemBus.emit('goo.scriptError', {
						message: e.message || e,
						scriptName: script.name || script.externals.name,
						phase: 'run'
					});
				}
			}
		}
	};

	/**
	 * Reverts any changes done by setup; called when the entity loses its ScriptComponent or is removed from the world.
	 * @private
	 */
	ScriptComponent.prototype.cleanup = function () {
		for (var i = 0; i < this.scripts.length; i++) {
			var script = this.scripts[i];
			if (script.context) {
				if (script.cleanup) {
					try {
						script.cleanup(script.parameters, script.context, this._gooClasses);
					} catch (e) {
						SystemBus.emit('goo.scriptError', {
							message: e.message || e,
							scriptName: script.name || script.externals.name,
							phase: 'cleanup'
						});
					}
				}
				script.enabled = false;
				script.context = null;
			}
		}
	};

	/**
	 * Called when script component is detached from entity.
	 * @private
	 * @type {setup}
	 */
	//ScriptComponent.prototype.detached = ScriptComponent.prototype.cleanup;

	/**
	 * Attempts to add a script to an entity. The object can be a { run: Function } object or a Function. The entity is supposed to get a ScriptComponent with a script created out of the passed object
	 * @private
	 * @param obj {Function | { run: Function }}
	 * @param entity {Entity}
	 * @returns {boolean}
	 */
	ScriptComponent.applyOnEntity = function (obj, entity) {
		if (obj instanceof Function || (obj && obj.run instanceof Function) || (obj && obj.update instanceof Function)) {
			var scriptComponent;
			if (!entity.scriptComponent) {
				scriptComponent = new ScriptComponent();
				entity.setComponent(scriptComponent);
			} else {
				scriptComponent = entity.scriptComponent;
			}
			scriptComponent.scripts.push(obj.run instanceof Function || obj.update instanceof Function ? obj : { run: obj });

			return true;
		}
	};

	return ScriptComponent;
});<commit_msg>Now console.erroring the error #1327<commit_after>define([
	'goo/entities/components/Component',
	'goo/entities/SystemBus',
	'goo/scripts/Scripts',
	'goo/util/ObjectUtil',
	'goo/scripts/ScriptRegister'
],
/** @lends */
function (
	Component,
	SystemBus,
	Scripts,
	_
) {
	'use strict';

	/**
	 * @class Contains scripts to be executed each frame when set on an active entity.
	 * @param {object[]|object} [scripts] A script-object or an array of script-objects to attach to the entity.
	 * The script-object needs to define the function run({@link Entity} entity, number tpf).
	 * @extends Component
	 */
	function ScriptComponent(scripts) {
		this.type = 'ScriptComponent';
		this._gooClasses = Scripts.getClasses();

		if (scripts instanceof Array) {
			this.scripts = scripts;
		} else if (scripts) {
			this.scripts = [scripts];
		} else {
			/**
			* Array of scripts tied to this script component. Scripts can be added to the component
			* using the constructor or by manually adding to the array.
			* @type {object[]}
			* @example
			* // Add a script to script component
			* var scriptComponent = new ScriptComponent();
			* var controlScript = new WASDControlScript();
			* scriptComponent.scripts.push(controlScript);
			*/
			this.scripts = [];
		}
	}

	ScriptComponent.prototype = Object.create(Component.prototype);
	ScriptComponent.prototype.constructor = ScriptComponent;

	/**
	 * Runs the .setup method on each script; called when the ScriptComponent is attached to the entity or when the entity is added to the world.
	 * @private
	 * @param entity
	 */
	ScriptComponent.prototype.setup = function (entity) {
		var systemContext = entity._world.getSystem('ScriptSystem').context;
		var componentContext = Object.create(systemContext);
		_.extend(componentContext, {
			entity: entity,
			entityData: {}
		});

		for (var i = 0; i < this.scripts.length; i++) {
			var script = this.scripts[i];
			if (!script.context) {
				script.context = Object.create(componentContext);
				if (script.parameters && script.parameters.enabled !== undefined) {
					script.enabled = script.parameters.enabled;
				} else {
					script.enabled = true;
				}
				if (script.setup) {
					try {
						script.setup(script.parameters, script.context, this._gooClasses);
					} catch (e) {
						var err = {
							message: e.message || e,
							phase: 'setup',
							scriptName: script.name || script.externals.name
						};
						console.error(err);
						script.enabled = false;
						SystemBus.emit('goo.scriptError', err);
					}
				}
			}
		}
	};

	/**
	 * Called when script component is attached to entity.
	 * @private
	 * @type {setup}
	 */
	//ScriptComponent.prototype.attached = ScriptComponent.prototype.setup;

	/**
	 * Runs the update function on every script attached to this entity.
	 * @private
	 * @param entity {Entity}
	 * @param tpf {number}
	 * @param context
	 */
	ScriptComponent.prototype.run = function (entity) {
		for (var i = 0; i < this.scripts.length; i++) {
			var script = this.scripts[i];
			if (script && script.run && (script.enabled === undefined || script.enabled)) {
				try {
					script.run(entity, entity._world.tpf, script.context, script.parameters);
				} catch (e) {}
			} else if (script.update && (script.enabled === undefined || script.enabled)) {
				try {
					script.update(script.parameters, script.context, this._gooClasses);
				} catch (e) {
					var err = {
						message: e.message || e,
						scriptName: script.name || script.externals.name,
						phase: 'update'
					};
					console.error(err);
					script.enabled = false;
					SystemBus.emit('goo.scriptError', err);
				}
			}
		}
	};

	/**
	 * Reverts any changes done by setup; called when the entity loses its ScriptComponent or is removed from the world.
	 * @private
	 */
	ScriptComponent.prototype.cleanup = function () {
		for (var i = 0; i < this.scripts.length; i++) {
			var script = this.scripts[i];
			if (script.context) {
				if (script.cleanup) {
					try {
						script.cleanup(script.parameters, script.context, this._gooClasses);
					} catch (e) {
						var err = {
							message: e.message || e,
							scriptName: script.name || script.externals.name,
							phase: 'cleanup'
						};
						console.error(err);
						SystemBus.emit('goo.scriptError', err);
					}
				}
				script.enabled = false;
				script.context = null;
			}
		}
	};

	/**
	 * Called when script component is detached from entity.
	 * @private
	 * @type {setup}
	 */
	//ScriptComponent.prototype.detached = ScriptComponent.prototype.cleanup;

	/**
	 * Attempts to add a script to an entity. The object can be a { run: Function } object or a Function. The entity is supposed to get a ScriptComponent with a script created out of the passed object
	 * @private
	 * @param obj {Function | { run: Function }}
	 * @param entity {Entity}
	 * @returns {boolean}
	 */
	ScriptComponent.applyOnEntity = function (obj, entity) {
		if (obj instanceof Function || (obj && obj.run instanceof Function) || (obj && obj.update instanceof Function)) {
			var scriptComponent;
			if (!entity.scriptComponent) {
				scriptComponent = new ScriptComponent();
				entity.setComponent(scriptComponent);
			} else {
				scriptComponent = entity.scriptComponent;
			}
			scriptComponent.scripts.push(obj.run instanceof Function || obj.update instanceof Function ? obj : { run: obj });

			return true;
		}
	};

	return ScriptComponent;
});<|endoftext|>


<commit_before>/*jshint esversion: 6 */

var Docker = require('dockerode');
var DockerEvents = require('docker-events');

var docker = new Docker();
var dockerEmitter = new DockerEvents({docker:docker});

exports.getDockerEmitter = function () {
  return dockerEmitter;
};

exports.getDocker = function () {
    return docker;
};

//kill a container without updating the slastore
exports.kill = function (id) {
  return new Promise( (resolve, reject) =>  {
    container = docker.getContainer(id);
    container.stop({},(err,data) => {
        resolve();
      });
    });
}

//force container removal
exports.remove = function (id) {
  return new Promise( (resolve, reject) =>  {
    container = docker.getContainer(id);
    container.remove({force: true},(err,data) => {
      if(err) {
        console.log("[remove]" + err);
        reject(err);
        return;
      }
      resolve();
    });
  });
}

exports.createNetwork = function(name, external) {
  return new Promise( (resolve, reject) =>  {
    docker.createNetwork({
        Name: name,
        Driver: 'bridge',
        Internal: !external
      }, (err,data) => {
      if(err) {
        reject("[createNetwork] Can't list networks");
        return;
      }
      resolve(data);
    })
  });
}

var listNetworks = function() {
  return new Promise( (resolve, reject) =>  {
    docker.listNetworks({}, (err,data) => {
      if(err) reject("[listNetworks] Can't list networks");
      resolve(data);
    })
  });
}
exports.listNetworks = listNetworks;

var getNetwork = function(networks, name, external) {
  return new Promise( (resolve, reject) =>  {
    for(i in networks) {
          var net = networks[i];
          if(net.Name === name) {
            var n = docker.getNetwork(net.Id)
            resolve(n)
            return;
          }
      }

      docker.createNetwork({
          Name: name,
          Driver: 'bridge',
          Internal: !external
        }, (err,data) => {
        if(err) reject("[getNetwork] Can't create networks")
        resolve(data);
      })
  });
}
exports.getNetwork = getNetwork;

exports.connectToNetwork = function (container, networkName) {
  return new Promise( (resolve, reject) =>  {
    console.log('[' + container.name + '] Connecting to ' + networkName);
    listNetworks({})
    .then( (nets) => { return getNetwork(nets,networkName)})
    .then( (net) => {
        net.connect({'Container':container.id}, (err,data) => {
          if(err) {
            reject("Can't connect to network" + err);
            return;
          }
          resolve(container);
        });
      })
      .catch(err => reject('[connectToNetwork]' + err))
  });
};

exports.disconnectFromNetwork = function (container, networkName) {
  return new Promise( (resolve, reject) =>  {
    listNetworks({})
    .then( (nets) => { return getNetwork(nets,networkName)})
    .then( (net) => {
        net.disconnect({'Container':container.id}, (err,data) => {
          if(err) {
            reject("Can't disconnect from network" + err);
            return;
          }
          resolve(container);
        });
      })
      .catch(err => reject('[disconnectFromNetwork]' + err))
  });
};

exports.createContainer = function(opts) {
  return new Promise( (resolve, reject) =>  {
    //TODO: check opts
    docker.createContainer(opts,(err ,cont) => {
      if(err) {
        reject('createContainer'+err);
        return;
      }
      resolve(cont);
    })
  });
}

exports.inspectContainer = function(cont) {
  return new Promise( (resolve, reject) =>  {
    //TODO: check cont
    cont.inspect((err ,data, cont) => {
      if(err) {
        reject('inspectContainer::'+err);
        return;
      }
      resolve(data);
    })
  });
}
<commit_msg>Fix network creation heisenbug<commit_after>/*jshint esversion: 6 */

var Docker = require('dockerode');
var DockerEvents = require('docker-events');

var docker = new Docker();
var dockerEmitter = new DockerEvents({docker:docker});

exports.getDockerEmitter = function () {
  return dockerEmitter;
};

exports.getDocker = function () {
    return docker;
};

//kill a container without updating the slastore
exports.kill = function (id) {
  return new Promise( (resolve, reject) =>  {
    container = docker.getContainer(id);
    container.stop({},(err,data) => {
        resolve();
      });
    });
}

//force container removal
exports.remove = function (id) {
  return new Promise( (resolve, reject) =>  {
    container = docker.getContainer(id);
    container.remove({force: true},(err,data) => {
      if(err) {
        console.log("[remove]" + err);
        reject(err);
        return;
      }
      resolve();
    });
  });
}

exports.createNetwork = function(name, external) {
  return new Promise( (resolve, reject) =>  {
    docker.createNetwork({
        Name: name,
        Driver: 'bridge',
        Internal: !external
      }, (err,data) => {
        if(err) {
          reject("[createNetwork] Can't list networks:", err);
          return;
        }
        resolve(data);
      });
  });
}

var listNetworks = function() {
  return new Promise( (resolve, reject) =>  {
    docker.listNetworks({}, (err,data) => {
      if(err) reject("[listNetworks] Can't list networks");
      resolve(data);
    })
  });
}
exports.listNetworks = listNetworks;

var getNetwork = function(networks, name, external) {
  return new Promise( (resolve, reject) =>  {
    for(i in networks) {
          var net = networks[i];
          if(net.Name === name) {
            var n = docker.getNetwork(net.Id)
            resolve(n)
            return;
          }
      }

      docker.createNetwork({
          Name: name,
          Driver: 'bridge',
          Internal: !external
        }, (err,data) => {
          if(err) {
            reject("[getNetwork] Can't create networks:", err);
            return;
          }
          resolve(data);
        });
  });
}
exports.getNetwork = getNetwork;

exports.connectToNetwork = function (container, networkName) {
  return new Promise( (resolve, reject) =>  {
    console.log('[' + container.name + '] Connecting to ' + networkName);
    listNetworks({})
    .then( (nets) => { return getNetwork(nets,networkName)})
    .then( (net) => {
        net.connect({'Container':container.id}, (err,data) => {
          if(err) {
            reject("Can't connect to network" + err);
            return;
          }
          resolve(container);
        });
      })
      .catch(err => reject('[connectToNetwork]' + err))
  });
};

exports.disconnectFromNetwork = function (container, networkName) {
  return new Promise( (resolve, reject) =>  {
    listNetworks({})
    .then( (nets) => { return getNetwork(nets,networkName)})
    .then( (net) => {
        net.disconnect({'Container':container.id}, (err,data) => {
          if(err) {
            reject("Can't disconnect from network" + err);
            return;
          }
          resolve(container);
        });
      })
      .catch(err => reject('[disconnectFromNetwork]' + err))
  });
};

exports.createContainer = function(opts) {
  return new Promise( (resolve, reject) =>  {
    //TODO: check opts
    docker.createContainer(opts,(err ,cont) => {
      if(err) {
        reject('createContainer'+err);
        return;
      }
      resolve(cont);
    })
  });
}

exports.inspectContainer = function(cont) {
  return new Promise( (resolve, reject) =>  {
    //TODO: check cont
    cont.inspect((err ,data, cont) => {
      if(err) {
        reject('inspectContainer::'+err);
        return;
      }
      resolve(data);
    })
  });
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief test the collection interface
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");
var arangodb = require("org/arangodb");
var ArangoCollection = arangodb.ArangoCollection;
var testHelper = require("org/arangodb/test-helper").Helper;
var db = arangodb.db;
var ERRORS = arangodb.errors;

// -----------------------------------------------------------------------------
// --SECTION--                                                collection methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: collection
////////////////////////////////////////////////////////////////////////////////

function CollectionSuite () {
  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief rotate
////////////////////////////////////////////////////////////////////////////////

    testRotate : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.save({ _key: "test1" });
      var f = c1.figures();
      assertEqual(0, f.datafiles.count);

      testHelper.rotate(c1);

      f = c1.figures();
      assertEqual(1, f.datafiles.count);

      c1.save({ _key: "test2" });
      testHelper.rotate(c1);

      f = c1.figures();
      // we may have one or two datafiles, depending on the compaction
      assertTrue(f.datafiles.count >= 1);

      c1.unload();

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief rotate w/o journal
////////////////////////////////////////////////////////////////////////////////

    testRotateNoJournal : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      try {
        testHelper.rotate(c1);
        fail();
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_ARANGO_NO_JOURNAL.code, err.errorNum);
      }

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief rename loaded collection
////////////////////////////////////////////////////////////////////////////////

    testRenameLoaded : function () {
      var cn = "example";
      var nn = "example2";

      db._drop(cn);
      db._drop(nn);
      var c1 = db._create(cn);

      c1.save({ a : 1 });

      assertTypeOf("string", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());
      assertEqual(ArangoCollection.TYPE_DOCUMENT, c1.type());
      assertTypeOf("number", c1.type());

      var id = c1._id;

      c1.rename(nn);

      assertEqual(id, c1._id);
      assertEqual(nn, c1.name());
      assertTypeOf("number", c1.status());
      assertEqual(ArangoCollection.TYPE_DOCUMENT, c1.type());
      assertTypeOf("number", c1.type());

      var c2 = db._collection(cn);

      assertEqual(null, c2);

      db._drop(nn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief rename unloaded collection
////////////////////////////////////////////////////////////////////////////////

    testRenameUnloaded : function () {
      var cn = "example";
      var nn = "example2";

      db._drop(cn);
      db._drop(nn);
      var c1 = db._create(cn);

      c1.save({ a : 1 });
      c1.unload();

      assertTypeOf("string", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());
      assertEqual(ArangoCollection.TYPE_DOCUMENT, c1.type());
      assertTypeOf("number", c1.type());

      var id = c1._id;

      c1.rename(nn);

      assertEqual(id, c1._id);
      assertEqual(nn, c1.name());
      assertTypeOf("number", c1.status());
      assertEqual(ArangoCollection.TYPE_DOCUMENT, c1.type());
      assertTypeOf("number", c1.type());

      var c2 = db._collection(cn);

      assertEqual(null, c2);

      db._drop(nn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief rename a collection to an already existing collection
////////////////////////////////////////////////////////////////////////////////

    testRenameExisting : function () {
      var cn1 = "example";
      var cn2 = "example2";

      db._drop(cn1);
      db._drop(cn2);
      var c1 = db._create(cn1);
      db._create(cn2);

      try {
        c1.rename(cn2);
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_ARANGO_DUPLICATE_NAME.code, err.errorNum);
      }
      db._drop(cn1);
      db._drop(cn2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test checksum
////////////////////////////////////////////////////////////////////////////////

    testChecksum : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      // empty collection, checksum should be 0
      var r1 = c1.checksum(true);
      assertTypeOf("string", r1.revision);
      assertTrue(r1.revision !== "");
      assertTrue(r1.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r1.checksum);
      assertEqual(0, r1.checksum);

      // inserting a doc, checksum should change
      c1.save({ a : 1 });
      var r2 = c1.checksum(true);
      assertNotEqual(r1.revision, r2.revision);
      assertTypeOf("string", r2.revision);
      assertTrue(r2.revision !== "");
      assertTrue(r2.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r2.checksum);
      assertNotEqual(0, r2.checksum);

      // inserting another doc, checksum should change
      c1.save({ a : 2 });
      var r3 = c1.checksum(true);
      assertNotEqual(r1.revision, r3.revision);
      assertNotEqual(r2.revision, r3.revision);
      assertTypeOf("string", r3.revision);
      assertTrue(r3.revision !== "");
      assertTrue(r3.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r3.checksum);
      assertNotEqual(0, r3.checksum);
      assertNotEqual(r2.checksum, r3.checksum);

      // test after unloading
      c1.unload();
      var r4 = c1.checksum(true);
      assertTypeOf("string", r4.revision);
      assertEqual(r3.revision, r4.revision);
      assertTypeOf("number", r4.checksum);
      assertNotEqual(0, r4.checksum);
      assertEqual(r3.checksum, r4.checksum);

      // test withData
      var r5 = c1.checksum(true, true);
      assertTypeOf("string", r5.revision);
      assertEqual(r4.revision, r5.revision);
      assertTypeOf("number", r5.checksum);
      assertNotEqual(0, r5.checksum);
      assertNotEqual(r4.checksum, r5.checksum);

      // test after truncation
      c1.truncate();
      var r6 = c1.checksum(true);
      assertTypeOf("string", r6.revision);
      assertNotEqual(r4.revision, r6.revision);
      assertNotEqual(r5.revision, r6.revision);
      assertTypeOf("number", r6.checksum);
      assertEqual(0, r6.checksum);

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test checksum
////////////////////////////////////////////////////////////////////////////////

    testChecksumEdge : function () {
      var cn = "example";
      var vn = "example2";

      db._drop(cn);
      db._drop(vn);
      db._create(vn);
      var c1 = db._createEdgeCollection(cn);

      var r1 = c1.checksum(true);
      assertTypeOf("string", r1.revision);
      assertTrue(r1.revision !== "");
      assertTrue(r1.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r1.checksum);
      assertEqual(0, r1.checksum);

      c1.save(vn + "/1", vn + "/2", { a : 1 });
      var r2 = c1.checksum(true);
      assertNotEqual(r1.revision, r2.revision);
      assertTypeOf("string", r2.revision);
      assertTrue(r2.revision !== "");
      assertTrue(r2.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r2.checksum);
      assertNotEqual(0, r2.checksum);

      c1.save(vn + "/1", vn + "/2", { a : 2 });
      var r3 = c1.checksum(true);
      assertNotEqual(r1.revision, r3.revision);
      assertNotEqual(r2.revision, r3.revision);
      assertTypeOf("string", r3.revision);
      assertTrue(r3.revision !== "");
      assertTrue(r3.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r3.checksum);
      assertNotEqual(0, r3.checksum);
      assertNotEqual(r2.checksum, r3.checksum);

      c1.unload();
      var r4 = c1.checksum(true);
      assertTypeOf("string", r4.revision);
      assertEqual(r3.revision, r4.revision);
      assertTypeOf("number", r4.checksum);
      assertEqual(r3.checksum, r4.checksum);

      // test withData
      var r5 = c1.checksum(true, true);
      assertTypeOf("string", r5.revision);
      assertEqual(r4.revision, r5.revision);
      assertTypeOf("number", r5.checksum);
      assertNotEqual(0, r5.checksum);
      assertNotEqual(r4.checksum, r5.checksum);

      // test after truncation
      c1.truncate();
      var r6 = c1.checksum(true);
      assertTypeOf("string", r6.revision);
      assertNotEqual(r4.revision, r6.revision);
      assertNotEqual(r5.revision, r6.revision);
      assertTypeOf("number", r6.checksum);
      assertEqual(0, r6.checksum);

      db._drop(cn);
      db._drop(vn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test checksum two different collections
////////////////////////////////////////////////////////////////////////////////

    testChecksumDifferent : function () {
      var cn1 = "example";
      var cn2 = "example2";

      db._drop(cn1);
      db._drop(cn2);
      var c1 = db._create(cn1);
      var c2 = db._create(cn2);

      // collections are empty, checksums are identical
      var cs1 = c1.checksum().checksum;
      var cs2 = c2.checksum().checksum;

      assertEqual(cs1, cs2);

      c1.save({ _key: "foobar", value: 123 });
      c2.save({ _key: "foobar", value: 123 });

      // keys are the same
      cs1 = c1.checksum().checksum;
      cs2 = c2.checksum().checksum;

      assertEqual(cs1, cs2);

      // data is the same
      cs1 = c1.checksum(false, true).checksum;
      cs2 = c2.checksum(false, true).checksum;

      assertEqual(cs1, cs2);

      // revisions are different
      cs1 = c1.checksum(true, false).checksum;
      cs2 = c2.checksum(true, false).checksum;

      assertNotEqual(cs1, cs2);

      // revisions are still different
      cs1 = c1.checksum(true, true).checksum;
      cs2 = c2.checksum(true, true).checksum;

      assertNotEqual(cs1, cs2);

      // update document in c1, keep data
      c1.replace("foobar", { value: 123 });

      // keys are still the same
      cs1 = c1.checksum().checksum;
      cs2 = c2.checksum().checksum;

      assertEqual(cs1, cs2);

      // data is still the same
      cs1 = c1.checksum(false, true).checksum;
      cs2 = c2.checksum(false, true).checksum;

      assertEqual(cs1, cs2);

      // revisions are still different
      cs1 = c1.checksum(true, false).checksum;
      cs2 = c2.checksum(true, false).checksum;

      // update document in c1, changing data
      c1.replace("foobar", { value: 124 });

      // keys are still the same
      cs1 = c1.checksum().checksum;
      cs2 = c2.checksum().checksum;

      assertEqual(cs1, cs2);

      // data is not the same
      cs1 = c1.checksum(false, true).checksum;
      cs2 = c2.checksum(false, true).checksum;

      assertNotEqual(cs1, cs2);

      // revisions are still different
      cs1 = c1.checksum(true, false).checksum;
      cs2 = c2.checksum(true, false).checksum;

      db._drop(cn1);
      db._drop(cn2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test system collection dropping / renaming / unloading
////////////////////////////////////////////////////////////////////////////////

    testSystemSpecial : function () {
      var cn = "_users";
      var c = db._collection(cn);

      // drop
      try {
        c.drop();
        fail();
      }
      catch (err1) {
        assertEqual(ERRORS.ERROR_FORBIDDEN.code, err1.errorNum);
      }

      // rename
      var cn = "example";
      db._drop(cn);

      try {
        c.rename(cn);
        fail();
      }
      catch (err2) {
        assertEqual(ERRORS.ERROR_FORBIDDEN.code, err2.errorNum);
      }

      // unload is allowed
      c.unload();
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test special properties of replication collection
////////////////////////////////////////////////////////////////////////////////

    testSpecialReplication : function () {
      var repl = db._collection('_replication');

      // drop is not allowed
      try {
        repl.drop();
        fail();
      }
      catch (err1) {
        assertEqual(ERRORS.ERROR_FORBIDDEN.code, err1.errorNum);
      }

      // rename is not allowed
      try {
        var cn = "example";
        db._drop(cn);
        repl.rename(cn);
      }
      catch (err2) {
        assertEqual(ERRORS.ERROR_FORBIDDEN.code, err2.errorNum);
      }

      // unload is not allowed
      try {
        repl.unload();
      }
      catch (err3) {
        assertEqual(ERRORS.ERROR_FORBIDDEN.code, err3.errorNum);
      }
    }

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(CollectionSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<commit_msg>excluded collection<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief test the collection interface
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");
var arangodb = require("org/arangodb");
var ArangoCollection = arangodb.ArangoCollection;
var testHelper = require("org/arangodb/test-helper").Helper;
var db = arangodb.db;
var ERRORS = arangodb.errors;

// -----------------------------------------------------------------------------
// --SECTION--                                                collection methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: collection
////////////////////////////////////////////////////////////////////////////////

function CollectionSuite () {
  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief rotate
////////////////////////////////////////////////////////////////////////////////

    testRotate : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.save({ _key: "test1" });
      var f = c1.figures();
      assertEqual(0, f.datafiles.count);

      testHelper.rotate(c1);

      f = c1.figures();
      assertEqual(1, f.datafiles.count);

      c1.save({ _key: "test2" });
      testHelper.rotate(c1);

      f = c1.figures();
      // we may have one or two datafiles, depending on the compaction
      assertTrue(f.datafiles.count >= 1);

      c1.unload();

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief rotate w/o journal
////////////////////////////////////////////////////////////////////////////////

    testRotateNoJournal : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      try {
        testHelper.rotate(c1);
        fail();
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_ARANGO_NO_JOURNAL.code, err.errorNum);
      }

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief rename loaded collection
////////////////////////////////////////////////////////////////////////////////

    testRenameLoaded : function () {
      var cn = "example";
      var nn = "example2";

      db._drop(cn);
      db._drop(nn);
      var c1 = db._create(cn);

      c1.save({ a : 1 });

      assertTypeOf("string", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());
      assertEqual(ArangoCollection.TYPE_DOCUMENT, c1.type());
      assertTypeOf("number", c1.type());

      var id = c1._id;

      c1.rename(nn);

      assertEqual(id, c1._id);
      assertEqual(nn, c1.name());
      assertTypeOf("number", c1.status());
      assertEqual(ArangoCollection.TYPE_DOCUMENT, c1.type());
      assertTypeOf("number", c1.type());

      var c2 = db._collection(cn);

      assertEqual(null, c2);

      db._drop(nn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief rename unloaded collection
////////////////////////////////////////////////////////////////////////////////

    testRenameUnloaded : function () {
      var cn = "example";
      var nn = "example2";

      db._drop(cn);
      db._drop(nn);
      var c1 = db._create(cn);

      c1.save({ a : 1 });
      c1.unload();

      assertTypeOf("string", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());
      assertEqual(ArangoCollection.TYPE_DOCUMENT, c1.type());
      assertTypeOf("number", c1.type());

      var id = c1._id;

      c1.rename(nn);

      assertEqual(id, c1._id);
      assertEqual(nn, c1.name());
      assertTypeOf("number", c1.status());
      assertEqual(ArangoCollection.TYPE_DOCUMENT, c1.type());
      assertTypeOf("number", c1.type());

      var c2 = db._collection(cn);

      assertEqual(null, c2);

      db._drop(nn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief rename a collection to an already existing collection
////////////////////////////////////////////////////////////////////////////////

    testRenameExisting : function () {
      var cn1 = "example";
      var cn2 = "example2";

      db._drop(cn1);
      db._drop(cn2);
      var c1 = db._create(cn1);
      db._create(cn2);

      try {
        c1.rename(cn2);
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_ARANGO_DUPLICATE_NAME.code, err.errorNum);
      }
      db._drop(cn1);
      db._drop(cn2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test checksum
////////////////////////////////////////////////////////////////////////////////

    testChecksum : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      // empty collection, checksum should be 0
      var r1 = c1.checksum(true);
      assertTypeOf("string", r1.revision);
      assertTrue(r1.revision !== "");
      assertTrue(r1.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r1.checksum);
      assertEqual(0, r1.checksum);

      // inserting a doc, checksum should change
      c1.save({ a : 1 });
      var r2 = c1.checksum(true);
      assertNotEqual(r1.revision, r2.revision);
      assertTypeOf("string", r2.revision);
      assertTrue(r2.revision !== "");
      assertTrue(r2.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r2.checksum);
      assertNotEqual(0, r2.checksum);

      // inserting another doc, checksum should change
      c1.save({ a : 2 });
      var r3 = c1.checksum(true);
      assertNotEqual(r1.revision, r3.revision);
      assertNotEqual(r2.revision, r3.revision);
      assertTypeOf("string", r3.revision);
      assertTrue(r3.revision !== "");
      assertTrue(r3.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r3.checksum);
      assertNotEqual(0, r3.checksum);
      assertNotEqual(r2.checksum, r3.checksum);

      // test after unloading
      c1.unload();
      var r4 = c1.checksum(true);
      assertTypeOf("string", r4.revision);
      assertEqual(r3.revision, r4.revision);
      assertTypeOf("number", r4.checksum);
      assertNotEqual(0, r4.checksum);
      assertEqual(r3.checksum, r4.checksum);

      // test withData
      var r5 = c1.checksum(true, true);
      assertTypeOf("string", r5.revision);
      assertEqual(r4.revision, r5.revision);
      assertTypeOf("number", r5.checksum);
      assertNotEqual(0, r5.checksum);
      assertNotEqual(r4.checksum, r5.checksum);

      // test after truncation
      c1.truncate();
      var r6 = c1.checksum(true);
      assertTypeOf("string", r6.revision);
      assertNotEqual(r4.revision, r6.revision);
      assertNotEqual(r5.revision, r6.revision);
      assertTypeOf("number", r6.checksum);
      assertEqual(0, r6.checksum);

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test checksum
////////////////////////////////////////////////////////////////////////////////

    testChecksumEdge : function () {
      var cn = "example";
      var vn = "example2";

      db._drop(cn);
      db._drop(vn);
      db._create(vn);
      var c1 = db._createEdgeCollection(cn);

      var r1 = c1.checksum(true);
      assertTypeOf("string", r1.revision);
      assertTrue(r1.revision !== "");
      assertTrue(r1.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r1.checksum);
      assertEqual(0, r1.checksum);

      c1.save(vn + "/1", vn + "/2", { a : 1 });
      var r2 = c1.checksum(true);
      assertNotEqual(r1.revision, r2.revision);
      assertTypeOf("string", r2.revision);
      assertTrue(r2.revision !== "");
      assertTrue(r2.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r2.checksum);
      assertNotEqual(0, r2.checksum);

      c1.save(vn + "/1", vn + "/2", { a : 2 });
      var r3 = c1.checksum(true);
      assertNotEqual(r1.revision, r3.revision);
      assertNotEqual(r2.revision, r3.revision);
      assertTypeOf("string", r3.revision);
      assertTrue(r3.revision !== "");
      assertTrue(r3.revision.match(/^[0-9]+$/));
      assertTypeOf("number", r3.checksum);
      assertNotEqual(0, r3.checksum);
      assertNotEqual(r2.checksum, r3.checksum);

      c1.unload();
      var r4 = c1.checksum(true);
      assertTypeOf("string", r4.revision);
      assertEqual(r3.revision, r4.revision);
      assertTypeOf("number", r4.checksum);
      assertEqual(r3.checksum, r4.checksum);

      // test withData
      var r5 = c1.checksum(true, true);
      assertTypeOf("string", r5.revision);
      assertEqual(r4.revision, r5.revision);
      assertTypeOf("number", r5.checksum);
      assertNotEqual(0, r5.checksum);
      assertNotEqual(r4.checksum, r5.checksum);

      // test after truncation
      c1.truncate();
      var r6 = c1.checksum(true);
      assertTypeOf("string", r6.revision);
      assertNotEqual(r4.revision, r6.revision);
      assertNotEqual(r5.revision, r6.revision);
      assertTypeOf("number", r6.checksum);
      assertEqual(0, r6.checksum);

      db._drop(cn);
      db._drop(vn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test checksum two different collections
////////////////////////////////////////////////////////////////////////////////

    testChecksumDifferent : function () {
      var cn1 = "example";
      var cn2 = "example2";

      db._drop(cn1);
      db._drop(cn2);
      var c1 = db._create(cn1);
      var c2 = db._create(cn2);

      // collections are empty, checksums are identical
      var cs1 = c1.checksum().checksum;
      var cs2 = c2.checksum().checksum;

      assertEqual(cs1, cs2);

      c1.save({ _key: "foobar", value: 123 });
      c2.save({ _key: "foobar", value: 123 });

      // keys are the same
      cs1 = c1.checksum().checksum;
      cs2 = c2.checksum().checksum;

      assertEqual(cs1, cs2);

      // data is the same
      cs1 = c1.checksum(false, true).checksum;
      cs2 = c2.checksum(false, true).checksum;

      assertEqual(cs1, cs2);

      // revisions are different
      cs1 = c1.checksum(true, false).checksum;
      cs2 = c2.checksum(true, false).checksum;

      assertNotEqual(cs1, cs2);

      // revisions are still different
      cs1 = c1.checksum(true, true).checksum;
      cs2 = c2.checksum(true, true).checksum;

      assertNotEqual(cs1, cs2);

      // update document in c1, keep data
      c1.replace("foobar", { value: 123 });

      // keys are still the same
      cs1 = c1.checksum().checksum;
      cs2 = c2.checksum().checksum;

      assertEqual(cs1, cs2);

      // data is still the same
      cs1 = c1.checksum(false, true).checksum;
      cs2 = c2.checksum(false, true).checksum;

      assertEqual(cs1, cs2);

      // revisions are still different
      cs1 = c1.checksum(true, false).checksum;
      cs2 = c2.checksum(true, false).checksum;

      // update document in c1, changing data
      c1.replace("foobar", { value: 124 });

      // keys are still the same
      cs1 = c1.checksum().checksum;
      cs2 = c2.checksum().checksum;

      assertEqual(cs1, cs2);

      // data is not the same
      cs1 = c1.checksum(false, true).checksum;
      cs2 = c2.checksum(false, true).checksum;

      assertNotEqual(cs1, cs2);

      // revisions are still different
      cs1 = c1.checksum(true, false).checksum;
      cs2 = c2.checksum(true, false).checksum;

      db._drop(cn1);
      db._drop(cn2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test system collection dropping / renaming / unloading
////////////////////////////////////////////////////////////////////////////////

    testSystemSpecial : function () {
      var cn = "_users";
      var c = db._collection(cn);

      // drop
      try {
        c.drop();
        fail();
      }
      catch (err1) {
        assertEqual(ERRORS.ERROR_FORBIDDEN.code, err1.errorNum);
      }

      // rename
      var cn = "example";
      db._drop(cn);

      try {
        c.rename(cn);
        fail();
      }
      catch (err2) {
        assertEqual(ERRORS.ERROR_FORBIDDEN.code, err2.errorNum);
      }

      // unload is allowed
      c.unload();
    }

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(CollectionSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<|endoftext|>


<commit_before>// temporary script to show message about Random renamed to Volatile on trading page

pjax_config_page('trading', function(){
    return {
        onLoad: function() {
            $('#close_temp_msg').click(function() {
                $('#temp_notice_msg').addClass('invisible');
            });
        }
    };

});
<commit_msg>Remember user choose to hide per session<commit_after>// temporary script to show message about Random renamed to Volatile on trading page

pjax_config_page('trading', function(){
    return {
        onLoad: function() {
            var tempMsgKey = 'hide_temp_msg';
            if (SessionStore.get(tempMsgKey)) {
                $('#temp_notice_msg').addClass('invisible');
            }

            $('#close_temp_msg').click(function() {
                SessionStore.set(tempMsgKey, '1');
                $('#temp_notice_msg').addClass('invisible');
            });
        }
    };

});
<|endoftext|>


<commit_before>"use strict";
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const usr = require('../models/user');

// Passport session set-up
passport.serializeUser((user, done) => {
    done(null, user.user_id);
});

passport.deserializeUser(async (req, id, done) => {
    const queryRes = await usr.getUserByField('user_id', id);
    if (queryRes.rowCount === 0) {
        done(null, {});
    } else {
        done(null, queryRes.rows[0]);
    }
});

passport.use(new LocalStrategy({usernameField: 'username', passwordField: 'password', passReqToCallback: true},
    async (req, username, password, done) => {
        const queryRes = await usr.getUserByField('username', username);
        if (queryRes.rowCount === 0) {
            req.flash('error', 'No such user');
            req.session.save(() => {
                return done(null, false);
            });
        } else {
            const authOK = await usr.checkPassword(queryRes.rows[0], password);
            if (authOK) {
                return done(null, queryRes.rows[0]);
            } else {
                req.flash('error', 'Wrong password');
                req.session.save(() => {
                    return done(null, false);
                });
            }
        }
    })
);

module.exports = passport;
<commit_msg>Fix exception on api login<commit_after>"use strict";
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const usr = require('../models/user');

// Passport session set-up
passport.serializeUser((user, done) => {
    done(null, user.user_id);
});

passport.deserializeUser(async (req, id, done) => {
    const queryRes = await usr.getUserByField('user_id', id);
    if (queryRes.rowCount === 0) {
        done(null, {});
    } else {
        done(null, queryRes.rows[0]);
    }
});

passport.use(new LocalStrategy({usernameField: 'username', passwordField: 'password', passReqToCallback: true},
    async (req, username, password, done) => {
        const queryRes = await usr.getUserByField('username', username);
        if (queryRes.rowCount === 0) {
            // No sessions with API logins, so don't store flash message and save sessions
            try {
                req.flash('error', 'No such user');
                req.session.save(() => {
                    return done(null, false);
                });
            } catch (err) {
                return done(null, false);
            }
        } else {
            const authOK = await usr.checkPassword(queryRes.rows[0], password);
            if (authOK) {
                return done(null, queryRes.rows[0]);
            } else {
                // No sessions with API logins, so don't store flash message and save sessions
                try {
                    req.flash('error', 'Wrong password');
                    req.session.save(() => {
                        return done(null, false);
                    });
                } catch (err) {
                    return done(null, false);
                }
            }
        }
    })
);

module.exports = passport;
<|endoftext|>


<commit_before>describe("ScreenOrientation JS API Test", function () {

    var displayflag = false;
    var orientationType = '';
    var callbackFired = false;

    beforeEach(function () {
        /* ... Set up your object ... */
        displayflag = false;
        orientationType = '';
        callbackFired = false;
    });

    afterEach(function () {
        Rho.ScreenOrientation.autoRotate = true;
    });

    var screenorientation_callback = function (data) {

        orientationType = data;
        displayResult('DATA:- ', JSON.stringify(data));
        callbackFired = true;

    }

    it("should enable automatic screen orientation", function() {
        expect(Rho.ScreenOrientation.autoRotate).toBe(true);
        //expect(enable()).toBe(true);
    });

    it("should disable automatic screen orientation", function() {
        Rho.ScreenOrientation.autoRotate = false;
        expect(Rho.ScreenOrientation.autoRotate).toBe(false);
        //expect(disable()).toBe(false);
    });

    if (isAnyButApplePlatform()) {

        it("VT281-0905 | Test Screen Orientation rightHanded with callback |", function() {

		runs(function()
		{
			//dispCurrentProcess("VT281-0905 | Test Screen Orientation rightHanded with callback |");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.rightHanded();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "rightHanded") )
		}, 'The Screen Orientation should display', 30000);
		});

        it("VT281-0906 | Test Screen Orientation leftHanded with callback |", function() {
		runs(function()
		{
			//dispCurrentProcess("VT281-0906 | Test Screen Orientation leftHanded with callback |");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.leftHanded();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "leftHanded") )
		}, 'The Screen Orientation should display', 30000);
		});

        it("VT281-0907 | Test Screen Orientation upsideDown with callback |", function() {
		runs(function()
		{
			//dispCurrentProcess("VT281-0907 | Test Screen Orientation upsideDown with callback |");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.upsideDown();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "upsideDown") )
		}, 'The Screen Orientation should display', 30000);
		});

        it("VT281-0908 | Test Screen Orientation normal with callback |", function() {
		runs(function()
		{
			//dispCurrentProcess("VT281-0908 | Test Screen Orientation normal with callback |");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.normal();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "normal") )
		}, 'The Screen Orientation should display', 30000);
		});

        it("VT281-0910 | Set autoRotate as false and call righthand method |", function() {

		runs(function()
		{
			//dispCurrentProcess("VT281-0910 | Set autoRotate as false and call righthand method");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.autoRotate = false;
			Rho.ScreenOrientation.rightHanded();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "rightHanded") )
		}, 'The Screen Orientation should display', 30000);
		});

		if ( !isAndroidPlatform() ) //this spec is too fragile on Android emulator, won't run good on Travis
		{
			it("VT281-0912| Set autoRotate as true and call normal method |", function() {

				runs(function()
				{
					//dispCurrentProcess("VT281-0912| Set autoRotate as true and call normal method");
					Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
					Rho.ScreenOrientation.normal();
				});

				waitsFor(function()
				{
					return ( (callbackFired == true) && (orientationType == "normal") )
				}, 'The Screen Orientation should display', 30000);
			});
		}
    }
});
<commit_msg>supressing rotation tests on android<commit_after>describe("ScreenOrientation JS API Test", function () {

    var displayflag = false;
    var orientationType = '';
    var callbackFired = false;

    beforeEach(function () {
        /* ... Set up your object ... */
        displayflag = false;
        orientationType = '';
        callbackFired = false;
    });

    afterEach(function () {
        Rho.ScreenOrientation.autoRotate = true;
    });

    var screenorientation_callback = function (data) {

        orientationType = data;
        displayResult('DATA:- ', JSON.stringify(data));
        callbackFired = true;

    }

    it("should enable automatic screen orientation", function() {
        expect(Rho.ScreenOrientation.autoRotate).toBe(true);
        //expect(enable()).toBe(true);
    });

    it("should disable automatic screen orientation", function() {
        Rho.ScreenOrientation.autoRotate = false;
        expect(Rho.ScreenOrientation.autoRotate).toBe(false);
        //expect(disable()).toBe(false);
    });

    if (isAnyButApplePlatform() && !isAndroidPlatform()) {

        it("VT281-0905 | Test Screen Orientation rightHanded with callback |", function() {

		runs(function()
		{
			//dispCurrentProcess("VT281-0905 | Test Screen Orientation rightHanded with callback |");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.rightHanded();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "rightHanded") )
		}, 'The Screen Orientation should display', 30000);
		});

        it("VT281-0906 | Test Screen Orientation leftHanded with callback |", function() {
		runs(function()
		{
			//dispCurrentProcess("VT281-0906 | Test Screen Orientation leftHanded with callback |");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.leftHanded();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "leftHanded") )
		}, 'The Screen Orientation should display', 30000);
		});

        it("VT281-0907 | Test Screen Orientation upsideDown with callback |", function() {
		runs(function()
		{
			//dispCurrentProcess("VT281-0907 | Test Screen Orientation upsideDown with callback |");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.upsideDown();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "upsideDown") )
		}, 'The Screen Orientation should display', 30000);
		});

        it("VT281-0908 | Test Screen Orientation normal with callback |", function() {
		runs(function()
		{
			//dispCurrentProcess("VT281-0908 | Test Screen Orientation normal with callback |");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.normal();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "normal") )
		}, 'The Screen Orientation should display', 30000);
		});

        it("VT281-0910 | Set autoRotate as false and call righthand method |", function() {

		runs(function()
		{
			//dispCurrentProcess("VT281-0910 | Set autoRotate as false and call righthand method");
			Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
			Rho.ScreenOrientation.autoRotate = false;
			Rho.ScreenOrientation.rightHanded();
		});

		waitsFor(function()
		{
			return ( (callbackFired == true) && (orientationType == "rightHanded") )
		}, 'The Screen Orientation should display', 30000);
		});

		if ( !isAndroidPlatform() ) //this spec is too fragile on Android emulator, won't run good on Travis
		{
			it("VT281-0912| Set autoRotate as true and call normal method |", function() {

				runs(function()
				{
					//dispCurrentProcess("VT281-0912| Set autoRotate as true and call normal method");
					Rho.ScreenOrientation.setScreenOrientationEvent(screenorientation_callback);
					Rho.ScreenOrientation.normal();
				});

				waitsFor(function()
				{
					return ( (callbackFired == true) && (orientationType == "normal") )
				}, 'The Screen Orientation should display', 30000);
			});
		}
    }
});
<|endoftext|>