<commit_before>'use strict';

const transd = require('../'),
      { transform } = transd;

const xform = transd.compose(
        transform.square,
        transform.log
      ),
      iterable = {
        alpha: 1,
        beta: 2,
        gamma: 5,
        delta: 5
      };

const array = transd.into(xform, [], iterable),
      object = transd.into(xform, {}, iterable),
      map = transd.into(xform, new Map(), iterable),
      set = transd.into(xform, new Set(), iterable);

console.log('Array:  ', array);  // [ 2, 6, 6 ]
console.log('Object: ', object); // { alpha: 2, gamma: 6, delta: 6 }
console.log('Map:    ', map);    // Map { 'alpha' => 2, 'gamma' => 6, 'delta' => 6 }
console.log('Set:    ', set);    // Set { 2, 6 }
<commit_msg>add some examples for strings<commit_after>'use strict';

const transd = require('../'),
      { transform } = transd;

const xform = transd.compose(
        transform.square,
        transform.log
      ),
      iterable = {
        alpha: 1,
        beta: 2,
        gamma: 5,
        delta: 5
      };

const array = transd.into(xform, [], iterable),
      object = transd.into(xform, {}, iterable),
      map = transd.into(xform, new Map(), iterable),
      set = transd.into(xform, new Set(), iterable),
      string = transd.into(xform, '', iterable);

console.log('Array:  ', array);  // [ 2, 6, 6 ]
console.log('Object: ', object); // { alpha: 2, gamma: 6, delta: 6 }
console.log('Map:    ', map);    // Map { 'alpha' => 2, 'gamma' => 6, 'delta' => 6 }
console.log('Set:    ', set);    // Set { 2, 6 }
console.log('String: ', string); // Set { 2, 6 }
<|endoftext|>


<commit_before>'use strict';

var request = require('request');
var async = require('async');
var core = require('../../modules/soajs.core');

var regEnvironment = (process.env.SOAJS_ENV || "dev");
regEnvironment = regEnvironment.toLowerCase();

var serviceAwarenessObj = {};
var controllerHosts = null;
var timeLoaded = 0;
var registry = core.registry.get();
var param = null;

var fetchControllerHosts = function (next) {
    registry = core.registry.get();
    core.registry.loadOtherEnvControllerHosts(function (error, hosts) {
        if (error)
            param.log.warn("Failed to load controller hosts. reusing from previous load. Reason: " + error.message);
        else {
            controllerHosts = hosts;
            controllerHosts.forEach(function (oneHost) {
                oneHost.name = "controller";
            });
        }
        param.log.info("Self Awareness ENV reloaded controller hosts. next reload is in [" + registry.serviceConfig.awareness.autoRelaodRegistry + "] milliseconds");
        setTimeout(fetchControllerHosts, registry.serviceConfig.awareness.autoRelaodRegistry);

        if (next && typeof next === "function")
            next();
    });
};

var awareness_healthCheck = function () {
    registry = core.registry.get();

    var resume = function () {
        if (controllerHosts && Array.isArray(controllerHosts) && controllerHosts.length > 0) {
            var controllerPort = registry.services.controller.port;
            async.each(controllerHosts,
                function (sObj, callback) {
                    if (!serviceAwarenessObj[sObj.env])
                        serviceAwarenessObj[sObj.env] = {};
                    if (!serviceAwarenessObj[sObj.env][sObj.name])
                        serviceAwarenessObj[sObj.env][sObj.name] = {"healthy": {}, "indexes": {}, "latest": 1};
                    if (!serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version])
                        serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version] = [];
                    if (!serviceAwarenessObj[sObj.env][sObj.name].indexes[sObj.version])
                        serviceAwarenessObj[sObj.env][sObj.name].indexes[sObj.version] = 0;
                    request({
                        'uri': 'http://' + sObj.ip + ':' + (controllerPort + registry.serviceConfig.ports.maintenanceInc) + '/heartbeat'
                    }, function (error, response, body) {
                        if (serviceAwarenessObj[sObj.env][sObj.name].latest < sObj.version)
                            serviceAwarenessObj[sObj.env][sObj.name].latest = sObj.version;
                        if (!error && response.statusCode === 200) {
                            if (serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].indexOf(sObj.ip) === -1)
                                serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].push(sObj.ip);
                        }
                        else {
                            if (serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].indexOf(sObj.ip) !== -1) {
                                //TODO: if we guarantee uniqueness we will not need the for loop
                                for (var ii = 0; ii < serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].length; ii++) {
                                    if (serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version][ii] === sObj.ip)
                                        serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].splice(ii, 1);
                                }
                            }
                        }
                        callback();
                    });
                }, function (err) {
                    if (err)
                        param.log.warn('Unable to build awareness ENV structure for controllers: ' + err);
                });
        }
        setTimeout(awareness_healthCheck, registry.serviceConfig.awareness.healthCheckInterval);
    };

    if (timeLoaded !== registry.timeLoaded)
        fetchControllerHosts(resume);
    else
        resume();

    timeLoaded = registry.timeLoaded;
};

function roundRobin (s, v, env, cb) {
    if (!cb && typeof env === "function") {
        cb = env;
        env = regEnvironment;
    }
    else if (!cb && typeof v === "function") {
        cb = v;
        v = null;
    }
    else if (!cb && typeof s === "function") {
        cb = s;
        s = "controller";
    }

    if (env, s && serviceAwarenessObj[env] && serviceAwarenessObj[env][s] && serviceAwarenessObj[env][s].healthy) {
        if (!v)
            v = serviceAwarenessObj[env][s].latest;
        if (serviceAwarenessObj[env][s].healthy[v] && serviceAwarenessObj[env][s].healthy[v].length > 0) {
            if (!serviceAwarenessObj[env][s].indexes)
                serviceAwarenessObj[env][s].indexes = {};
            if (!serviceAwarenessObj[env][s].indexes[v] || serviceAwarenessObj[env][s].indexes[v] >= serviceAwarenessObj[env][s].healthy[v].length)
                serviceAwarenessObj[env][s].indexes[v] = 0;
            var host = serviceAwarenessObj[env][s].healthy[v][serviceAwarenessObj[env][s].indexes[v]];
            serviceAwarenessObj[env][s].indexes[v] += 1;
            return cb(host);
        }
        else
            return cb(null);
    }
    else
        return cb(null);
};

function init (_param) {
    param = _param;

    if (registry.serviceConfig.awareness.autoRelaodRegistry)
        setTimeout(fetchControllerHosts, registry.serviceConfig.awareness.autoRelaodRegistry);
    if (registry.serviceConfig.awareness.healthCheckInterval)
        awareness_healthCheck();
}

module.exports = {
    "init" : init,
    "getControllerEnvHost" : roundRobin
};<commit_msg>in awarnessEnv the service name is available no need to loop to add it<commit_after>'use strict';

var request = require('request');
var async = require('async');
var core = require('../../modules/soajs.core');

var regEnvironment = (process.env.SOAJS_ENV || "dev");
regEnvironment = regEnvironment.toLowerCase();

var serviceAwarenessObj = {};
var controllerHosts = null;
var timeLoaded = 0;
var registry = core.registry.get();
var param = null;

var fetchControllerHosts = function (next) {
    registry = core.registry.get();
    core.registry.loadOtherEnvControllerHosts(function (error, hosts) {
        if (error)
            param.log.warn("Failed to load controller hosts. reusing from previous load. Reason: " + error.message);
        else {
            controllerHosts = hosts;
        }
        param.log.info("Self Awareness ENV reloaded controller hosts. next reload is in [" + registry.serviceConfig.awareness.autoRelaodRegistry + "] milliseconds");
        setTimeout(fetchControllerHosts, registry.serviceConfig.awareness.autoRelaodRegistry);

        if (next && typeof next === "function")
            next();
    });
};

var awareness_healthCheck = function () {
    registry = core.registry.get();

    var resume = function () {
        if (controllerHosts && Array.isArray(controllerHosts) && controllerHosts.length > 0) {
            var controllerPort = registry.services.controller.port;
            async.each(controllerHosts,
                function (sObj, callback) {
                    if (!serviceAwarenessObj[sObj.env])
                        serviceAwarenessObj[sObj.env] = {};
                    if (!serviceAwarenessObj[sObj.env][sObj.name])
                        serviceAwarenessObj[sObj.env][sObj.name] = {"healthy": {}, "indexes": {}, "latest": 1};
                    if (!serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version])
                        serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version] = [];
                    if (!serviceAwarenessObj[sObj.env][sObj.name].indexes[sObj.version])
                        serviceAwarenessObj[sObj.env][sObj.name].indexes[sObj.version] = 0;
                    request({
                        'uri': 'http://' + sObj.ip + ':' + (controllerPort + registry.serviceConfig.ports.maintenanceInc) + '/heartbeat'
                    }, function (error, response, body) {
                        if (serviceAwarenessObj[sObj.env][sObj.name].latest < sObj.version)
                            serviceAwarenessObj[sObj.env][sObj.name].latest = sObj.version;
                        if (!error && response.statusCode === 200) {
                            if (serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].indexOf(sObj.ip) === -1)
                                serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].push(sObj.ip);
                        }
                        else {
                            if (serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].indexOf(sObj.ip) !== -1) {
                                //TODO: if we guarantee uniqueness we will not need the for loop
                                for (var ii = 0; ii < serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].length; ii++) {
                                    if (serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version][ii] === sObj.ip)
                                        serviceAwarenessObj[sObj.env][sObj.name].healthy[sObj.version].splice(ii, 1);
                                }
                            }
                        }
                        callback();
                    });
                }, function (err) {
                    if (err)
                        param.log.warn('Unable to build awareness ENV structure for controllers: ' + err);
                });
        }
        setTimeout(awareness_healthCheck, registry.serviceConfig.awareness.healthCheckInterval);
    };

    if (timeLoaded !== registry.timeLoaded)
        fetchControllerHosts(resume);
    else
        resume();

    timeLoaded = registry.timeLoaded;
};

function roundRobin (s, v, env, cb) {
    if (!cb && typeof env === "function") {
        cb = env;
        env = regEnvironment;
    }
    else if (!cb && typeof v === "function") {
        cb = v;
        v = null;
    }
    else if (!cb && typeof s === "function") {
        cb = s;
        s = "controller";
    }

    if (env, s && serviceAwarenessObj[env] && serviceAwarenessObj[env][s] && serviceAwarenessObj[env][s].healthy) {
        if (!v)
            v = serviceAwarenessObj[env][s].latest;
        if (serviceAwarenessObj[env][s].healthy[v] && serviceAwarenessObj[env][s].healthy[v].length > 0) {
            if (!serviceAwarenessObj[env][s].indexes)
                serviceAwarenessObj[env][s].indexes = {};
            if (!serviceAwarenessObj[env][s].indexes[v] || serviceAwarenessObj[env][s].indexes[v] >= serviceAwarenessObj[env][s].healthy[v].length)
                serviceAwarenessObj[env][s].indexes[v] = 0;
            var host = serviceAwarenessObj[env][s].healthy[v][serviceAwarenessObj[env][s].indexes[v]];
            serviceAwarenessObj[env][s].indexes[v] += 1;
            return cb(host);
        }
        else
            return cb(null);
    }
    else
        return cb(null);
};

function init (_param) {
    param = _param;

    if (registry.serviceConfig.awareness.autoRelaodRegistry)
        setTimeout(fetchControllerHosts, registry.serviceConfig.awareness.autoRelaodRegistry);
    if (registry.serviceConfig.awareness.healthCheckInterval)
        awareness_healthCheck();
}

module.exports = {
    "init" : init,
    "getControllerEnvHost" : roundRobin
};<|endoftext|>


<commit_before>// The angular app.
var app = angular.module("base-converter", []);

/**
 * Controller for the app.
 */
app.controller('controller', ['$scope', function($scope) {

    // The first NumberWithBase. This is the number that the user enters.
    $scope.first = new NumberWithBase('', '');

    // The second NumberWithBase. The user enters the base of this number, and the value is the
    // result of the conversion of the first number to this new base.
    $scope.second = new NumberWithBase('', '');

    /**
     * A flag indicating that one or more of the characters in the number is larger than it's
     * base permits. For example, if the value is "aaa" but the base is 10, the flag is set to true
     * and conversion does not occur.
     *
     * @param {NumberWithBase} numberWithBase The NumberWithBase to check for invalid digits.
     *
     * @return {boolean} True if numberWithBase's number component contains invalid characters,
     *     false otherwise.
     */
    $scope.incompatible = function(numberWithBase) {
        if (numberWithBase.base < 2)
            return false;
        for (var i = 0; i < numberWithBase.number.length; i++) {
            if (charToInt(numberWithBase.number.charAt(i)) >= numberWithBase.base)
                return true;
        }
        return false;
    };
}]);

/**
 * Directive for an input which takes a base, which is a decimal number in [2, 36].
 */
app.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {

            // Must have type='base'.
            if (attr.type !== 'base')
                return;

            // Only numbers from 1 - 36 are allowed to be input.
            element.bind('input', function() {
                var onlyNumbers = this.value.replace(/[^0-9]/g, '');

                if (parseInt(onlyNumbers) > 36)
                    onlyNumbers = '36';
                else if (onlyNumbers == 0)
                    onlyNumbers = '';

                scope.$apply(function() {
                    ngModel.$setViewValue(onlyNumbers);
                    ngModel.$render();
                });
            });

            // The number '1' is allowed to be input, but a single '1' is not a valid base.
            // Therefore, if the number === 1 when the user leaves this input element, it is
            // automatically changed to a 2.
            element.bind('focusout', function () {
                if (parseInt(this.value) === 1) {
                    scope.$apply(function() {
                        ngModel.$setViewValue(2);
                        ngModel.$render();
                    });
                }
            });
        }
    };
});

/**
 * Directive for inputs that take floating point numbers in any base in [2, 36].
 */
app.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {

            if (attr.type !== 'float')
                return;

            // Only allow alpha-numeric input.
            element.bind('input', function () {
                scope.$apply(function() {
                    ngModel.$setViewValue(element.val().replace(/[^.0-9a-z]/gi, ''));
                    ngModel.$render();
                });
            });
        }
    };
});

/**
 * Converts an alphanumeric character to an integer. Digits have the same value as a character.
 * Letters are converted to their index in the alphabet (starting with A = 0) plus 10. So A = 10,
 * B = 11, etc. No distinction is made between upper and lowercase characters.
 *
 * @param {string} ch A string of length 1, containing only the character to be converted.
 *
 * @return {number} The numeric equivalent of the character ch.
 */
function charToInt (ch) {
    if (!isNaN(ch))
        return parseInt(ch);
    return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(ch.toUpperCase()) + 10;
}

/**
 * Converts an integer in [0, 36] to a character. Number below 10 retain the same value. Numbers
 * above 10 are converted to an appropriate letter, starting with 10 = A, 11 = B, etc.
 *
 * @param {number} i The integer to convert.
 *
 * @return {string} A string with length 1 containing the character representation of i.
 */
function intToChar (i) {
    if (i < 10)
        return i.toString();
    return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(i - 10);
}

/**
 * A number that is in an arbitrary base.
 *
 * @param {string} number The value of the number.
 * @param {number} base The base of the number.
 */
function NumberWithBase(number, base) {
    this.number = number;
    this.base = base;
}

/**
 * Converts another NumberWithBase to a NumberWithBase having this base.
 *
 * @param {NumberWithBase} other Another NumberWithBase to which we want this NumberWithBase to have
 *     an equivalent value.
 */
NumberWithBase.prototype.convert = function(other) {

    if (this.base < 2 || other.base < 2)
        return;

    // Fractional precision is set at 8 places after the radix point. Does not apply to integers.
    var fractionalPrecision = 8;

    // Find the position of the radix point in the number.
    var radixPosition = other.number.indexOf('.');
    if (radixPosition === -1)
        radixPosition = other.number.length;
    radixPosition--;

    var decimalNumber;

    // Convert to decimal number.
    if (other.base == 10) {
        decimalNumber = other.number;
    } else {
        decimalNumber = 0;
        for (var i = 0; i < other.number.length; i++) {
            if (other.number.charAt(i) === '.')
                continue;
            decimalNumber += (charToInt(other.number.charAt(i))
                * Math.pow(other.base, radixPosition));
            radixPosition--;
        }
    }

    // If we are converting to decimal, the process is complete.
    if (this.base == 10) {
        decimalNumber = decimalNumber.toString();
        radixPosition = decimalNumber.indexOf('.')
        if (radixPosition === -1)
            this.number = decimalNumber;
        else
            this.number = decimalNumber.substring(0, radixPosition + fractionalPrecision + 1);
        return;
    }

    var convertedNumber = '';

    // Split number into integer and fractional parts.
    var integerPart = parseInt(decimalNumber);
    var fractionalPart = decimalNumber - integerPart;

    // Convert integer part from decimal to the new base.
    while (integerPart > 0) {
        var rem = intToChar(integerPart % this.base);
        integerPart = parseInt(integerPart / this.base);
        convertedNumber = rem.toString().concat(convertedNumber);
    }

    // If the number was an integer, we're done now.
    if (fractionalPart === 0) {
        this.number = convertedNumber;
        return;
    }

    // Add the radix point.
    convertedNumber = convertedNumber.concat('.');

    // Convert fractional part from decimal to new base.
    while (fractionalPrecision > 0 && fractionalPart !== 0) {
        var result = fractionalPart * this.base;
        var digit = intToChar(parseInt(result));
        fractionalPart = result - parseInt(result);
        convertedNumber = convertedNumber.concat(digit);
        fractionalPrecision--;
    }

    this.number = convertedNumber;
}
<commit_msg>Added invalid digit check in convert method.<commit_after>// The angular app.
var app = angular.module("base-converter", []);

/**
 * Controller for the app.
 */
app.controller('controller', ['$scope', function($scope) {

    // The first NumberWithBase. This is the number that the user enters.
    $scope.first = new NumberWithBase('', '');

    // The second NumberWithBase. The user enters the base of this number, and the value is the
    // result of the conversion of the first number to this new base.
    $scope.second = new NumberWithBase('', '');

    // Tests for digits too large for their base.
    $scope.incompatible = invalidDigit;
}]);

/**
 * Directive for an input which takes a base, which is a decimal number in [2, 36].
 */
app.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {

            // Must have type='base'.
            if (attr.type !== 'base')
                return;

            // Only numbers from 1 - 36 are allowed to be input.
            element.bind('input', function() {
                var onlyNumbers = this.value.replace(/[^0-9]/g, '');

                if (parseInt(onlyNumbers) > 36)
                    onlyNumbers = '36';
                else if (onlyNumbers == 0)
                    onlyNumbers = '';

                scope.$apply(function() {
                    ngModel.$setViewValue(onlyNumbers);
                    ngModel.$render();
                });
            });

            // The number '1' is allowed to be input, but a single '1' is not a valid base.
            // Therefore, if the number === 1 when the user leaves this input element, it is
            // automatically changed to a 2.
            element.bind('focusout', function () {
                if (parseInt(this.value) === 1) {
                    scope.$apply(function() {
                        ngModel.$setViewValue(2);
                        ngModel.$render();
                    });
                }
            });
        }
    };
});

/**
 * Directive for inputs that take floating point numbers in any base in [2, 36].
 */
app.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {

            if (attr.type !== 'float')
                return;

            // Only allow alpha-numeric input.
            element.bind('input', function () {
                scope.$apply(function() {
                    ngModel.$setViewValue(element.val().replace(/[^.0-9a-z]/gi, ''));
                    ngModel.$render();
                });
            });
        }
    };
});

/**
 * Indicates whether or not one or more of the characters in the number is larger than it's
 * base permits. For example, if the value is "aaa" but the base is 10, the flag is set to true
 * and conversion does not occur.
 *
 * @param {NumberWithBase} numberWithBase The NumberWithBase to check for invalid digits.
 *
 * @return {boolean} True if numberWithBase's number component contains invalid characters,
 *     false otherwise.
 */
function invalidDigit(numberWithBase) {
    if (numberWithBase.base < 2)
        return false;
    for (var i = 0; i < numberWithBase.number.length; i++) {
        if (charToInt(numberWithBase.number.charAt(i)) >= numberWithBase.base)
            return true;
    }
    return false;
}

/**
 * Converts an alphanumeric character to an integer. Digits have the same value as a character.
 * Letters are converted to their index in the alphabet (starting with A = 0) plus 10. So A = 10,
 * B = 11, etc. No distinction is made between upper and lowercase characters.
 *
 * @param {string} ch A string of length 1, containing only the character to be converted.
 *
 * @return {number} The numeric equivalent of the character ch.
 */
function charToInt (ch) {
    if (!isNaN(ch))
        return parseInt(ch);
    return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(ch.toUpperCase()) + 10;
}

/**
 * Converts an integer in [0, 36] to a character. Number below 10 retain the same value. Numbers
 * above 10 are converted to an appropriate letter, starting with 10 = A, 11 = B, etc.
 *
 * @param {number} i The integer to convert.
 *
 * @return {string} A string with length 1 containing the character representation of i.
 */
function intToChar (i) {
    if (i < 10)
        return i.toString();
    return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(i - 10);
}

/**
 * A number that is in an arbitrary base.
 *
 * @param {string} number The value of the number.
 * @param {number} base The base of the number.
 */
function NumberWithBase(number, base) {
    this.number = number;
    this.base = base;
}

/**
 * Converts another NumberWithBase to a NumberWithBase having this base.
 *
 * @param {NumberWithBase} other Another NumberWithBase to which we want this NumberWithBase to have
 *     an equivalent value.
 */
NumberWithBase.prototype.convert = function(other) {

    if (this.base < 2 || other.base < 2 || invalidDigit(other))
        return;

    // Fractional precision is set at 8 places after the radix point. Does not apply to integers.
    var fractionalPrecision = 8;

    // Find the position of the radix point in the number.
    var radixPosition = other.number.indexOf('.');
    if (radixPosition === -1)
        radixPosition = other.number.length;
    radixPosition--;

    var decimalNumber;

    // Convert to decimal number.
    if (other.base == 10) {
        decimalNumber = other.number;
    } else {
        decimalNumber = 0;
        for (var i = 0; i < other.number.length; i++) {
            if (other.number.charAt(i) === '.')
                continue;
            decimalNumber += (charToInt(other.number.charAt(i))
                * Math.pow(other.base, radixPosition));
            radixPosition--;
        }
    }

    // If we are converting to decimal, the process is complete.
    if (this.base == 10) {
        decimalNumber = decimalNumber.toString();
        radixPosition = decimalNumber.indexOf('.')
        if (radixPosition === -1)
            this.number = decimalNumber;
        else
            this.number = decimalNumber.substring(0, radixPosition + fractionalPrecision + 1);
        return;
    }

    var convertedNumber = '';

    // Split number into integer and fractional parts.
    var integerPart = parseInt(decimalNumber);
    var fractionalPart = decimalNumber - integerPart;

    // Convert integer part from decimal to the new base.
    while (integerPart > 0) {
        var rem = intToChar(integerPart % this.base);
        integerPart = parseInt(integerPart / this.base);
        convertedNumber = rem.toString().concat(convertedNumber);
    }

    // If the number was an integer, we're done now.
    if (fractionalPart === 0) {
        this.number = convertedNumber;
        return;
    }

    // Add the radix point.
    convertedNumber = convertedNumber.concat('.');

    // Convert fractional part from decimal to new base.
    while (fractionalPrecision > 0 && fractionalPart !== 0) {
        var result = fractionalPart * this.base;
        var digit = intToChar(parseInt(result));
        fractionalPart = result - parseInt(result);
        convertedNumber = convertedNumber.concat(digit);
        fractionalPrecision--;
    }

    this.number = convertedNumber;
}
<|endoftext|>


<commit_before>var TranslationSystem = {
    TRANSLATABLE_ATTRIBUTES: [
        'title',
        'alt',
        'placeholder'
    ],
    translations: undefined,

    init: function() {
        var settings = new Settings();
        TranslationSystem.changeLanguage(settings.language);

        $('#translations').click(function() {
            $(this).arrowPopup("#translationsPopup");
        });
    },

    get: function(original) {
        if (TranslationSystem.translations.hasOwnProperty(original)) {
            return TranslationSystem.translations[original];
        }
        return original;
    },

    updateMarkup: function(data) {
        TranslationSystem.translations = data; // global

        $('.translatable').each(function(i, elem) {
            elem = $(elem);

            var translationKeys = elem.data('translationKeys') || {},
                key;

            if (translationKeys.hasOwnProperty('text')) {
                key = translationKeys.text;
            } else {
                key = elem.text();
                translationKeys.text = key;
            }

            if (TranslationSystem.translations.hasOwnProperty(key)) {
                elem.text(TranslationSystem.translations[key]);
            }

            $.each(TranslationSystem.TRANSLATABLE_ATTRIBUTES, function(j, attr) {
                if (elem.attr(attr) !== undefined) {
                    if (translationKeys.hasOwnProperty(attr)) {
                        key = translationKeys[attr];
                    } else {
                        key = elem.attr(attr);
                        translationKeys[attr] = key;
                    }
                    if (TranslationSystem.translations.hasOwnProperty(key)) {
                        elem.attr(attr, TranslationSystem.translations[key]);
                    }
                }
            });

            elem.data('translationKeys', translationKeys);
        });
    },

    changeLanguage: function(code) {
        $('#settings .language option[value=' + code + ']').attr('selected', 'selected');

        if (autoDetectedLanguageByServer === code) {
            TranslationSystem.updateMarkup(autoDetectedTranslations);
        } else {
            $.getJSON('/api/translations/' + code, function(data, textStatus) {
                TranslationSystem.updateMarkup(data);
            });
        }
    }
};
<commit_msg>Fix bug with empty translations showing up<commit_after>var TranslationSystem = {
    TRANSLATABLE_ATTRIBUTES: [
        'title',
        'alt',
        'placeholder'
    ],
    translations: undefined,

    init: function() {
        var settings = new Settings();
        TranslationSystem.changeLanguage(settings.language);

        $('#translations').click(function() {
            $(this).arrowPopup("#translationsPopup");
        });
    },

    get: function(original) {
        if (TranslationSystem.translations.hasOwnProperty(original) && TranslationSystem.translations[original].length) {
            return TranslationSystem.translations[original];
        }
        return original;
    },

    updateMarkup: function(data) {
        TranslationSystem.translations = data; // global

        $('.translatable').each(function(i, elem) {
            elem = $(elem);

            var translationKeys = elem.data('translationKeys') || {},
                key;

            if (translationKeys.hasOwnProperty('text')) {
                key = translationKeys.text;
            } else {
                key = elem.text();
                translationKeys.text = key;
            }

            if (TranslationSystem.translations.hasOwnProperty(key)) {
                elem.text(TranslationSystem.get(key));
            }

            $.each(TranslationSystem.TRANSLATABLE_ATTRIBUTES, function(j, attr) {
                if (elem.attr(attr) !== undefined) {
                    if (translationKeys.hasOwnProperty(attr)) {
                        key = translationKeys[attr];
                    } else {
                        key = elem.attr(attr);
                        translationKeys[attr] = key;
                    }
                    if (TranslationSystem.translations.hasOwnProperty(key)) {
                        elem.attr(attr, TranslationSystem.get(key));
                    }
                }
            });

            elem.data('translationKeys', translationKeys);
        });
    },

    changeLanguage: function(code) {
        $('#settings .language option[value=' + code + ']').attr('selected', 'selected');

        if (autoDetectedLanguageByServer === code) {
            TranslationSystem.updateMarkup(autoDetectedTranslations);
        } else {
            $.getJSON('/api/translations/' + code, function(data, textStatus) {
                TranslationSystem.updateMarkup(data);
            });
        }
    }
};
<|endoftext|>


<commit_before>'use strict';

function manageDojosCtrl($scope, alertService, auth, tableUtils, cdDojoService, $location, cdCountriesService) {
  $scope.filter = {};
  $scope.filter.verified = 1;
  $scope.itemsPerPage = 10;

  $scope.pageChanged = function () {
    $scope.loadPage($scope.filter, false);
  };

  var verificationStates = [
    {label: 'Unverified', value: 0},
    {label: 'Verified', value: 1},
    {label: 'Previous', value: 2}
  ];

  var changedDojos = [];

  $scope.getVerificationStates = function (agreements) {
    var states = verificationStates.slice();

    // TODO: single origin point for current agreement version
    var currentAgreementVersion = 2;
    if (!_.any(agreements, function (agreement) {
        return agreement.agreementVersion === currentAgreementVersion;
      })) {
      //
      states = _.reject(states, function (state) { return state.value === 1 });
    }

    return states;
  };

  $scope.setStyle = function(agreements){
    // TODO: single origin point for current agreement version
    var currentAgreementVersion = 2;

    var isSigned  = _.any(agreements, function(agreement) {
      return agreement.agreementVersion === currentAgreementVersion;
    });

    return !isSigned ? {color:'red'} : {color: 'black'};
  };

  $scope.editDojo = function (dojo) {
    cdDojoService.setDojo(dojo, function (response) {
      $location.path('/dashboard/edit-dojo');
    }, function (err) {
      if (err) {
        alertService.showError(
          'An error has occurred while editing dojo:
 ' +
          (err.error || JSON.stringify(err))
        );
      }
    });
  };

  $scope.resetFilter = function () {
    $scope.filter = {};
    $scope.filter.verified = 1;

    $scope.loadPage($scope.filter, true);
  };

  $scope.loadPage = function (filter, resetFlag, cb) {
    cb = cb || function () {};
    var filteredQuery = {};
    filteredQuery.query = {};
    filteredQuery.query.filtered = {};

    if(!_.isNull(filter.email) && filter.email !== '' && !_.isUndefined(filter.email)){
      filteredQuery.query.filtered.query = {
        "regexp" : {
          "email" : {
              "value": ".*" + filter.email + ".*"
          }
        }
      };
    }

    var query = _.omit({
      verified: filter.verified,
      stage: filter.stage,
      alpha2: filter.country && filter.country.alpha2
    }, function (value) { return value === '' || _.isNull(value) || _.isUndefined(value) });

    var loadPageData = tableUtils.loadPage(resetFlag, $scope.itemsPerPage, $scope.pageNo, query);
    $scope.pageNo = loadPageData.pageNo;
    $scope.dojos = [];

    var meta = {
      sort: [{
        created: 'desc'
      }],
      from: loadPageData.skip,
      size: $scope.itemsPerPage
    };

    filteredQuery = _.extend(filteredQuery, meta);

    if (!_.isEmpty(query)) {
      filteredQuery.query.filtered.filter = {
        and: _.map(query, function (value, key) {
          var term = {};
          term[key] = value.toLowerCase ? value.toLowerCase() : value;
          return {term: term};
        })
      };
    }

    cdDojoService.search(filteredQuery).then(function (result) {
      $scope.dojos = _.map(result.records, function (dojo) {
        dojo.verified = _.findWhere(verificationStates, {value: dojo.verified});
        return dojo;
      });

      $scope.totalItems = result.total;

      return cb();
    }, function (err) {
      alertService.showError('An error has occurred while loading Dojos:
' +
        (err.error || JSON.stringify(err))
      );

      return cb(err);
    });
  };

  $scope.filterDojos = function () {
    $scope.loadPage($scope.filter, true);
    changedDojos = [];
  };

  $scope.processDojos = function (event) {

    changedDojos = _.map(changedDojos, function (dojo) {
      if (dojo.creatorEmail) {
        delete dojo.creatorEmail;
      }

      if (dojo.agreements) {
        delete dojo.agreements;
      }

      return dojo;
    });

    $scope.dojosToBeDeleted = _.filter(changedDojos, function (changedDojo) {
      return changedDojo.toBeDeleted;
    });

    $scope.dojosToBeUpdated = _.filter(changedDojos, function (changedDojo) {
      return !changedDojo.toBeDeleted;
    });

    function updateDojos(cb) {
      if (_.isEmpty($scope.dojosToBeUpdated)) {
        return cb();
      }

      var dojosToBeUpdated = _.map($scope.dojosToBeUpdated, function (dojo) {
        return {
          id: dojo.id,
          verified: dojo.verified.value
        }
      });

      cdDojoService.bulkUpdate(dojosToBeUpdated).then(function (response) {
        // TODO: review, should notify user on successfull update?

        return cb();
      }, function (err) {
        alertService.showError('An error has occurred while updating Dojos:
' +
        (err.error || JSON.stringify(err)));

        cb(err);
      });
    }

    function deleteDojos(cb) {
      if (_.isEmpty($scope.dojosToBeDeleted)) {
        return cb();
      }

      var dojos = _.map($scope.dojosToBeDeleted, function (dojo) {
        return {id: dojo.id, creator: dojo.creator};
      });

      cdDojoService.bulkDelete(dojos).then(function (response) {
        // TODO: review, should notify user on successfull delete?

        return cb();
      }, function (err) {
        alertService.showError('An error has occurred while deleting Dojos:
' +
        (err.error || JSON.stringify(err)));

        cb(err);
      });
    }

    async.series([updateDojos, deleteDojos], function (err) {
      delete $scope.dojosToBeDeleted;
      delete $scope.dojosToBeUpdated;
      changedDojos = [];
      if (err) {
        alertService.showError('An error has occurred while updating Dojos:
' +
        (err.error || JSON.stringify(err)));
      }
      $scope.loadPage($scope.filter, false);
    });
  };

  cdCountriesService.listCountries(function (countries) {
    $scope.countries = _.map(countries, function (country) {
      return _.omit(country, 'entity$');
    });
  });

  $scope.pushChangedDojo = function (dojo) {
    var filterVerified, exists = !!(_.find(changedDojos, function (changedDojo) {
      return dojo.id === changedDojo.id;
    }));

    filterVerified = $scope.filter && $scope.filter.verified;

    if ((dojo.verified.value !== filterVerified) || (dojo.toBeDeleted)) {
      if (!exists) {
        changedDojos.push(dojo);
      }

    } else if (dojo.verified.value === filterVerified && !dojo.toBeDeleted) {
      changedDojos = _.filter(changedDojos, function (filteredDojo) {
        return dojo.id !== filteredDojo.id;
      });
    }

  };

  auth.get_loggedin_user(function () {
    $scope.loadPage($scope.filter, true);
  });
}

angular.module('cpZenPlatform')
  .controller('manage-dojo-controller',
  ['$scope', 'alertService', 'auth', 'tableUtils', 'cdDojoService', '$location', 'cdCountriesService', manageDojosCtrl]);

<commit_msg>Clean up<commit_after>'use strict';

function manageDojosCtrl($scope, alertService, auth, tableUtils, cdDojoService, $location, cdCountriesService) {
  $scope.filter = {};
  $scope.filter.verified = 1;
  $scope.itemsPerPage = 10;

  $scope.pageChanged = function () {
    $scope.loadPage($scope.filter, false);
  };

  var verificationStates = [
    {label: 'Unverified', value: 0},
    {label: 'Verified', value: 1},
    {label: 'Previous', value: 2}
  ];

  var changedDojos = [];

  $scope.getVerificationStates = function (agreements) {
    var states = verificationStates.slice();

    // TODO: single origin point for current agreement version
    var currentAgreementVersion = 2;
    if (!_.any(agreements, function (agreement) {
        return agreement.agreementVersion === currentAgreementVersion;
      })) {

      states = _.reject(states, function (state) { return state.value === 1 });
    }

    return states;
  };

  $scope.setStyle = function(agreements){
    // TODO: single origin point for current agreement version
    var currentAgreementVersion = 2;

    var isSigned  = _.any(agreements, function(agreement) {
      return agreement.agreementVersion === currentAgreementVersion;
    });

    return !isSigned ? {color:'red'} : {color: 'black'};
  };

  $scope.editDojo = function (dojo) {
    cdDojoService.setDojo(dojo, function (response) {
      $location.path('/dashboard/edit-dojo');
    }, function (err) {
      if (err) {
        alertService.showError(
          'An error has occurred while editing dojo:
 ' +
          (err.error || JSON.stringify(err))
        );
      }
    });
  };

  $scope.resetFilter = function () {
    $scope.filter = {};
    $scope.filter.verified = 1;

    $scope.loadPage($scope.filter, true);
  };

  $scope.loadPage = function (filter, resetFlag, cb) {
    cb = cb || function () {};
    var filteredQuery = { query: { filtered: {}}};

    if(filter.email){
      filteredQuery.query.filtered.query = {
        "regexp" : {
          "email" : {
            "value": ".*" + filter.email + ".*"
          }
        }
      };
    }

    var query = _.omit({
      verified: filter.verified,
      stage: filter.stage,
      alpha2: filter.country && filter.country.alpha2
    }, function (value) { return value === '' || _.isNull(value) || _.isUndefined(value) });

    var loadPageData = tableUtils.loadPage(resetFlag, $scope.itemsPerPage, $scope.pageNo, query);
    $scope.pageNo = loadPageData.pageNo;
    $scope.dojos = [];

    var meta = {
      sort: [{
        created: 'desc'
      }],
      from: loadPageData.skip,
      size: $scope.itemsPerPage
    };

    filteredQuery = _.extend(filteredQuery, meta);

    if (!_.isEmpty(query)) {
      filteredQuery.query.filtered.filter = {
        and: _.map(query, function (value, key) {
          var term = {};
          term[key] = value.toLowerCase ? value.toLowerCase() : value;
          return {term: term};
        })
      };
    }

    cdDojoService.search(filteredQuery).then(function (result) {
      $scope.dojos = _.map(result.records, function (dojo) {
        dojo.verified = _.findWhere(verificationStates, {value: dojo.verified});
        return dojo;
      });

      $scope.totalItems = result.total;

      return cb();
    }, function (err) {
      alertService.showError('An error has occurred while loading Dojos:
' +
        (err.error || JSON.stringify(err))
      );

      return cb(err);
    });
  };

  $scope.filterDojos = function () {
    $scope.loadPage($scope.filter, true);
    changedDojos = [];
  };

  $scope.processDojos = function (event) {

    changedDojos = _.map(changedDojos, function (dojo) {
      if (dojo.creatorEmail) {
        delete dojo.creatorEmail;
      }

      if (dojo.agreements) {
        delete dojo.agreements;
      }

      return dojo;
    });

    $scope.dojosToBeDeleted = _.filter(changedDojos, function (changedDojo) {
      return changedDojo.toBeDeleted;
    });

    $scope.dojosToBeUpdated = _.filter(changedDojos, function (changedDojo) {
      return !changedDojo.toBeDeleted;
    });

    function updateDojos(cb) {
      if (_.isEmpty($scope.dojosToBeUpdated)) {
        return cb();
      }

      var dojosToBeUpdated = _.map($scope.dojosToBeUpdated, function (dojo) {
        return {
          id: dojo.id,
          verified: dojo.verified.value
        }
      });

      cdDojoService.bulkUpdate(dojosToBeUpdated).then(function (response) {
        // TODO: review, should notify user on successfull update?

        return cb();
      }, function (err) {
        alertService.showError('An error has occurred while updating Dojos:
' +
        (err.error || JSON.stringify(err)));

        cb(err);
      });
    }

    function deleteDojos(cb) {
      if (_.isEmpty($scope.dojosToBeDeleted)) {
        return cb();
      }

      var dojos = _.map($scope.dojosToBeDeleted, function (dojo) {
        return {id: dojo.id, creator: dojo.creator};
      });

      cdDojoService.bulkDelete(dojos).then(function (response) {
        // TODO: review, should notify user on successfull delete?

        return cb();
      }, function (err) {
        alertService.showError('An error has occurred while deleting Dojos:
' +
        (err.error || JSON.stringify(err)));

        cb(err);
      });
    }

    async.series([updateDojos, deleteDojos], function (err) {
      delete $scope.dojosToBeDeleted;
      delete $scope.dojosToBeUpdated;
      changedDojos = [];
      if (err) {
        alertService.showError('An error has occurred while updating Dojos:
' +
        (err.error || JSON.stringify(err)));
      }
      $scope.loadPage($scope.filter, false);
    });
  };

  cdCountriesService.listCountries(function (countries) {
    $scope.countries = _.map(countries, function (country) {
      return _.omit(country, 'entity$');
    });
  });

  $scope.pushChangedDojo = function (dojo) {
    var filterVerified, exists = !!(_.find(changedDojos, function (changedDojo) {
      return dojo.id === changedDojo.id;
    }));

    filterVerified = $scope.filter && $scope.filter.verified;

    if ((dojo.verified.value !== filterVerified) || (dojo.toBeDeleted)) {
      if (!exists) {
        changedDojos.push(dojo);
      }

    } else if (dojo.verified.value === filterVerified && !dojo.toBeDeleted) {
      changedDojos = _.filter(changedDojos, function (filteredDojo) {
        return dojo.id !== filteredDojo.id;
      });
    }

  };

  auth.get_loggedin_user(function () {
    $scope.loadPage($scope.filter, true);
  });
}

angular.module('cpZenPlatform')
  .controller('manage-dojo-controller',
  ['$scope', 'alertService', 'auth', 'tableUtils', 'cdDojoService', '$location', 'cdCountriesService', manageDojosCtrl]);

<|endoftext|>


<commit_before>(function () {
    var game = new Phaser.Game(
        1024, 768, Phaser.AUTO, 'tankr',
        { preload: preload,
          create: create,
          update: update,
          render: render }
    );
    var map;
    var player;
    var turret;
    var cursors;
    var bullets;
    var explosions;
    var spacebar;
    var timer;
    var last_fired = 0;
    var reload_time = 400;
    var speed_units = 300;
    var speed_angle = 90;

    var enemies;
    var enemiesCount;

    var sandbagsCount = 15;
    var barrelGreyCount = 15;

    EnemyTank = function (index, game, player, bullets) {
        var x = game.world.randomX;
        var y = game.world.randomY;

        this.game = game;
        this.health = 3;
        this.player = player;
        this.bullets = bullets;
        this.fireRate = 1000;
        this.nextFire = 0;
        this.alive = true;

        this.tank = game.add.sprite(x, y, 'tankRed');
        this.tank.anchor.setTo(0.5, 0.5);
        this.turret = game.add.sprite(x, y, 'barrelRed');

        this.tank.name = index.toString();
        game.physics.enable(this.tank, Phaser.Physics.ARCADE);
        this.tank.body.immovable = false;
        this.tank.body.collideWorldBounds = true;
        this.tank.body.bounce.setTo(1, 1);
    }

    EnemyTank.prototype.update = function() {
        this.turret.x = this.tank.x -7;
        this.turret.y = this.tank.y -50;
    }

    function hitBarrel (barrel, bullet) {
        var animation = explosions.getFirstExists(false);
        animation.reset(barrel.x, barrel.y);
        animation.play('kaboom', 30, false, true);

        barrel.kill();
        bullet.kill();
    }

    Math.degToRad = function (degrees) {
        return degrees * Math.PI / 180;
    };

    function preload() {
        // tanks
        game.load.image('tankBlue', 'assets/img/Tanks/tankBlue.png');
        game.load.image('tankRed', 'assets/img/Tanks/tankRed.png');
        game.load.image('barrelBlue', 'assets/img/Tanks/barrelBlue.png');
        game.load.image('barrelRed', 'assets/img/Tanks/barrelRed.png');
        game.load.image('bullet', 'assets/img/Bullets/bulletBlue.png');

        // terrain
        game.load.image('grass', 'assets/img/Environment/grass.png');

        // obstacles
        game.load.image('sandbagBrown', 'assets/img/Obstacles/sandbagBrown.png');
        game.load.image('barrelGrey', 'assets/img/Obstacles/barrelGrey_up.png');

        // 'splosions
        game.load.spritesheet('kaboom', 'assets/img/Smoke/explosion.png', 64, 64, 23);
    }

    function create() {
        game.world.setBounds(-1000, -1000, 2000, 2000);

        land = game.add.tileSprite(0, 0, 2000, 2000, 'grass');
        land.fixedToCamera = true;
        spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        player = game.add.sprite(game.world.centerX, game.world.centerY, 'tankBlue');
        player.anchor.setTo(0.5, 0.5);
        game.camera.follow(player);
        game.physics.enable(player, Phaser.Physics.ARCADE);
        game.physics.startSystem(Phaser.Physics.ARCADE);

        player.anchor.setTo(0.5, 0.5);
        turret = game.add.sprite(0, 0, 'barrelBlue');

        // add sandbags with collision
        sandbags = game.add.group();
        sandbags.physicsBodyType = Phaser.Physics.ARCADE;
        sandbags.enableBody = true;
        for (var i = 0; i < sandbagsCount; i++) {
            var sbag = sandbags.create(game.world.randomX, game.world.randomY, 'sandbagBrown');
            sbag.body.immovable = true;
        }

        // add empty barrels
        barrelGrey = game.add.group();
        barrelGrey.physicsBodyType = Phaser.Physics.ARCADE;
        barrelGrey.enableBody = true;

        for (var i = 0; i < barrelGreyCount; i++) {
            var bg = barrelGrey.create(game.world.randomX, game.world.randomY, 'barrelGrey');
            bg.body.onCollide = new Phaser.Signal();
            bg.body.onCollide.add(hitBarrel, this);
            bg.body.immovable = false;
        }

        cursors = game.input.keyboard.createCursorKeys();
        bullets = game.add.group();
        bullets.enableBody = true;
        bullets.physicsBodyType = Phaser.Physics.ARCADE;
        bullets.createMultiple(30, 'bullet', 0, false);
        bullets.setAll('anchor.x', 0.5);
        bullets.setAll('anchor.y', 0.5);
        bullets.setAll('outOfBoundsKill', true);
        bullets.setAll('checkWorldBounds', true);

        explosions = game.add.group();
        for (var i = 0; i < 10; i++) {
            var explosionAnimation = explosions.create(0, 0, 'kaboom', [0], false);
            explosionAnimation.anchor.setTo(0.5, 0.5);
            explosionAnimation.animations.add('kaboom');
        }
        // create enemies
        enemies = [];
        enemiesCount = 7;
        for (var i = 0; i < enemiesCount; i++) {
             enemies.push(new EnemyTank(i, game, player, []));
        }
    }

    function update() {
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;
        player.body.angularVelocity = 0;

        game.physics.arcade.collide(player, sandbags);
        game.physics.arcade.collide(player, barrelGrey);
        game.physics.arcade.collide(barrelGrey, bullets);

        if (cursors.left.isDown) {
            player.body.angularVelocity = -speed_angle;
        } else if (cursors.right.isDown) {
            player.body.angularVelocity = speed_angle;
        } else if (cursors.down.isDown) {
            game.physics.arcade.velocityFromAngle(
                player.angle + 90,
                speed_units,
                player.body.velocity
            );
        } else if (cursors.up.isDown) {
            game.physics.arcade.velocityFromAngle(
                player.angle + -90,
                speed_units,
                player.body.velocity
            );
        } else if (spacebar.isDown) {
            now = game.time.now;
            if (last_fired + reload_time < now) {
                var bullet = bullets.getFirstExists(false);

                bullet.reset(turret.x, turret.y);
                bullet.angle = player.angle;
                ix = player.x + 100 * Math.cos(Math.degToRad(player.angle - 90));
                iy = player.y + 100 * Math.sin(Math.degToRad(player.angle - 90));
                game.physics.arcade.moveToXY(bullet, ix, iy, 500);
                last_fired = now;
            }
        } else {
            player.animations.stop();
            player.frame = 4;
        }
        if (cursors.up.isDown && player.body.touching.down)
        {
            player.body.velocity.y = -350;
        }
        turret.x = player.x + 8;
        turret.y = player.y;
        turret.angle = 180 + player.angle;

        game.camera.x = player.x;
        game.camera.y = player.y;

        for (var i = 0; i < enemies.length; i++) {
            game.physics.arcade.collide(player, enemies[i].tank);
            game.physics.arcade.collide(enemies[i].tank, sandbags);
            game.physics.arcade.collide(enemies[i].tank, barrelGrey);
            enemies[i].update();
        }
    }

    function render() {
        game.debug.cameraInfo(game.camera, 32, 64);
    }
}());
<commit_msg>Boom tanks<commit_after>(function () {
    var game = new Phaser.Game(
        1024, 768, Phaser.AUTO, 'tankr',
        { preload: preload,
          create: create,
          update: update,
          render: render }
    );
    var map;
    var player;
    var turret;
    var cursors;
    var bullets;
    var explosions;
    var spacebar;
    var timer;
    var last_fired = 0;
    var reload_time = 400;
    var speed_units = 300;
    var speed_angle = 90;

    var enemies;
    var enemiesCount;

    var sandbagsCount = 15;
    var barrelGreyCount = 15;

    EnemyTank = function (index, game, player, bullets) {
        var x = game.world.randomX;
        var y = game.world.randomY;

        this.game = game;
        this.health = 3;
        this.player = player;
        this.bullets = bullets;
        this.fireRate = 1000;
        this.nextFire = 0;
        this.alive = true;

        this.tank = game.add.sprite(x, y, 'tankRed');
        this.tank.anchor.setTo(0.5, 0.5);
        this.turret = game.add.sprite(x, y, 'barrelRed');
        this.tank.turret = this.turret;

        this.tank.name = index.toString();
        game.physics.enable(this.tank, Phaser.Physics.ARCADE);
        this.tank.body.immovable = true;
        this.tank.body.collideWorldBounds = true;
        this.tank.body.bounce.setTo(1, 1);
    }

    EnemyTank.prototype.update = function() {
        this.turret.x = this.tank.x -7;
        this.turret.y = this.tank.y -50;
    }

    function hitBarrel (barrel, bullet) {
        var animation = explosions.getFirstExists(false);
        animation.reset(barrel.x, barrel.y);
        animation.play('kaboom', 30, false, true);

        barrel.kill();
        bullet.kill();
    }

    function hitEnemy (enemy, bullet) {
        enemy.health -= 0.5;
        if (enemy.health <= 0) {
            var animation = explosions.getFirstExists(false);
            animation.reset(enemy.x, enemy.y);
            animation.play('kaboom', 30, false, true);
            enemy.turret.kill();
            enemy.kill();
        }

        bullet.kill();
    }

    Math.degToRad = function (degrees) {
        return degrees * Math.PI / 180;
    };

    function preload() {
        // tanks
        game.load.image('tankBlue', 'assets/img/Tanks/tankBlue.png');
        game.load.image('tankRed', 'assets/img/Tanks/tankRed.png');
        game.load.image('barrelBlue', 'assets/img/Tanks/barrelBlue.png');
        game.load.image('barrelRed', 'assets/img/Tanks/barrelRed.png');
        game.load.image('bullet', 'assets/img/Bullets/bulletBlue.png');

        // terrain
        game.load.image('grass', 'assets/img/Environment/grass.png');

        // obstacles
        game.load.image('sandbagBrown', 'assets/img/Obstacles/sandbagBrown.png');
        game.load.image('barrelGrey', 'assets/img/Obstacles/barrelGrey_up.png');

        // 'splosions
        game.load.spritesheet('kaboom', 'assets/img/Smoke/explosion.png', 64, 64, 23);
    }

    function create() {
        game.world.setBounds(-1000, -1000, 2000, 2000);

        land = game.add.tileSprite(0, 0, 2000, 2000, 'grass');
        land.fixedToCamera = true;
        spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        player = game.add.sprite(game.world.centerX, game.world.centerY, 'tankBlue');
        player.anchor.setTo(0.5, 0.5);
        game.camera.follow(player);
        game.physics.enable(player, Phaser.Physics.ARCADE);
        game.physics.startSystem(Phaser.Physics.ARCADE);

        player.anchor.setTo(0.5, 0.5);
        turret = game.add.sprite(0, 0, 'barrelBlue');

        // add sandbags with collision
        sandbags = game.add.group();
        sandbags.physicsBodyType = Phaser.Physics.ARCADE;
        sandbags.enableBody = true;
        for (var i = 0; i < sandbagsCount; i++) {
            var sbag = sandbags.create(game.world.randomX, game.world.randomY, 'sandbagBrown');
            sbag.body.immovable = true;
        }

        // add empty barrels
        barrelGrey = game.add.group();
        barrelGrey.physicsBodyType = Phaser.Physics.ARCADE;
        barrelGrey.enableBody = true;

        for (var i = 0; i < barrelGreyCount; i++) {
            var bg = barrelGrey.create(game.world.randomX, game.world.randomY, 'barrelGrey');
            bg.body.onCollide = new Phaser.Signal();
            bg.body.onCollide.add(hitBarrel, this);
            bg.body.immovable = false;
        }

        cursors = game.input.keyboard.createCursorKeys();
        bullets = game.add.group();
        bullets.enableBody = true;
        bullets.physicsBodyType = Phaser.Physics.ARCADE;
        bullets.createMultiple(30, 'bullet', 0, false);
        bullets.setAll('anchor.x', 0.5);
        bullets.setAll('anchor.y', 0.5);
        bullets.setAll('outOfBoundsKill', true);
        bullets.setAll('checkWorldBounds', true);

        explosions = game.add.group();
        for (var i = 0; i < 10; i++) {
            var explosionAnimation = explosions.create(0, 0, 'kaboom', [0], false);
            explosionAnimation.anchor.setTo(0.5, 0.5);
            explosionAnimation.animations.add('kaboom');
        }
        // create enemies
        enemies = [];
        enemiesCount = 7;
        for (var i = 0; i < enemiesCount; i++) {
            enemy = new EnemyTank(i, game, player, []);
            enemy.tank.enableBody = true;
            enemies.push(enemy);
        }
    }

    function update() {
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;
        player.body.angularVelocity = 0;

        game.physics.arcade.collide(player, sandbags);
        game.physics.arcade.collide(player, barrelGrey);
        game.physics.arcade.collide(barrelGrey, bullets);
        for (var i=0; i<enemies.length; i++) {
            game.physics.arcade.collide(enemies[i].tank, bullets, hitEnemy);
        }

        if (cursors.left.isDown) {
            player.body.angularVelocity = -speed_angle;
        } else if (cursors.right.isDown) {
            player.body.angularVelocity = speed_angle;
        } else if (cursors.down.isDown) {
            game.physics.arcade.velocityFromAngle(
                player.angle + 90,
                speed_units,
                player.body.velocity
            );
        } else if (cursors.up.isDown) {
            game.physics.arcade.velocityFromAngle(
                player.angle + -90,
                speed_units,
                player.body.velocity
            );
        } else if (spacebar.isDown) {
            now = game.time.now;
            if (last_fired + reload_time < now) {
                var bullet = bullets.getFirstExists(false);

                bullet.reset(turret.x, turret.y);
                bullet.angle = player.angle;
                ix = player.x + 100 * Math.cos(Math.degToRad(player.angle - 90));
                iy = player.y + 100 * Math.sin(Math.degToRad(player.angle - 90));
                game.physics.arcade.moveToXY(bullet, ix, iy, 500);
                last_fired = now;
            }
        } else {
            player.animations.stop();
            player.frame = 4;
        }
        if (cursors.up.isDown && player.body.touching.down)
        {
            player.body.velocity.y = -350;
        }
        turret.x = player.x + 8;
        turret.y = player.y;
        turret.angle = 180 + player.angle;

        game.camera.x = player.x;
        game.camera.y = player.y;

        for (var i = 0; i < enemies.length; i++) {
            game.physics.arcade.collide(player, enemies[i].tank);
            game.physics.arcade.collide(enemies[i].tank, sandbags);
            game.physics.arcade.collide(enemies[i].tank, barrelGrey);
            enemies[i].update();
        }
    }

    function render() {
        game.debug.cameraInfo(game.camera, 32, 64);
    }
}());
<|endoftext|>


<commit_before>// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require('jasmine-spec-reporter');

// Waiting for the following issues to fix e2e tests using firebase
// - https://github.com/angular/protractor/issues/4300
// - https://github.com/angular/angularfire2/issues/19
// - https://github.com/angular/angularfire2/issues/779

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './e2e/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome'
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: () => undefined
  },
  onPrepare() {
    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};
<commit_msg>Reformat protractor config<commit_after>// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require('jasmine-spec-reporter');

// Waiting for the following issues to fix e2e tests using firebase
// - https://github.com/angular/protractor/issues/4300
// - https://github.com/angular/angularfire2/issues/19
// - https://github.com/angular/angularfire2/issues/779

exports.config = {
  allScriptsTimeout: 11000,
  specs: ['./e2e/**/*.e2e-spec.ts'],
  capabilities: {
    browserName: 'chrome'
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: () => {}
  },
  onPrepare() {
    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};
<|endoftext|>


<commit_before>import '../AsyncSupport';
import '../XMLDomInit';
import xmldom from 'xmldom';
import test from 'ava';
import sinon from 'sinon';
import GrimoireInterface from "../../lib-es5/GrimoireInterface";
import Constants from "../../lib-es5/Base/Constants";
import Component from "../../lib-es5/Node/Component";
import jsdomAsync from "../JsDOMAsync";
import GomlParser from "../../lib-es5/Node/GomlParser";
import GomlLoader from "../../lib-es5/Node/GomlLoader";
import NSIdentity from "../../lib-es5/Base/NSIdentity";
import GomlNode from "../../lib-es5/Node/GomlNode";

global.Node = {
  ELEMENT_NODE: 1
};

test.beforeEach(() => {
  GrimoireInterface.clear();
  const parser = new DOMParser();
  const htmlDoc = parser.parseFromString("", "text/html");
  global.document = htmlDoc;
  GrimoireInterface.registerNode("goml");
  GrimoireInterface.registerNode("scenes");
  GrimoireInterface.registerNode("scene")
});

test("addChild method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  node.addChild(node2, null, null);
  node.addChild(node2, null, null);
  t.truthy(node.children[0].id === node2.id);
  t.truthy(node.children.length === 2);
});

test("delete method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node2.delete();
  t.truthy(node.children.length === 0);
  t.truthy(node2.parent === null);
  t.truthy(node2.deleted === true);
  t.truthy(node3.deleted === true);
  t.truthy(node3.parent === null);
});

test("removeChild method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node.removeChild(node2);
  t.truthy(node2.deleted === true);
  t.truthy(node3.deleted === true);
});

test("detachChild method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node.detachChild(node2);
  t.truthy(node.children.length === 0);
  t.truthy(node2.deleted === false);
  t.truthy(node3.parent.id === node2.id);
  t.truthy(node3.deleted === false);
});

test("detach method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node2.detach();
  try {
    node.detach()
  } catch (err) {
    t.truthy(err.message === "root Node cannot be detached.");
  }
  t.truthy(node.children.length === 0);
  t.truthy(node2.deleted === false);
  t.truthy(node3.parent.id === node2.id);
  t.truthy(node3.deleted === false);
});

test("attr method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  t.truthy(false);
});

test("addAttribute method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  t.truthy(false);
});

test("getComponents method works correctly", t => {
  GrimoireInterface.registerComponent("testComponent", {
    attr1: "testAttr"
  });
  GrimoireInterface.registerNode("testNode", ["testComponent"]);
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("testNode"), null);
  const components = node.getComponents();
  t.truthy(components.length === 2);
  t.truthy(node._components[0].id === components[0].id);
});
test("getComponent method works correctly", t => {
  GrimoireInterface.registerComponent("testComponent", {
    attr1: "testAttr"
  });
  GrimoireInterface.registerComponent("testComponent2", {
    attr2: "testAttr2"
  });
});

test("setMounted method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node.setMounted(true);
  t.truthy(node.mounted === true);
  t.truthy(node2.mounted === true);
  t.truthy(node3.mounted === true);
});
test("index method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  node.addChild(node2, null, null);
  t.truthy(node2.index() === 0);
});
<commit_msg>fix: GomlNodeTest<commit_after>import '../AsyncSupport';
import '../XMLDomInit';
import xmldom from 'xmldom';
import test from 'ava';
import sinon from 'sinon';
import GrimoireInterface from "../../lib-es5/GrimoireInterface";
import Constants from "../../lib-es5/Base/Constants";
import Component from "../../lib-es5/Node/Component";
import jsdomAsync from "../JsDOMAsync";
import GomlParser from "../../lib-es5/Node/GomlParser";
import GomlLoader from "../../lib-es5/Node/GomlLoader";
import NSIdentity from "../../lib-es5/Base/NSIdentity";
import GomlNode from "../../lib-es5/Node/GomlNode";

global.Node = {
  ELEMENT_NODE: 1
};

test.beforeEach(() => {
  GrimoireInterface.clear();
  const parser = new DOMParser();
  const htmlDoc = parser.parseFromString("", "text/html");
  global.document = htmlDoc;
  GrimoireInterface.registerNode("goml");
  GrimoireInterface.registerNode("scenes");
  GrimoireInterface.registerNode("scene")
});

test("addChild method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  node.addChild(node2, null, null);
  node.addChild(node2, null, null);
  t.truthy(node.children[0].id === node2.id);
  t.truthy(node.children.length === 2);
});

test("delete method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node2.delete();
  t.truthy(node.children.length === 0);
  t.truthy(node2.parent === null);
  t.truthy(node2.deleted === true);
  t.truthy(node3.deleted === true);
  t.truthy(node3.parent === null);
});

test("removeChild method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node.removeChild(node2);
  t.truthy(node2.deleted === true);
  t.truthy(node3.deleted === true);
});

test("detachChild method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node.detachChild(node2);
  t.truthy(node.children.length === 0);
  t.truthy(node2.deleted === false);
  t.truthy(node3.parent.id === node2.id);
  t.truthy(node3.deleted === false);
});

test("detach method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node2.detach();
  try {
    node.detach()
  } catch (err) {
    t.truthy(err.message === "root Node cannot be detached.");
  }
  t.truthy(node.children.length === 0);
  t.truthy(node2.deleted === false);
  t.truthy(node3.parent.id === node2.id);
  t.truthy(node3.deleted === false);
});

test("getComponents method works correctly", t => {
  GrimoireInterface.registerComponent("testComponent", {
    attr1: "testAttr"
  });
  GrimoireInterface.registerNode("testNode", ["testComponent"]);
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("testNode"), null);
  const components = node.getComponents();
  t.truthy(components.length === 2);
  t.truthy(node._components[0].id === components[0].id);
});
test("getComponent method works correctly", t => {
  GrimoireInterface.registerComponent("testComponent", {
    attr1: "testAttr"
  });
  GrimoireInterface.registerComponent("testComponent2", {
    attr2: "testAttr2"
  });
});

test("setMounted method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  const node3 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scene"), null);
  node.addChild(node2, null, null);
  node2.addChild(node3, null, null);
  node.setMounted(true);
  t.truthy(node.mounted === true);
  t.truthy(node2.mounted === true);
  t.truthy(node3.mounted === true);
});
test("index method works correctly", t => {
  const node = new GomlNode(GrimoireInterface.nodeDeclarations.get("goml"), null);
  const node2 = new GomlNode(GrimoireInterface.nodeDeclarations.get("scenes"), null);
  node.addChild(node2, null, null);
  t.truthy(node2.index() === 0);
});
<|endoftext|>


<commit_before>var refresh_gui = true;
var editor = null;

var series_data = [{
    name: 'cu_workload',
    data: [],
    tooltip: {
        valueSuffix: ' %'
    }
}, {
    name: 'plb_workload',
    data: [],
    tooltip: {
        valueSuffix: ' %'
    }
}, {
    name: 'hs_temperature',
    data: [],
    tooltip: {
        valueSuffix: ' °C'
    }
}, {
    name: 'thermal_consumption',
    data: [],
    tooltip: {
        valueSuffix: ' kW'
    }
}, {
    name: 'outside_temperature',
    data: [],
    tooltip: {
        valueSuffix: ' °C'
    }
}, {
    name: 'electrical_consumption',
    data: [],
    tooltip: {
        valueSuffix: ' kW'
    }
}];

// READY
$(function() {
    initialize_editor();
    initialize_svg();
    initialize_hourly_demands();
    initialize_event_handlers();

    $.getJSON("./api/settings/", function(data) {
        update_setting(data);
    }).done(function() {
        $.getJSON("./api/code/", function(data) {
            editor.setValue(data['editor_code'], 1);
        }).done(function() {
            $.getJSON("./api/data/", function(data) {
                for (var i = 0; i < data['time'].length; i++) {
                    var timestamp = get_timestamp(data['time'][i]);
                    series_data[0]['data'].push([timestamp, parseFloat(data['cu_workload'][i])]);
                    series_data[1]['data'].push([timestamp, parseFloat(data['plb_workload'][i])]);
                    series_data[2]['data'].push([timestamp, parseFloat(data['hs_temperature'][i])]);
                    series_data[3]['data'].push([timestamp, parseFloat(data['thermal_consumption'][i])]);
                    series_data[4]['data'].push([timestamp, parseFloat(data['outside_temperature'][i])]);
                    series_data[5]['data'].push([timestamp, parseFloat(data['electrical_consumption'][i])]);
                };
            }).done(function() {
                initialize_diagram();
                // set up refresh loop
                setInterval(function() {
                    refresh();
                }, 2000);
            });
        });
    });
});

// UPDATING
function refresh() {
    if (refresh_gui) {
        $.getJSON("./api/data/", function(data) {
            update_setup(data);
            update_diagram(data);
        });
    }
}

function update_setup(data) {
    $.each(data, function(key, value) {
        value = value[value.length - 1];
        var item = $('.' + key);
        if (item.length) { // check if item exists
            switch (key) {
                case "time":
                    item.text(format_date(new Date(parseFloat(value) * 1000)));
                    break;
                case "code_execution_status":
                    if (value == 1) {
                        item.removeClass('badge-danger');
                        item.addClass('badge-success');
                        item.text('OK');
                    } else {
                        item.removeClass('badge-success');
                        item.addClass('badge-danger');
                        item.text('Fail');
                    }
                    break;
                default:
                    item.text(value + " " + systems_units[key]);
            }
        }
    });
}

function update_diagram(data) {
    var chart = $('#simulation_diagram').highcharts();

    new_data = [
        [],
        [],
        [],
        [],
        [],
        []
    ];
    for (var i = 0; i < data['time'].length; i++) {
        var timestamp = get_timestamp(data['time'][i]);
        new_data[0].push([timestamp, data['cu_workload'][i]]);
        new_data[1].push([timestamp, data['plb_workload'][i]]);
        new_data[2].push([timestamp, data['hs_temperature'][i]]);
        new_data[3].push([timestamp, data['thermal_consumption'][i]]);
        new_data[4].push([timestamp, data['outside_temperature'][i]]);
        new_data[5].push([timestamp, data['electrical_consumption'][i]]);
    };

    for (var i = new_data.length - 1; i >= 0; i--) {
        chart.series[i].setData(new_data[i], false);
    };

    chart.redraw();
}

function update_setting(data) {
    $.each(data, function(key, value) {
        switch (key) {
            case "daily_thermal_demand":
                $.each(value, function(index, hour_value) {
                    $("#daily_thermal_demand_" + index).slider("value", hour_value * 100);
                });
                break;
            case "daily_electrical_variation":
                $.each(value, function(index, hour_value) {
                    $("#daily_electrical_variation_" + index).slider("value", hour_value * 10000);
                });
                break;
            case "cu_mode":
                if (value == 0)
                    $("#cu_mode_thermal_driven").attr('checked', true);
                else
                    $("#cu_mode_electrical_driven").attr('checked', true);
                break;
            case "code_snippets":
                $.each(value, function(index, snippet_name) {
                    $("#snippets").append('<option>' + snippet_name + '</option>');
                });
                break;
            default:
                $("#form_" + key).val(value);
        }
    });
}

// INITIALIZATIONS
function initialize_editor() {
    ace.require("ace/ext/language_tools");
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/github");
    editor.getSession().setMode("ace/mode/python");
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true
    });
    ace.config.loadModule('ace/snippets/snippets', function() {
        var snippetManager = ace.require('ace/snippets').snippetManager;
        ace.config.loadModule('ace/snippets/python', function(m) {
            if (m) {
                m.snippets = m.snippets.concat(custom_snippets);
                snippetManager.register(m.snippets, m.scope);
            }
        });
    });
}

function initialize_svg() {
    $.get("./static/img/simulation.svg", function(data) {
        var svg_item = document.importNode(data.documentElement, true);
        $("#simulation_setup").append(svg_item);
    }, "xml");
}

function initialize_hourly_demands() {
    for (var i = 0; i < 24; i++) {
        $("#daily_thermal_demand").append("" + i + "");
        $("#daily_electrical_variation").append("" + i + "");
    }

    $(".slider_thermal").slider({
        value: 0,
        min: 0,
        max: 3000,
        range: "min",
        animate: true,
        orientation: "vertical",
        slide: function(event, ui) {
            var text = "(Current value: " + ui.value / 100 + "C)";
            $("#daily_thermal_demand_info").text(text);
        },
        stop: function(event, ui) {
            $("#daily_thermal_demand_info").text('');
        }
    });

    $(".slider_electrical").slider({
        value: 0,
        min: 0,
        max: 20000,
        range: "min",
        animate: true,
        orientation: "vertical",
        slide: function(event, ui) {
            var text = "(Current value: " + ui.value / 100 + "%)";
            $("#daily_electrical_variation_info").text(text);
        },
        stop: function(event, ui) {
            $("#daily_electrical_variation_info").text('');
        }
    });
}

function initialize_event_handlers() {
    $("#settings").submit(function(event) {
        var post_data = $("#settings").serialize();
        for (var i = 0; i < 24; i++) {
            post_data += "&daily_thermal_demand_" + i + "=" + ($("#daily_thermal_demand_" + i).slider("value") / 100);
        }
        for (var i = 0; i < 24; i++) {
            post_data += "&daily_electrical_variation_" + i + "=" + ($("#daily_electrical_variation_" + i).slider("value") / 10000);
        }
        $.post("./api/settings/", post_data, function(data) {
            $("#settings_button").removeClass("btn-primary");
            $("#settings_button").addClass("btn-success");
            update_setting(data);
            setTimeout(function() {
                $("#settings_button").removeClass("btn-success");
                $("#settings_button").addClass("btn-primary");
            }, 500);
        });
        event.preventDefault();
    });

    $(".fast_forward_button").click(function(event) {
        $.post("./api/simulation/", {
            forward: $(this).val()
        });
    });

    $("#editor_button").click(function() {
        $.post("./api/settings/", {
            code: editor.getValue()
        }, function(data) {
            editor.setValue(data['editor_code'], 1);
        });
    });

    $("#pause_refresh").click(function(event) {
        refresh_gui = !refresh_gui;
        if (refresh_gui) {
            $("#pause_refresh span").removeClass('glyphicon-pause');
            $("#pause_refresh span").addClass('glyphicon-refresh');
        } else {
            $("#pause_refresh span").removeClass('glyphicon-refresh');
            $("#pause_refresh span").addClass('glyphicon-pause');

        }
        event.preventDefault();
    });

    $("#reset_simulation").click(function(event) {
        $.post("./api/simulation/", {
            reset: 1
        });
        // location.reload(true);
    });

    $("#save_snippet").submit(function(event) {
        $.post("./api/code/", {
            save_snippet: $("#snippet_name").val(),
            code: editor.getValue()
        }, function(data) {
            editor.setValue(data['editor_code'], 1);

            // refresh snippet list
            if ('code_snippets' in data) {
                $("#snippets").html('');
                $.each(data['code_snippets'], function(index, snippet_name) {
                    $("#snippets").append('<option>' + snippet_name + '</option>');
                });
            }
        });
        event.preventDefault();
    });

    $("#load_snippet").submit(function(event) {
        $.post("./api/code/", {
            snippet: $("#snippets").val()
        }, function(data) {
            editor.setValue(data['editor_code'], 1);
        });
        event.preventDefault();
    });

    $("#export_data").submit(function(event) {
        $.post("./api/simulation/", {
            export: $("#export_name").val()
        });
        event.preventDefault();
    });
}

function initialize_diagram() {
    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });

    // Create the chart
    $('#simulation_diagram').highcharts('StockChart', {
        chart: {
            height: 400,
            zoomType: 'x'
        },
        rangeSelector: {
            buttons: [{
                count: 6,
                type: 'hour',
                text: '6H'
            }, {
                count: 12,
                type: 'hour',
                text: '12H'
            }, {
                count: 1,
                type: 'day',
                text: '1D'
            }, {
                count: 1,
                type: 'week',
                text: '1W'
            }, {
                count: 2,
                type: 'week',
                text: '2W'
            }, {
                count: 1,
                type: 'month',
                text: '1M'
            }, {
                count: 6,
                type: 'month',
                text: '6M'
            }, {
                type: 'all',
                text: 'All'
            }],
            selected: 2,
            inputEnabled: false
        },
        yAxis: {
            min: -10
        },
        tooltip: {
            valueDecimals: 2
        },
        plotOptions: {
            series: {
                marker: {
                    enabled: false
                },
                lineWidth: 1,
            }
        },
        series: series_data,
        credits: {
            enabled: false
        }
    });
}

// HELPERS
function format_date(date) {
    date = date.toString();
    return date.substring(0, date.length - 15);
}

function get_timestamp(string) {
    return new Date(parseFloat(string) * 1000).getTime();
}<commit_msg>xy zooming enabled<commit_after>var refresh_gui = true;
var editor = null;

var series_data = [{
    name: 'cu_workload',
    data: [],
    tooltip: {
        valueSuffix: ' %'
    }
}, {
    name: 'plb_workload',
    data: [],
    tooltip: {
        valueSuffix: ' %'
    }
}, {
    name: 'hs_temperature',
    data: [],
    tooltip: {
        valueSuffix: ' °C'
    }
}, {
    name: 'thermal_consumption',
    data: [],
    tooltip: {
        valueSuffix: ' kW'
    }
}, {
    name: 'outside_temperature',
    data: [],
    tooltip: {
        valueSuffix: ' °C'
    }
}, {
    name: 'electrical_consumption',
    data: [],
    tooltip: {
        valueSuffix: ' kW'
    }
}];

// READY
$(function() {
    initialize_editor();
    initialize_svg();
    initialize_hourly_demands();
    initialize_event_handlers();

    $.getJSON("./api/settings/", function(data) {
        update_setting(data);
    }).done(function() {
        $.getJSON("./api/code/", function(data) {
            editor.setValue(data['editor_code'], 1);
        }).done(function() {
            $.getJSON("./api/data/", function(data) {
                for (var i = 0; i < data['time'].length; i++) {
                    var timestamp = get_timestamp(data['time'][i]);
                    series_data[0]['data'].push([timestamp, parseFloat(data['cu_workload'][i])]);
                    series_data[1]['data'].push([timestamp, parseFloat(data['plb_workload'][i])]);
                    series_data[2]['data'].push([timestamp, parseFloat(data['hs_temperature'][i])]);
                    series_data[3]['data'].push([timestamp, parseFloat(data['thermal_consumption'][i])]);
                    series_data[4]['data'].push([timestamp, parseFloat(data['outside_temperature'][i])]);
                    series_data[5]['data'].push([timestamp, parseFloat(data['electrical_consumption'][i])]);
                };
            }).done(function() {
                initialize_diagram();
                // set up refresh loop
                setInterval(function() {
                    refresh();
                }, 2000);
            });
        });
    });
});

// UPDATING
function refresh() {
    if (refresh_gui) {
        $.getJSON("./api/data/", function(data) {
            update_setup(data);
            update_diagram(data);
        });
    }
}

function update_setup(data) {
    $.each(data, function(key, value) {
        value = value[value.length - 1];
        var item = $('.' + key);
        if (item.length) { // check if item exists
            switch (key) {
                case "time":
                    item.text(format_date(new Date(parseFloat(value) * 1000)));
                    break;
                case "code_execution_status":
                    if (value == 1) {
                        item.removeClass('badge-danger');
                        item.addClass('badge-success');
                        item.text('OK');
                    } else {
                        item.removeClass('badge-success');
                        item.addClass('badge-danger');
                        item.text('Fail');
                    }
                    break;
                default:
                    item.text(value + " " + systems_units[key]);
            }
        }
    });
}

function update_diagram(data) {
    var chart = $('#simulation_diagram').highcharts();

    new_data = [
        [],
        [],
        [],
        [],
        [],
        []
    ];
    for (var i = 0; i < data['time'].length; i++) {
        var timestamp = get_timestamp(data['time'][i]);
        new_data[0].push([timestamp, data['cu_workload'][i]]);
        new_data[1].push([timestamp, data['plb_workload'][i]]);
        new_data[2].push([timestamp, data['hs_temperature'][i]]);
        new_data[3].push([timestamp, data['thermal_consumption'][i]]);
        new_data[4].push([timestamp, data['outside_temperature'][i]]);
        new_data[5].push([timestamp, data['electrical_consumption'][i]]);
    };

    for (var i = new_data.length - 1; i >= 0; i--) {
        chart.series[i].setData(new_data[i], false);
    };

    chart.redraw();
}

function update_setting(data) {
    $.each(data, function(key, value) {
        switch (key) {
            case "daily_thermal_demand":
                $.each(value, function(index, hour_value) {
                    $("#daily_thermal_demand_" + index).slider("value", hour_value * 100);
                });
                break;
            case "daily_electrical_variation":
                $.each(value, function(index, hour_value) {
                    $("#daily_electrical_variation_" + index).slider("value", hour_value * 10000);
                });
                break;
            case "cu_mode":
                if (value == 0)
                    $("#cu_mode_thermal_driven").attr('checked', true);
                else
                    $("#cu_mode_electrical_driven").attr('checked', true);
                break;
            case "code_snippets":
                $.each(value, function(index, snippet_name) {
                    $("#snippets").append('<option>' + snippet_name + '</option>');
                });
                break;
            default:
                $("#form_" + key).val(value);
        }
    });
}

// INITIALIZATIONS
function initialize_editor() {
    ace.require("ace/ext/language_tools");
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/github");
    editor.getSession().setMode("ace/mode/python");
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true
    });
    ace.config.loadModule('ace/snippets/snippets', function() {
        var snippetManager = ace.require('ace/snippets').snippetManager;
        ace.config.loadModule('ace/snippets/python', function(m) {
            if (m) {
                m.snippets = m.snippets.concat(custom_snippets);
                snippetManager.register(m.snippets, m.scope);
            }
        });
    });
}

function initialize_svg() {
    $.get("./static/img/simulation.svg", function(data) {
        var svg_item = document.importNode(data.documentElement, true);
        $("#simulation_setup").append(svg_item);
    }, "xml");
}

function initialize_hourly_demands() {
    for (var i = 0; i < 24; i++) {
        $("#daily_thermal_demand").append("" + i + "");
        $("#daily_electrical_variation").append("" + i + "");
    }

    $(".slider_thermal").slider({
        value: 0,
        min: 0,
        max: 3000,
        range: "min",
        animate: true,
        orientation: "vertical",
        slide: function(event, ui) {
            var text = "(Current value: " + ui.value / 100 + "C)";
            $("#daily_thermal_demand_info").text(text);
        },
        stop: function(event, ui) {
            $("#daily_thermal_demand_info").text('');
        }
    });

    $(".slider_electrical").slider({
        value: 0,
        min: 0,
        max: 20000,
        range: "min",
        animate: true,
        orientation: "vertical",
        slide: function(event, ui) {
            var text = "(Current value: " + ui.value / 100 + "%)";
            $("#daily_electrical_variation_info").text(text);
        },
        stop: function(event, ui) {
            $("#daily_electrical_variation_info").text('');
        }
    });
}

function initialize_event_handlers() {
    $("#settings").submit(function(event) {
        var post_data = $("#settings").serialize();
        for (var i = 0; i < 24; i++) {
            post_data += "&daily_thermal_demand_" + i + "=" + ($("#daily_thermal_demand_" + i).slider("value") / 100);
        }
        for (var i = 0; i < 24; i++) {
            post_data += "&daily_electrical_variation_" + i + "=" + ($("#daily_electrical_variation_" + i).slider("value") / 10000);
        }
        $.post("./api/settings/", post_data, function(data) {
            $("#settings_button").removeClass("btn-primary");
            $("#settings_button").addClass("btn-success");
            update_setting(data);
            setTimeout(function() {
                $("#settings_button").removeClass("btn-success");
                $("#settings_button").addClass("btn-primary");
            }, 500);
        });
        event.preventDefault();
    });

    $(".fast_forward_button").click(function(event) {
        $.post("./api/simulation/", {
            forward: $(this).val()
        });
    });

    $("#editor_button").click(function() {
        $.post("./api/settings/", {
            code: editor.getValue()
        }, function(data) {
            editor.setValue(data['editor_code'], 1);
        });
    });

    $("#pause_refresh").click(function(event) {
        refresh_gui = !refresh_gui;
        if (refresh_gui) {
            $("#pause_refresh span").removeClass('glyphicon-pause');
            $("#pause_refresh span").addClass('glyphicon-refresh');
        } else {
            $("#pause_refresh span").removeClass('glyphicon-refresh');
            $("#pause_refresh span").addClass('glyphicon-pause');

        }
        event.preventDefault();
    });

    $("#reset_simulation").click(function(event) {
        $.post("./api/simulation/", {
            reset: 1
        });
        // location.reload(true);
    });

    $("#save_snippet").submit(function(event) {
        $.post("./api/code/", {
            save_snippet: $("#snippet_name").val(),
            code: editor.getValue()
        }, function(data) {
            editor.setValue(data['editor_code'], 1);

            // refresh snippet list
            if ('code_snippets' in data) {
                $("#snippets").html('');
                $.each(data['code_snippets'], function(index, snippet_name) {
                    $("#snippets").append('<option>' + snippet_name + '</option>');
                });
            }
        });
        event.preventDefault();
    });

    $("#load_snippet").submit(function(event) {
        $.post("./api/code/", {
            snippet: $("#snippets").val()
        }, function(data) {
            editor.setValue(data['editor_code'], 1);
        });
        event.preventDefault();
    });

    $("#export_data").submit(function(event) {
        $.post("./api/simulation/", {
            export: $("#export_name").val()
        });
        event.preventDefault();
    });
}

function initialize_diagram() {
    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });

    // Create the chart
    $('#simulation_diagram').highcharts('StockChart', {
        chart: {
            height: 400,
            zoomType: 'xy'
        },
        rangeSelector: {
            buttons: [{
                count: 6,
                type: 'hour',
                text: '6H'
            }, {
                count: 12,
                type: 'hour',
                text: '12H'
            }, {
                count: 1,
                type: 'day',
                text: '1D'
            }, {
                count: 1,
                type: 'week',
                text: '1W'
            }, {
                count: 2,
                type: 'week',
                text: '2W'
            }, {
                count: 1,
                type: 'month',
                text: '1M'
            }, {
                count: 6,
                type: 'month',
                text: '6M'
            }, {
                type: 'all',
                text: 'All'
            }],
            selected: 2,
            inputEnabled: false
        },
        yAxis: {
            min: -10
        },
        tooltip: {
            valueDecimals: 2
        },
        plotOptions: {
            series: {
                marker: {
                    enabled: false
                },
                lineWidth: 1,
            }
        },
        series: series_data,
        credits: {
            enabled: false
        }
    });
}

// HELPERS
function format_date(date) {
    date = date.toString();
    return date.substring(0, date.length - 15);
}

function get_timestamp(string) {
    return new Date(parseFloat(string) * 1000).getTime();
}<|endoftext|>