<commit_before>const jpClient         = require('./country_base').jpClient;
const getLanguage      = require('../base/language').get;
const localize         = require('../base/localize').localize;
const getPropertyValue = require('../base/utility').getPropertyValue;

let currencies_config = {};

const formatMoney = (currency_value, amount, exclude_currency) => {
    if (amount) amount = String(amount).replace(/,/g, '');
    const sign = amount && Number(amount) < 0 ? '-' : '';
    const decimal_places = getDecimalPlaces(currency_value);
    let money;

    amount = isNaN(amount) ? 0 : Math.abs(amount);
    if (typeof Intl !== 'undefined') {
        const options = { minimumFractionDigits: decimal_places, maximumFractionDigits: decimal_places };
        money = new Intl.NumberFormat(getLanguage().toLowerCase().replace('_', '-'), options).format(amount);
    } else {
        money = addComma(amount, decimal_places);
    }

    return sign + (exclude_currency ? '' : formatCurrency(currency_value)) + money;
};

const formatCurrency = currency => `<span class="symbols ${(currency || '').toLowerCase()}"></span>`; // defined in binary-style

const addComma = (num, decimal_points, is_crypto) => {
    let number = String(num || 0).replace(/,/g, '');
    if (typeof decimal_points !== 'undefined') {
        number = (+number).toFixed(decimal_points);
    }
    if (is_crypto) {
        number = parseFloat(+number);
    }

    return number.toString().replace(/(^|[^\w.])(\d{4,})/g, ($0, $1, $2) => (
        $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, '$&,')
    ));
};

const getDecimalPlaces = currency => (
    currencies_config[currency] ? getPropertyValue(currencies_config, [currency, 'fractional_digits']) : (isCryptocurrency(currency) ? 8 : (jpClient() ? 0 : 2))
);

const setCurrencies = (website_status) => {
    currencies_config = website_status.currencies_config;
};

const isCryptocurrency = currency => /crypto/i.test(getPropertyValue(currencies_config, [currency, 'type']));

const crypto_config = {
    BTC: { name: 'Bitcoin',       min_payout: 0.005 },
    BCH: { name: 'Bitcoin Cash' },
    ETH: { name: 'Ether' },
    ETC: { name: 'Ether Classic' },
    LTC: { name: 'Litecoin',      min_payout: 0.1 },
};

const getCurrencyName = currency => localize(getPropertyValue(crypto_config, [currency, 'name']) || '');

const getMinPayout = currency => (
    jpClient() ?
        1 :
        (isCryptocurrency(currency) ?
            (getPropertyValue(currencies_config, [currency, 'stake_default']) || getPropertyValue(crypto_config, [currency, 'min_payout']) || 0.005) :
            10)
);

const getCurrencyList = (currencies) => {
    const $currencies = $('<select/>');
    const $fiat_currencies = $('<optgroup/>', { label: localize('Fiat Currency') });
    const $cryptocurrencies = $('<optgroup/>', { label: localize('Cryptocurrency') });

    currencies.forEach((currency) => {
        (isCryptocurrency(currency) ? $cryptocurrencies : $fiat_currencies)
            .append($('<option/>', { value: currency, text: currency }));
    });

    return $currencies.append($fiat_currencies.children().length ? $fiat_currencies : '').append($cryptocurrencies.children().length ? $cryptocurrencies : '');
};

module.exports = {
    formatMoney     : formatMoney,
    formatCurrency  : formatCurrency,
    addComma        : addComma,
    getDecimalPlaces: getDecimalPlaces,
    setCurrencies   : setCurrencies,
    getCurrencies   : () => currencies_config,
    isCryptocurrency: isCryptocurrency,
    getCurrencyName : getCurrencyName,
    getMinPayout    : getMinPayout,
    getCurrencyList : getCurrencyList,
};
<commit_msg>remove hardcoded values<commit_after>const jpClient         = require('./country_base').jpClient;
const getLanguage      = require('../base/language').get;
const localize         = require('../base/localize').localize;
const getPropertyValue = require('../base/utility').getPropertyValue;

let currencies_config = {};

const formatMoney = (currency_value, amount, exclude_currency) => {
    if (amount) amount = String(amount).replace(/,/g, '');
    const sign = amount && Number(amount) < 0 ? '-' : '';
    const decimal_places = getDecimalPlaces(currency_value);
    let money;

    amount = isNaN(amount) ? 0 : Math.abs(amount);
    if (typeof Intl !== 'undefined') {
        const options = { minimumFractionDigits: decimal_places, maximumFractionDigits: decimal_places };
        money = new Intl.NumberFormat(getLanguage().toLowerCase().replace('_', '-'), options).format(amount);
    } else {
        money = addComma(amount, decimal_places);
    }

    return sign + (exclude_currency ? '' : formatCurrency(currency_value)) + money;
};

const formatCurrency = currency => `<span class="symbols ${(currency || '').toLowerCase()}"></span>`; // defined in binary-style

const addComma = (num, decimal_points, is_crypto) => {
    let number = String(num || 0).replace(/,/g, '');
    if (typeof decimal_points !== 'undefined') {
        number = (+number).toFixed(decimal_points);
    }
    if (is_crypto) {
        number = parseFloat(+number);
    }

    return number.toString().replace(/(^|[^\w.])(\d{4,})/g, ($0, $1, $2) => (
        $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, '$&,')
    ));
};

const getDecimalPlaces = currency => (
    currencies_config[currency] ? getPropertyValue(currencies_config, [currency, 'fractional_digits']) : (isCryptocurrency(currency) ? 8 : (jpClient() ? 0 : 2))
);

const setCurrencies = (website_status) => {
    currencies_config = website_status.currencies_config;
};

const isCryptocurrency = currency => /crypto/i.test(getPropertyValue(currencies_config, [currency, 'type']));

const crypto_config = {
    BTC: { name: 'Bitcoin' },
    BCH: { name: 'Bitcoin Cash' },
    ETH: { name: 'Ether' },
    ETC: { name: 'Ether Classic' },
    LTC: { name: 'Litecoin' },
};

const getCurrencyName = currency => localize(getPropertyValue(crypto_config, [currency, 'name']) || '');

const getMinPayout = currency => (
    jpClient() ? 1 : (isCryptocurrency(currency) ? getPropertyValue(currencies_config, [currency, 'stake_default']) : 10)
);

const getCurrencyList = (currencies) => {
    const $currencies = $('<select/>');
    const $fiat_currencies = $('<optgroup/>', { label: localize('Fiat Currency') });
    const $cryptocurrencies = $('<optgroup/>', { label: localize('Cryptocurrency') });

    currencies.forEach((currency) => {
        (isCryptocurrency(currency) ? $cryptocurrencies : $fiat_currencies)
            .append($('<option/>', { value: currency, text: currency }));
    });

    return $currencies.append($fiat_currencies.children().length ? $fiat_currencies : '').append($cryptocurrencies.children().length ? $cryptocurrencies : '');
};

module.exports = {
    formatMoney     : formatMoney,
    formatCurrency  : formatCurrency,
    addComma        : addComma,
    getDecimalPlaces: getDecimalPlaces,
    setCurrencies   : setCurrencies,
    getCurrencies   : () => currencies_config,
    isCryptocurrency: isCryptocurrency,
    getCurrencyName : getCurrencyName,
    getMinPayout    : getMinPayout,
    getCurrencyList : getCurrencyList,
};
<|endoftext|>


<commit_before>"use strict";

const ImageData   = require("./ImageData");
const gm = require("gm").subClass({ imageMagick: true });

const cropSpec = /(\d+)x(\d+)([+-]\d+)?([+-]\d+)?(%)?/;

class ImageResizer {

    /**
     * Image Resizer
     * resize image with ImageMagick
     *
     * @constructor
     * @param Number width
     */
    constructor(options) {
        this.options = options;
    }

    /**
     * Execute resize
     *
     * @public
     * @param ImageData image
     * @return Promise
     */
    exec(image) {
      var sys = require('sys')

      var exec = require('child_process').exec;

      function puts(error, stdout, stderr) { sys.puts(stdout) }

      exec("convert --version", puts);

        console.log('Resize image: ' + image.fileName);
        console.log('Resize image size: ' + image.data.length);
        var toType = function(obj) {
            return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
        };
        console.log('image data type: ' + toType(image.data));
        const acl = this.options.acl;

        return new Promise((resolve, reject) => {
            var img = gm(new Buffer(image.data))
	              //.geometry(this.options.size.toString())
                      .toBuffer(function (err, buffer) {
                         console.log('buffer: ' + buffer.length);
                         if (err)
                           reject(err);
			 resolve(new ImageData(
						 image.fileName,
						 image.bucketName,
						 buffer,
						 image.headers,
						 acl
					      ));
			 })});

    }
}

module.exports = ImageResizer;
<commit_msg>log the size<commit_after>"use strict";

const ImageData   = require("./ImageData");
const gm = require("gm").subClass({ imageMagick: true });

const cropSpec = /(\d+)x(\d+)([+-]\d+)?([+-]\d+)?(%)?/;

class ImageResizer {

    /**
     * Image Resizer
     * resize image with ImageMagick
     *
     * @constructor
     * @param Number width
     */
    constructor(options) {
        this.options = options;
    }

    /**
     * Execute resize
     *
     * @public
     * @param ImageData image
     * @return Promise
     */
    exec(image) {
      var sys = require('sys')

      var exec = require('child_process').exec;

      function puts(error, stdout, stderr) { sys.puts(stdout) }

      exec("convert --version", puts);

        console.log('Resize image: ' + image.fileName);
        console.log('Resize image size: ' + image.data.length);
        var toType = function(obj) {
            return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
        };
        console.log('image data type: ' + toType(image.data));
        const acl = this.options.acl;

        return new Promise((resolve, reject) => {
            console.log('size: ' + this.options.size);
            var img = gm(new Buffer(image.data))

	              .geometry(this.options.size.toString())
                      .toBuffer(function (err, buffer) {
                         console.log('buffer: ' + buffer.length);
                         if (err)
                           reject(err);
			 resolve(new ImageData(
						 image.fileName,
						 image.bucketName,
						 buffer,
						 image.headers,
						 acl
					      ));
			 })});

    }
}

module.exports = ImageResizer;
<|endoftext|>


<commit_before>/**
 * Created by arminhammer on 11/18/15.
 */
console.log('Loaded!');
var P = require('bluebird');

var $ = jQuery = require('jquery');
window.$ = $;
require('bootstrap');
var m = require('mithril');
var _ = require('lodash');

//var ipcRenderer = P.promisifyAll(require('electron').ipcRenderer);

// In renderer process (web page).
var ipcRenderer = require('electron').ipcRenderer;
//console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"

var vpcs = m.prop([]);

var Resource = function(name, body) {
	this.name = name;
	this.body = body;
	this.inTemplate = m.prop(false);
};

var resources = {
	vpcs: []
};

console.log('Resources before');
console.log(resources.vpcs);

ipcRenderer.on('vpc-reply', function(event, res) {
	m.startComputation();
	res.Vpcs.forEach(function(vpc) {
		resources.vpcs.push(new Resource(vpc.VpcId, vpc));
	});
	m.endComputation();
});

ipcRenderer.send('vpc-request');

var ui = {
	controller: function() {
		this.resources = resources;
	},
	view: function(controller) {
		return ('div', [
			m('p', 'VPCs'),
			m('div', [
				controller.resources.vpcs.map(function(vpc) {
					console.log(vpc.name);
					console.log(vpc.inTemplate());
					//console.log(vpc);
					return m('div', [
						m('p', [
							m("input[type=checkbox]", { checked: vpc.inTemplate(), name: vpc.name, onclick: m.withAttr("checked", vpc.inTemplate ) }),
							vpc.name
						])
					])
				})
			])
		])
	}
};

m.mount(document.body,ui);
<commit_msg>Wrapping inTemplate m.prop into a function toggleInTemplate.<commit_after>/**
 * Created by arminhammer on 11/18/15.
 */
console.log('Loaded!');
var P = require('bluebird');

var $ = jQuery = require('jquery');
window.$ = $;
require('bootstrap');
var m = require('mithril');
var _ = require('lodash');

//var ipcRenderer = P.promisifyAll(require('electron').ipcRenderer);

// In renderer process (web page).
var ipcRenderer = require('electron').ipcRenderer;
//console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"

var vpcs = m.prop([]);

var Resource = function(name, body) {
	var self = this;
	self.name = name;
	self.body = body;
	self.inTemplate = m.prop(false);
	self.toggleInTemplate = function(setting) {
		console.log('toggled ' + setting);
		self.inTemplate(setting);
	}
};

var resources = {
	vpcs: []
};

console.log('Resources before');
console.log(resources.vpcs);

ipcRenderer.on('vpc-reply', function(event, res) {
	m.startComputation();
	res.Vpcs.forEach(function(vpc) {
		resources.vpcs.push(new Resource(vpc.VpcId, vpc));
	});
	m.endComputation();
});

ipcRenderer.send('vpc-request');

var ui = {
	controller: function() {
		this.resources = resources;
	},
	view: function(controller) {
		return ('div', [
			m('p', 'VPCs'),
			m('div', [
				controller.resources.vpcs.map(function(vpc) {
					console.log(vpc.name);
					console.log(vpc.inTemplate());
					//console.log(vpc);
					return m('div', [
						m('p', [
							m("input[type=checkbox]", { checked: vpc.inTemplate(), name: vpc.name, onclick: m.withAttr("checked", vpc.toggleInTemplate ) }),
							vpc.name
						])
					])
				})
			])
		])
	}
};

m.mount(document.body,ui);
<|endoftext|>


<commit_before>'use strict';

var lib = require('../lib'),
    path = require('path'),
    fs = require('fs-utils'),
    radic = require('radic'),
    _ = require('lodash'),
    util = radic.util,
    temp = require('temp'),
    yaml = require('js-yaml');

module.exports = function (grunt) {
    grunt.registerMultiTask('git', 'Git commands.', function () {
        var self = this;
        //var taskDone = this.async();
        var cwd = process.cwd();
        var ok = grunt.log.ok;
        var options = this.options({
            output: true
        });
        var commands = this.data.commands;

        var git = radic.binwraps.create('git');
        commands.forEach(function(command){
            var result = git.apply(git, command);
            if(options.output === true){
                grunt.log.writeln('code: ' + result.code);
                grunt.log.writeln(result.stdout);
            }
            //ok('Git command executed: ' + command[0]);
        });

        ok('Git commands executed');

        // Done
        //taskDone();
    });

};
<commit_msg>test commit<commit_after>'use strict';

var lib = require('../lib'),
    path = require('path'),
    fs = require('fs-utils'),
    radic = require('radic'),
    _ = require('lodash'),
    util = radic.util,
    temp = require('temp'),
    yaml = require('js-yaml');

module.exports = function (grunt) {
    grunt.registerMultiTask('git', 'Git commands.', function () {
        var self = this;
        //var taskDone = this.async();
        var cwd = process.cwd();
        var ok = grunt.log.ok;
        var options = this.options({
            output: true
        });
        var commands = this.data.commands;

        var git = radic.binwraps.create('git');
        commands.forEach(function(command){
            var result = git.apply(git, command);
            if(result.code === 1){
                grunt.verbose.error('Error: ' + result.stdout);
                grunt.log.error('An error occured');
                grunt.fail();
            }
            if(options.output === true){
                grunt.log.writeln('code: ' + result.code);
                grunt.log.writeln(result.stdout);
            }
        });

        ok('Git commands executed');

        // Done
        //taskDone();
    });

};
<|endoftext|>


<commit_before> // http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
// TODO - with massive messsages from serial reading a new channel/websocket/webworker would be nice to have
// TODO - possibly use promises (although I don't see the need at the moment)
// aysynch fun
// http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
// https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/
// http://embed.plnkr.co/EKvjs3izaQYNCMPuur6R/preview
// http://plnkr.co/edit/EKvjs3izaQYNCMPuur6R?p=preview
// https://docs.angularjs.org/api/ng/service/$q
// http://blog.thoughtram.io/angularjs/2015/01/14/exploring-angular-1.3-speed-up-with-applyAsync.html
// https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/

// communication begins with a synchronous /api/messages/getLocalServices
// the remote application will need to know
// #1 what service gateway we are attached too &
// #2 - runtime name

// TODO - gateways should make a hello() method available through their interface
// infomation returned - gateway name - mrl protokey ? & Runtime name

angular
.module('mrlapp.mrl', [])
.service('mrl', [function() {

        // The name of the gateway I am
        // currently attached to
        // tried to make these private ..
        // too much of a pain :P
        this.gateway;
        this.runtime;
        this.platform;

        var connected = false;

        var self = this;
        var instances = {};
        var registry = {};

        var transport = 'websocket';
        var socket = null;
        var callbacks = [];

        var msgCount = 0;

        // map of service names to callbacks
        var nameCallbackMap = {};
        // map of service types to callbacks
        var typeCallbackMap = {};
        // map of method names to callbacks
        var methodCallbackMap = {};

        if (typeof String.prototype.startsWith != 'function') {
            // see below for better implementation!
            String.prototype.startsWith = function(str) {
                return this.indexOf(str) === 0;
            };
        }

        function capitalize(string) {
            return string.charAt(0).toUpperCase() + string.slice(1);
        }

        this.getCallBackName = function(topicMethod) {
            // replacements
            if (topicMethod.startsWith("publish")) {
                return "on" + capitalize(topicMethod.substring(""))

            } else if (topicMethod.startsWith("get")) {
                return "get";
            }

            // no replacement - just pefix and capitalize
            // FIXME - subscribe to onMethod --- gets ---> onOnMethod :P
            return "on%s", capitalize(topicMethod);
        }

        // FIXME name would be subscribeToAllMsgs
        this.subscribeToMessages = function(callback) {
            callbacks.push(callback);
        };

        this.subscribeToService = function(callback, serviceName) {
            if (!(serviceName in nameCallbackMap)) {
                nameCallbackMap[serviceName] = [];
            }
            nameCallbackMap[serviceName].push(callback);
        }

        this.subscribeToType = function(callback, typeName) {
            if (!(typeName in typeCallbackMap)) {
                typeCallbackMap[typeName] = [];
            }
            typeCallbackMap[typeName].push(callback);
        }

        this.subscribeToMethod = function(callback, methodName) {
            if (!(methodName in methodCallbackMap)) {
                methodCallbackMap[methodName] = [];
            }
            methodCallbackMap[methodName].push(callback);
        }

        this.sendMessage = function(msg) {
            var json = jQuery.stringifyJSON(msg);
            this.sendRaw(json);
        };

        this.sendRaw = function(msg) {
            socket.push(msg);
            console.log('Sent msg: ' + msg);
        };

        // enternal onConnect event
        // happens when first connect with backend
        // currently its recieving and processing the
        // Runtime.getLocalServices method - but
        // this might change in the future

        var onConnect = function(inData) {

        }

        // since framework does not have a hello() onHello() defined
        // protocol - we are using Runtime.onLocalServices to do
        // initial processing of data after a connect
        this.onLocalServices = function(msg) {
            console.log('onLocalServices:');

            // find the gateway we are talking too
            // TODO make full service?
            // self.gateway = msg.sender;
            var gatewayName = msg.sender;
            self.platform = msg.data[0].platform;

            // instances update
            // find the name of the runtime
            // not sure if this is "right" - but this is how
            // it is in Java .. the instance map with a null protokey
            // is the "local" instance - dunno even if javascript supports a null/undefined
            // object member name :P - perhaps it should be the protokey of the gateway instead
            // of null
            instances["null"] = msg.data[0];
            sd = msg.data[0].serviceDirectory;

            // registry update
            for (var key in sd) {
                if (sd.hasOwnProperty(key)) {
                    // do stuff
                    var service = sd[key];
                    console.log("found " + key + " of type " + service.simpleName);
                    registry[key] = {};
                    registry[key] = service;
                    if (service.simpleName == "Runtime"){
                            // the one and only runtime
                            self.runtime = service;
                    }
                }
            }

            self.gateway = sd[gatewayName];
        }

        // onMessage gets all messaging from the Nettophere server
        // all asynchronous callbacks will be routhed here.  All
        // messages will be in a Message strucutre except for the
        // Atmosphere heartbeat

        this.onMessage = function(response) {
            ++msgCount;
            var body = response.responseBody;
            if (body == 'X') {
                console.log("heartbeat:", body);
            } else {
                var msg;
                try {
                    msg = jQuery.parseJSON(body);

                    // process name callbacks - most common
                    if (msg.sender in nameCallbackMap) {
                        cbs = nameCallbackMap[msg.sender];
                        for (var i = 0; i < cbs.length; i++) {
                            cbs[i](msg);
                        }
                    }

                    // TODO - type based callbacks - rare, except for Runtime

                    // process method callbacks - rare - possible collisions
                    // 'onHandleError' might be worthwhile - mrl managed error
                    if (msg.method in methodCallbackMap) {
                        cbs = methodCallbackMap[msg.method];
                        for (var i = 0; i < cbs.length; i++) {
                            cbs[i](msg);
                        }
                    }

                } catch (e) {
                    console.log('Error onMessage: ', e, body);
                    return;
                }
            }
        };

        this.onTransportFailure = function(errorMsg, request) {
            jQuery.atmosphere.info(errorMsg);
            if (window.EventSource) {
                request.fallbackTransport = "sse";
            } else {
                request.fallbackTransport = 'long-polling';
            }
            transport = request.fallbackTransport;
            console.log('Error: falling back to ' + transport + ' ' + errorMsg);
        };

        this.onClose = function(response) {
            console.log('websocket, onclose');
            if (response.state == "unsubscribe") {
                console.log('Info: ' + transport + ' closed.');
            }
        };

        this.onOpen = function(response) {
            console.log('Info: ' + transport + ' connection opened.');
        };

        // initial connect - purpose of this function is to establish
        // a connection with Atmosphere with the Nettophere backend.
        // It creates a request structure and assings mrl service methods
        // to that structure. request object is just a proxy for Atmosphere.
        // Configuration (different proxy) should allow
        this.connect = function(url, proxy) {
            var request = {
                url: url,
                transport: 'websocket',
                enableProtocol: true,
                trackMessageLength: true,
                logLevel: 'debug'
            };

            request.onOpen = this.onOpen;
            request.onClose = this.onClose;
            request.onTransportFailure = this.onTransportFailure;
            request.onMessage = this.onMessage;

            // setting up initial callback - this possibly will change
            // when the framework creates a "hello()" method
            this.subscribeToMethod(this.onLocalServices, 'onLocalServices');

            socket = $.atmosphere.subscribe(request);
        };
        // --------- ws end ---------------------

        // TODO createMessage
        this.createMessage = function(inName, inMethod, inParams) {
            var msg = {
                msgID: new Date().getTime(),
                name: inName,
                method: inMethod,
                data: inParams
            };
            return msg;
        }

        this.isUndefinedOrNull = function(val) {
            return angular.isUndefined(val) || val === null;
        }

        this.getService = function(name) {
            if (this.isUndefinedOrNull(registry[name])) {
                return null;
            }
            return registry[name];
        };

        this.addService = function(service) {
            registry[service.name] = service;
        };

        this.removeService = function(name) {
            delete registry[name];
        };

        this.sendTo = function(name, method, data) {
            console.log(arguments[0]);
            var args = Array.prototype.slice.call(arguments, 2);
            var msg = this.createMessage(name, method, args);
            msg.sendingMethod = 'sendTo';
            // console.log('SendTo:', msg);
            this.sendMessage(msg);
        };

        // IMPORTANT - subscribe subscribes
        this.subscribe = function(topicName, topicMethod) {
            this.sendTo(InstanceService.getName(),
            "subscribe", [publisherName, inMethod,
                outMethod]);
        };

        this.invoke = function(functionName, context) {
            var args = [].slice.call(arguments).splice(2);
            var namespaces = functionName.split(".");
            var func = namespaces.pop();
            for (var i = 0; i < namespaces.length; i++) {
                context = context[namespaces[i]];
            }
            return context[func].apply(this, args);
        }

        // FIXME - lazy loading Angular modules -
        // http://stackoverflow.com/questions/18591966/inject-module-dynamically-only-if-required
        // the following method should dynamically load the
        // Angular module
        // if not loaded &
        // instanciate a new instances with the (service)
        // data
        this.register = function(service) {
            registry[service.name] = {};
            registry[service.name] = service;

            // broadcast callback
            for (var i = 0; i < callbacks.length; i++) {
                callbacks[i](service);
            }
        }

        this.registerForServices = function(callback) {
            this.serviceListeners.push(callback);
        }

    // ws.subscribeToMessages(this.onMessage);

    }]);
<commit_msg>mrl.js<commit_after> // http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
// TODO - with massive messsages from serial reading a new channel/websocket/webworker would be nice to have
// TODO - possibly use promises (although I don't see the need at the moment)
// aysynch fun
// http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
// https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/
// http://embed.plnkr.co/EKvjs3izaQYNCMPuur6R/preview
// http://plnkr.co/edit/EKvjs3izaQYNCMPuur6R?p=preview
// https://docs.angularjs.org/api/ng/service/$q
// http://blog.thoughtram.io/angularjs/2015/01/14/exploring-angular-1.3-speed-up-with-applyAsync.html
// https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/

// communication begins with a synchronous /api/messages/getLocalServices
// the remote application will need to know
// #1 what service gateway we are attached too &
// #2 - runtime name

// TODO - gateways should make a hello() method available through their interface
// infomation returned - gateway name - mrl protokey ? & Runtime name

angular
.module('mrlapp.mrl', [])
.service('mrl', [function() {

        // The name of the gateway I am
        // currently attached to
        // tried to make these private ..
        // too much of a pain :P
        this.gateway;
        this.runtime;
        this.platform;

        var connected = false;

        var self = this;
        var instances = {};
        var registry = {};

        var transport = 'websocket';
        var socket = null;
        var callbacks = [];

        // connectivity related begins
        // required by AtmosphereJS
        // https://github.com/Atmosphere/atmosphere/wiki/jQuery.atmosphere.js-atmosphere.js-API
        this.url = document.location.origin.toString() + '/api/messages';
        this.transport = 'websocket';
        this.enableProtocol = true;
        this.trackMessageLength = true;
        this.logLevel = 'debug';
        // connectivity related end

        var msgCount = 0;

        // map of service names to callbacks
        var nameCallbackMap = {};
        // map of service types to callbacks
        var typeCallbackMap = {};
        // map of method names to callbacks
        var methodCallbackMap = {};

        if (typeof String.prototype.startsWith != 'function') {
            // see below for better implementation!
            String.prototype.startsWith = function(str) {
                return this.indexOf(str) === 0;
            };
        }

        function capitalize(string) {
            return string.charAt(0).toUpperCase() + string.slice(1);
        }

        this.getCallBackName = function(topicMethod) {
            // replacements
            if (topicMethod.startsWith("publish")) {
                return "on" + capitalize(topicMethod.substring(""))

            } else if (topicMethod.startsWith("get")) {
                return "get";
            }

            // no replacement - just pefix and capitalize
            // FIXME - subscribe to onMethod --- gets ---> onOnMethod :P
            return "on%s", capitalize(topicMethod);
        }

        // FIXME name would be subscribeToAllMsgs
        this.subscribeToMessages = function(callback) {
            callbacks.push(callback);
        };

        this.subscribeToService = function(callback, serviceName) {
            if (!(serviceName in nameCallbackMap)) {
                nameCallbackMap[serviceName] = [];
            }
            nameCallbackMap[serviceName].push(callback);
        }

        this.subscribeToType = function(callback, typeName) {
            if (!(typeName in typeCallbackMap)) {
                typeCallbackMap[typeName] = [];
            }
            typeCallbackMap[typeName].push(callback);
        }

        this.subscribeToMethod = function(callback, methodName) {
            if (!(methodName in methodCallbackMap)) {
                methodCallbackMap[methodName] = [];
            }
            methodCallbackMap[methodName].push(callback);
        }

        this.sendMessage = function(msg) {
            var json = jQuery.stringifyJSON(msg);
            this.sendRaw(json);
        };

        this.sendRaw = function(msg) {
            socket.push(msg);
            console.log('Sent msg: ' + msg);
        };

        // since framework does not have a hello() onHello() defined
        // protocol - we are using Runtime.onLocalServices to do
        // initial processing of data after a connect
        this.onLocalServices = function(msg) {
            console.log('onLocalServices:');

            // find the gateway we are talking too
            // TODO make full service?
            // self.gateway = msg.sender;
            var gatewayName = msg.sender;
            self.platform = msg.data[0].platform;

            // instances update
            // find the name of the runtime
            // not sure if this is "right" - but this is how
            // it is in Java .. the instance map with a null protokey
            // is the "local" instance - dunno even if javascript supports a null/undefined
            // object member name :P - perhaps it should be the protokey of the gateway instead
            // of null
            instances["null"] = msg.data[0];
            sd = msg.data[0].serviceDirectory;

            // registry update
            for (var key in sd) {
                if (sd.hasOwnProperty(key)) {
                    // do stuff
                    var service = sd[key];
                    console.log("found " + key + " of type " + service.simpleName);
                    registry[key] = {};
                    registry[key] = service;
                    if (service.simpleName == "Runtime"){
                            // the one and only runtime
                            self.runtime = service;
                    }
                }
            }

            self.gateway = sd[gatewayName];

            // ok now we are connected
            this.connected = true;
        }

        // onMessage gets all messaging from the Nettophere server
        // all asynchronous callbacks will be routhed here.  All
        // messages will be in a Message strucutre except for the
        // Atmosphere heartbeat

        this.onMessage = function(response) {
            ++msgCount;
            var body = response.responseBody;
            if (body == 'X') {
                console.log("heartbeat:", body);
            } else {
                var msg;
                try {
                    msg = jQuery.parseJSON(body);

                    // process name callbacks - most common
                    if (msg.sender in nameCallbackMap) {
                        cbs = nameCallbackMap[msg.sender];
                        for (var i = 0; i < cbs.length; i++) {
                            cbs[i](msg);
                        }
                    }

                    // TODO - type based callbacks - rare, except for Runtime

                    // process method callbacks - rare - possible collisions
                    // 'onHandleError' might be worthwhile - mrl managed error
                    if (msg.method in methodCallbackMap) {
                        cbs = methodCallbackMap[msg.method];
                        for (var i = 0; i < cbs.length; i++) {
                            cbs[i](msg);
                        }
                    }

                } catch (e) {
                    console.log('Error onMessage: ', e, body);
                    return;
                }
            }
        };

        this.onTransportFailure = function(errorMsg, request) {
            jQuery.atmosphere.info(errorMsg);
            if (window.EventSource) {
                request.fallbackTransport = "sse";
            } else {
                request.fallbackTransport = 'long-polling';
            }
            transport = request.fallbackTransport;
            console.log('Error: falling back to ' + transport + ' ' + errorMsg);
        };

        this.onClose = function(response) {
            this.connected = false;
            console.log('websocket, onclose');
            if (response.state == "unsubscribe") {
                console.log('Info: ' + transport + ' closed.');
            }
        };

        this.onOpen = function(response) {
            // this.connected = true; mrl.isConnected means data
            // was asked and recieved from the backend
            console.log('Info: ' + transport + ' connection opened.');
        };

        this.isConnected = function() {
            return connected;
        }

        // initial connect - purpose of this function is to establish
        // a connection with Atmosphere with the Nettophere backend.
        // It creates a request structure and assings mrl service methods
        // to that structure. request object is just a proxy for Atmosphere.
        // Configuration (different proxy) should allow
        this.connect = function(url, proxy) {

            if (connected) {
                console.log("aleady connected");
                return;
            }

            // TODO - use proxy for connectionless testing
            if (url != undefined && url != null) {
                this.url = url;
            }

            // FIXME - make a hello() protocol !!
            // setting up initial callback - this possibly will change
            // when the framework creates a "hello()" method
            this.subscribeToMethod(this.onLocalServices, 'onLocalServices');

            socket = $.atmosphere.subscribe(this);
        };
        // --------- ws end ---------------------

        // TODO createMessage
        this.createMessage = function(inName, inMethod, inParams) {
            var msg = {
                msgID: new Date().getTime(),
                name: inName,
                method: inMethod,
                data: inParams
            };
            return msg;
        }

        this.isUndefinedOrNull = function(val) {
            return angular.isUndefined(val) || val === null;
        }

        this.getService = function(name) {
            if (this.isUndefinedOrNull(registry[name])) {
                return null;
            }
            return registry[name];
        };

        this.addService = function(service) {
            registry[service.name] = service;
        };

        this.removeService = function(name) {
            delete registry[name];
        };

        this.sendTo = function(name, method, data) {
            console.log(arguments[0]);
            var args = Array.prototype.slice.call(arguments, 2);
            var msg = this.createMessage(name, method, args);
            msg.sendingMethod = 'sendTo';
            // console.log('SendTo:', msg);
            this.sendMessage(msg);
        };

        // IMPORTANT - subscribe subscribes
        this.subscribe = function(topicName, topicMethod) {
            this.sendTo(InstanceService.getName(),
            "subscribe", [publisherName, inMethod,
                outMethod]);
        };

        this.invoke = function(functionName, context) {
            var args = [].slice.call(arguments).splice(2);
            var namespaces = functionName.split(".");
            var func = namespaces.pop();
            for (var i = 0; i < namespaces.length; i++) {
                context = context[namespaces[i]];
            }
            return context[func].apply(this, args);
        }

        // FIXME - lazy loading Angular modules -
        // http://stackoverflow.com/questions/18591966/inject-module-dynamically-only-if-required
        // the following method should dynamically load the
        // Angular module
        // if not loaded &
        // instanciate a new instances with the (service)
        // data
        this.register = function(service) {
            registry[service.name] = {};
            registry[service.name] = service;

            // broadcast callback
            for (var i = 0; i < callbacks.length; i++) {
                callbacks[i](service);
            }
        }

        this.registerForServices = function(callback) {
            this.serviceListeners.push(callback);
        }

    // ws.subscribeToMessages(this.onMessage);

    }]);
<|endoftext|>


<commit_before>'use strict';

angular.module('nearby').controller('NearbyController', ['$scope', 'Breweries', 'geolocation', '$stateParams', 'uiGmapLogger', '$anchorScroll', '$location', 'usSpinnerService',
	function($scope, Breweries, geolocation, $stateParams, uiGmapLogger, $anchorScroll, $location, usSpinnerService) {

    // enable logging of google map info and error
    uiGmapLogger.doLog = true;

    $scope.breweries = []; // used to fetch data from brewerydb factory
    $scope.coords = {}; // user's current coordinates

    // pushing breweries data from $http request and place markers
    var handleSuccess = function(data, status){
      if (data.data){
        $scope.breweries = data.data;
        placeMarker();
      } else {
        $scope.breweries = [{
          brewery: {
            name: 'Sorry',
            description: 'No breweries nearby'
          }
        }];
      }
      usSpinnerService.stop('spinner-1'); //stop the spinner
    };

    // function to access users geolocation coordinates, draw map and place markers
    geolocation.getLocation().then(function(data){
      // set to san francisco by Default for Victor
      // $scope.coords = {lat:37.7833, long:-122.4167};

      $scope.coords = {lat:data.coords.latitude, long:data.coords.longitude};
       $scope.map = { center: { latitude: $scope.coords.lat, longitude: $scope.coords.long }, zoom: 12}; // initialize the Google map
      curLocationMarker(); // add marker for current location
      Breweries.getData($scope.coords).success(handleSuccess); // get brewery data from factory
    });

    // marker for current coordinate
    $scope.title = 'You are here!';
    var curLocationMarker = function(){
      $scope.marker = {
        id: 'curLoc',
        coords: {
          latitude: $scope.coords.lat,
          longitude: $scope.coords.long,
        }
      };
    };

    $scope.closeClick = function() {
      $scope.windowOptions.visible = false;
    };

    // create markers for all breweries
    var createMarker = function (i) {
      // var hours = $scope.breweries[i].hoursOfOperation || '';
      // hours = hours.replace(/\n/g, "
");
      var name = $scope.breweries[i].brewery.name;
      var addr = $scope.breweries[i].streetAddress;
      var phone = $scope.breweries[i].phone;
      var id = $scope.breweries[i].brewery.id;
      var dist = $scope.breweries[i].distance;
      var desc = '' + name + '
' + dist + ' miles away
' + addr + '
' + phone + '
' + 'List their beers';
      var ret = {
        id: i,
        breweryId: id,
        coords: {
          latitude: $scope.breweries[i].latitude,
          longitude: $scope.breweries[i].longitude
        },
        options: {
          title: name
        },
        desc: desc,
        icon: '/modules/nearby/images/beer-icon.png',
        show: false
      };
      ret.onClick = function() {
        ret.show = !ret.show;
      };

      return ret;
    };

    $scope.allMarkers = []; // array to store the brewery markers
    var placeMarker = function() { // places all the brewery markers
      var markers = [];
      for (var i = 0; i < $scope.breweries.length; i++) {
        markers.push(createMarker(i));
      }
      $scope.allMarkers = markers;
    };

  }
]);
<commit_msg>added in check for Google Maps SDK ready<commit_after>'use strict';

angular.module('nearby').controller('NearbyController', ['$scope', 'uiGmapGoogleMapApi', 'Breweries', 'geolocation', 'uiGmapLogger', 'usSpinnerService',
	function($scope, uiGmapGoogleMapApi, Breweries, geolocation, uiGmapLogger, usSpinnerService) {

    // enable logging of google map info and error
    uiGmapLogger.doLog = true;

    $scope.breweries = []; // used to fetch data from brewerydb factory
    $scope.coords = {}; // user's current coordinates

uiGmapGoogleMapApi.then(function(maps) {

    // pushing breweries data from $http request and place markers
    var handleSuccess = function(data, status){
      if (data.data){
        $scope.breweries = data.data;
        placeMarker();
      } else {
        $scope.breweries = [{
          brewery: {
            name: 'Sorry',
            description: 'No breweries nearby'
          }
        }];
      }
      usSpinnerService.stop('spinner-1'); //stop the spinner
    };

    // function to access users geolocation coordinates, draw map and place markers
    geolocation.getLocation().then(function(data){
      // set to san francisco by Default for Victor
      // $scope.coords = {lat:37.7833, long:-122.4167};

      $scope.coords = {lat:data.coords.latitude, long:data.coords.longitude};
       $scope.map = { center: { latitude: $scope.coords.lat, longitude: $scope.coords.long }, zoom: 12}; // initialize the Google map
      curLocationMarker(); // add marker for current location
      Breweries.getData($scope.coords).success(handleSuccess); // get brewery data from factory
    });

    // marker for current coordinate
    $scope.title = 'You are here!';
    var curLocationMarker = function(){
      $scope.marker = {
        id: 'curLoc',
        coords: {
          latitude: $scope.coords.lat,
          longitude: $scope.coords.long,
        }
      };
    };

    $scope.closeClick = function() {
      $scope.windowOptions.visible = false;
    };

    // create markers for all breweries
    var createMarker = function (i) {
      // var hours = $scope.breweries[i].hoursOfOperation || '';
      // hours = hours.replace(/\n/g, "
");
      var name = $scope.breweries[i].brewery.name;
      var addr = $scope.breweries[i].streetAddress;
      var phone = $scope.breweries[i].phone;
      var id = $scope.breweries[i].brewery.id;
      var dist = $scope.breweries[i].distance;
      var desc = '' + name + '
' + dist + ' miles away
' + addr + '
' + phone + '
' + 'List their beers';
      var ret = {
        id: i,
        breweryId: id,
        coords: {
          latitude: $scope.breweries[i].latitude,
          longitude: $scope.breweries[i].longitude
        },
        options: {
          title: name
        },
        desc: desc,
        icon: '/modules/nearby/images/beer-icon.png',
        show: false
      };
      ret.onClick = function() {
        ret.show = !ret.show;
      };

      return ret;
    };

    $scope.allMarkers = []; // array to store the brewery markers
    var placeMarker = function() { // places all the brewery markers
      var markers = [];
      for (var i = 0; i < $scope.breweries.length; i++) {
        markers.push(createMarker(i));
      }
      $scope.allMarkers = markers;
    };

});

  }
]);
<|endoftext|>


<commit_before>var http=require("http");
var unmon={};

/* Your default stack */
var routes=unmon.routes=[];

/* route produces new routes, and pushes them to a stack */
var route=unmon.route=function(patt,f,opts){
    opts=opts||{}; // you don't have to provide options
    // make sure the discriminator is defined
    opts.disc=opts.disc||'url'; // your router parses by url by default
    opts.stack=opts.stack||routes; // you can provide an alternate stack

    // push your new route to the stack in question
    opts.stack.push(function(req,res,Next){
        // encapsulate Next so that we don't always have to pass req and res
        var next=function(){Next(req,res);};
        if(patt.test(req[opts.disc])){
            f(req,res,next);
        }else{
            next();
        }
    });
};

/*    makeRouter accepts a stack of routes and collapses it into a single function
        which is compatible with the NodeJS http api
        of the form function(request,response)    */
var makeRouter=unmon.makeRouter=function(stack){
    return stack.reduceRight(function(b,a,i,z){
        return function(req,res){
            a(req,res,b);
        };
    });
};

/* If being run as a standalone server, load routes and launch a server */

if(require.main === module){
    console.log("Running unmon as standalone script");

    var __dirname=process.argv[1].replace(/\/[^\/]*$/,'');
    console.log(__dirname);

    /* instantiate error logging behaviour
        this catches ALL uncaught exceptions
        which is possibly a security risk if your server SHOULD crash */
    global.logError=require("./lib/error.js")();

    /* This is where you add your routes */

    /* infer appropriate caching behaviour from requested urls */
    route(/.*/,require("./lib/cache")());

    /* Enable CORS headers for api access */
    route(/.*/,require("./lib/cors.js")());

    /* Log all requests to file */
    route(/.*/,require("./lib/logger.js")({path:process.env.PWD+'/log/'}));

    /* Process post requests and export them as req.postdata */
    route(/.*/,require("./lib/posted.js")());

    /* Templating and serverside scripting */
    route(/.*/,require("./lib/koan.js")({
        error:logError
    }));

    /* find and serve static files */
    route(/.*/,require("./lib/fixed")({
        path:__dirname+'/static'
    }));

    route(/\/shared\/.*/,require("./lib/directive")({
        path:__dirname+'/static/'
    }));

    /* load the blag plugin for serving templated markdown files */
    route(/.*/,require("./lib/blag.js")({path:process.env.PWD+"/md/",title:" "}));

    /* 404 as a last resort */
    route(/.*/,require("./lib/parcel.js")(process.env.PWD+"/static/html/404.html"));

    // produce a new router
    var router=makeRouter(routes)

    // make the port known globally for other scripts
    global.thisServersPort=8083;

    // bind to all ipv4 addresses by default
    var addresses=[''];

    // check if you have a unique local ipv6 address
    (function(){
        global.thisServersIPV6=require("./lib/fc.js")();
        if(thisServersIPV6)
            addresses.push(thisServersIPV6[0]);
    })();

    // instantiate and launch a server for each address in addresses
    var servers=addresses.map(function(addy){
        var server=http.createServer(router);
        server.listen(thisServersPort,addy,function(){
            console.log("unmon is running on %s:%s",addy,thisServersPort);
        });
        return server;
    });

}else{
    /*    If this module is being loaded as a library by another file
            just export the router functions */
    console.log("Exporting unmon as a library.");
    module.exports=unmon;
}
<commit_msg>unmon.js : add unmon.plugin. closes #2<commit_after>var http=require("http");
var unmon={};

/* Your default stack */
var routes=unmon.routes=[];

var debug=unmon.debug=true;

var plugin=unmon.plugin=function(name){
    var mod;

    if(unmon.debug){
        console.log("Loading %s plugin",name);
    }

    try{
        mod=require("./lib/"+name);
    }catch(err){
        if(unmon.debug){
            console.error("Error loading %s",name);
            console.error(err);
        }
    }
    return mod;
};

/* route produces new routes, and pushes them to a stack */
var route=unmon.route=function(patt,f,opts){
    opts=opts||{}; // you don't have to provide options
    // make sure the discriminator is defined
    opts.disc=opts.disc||'url'; // your router parses by url by default
    opts.stack=opts.stack||routes; // you can provide an alternate stack

    // push your new route to the stack in question
    opts.stack.push(function(req,res,Next){
        // encapsulate Next so that we don't always have to pass req and res
        var next=function(){Next(req,res);};
        if(patt.test(req[opts.disc])){
            f(req,res,next);
        }else{
            next();
        }
    });
};

/*    makeRouter accepts a stack of routes and collapses it into a single function
        which is compatible with the NodeJS http api
        of the form function(request,response)    */
var makeRouter=unmon.makeRouter=function(stack){
    return stack.reduceRight(function(b,a,i,z){
        return function(req,res){
            a(req,res,b);
        };
    });
};

/* If being run as a standalone server, load routes and launch a server */

if(require.main === module){
    console.log("Running unmon as standalone script");

    var __dirname=process.argv[1].replace(/\/[^\/]*$/,'');
    console.log(__dirname);

    /* instantiate error logging behaviour
        this catches ALL uncaught exceptions
        which is possibly a security risk if your server SHOULD crash */
    global.logError=plugin('error')();

    /* This is where you add your routes */

    /* infer appropriate caching behaviour from requested urls */
    route(/.*/,plugin('cache')());

    /* Enable CORS headers for api access */
    route(/.*/,plugin('cors')());

    /* Log all requests to file */
    route(/.*/,plugin('logger')({path:process.env.PWD+'/log/'}));

    /* Process post requests and export them as req.postdata */
    route(/.*/,plugin('posted')());

    /* Templating and serverside scripting */
    route(/.*/,plugin('koan')({
        error:logError
    }));

    /* find and serve static files */
    route(/.*/,plugin('fixed')({
        path:__dirname+'/static'
    }));

    route(/\/shared\/.*/,plugin('directive')({
        path:__dirname+'/static/'
    }));

    /* load the blag plugin for serving templated markdown files */
    route(/.*/,plugin('blag')({path:process.env.PWD+"/md/",title:" "}));

    /* 404 as a last resort */
    route(/.*/,plugin('parcel')(process.env.PWD+"/static/html/404.html"));

    // produce a new router
    var router=makeRouter(routes)

    // make the port known globally for other scripts
    global.thisServersPort=8083;

    // bind to all ipv4 addresses by default
    var addresses=[''];

    // check if you have a unique local ipv6 address
    (function(){
        global.thisServersIPV6=plugin('fc')();
        if(thisServersIPV6)
            addresses.push(thisServersIPV6[0]);
    })();

    // instantiate and launch a server for each address in addresses
    var servers=addresses.map(function(addy){
        var server=http.createServer(router);
        server.listen(thisServersPort,addy,function(){
            console.log("unmon is running on %s:%s",addy,thisServersPort);
        });
        return server;
    });

}else{
    /*    If this module is being loaded as a library by another file
            just export the router functions */
    console.log("Exporting unmon as a library.");
    module.exports=unmon;
}
<|endoftext|>


<commit_before>/* eslint-env mocha */

let chai = require('chai');
let expect = chai.expect;
let dirtyChai = require('dirty-chai');
let proxyquire = require('proxyquire');

let Graph = require('../../lib/graph');

chai.use(dirtyChai);

describe('Graph class module', () => {
  // Removes console printing for our modules
  console.error = () => {};
  describe('constructor', () => {
    let projectId = 1;
    let url = 'url';
    let stubs = {};
    let data = [];
    let Graph = proxyquire('../../lib/graph', {'./projects': stubs});
    let newGraph;
    let resolvedNamePromise = () => {
      return new Promise((resolve, reject) => {
        data = 'mocked project name';
        resolve(data);
      });
    };
    let resolvedItemsPromise = () => {
      return new Promise((resolve, reject) => {
        data = [{'id': 10, 'name': 'item name', 'type': 99}];
        resolve(data);
      });
    };
    let resolvedRelationshipsPromise = () => {
      return new Promise((resolve, reject) => {
        data = [{'id': 10, 'source': 1, 'target': 2, 'type': 99}];
        resolve(data);
      });
    };
    let rejectedTimeoutPromise = () => {
      return new Promise((resolve, reject) => {
        let error = { 'connect': true, 'code': 'ETIMEDOUT' };
        reject(error);
      });
    };
    let rejectedErrorPromise = () => {
      return new Promise((resolve, reject) => {
        let error = { 'statusCode': 401, 'status': 'Not found', 'connect': false, 'code': '' };
        reject(error);
      });
    };

    it('should return a graph with nonempty data members when project ID and url are valid.', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url);
      setTimeout(() => {
        expect(newGraph.name).to.equal('mocked project name');
        expect(newGraph.nodes[0].id).to.equal(10);
        expect(newGraph.nodes[0].name).to.equal('item name');
        expect(newGraph.nodes[0].type).to.equal(99);
        expect(newGraph.edges[0].id).to.equal(10);
        expect(newGraph.edges[0].source).to.equal(1);
        expect(newGraph.edges[0].target).to.equal(2);
        expect(newGraph.edges[0].type).to.equal(99);
      }, 5000);
    });

    it('should return a graph that contains nothing when either project ID or url are invalid.', () => {
      stubs.getProjectName = () => rejectedErrorPromise();
      stubs.getProjectItems = () => rejectedErrorPromise();
      stubs.getProjectRelationships = () => rejectedErrorPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
      console.log('------------------------------------------------');
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectItems', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectRelationships', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName and getProjectItems',
      () => {
        stubs.getProjectName = () => rejectedTimeoutPromise();
        stubs.getProjectItems = () => rejectedTimeoutPromise();
        stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
        newGraph = new Graph(projectId, url);
        expect(newGraph.name).to.be.empty();
        expect(newGraph.nodes).to.be.empty();
        expect(newGraph.edges).to.be.empty();
      });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectItems and' +
      'getProjectRelationships', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName and' +
      'getProjectRelationships', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for all three helper functions', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when an error not including timeout is encountered', () => {
      stubs.getProjectName = () => rejectedErrorPromise();
      stubs.getProjectItems = () => rejectedErrorPromise();
      stubs.getProjectRelationships = () => rejectedErrorPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });
  });

  describe('toJson function', () => {
    let badNodes = [{'id': '10', 'name': 'item name', 'type': '99'}];
    let badEdges = [{'id': '10', 'source': '1', 'target': '2', 'type': '99'}];
    let nodes = [{'id': 10, 'name': 'item name', 'type': 99, 'image': 'url'}];
    let edges = [{'id': 10, 'source': 1, 'target': 2, 'type': 99, 'suspect': true}];

    it('should print an error message if the data Graph contains is invalid', () => {
      let graph = new Graph();
      graph.nodes = badNodes;
      graph.edges = badEdges;
      expect(graph.toJson()).to.be.empty();
    });

    it('should return a valid relationship graph json object if Graph contains valid data', () => {
      let graph = new Graph();
      graph.nodes = nodes;
      graph.edges = edges;
      expect(graph.toJson()).to.not.be.empty();
    });
  });

  describe('fromJson function', () => {
    let badNodes = [{'id': '10', 'name': 'item name', 'type': '99'}];
    let badEdges = [{'id': '10', 'source': '1', 'target': '2', 'type': '99'}];
    let nodes = [{'id': 10, 'name': 'item name', 'type': 99, 'image': 'url'}];
    let edges = [{'id': 10, 'source': 1, 'target': 2, 'type': 99, 'suspect': false}];

    it('should print an error message if the data Graph contains is invalid', () => {
      let relGraphObj = {'items': badNodes, 'relationships': badEdges};
      expect(Graph.fromJson(relGraphObj)).to.be.null;
    });

    it('should return a valid relationship graph json object if graph contains valid data', () => {
      let graph = new Graph();
      graph.nodes = nodes;
      graph.edges = edges;
      let relGraphBlob = {'items': nodes, 'relationships': edges};
      let newGraph = Graph.fromJson(relGraphBlob);
      expect(newGraph.nodes).to.deep.equal(nodes);
      expect(newGraph.edges).to.deep.equal(edges);
    });
  });
});
<commit_msg>handle console errors<commit_after>/* eslint-env mocha */

let chai = require('chai');
let expect = chai.expect;
let dirtyChai = require('dirty-chai');
let proxyquire = require('proxyquire');

let Graph = require('../../lib/graph');

chai.use(dirtyChai);

describe('Graph class module', () => {
  // Removes console printing for our modules
  let oldError = console.error;
  before(() => {
    console.error = () => {};
  });
  after(() => {
    console.error = oldError;
  });
  describe('constructor', () => {
    let projectId = 1;
    let url = 'url';
    let stubs = {};
    let data = [];
    let Graph = proxyquire('../../lib/graph', {'./projects': stubs});
    let newGraph;
    let resolvedNamePromise = () => {
      return new Promise((resolve, reject) => {
        data = 'mocked project name';
        resolve(data);
      });
    };
    let resolvedItemsPromise = () => {
      return new Promise((resolve, reject) => {
        data = [{'id': 10, 'name': 'item name', 'type': 99}];
        resolve(data);
      });
    };
    let resolvedRelationshipsPromise = () => {
      return new Promise((resolve, reject) => {
        data = [{'id': 10, 'source': 1, 'target': 2, 'type': 99}];
        resolve(data);
      });
    };
    let rejectedTimeoutPromise = () => {
      return new Promise((resolve, reject) => {
        let error = { 'connect': true, 'code': 'ETIMEDOUT' };
        reject(error);
      });
    };
    let rejectedErrorPromise = () => {
      return new Promise((resolve, reject) => {
        let error = { 'statusCode': 401, 'status': 'Not found', 'connect': false, 'code': '' };
        reject(error);
      });
    };

    it('should return a graph with nonempty data members when project ID and url are valid.', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url);
      setTimeout(() => {
        expect(newGraph.name).to.equal('mocked project name');
        expect(newGraph.nodes[0].id).to.equal(10);
        expect(newGraph.nodes[0].name).to.equal('item name');
        expect(newGraph.nodes[0].type).to.equal(99);
        expect(newGraph.edges[0].id).to.equal(10);
        expect(newGraph.edges[0].source).to.equal(1);
        expect(newGraph.edges[0].target).to.equal(2);
        expect(newGraph.edges[0].type).to.equal(99);
      }, 5000);
    });

    it('should return a graph that contains nothing when either project ID or url are invalid.', () => {
      stubs.getProjectName = () => rejectedErrorPromise();
      stubs.getProjectItems = () => rejectedErrorPromise();
      stubs.getProjectRelationships = () => rejectedErrorPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectItems', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectRelationships', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName and getProjectItems',
      () => {
        stubs.getProjectName = () => rejectedTimeoutPromise();
        stubs.getProjectItems = () => rejectedTimeoutPromise();
        stubs.getProjectRelationships = () => resolvedRelationshipsPromise();
        newGraph = new Graph(projectId, url);
        expect(newGraph.name).to.be.empty();
        expect(newGraph.nodes).to.be.empty();
        expect(newGraph.edges).to.be.empty();
      });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectItems and' +
      'getProjectRelationships', () => {
      stubs.getProjectName = () => resolvedNamePromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for getProjectName and' +
      'getProjectRelationships', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => resolvedItemsPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when a timeout has occurred for all three helper functions', () => {
      stubs.getProjectName = () => rejectedTimeoutPromise();
      stubs.getProjectItems = () => rejectedTimeoutPromise();
      stubs.getProjectRelationships = () => rejectedTimeoutPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });

    it('should return a graph that contains nothing when an error not including timeout is encountered', () => {
      stubs.getProjectName = () => rejectedErrorPromise();
      stubs.getProjectItems = () => rejectedErrorPromise();
      stubs.getProjectRelationships = () => rejectedErrorPromise();
      newGraph = new Graph(projectId, url);
      expect(newGraph.name).to.be.empty();
      expect(newGraph.nodes).to.be.empty();
      expect(newGraph.edges).to.be.empty();
    });
  });

  describe('toJson function', () => {
    let badNodes = [{'id': '10', 'name': 'item name', 'type': '99'}];
    let badEdges = [{'id': '10', 'source': '1', 'target': '2', 'type': '99'}];
    let nodes = [{'id': 10, 'name': 'item name', 'type': 99, 'image': 'url'}];
    let edges = [{'id': 10, 'source': 1, 'target': 2, 'type': 99, 'suspect': true}];

    it('should print an error message if the data Graph contains is invalid', () => {
      let graph = new Graph();
      graph.nodes = badNodes;
      graph.edges = badEdges;
      expect(graph.toJson()).to.be.empty();
    });

    it('should return a valid relationship graph json object if Graph contains valid data', () => {
      let graph = new Graph();
      graph.nodes = nodes;
      graph.edges = edges;
      expect(graph.toJson()).to.not.be.empty();
    });
  });

  describe('fromJson function', () => {
    let badNodes = [{'id': '10', 'name': 'item name', 'type': '99'}];
    let badEdges = [{'id': '10', 'source': '1', 'target': '2', 'type': '99'}];
    let nodes = [{'id': 10, 'name': 'item name', 'type': 99, 'image': 'url'}];
    let edges = [{'id': 10, 'source': 1, 'target': 2, 'type': 99, 'suspect': false}];

    it('should print an error message if the data Graph contains is invalid', () => {
      let relGraphObj = {'items': badNodes, 'relationships': badEdges};
      expect(Graph.fromJson(relGraphObj)).to.be.null;
    });

    it('should return a valid relationship graph json object if graph contains valid data', () => {
      let graph = new Graph();
      graph.nodes = nodes;
      graph.edges = edges;
      let relGraphBlob = {'items': nodes, 'relationships': edges};
      let newGraph = Graph.fromJson(relGraphBlob);
      expect(newGraph.nodes).to.deep.equal(nodes);
      expect(newGraph.edges).to.deep.equal(edges);
    });
  });
});
<|endoftext|>


<commit_before>var XHR = function(method, ad, params) {
	var xhr = new XMLHttpRequest();
	xhr.onload = params.onload || null;
	xhr.open(method, ad);
	if (method == 'POST') {
		xhr.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded');
	}
	var variables = params.variables || null, str = '';
	for ( var i in variables) {
		str += i + '=' + encodeURIComponent(variables[i]) + '&';
	}
	xhr.send(str);
}

var endGame = false;
var waitingOther = false;

function endGameOrNot(){
    return endGame;
}

function authorizeMove(sens, configPlateau, ligne, colonne){
                     if(sens == "d"){
                        if(configPlateau.board[line][l].g == 1){
                             $(".ligne"+line+" "+".colonne"+(l-1)).addClass("case_deplacement");
                            return
                        }else if(configPlateau.board[line][l].d == 1){
                             $(".ligne"+line+" "+".colonne"+(l)).addClass("case_deplacement");
                            return
                        }
                     }
                }

function generatePlateau(idGame){
 			    XHR('GET', idGame, {onload: function() {

 						var configPlateau = JSON.parse(this.responseText);

                        printTable(configPlateau);

 					} } );
}

function printTable(configPlateau){
                    var table = new Array();
                    $("#board").empty();
 						for (var i = 0; i < configPlateau.board.length; i++) {
 							// $("#board").append("
");
                            var value = "";
 							for (var j = 0; j < configPlateau.board[i].length; j++) {
 								var border = flatArray(Object.keys(configPlateau.board[i][j]));
                                var classBorder = "";
                                if(border=="g"){
                                    classBorder = "bord_gauche";
                                }else if(border=="d"){
                                    classBorder = "bord_droit";
                                }else if(border=="b"){
                                    classBorder = "bord_bas";
                                }else if(border=="h"){
                                    classBorder = "bord_haut";
                                }else if(border=="gh" || border=="hg"){
                                    classBorder = "angle_haut_gauche";
                                }else if(border=="dh" || border=="hd"){
                                    classBorder = "angle_haut_droit";
                                }else if(border=="gb" || border=="bg"){
                                    classBorder = "angle_bas_gauche";
                                }else if(border=="db" || border=="bd"){
                                    classBorder = "angle_bas_droit";
                                }
 								value +="	";
 							};
 							$("#board").append("
"+value+"
");
 						};

                        var posRobot = new Array();
                        posRobot = configPlateau.robots;

                        for(var k = 0; k<posRobot.length; k++){
                            $(".ligne"+posRobot[k].line+" "+".colonne"+posRobot[k].column).html("

");
                            $(".ligne"+posRobot[k].line+" "+".colonne"+posRobot[k].column).attr('onclick','').unbind('click');
                        }

                        var posTarget = configPlateau.target;
                        $("#targetColor").val(posTarget.t);
                        $(".ligne"+posTarget.l+" "+".colonne"+posTarget.c).html("

");

                        var line = posRobot[0].line;

                        for(var l = posRobot[0].column+1; l<configPlateau.board[0].length ; l++){
                            var border = flatArray(Object.keys(configPlateau.board[line][l]));

// $(".ligne"+line+" "+".colonne"+(l)).addClass("case_deplacement");
                        }
                }

var solutions = {};

function init(idGame,idPlayer) {
	// Connect to the SocketIO server to retrieve ongoing games.
    generatePlateau(idGame);

	socket = io.connect();
	socket.on('participants', function(data) {
		var ul = document.getElementById('lesParticipants');
		ul.innerHTML = '';
		for (p in data.participants) {
			var li = document.createElement('li');
			ul.appendChild(li);
			li.appendChild(document.createTextNode(data.participants[p]));
		}
	});
	socket.on('FinalCountDown', function(data) {
        var ms = data.FinalCountDown;
        finalCountDown(ms/1000,ms/1000);
	});
	socket.on('TerminateGame', function(data) {
        endGame=true;
        if(endGame && solutions.solutions.length>0){
            determineWinner(idPlayer);
        }
	});
	socket.on('solutions', function(data) {
        console.log("solution ", data);
        solutions=data;
		var ul = document.getElementById('lesSolutions');
		ul.innerHTML = '';
		for (s in data.solutions) {
			var li = document.createElement('li');
			ul.appendChild(li);
			li.appendChild(document.createTextNode(data.solutions[s]));
		}
		console.log("Solutions are :\n" + JSON.stringify(data.solutions));
        if(endGame){
            determineWinneridPlayer
        }
	});
	socket.emit('identification', {
		login : document.getElementById('login').value,
		idGame : document.getElementById('idGame').value
	});
}

function determineWinner(idPlayer){
    $('#sendSolution').prop('disabled', true);
    $('#resetSolution').prop('disabled', true);
    var nameWinner = [];
    var propMin = 10000000;

    for(var i = 0; i<solutions.solutions.length; i++){
        if(solutions.solutions[i].proposition.length<propMin){
            propMin=solutions.solutions[i].proposition.length;
            nameWinner[nameWinner.length] = solutions.solutions[i].player;
        }
    }

    var winnerYou = false;

    if(nameWinner.length==1){
        console.log("Winner ",nameWinner[0]);
        winnerYou = winnerOrNot(nameWinner[0],idPlayer);
    }else{
        console.log("Ex eaquo ");
        for(var j = 0; j<nameWinner.length; j++){
            winnerYou = winnerOrNot(nameWinner[j],idPlayer);
        }
    }
    h1 = document.querySelector('body > header > h1');
    h1.innerHTML += ' est terminée !';
}

function winnerOrNot(playerWin, playerId){
    if(playerWin==playerId){
        console.log("You are the winner");
        return true;
    }
    return false;
}

function finalCountDown(time,all){
    if(!waitingOther){
            if(time>=0){
                $("#barre").css("width",((time*100)/all)+"%");
                $(".zone-nb-temps").html(time + "s");
            }
            if(time>0){
                time--;
                setTimeout("finalCountDown("+time+","+all+")", 1000);
            }else{
                //LOCK GAME
            }
    }else{
        $(".zone-nb-temps").html("En attente des autres joueurs");
    }

}

/**
 * Show the list of "participants"
 */
function showParticipants() {
	socket = io.connect();
	socket.on('participants', function(data) {
		var ul = document.getElementById('lesParticipants');
		ul.innerHTML = '';
		for (p in data.participants) {
			var li = document.createElement('li');
			ul.appendChild(li);
			li.appendChild(document.createTextNode(data.participants[p]));
		}
	});
	socket.emit('identification', {
		login : document.getElementById('login').value,
		idGame : document.getElementById('idGame').value
	});

}

/**
 * Propose a move for a robot
 */
function proposition(){
  var loginValue = document.getElementById('login').value;
  var idGameValue = document.getElementById('idGame').value;
  var jsonProposition = '['+document.getElementById('jsonProposition').value+']';

  XHR( "POST"
           , "/proposition"
           ,   {
           onload : function() {
             var reponseServer = JSON.parse(this.responseText);
             receivePropositionResponse(reponseServer);
               console.log(reponseServer);
               if(reponseServer.state=="SUCCESS"){
                    waitingOther = true;
                    $('#sendSolution').prop('disabled', true);
                    $('#resetSolution').prop('disabled', true);
               }

           }
           , variables : {
             login : loginValue
             , idGame : idGameValue
             , proposition : jsonProposition
           }
           }
     );
}

/**
 * Propose a single movement.
 * @param robotColor the color of the robot.
 * @param lineDestination the destination line.
 * @param columnDestination the destination column.
 */
function proposeSingleMovement(robotColor,lineDestination,columnDestination){
	  var loginValue = document.getElementById('login').value;
	  var idGameValue = document.getElementById('idGame').value;
	  var proposition = '[' +'{"command": "select" , "robot": "'+robotColor+'"} , {"command": "move" , "line": '+lineDestination+', "column": '+columnDestination+'}]';
	  XHR( "POST"
	           , "/proposition"
	           ,   {
	           onload : function() {
	             var reponseServer = JSON.parse(this.responseText);
	             receivePropositionResponse(reponseServer);

	           }
	           , variables : {
	             login : loginValue
	             , idGame : idGameValue
	             , proposition : proposition
	           }
	           }
	     );
}

/**
 * Reset the game
 */
function reset(){
	var idGame = $("#idGame").val();
	init(idGame);
	$("#moveState").text("");
    //$(".zone-nb-temps").html('<object xmlns="http://www.w3.org/1999/xhtml" data="medias/images-svg/infinity-icon.svg" type="image/svg+xml">infini</object>');
	$("#selectedRobotLine").val("");
	$("#selectedRobotColumn").val("");
	$("#selectedRobot").text("");
	$("#jsonProposition").val("");
	$("#nombreCoups").val("0");
	$(".zone-nb-coups").text("0");

}

/**
 * Manage the proposition response from the server.
 *
 * @param reponseServer
 *            the response from the server.
 */
function receivePropositionResponse(reponseServer){
	$("#jsonPropositionResponse").val(reponseServer.state);
	switch (reponseServer.state) {
	case "INVALID_EMPTY":
		document.getElementById('moveState').innerHTML = "Aucune proposition envoyée.";
		break;
	case "SUCCESS":
		document.getElementById('moveState').innerHTML = "Proposition valide !";
		break;
	case "INCOMPLETE":
		document.getElementById('moveState').innerHTML = "Proposition incomplète.";
		break;
	case "INVALID_MOVE":
		document.getElementById('moveState').innerHTML = "Un robot doit bouger le long d'une ligne ou d'une colonne jusqu'à ce qu'il rencontre un autre robot ou un mur.";
		break;
	case "INVALID_SELECT":
		document.getElementById('moveState').innerHTML = "Vous ne pouvez pas bouger un robot après l'avoir relaché.";
		break;
	default:
		document.getElementById('moveState').innerHTML = reponseServer.state;
		break;
	}
}
<commit_msg>Ajout pop in gagnant<commit_after>var XHR = function(method, ad, params) {
	var xhr = new XMLHttpRequest();
	xhr.onload = params.onload || null;
	xhr.open(method, ad);
	if (method == 'POST') {
		xhr.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded');
	}
	var variables = params.variables || null, str = '';
	for ( var i in variables) {
		str += i + '=' + encodeURIComponent(variables[i]) + '&';
	}
	xhr.send(str);
}

var endGame = false;
var waitingOther = false;

function endGameOrNot(){
    return endGame;
}

function authorizeMove(sens, configPlateau, ligne, colonne){
                     if(sens == "d"){
                        if(configPlateau.board[line][l].g == 1){
                             $(".ligne"+line+" "+".colonne"+(l-1)).addClass("case_deplacement");
                            return
                        }else if(configPlateau.board[line][l].d == 1){
                             $(".ligne"+line+" "+".colonne"+(l)).addClass("case_deplacement");
                            return
                        }
                     }
                }

function generatePlateau(idGame){
 			    XHR('GET', idGame, {onload: function() {

 						var configPlateau = JSON.parse(this.responseText);

                        printTable(configPlateau);

 					} } );
}

function printTable(configPlateau){
                    var table = new Array();
                    $("#board").empty();
 						for (var i = 0; i < configPlateau.board.length; i++) {
 							// $("#board").append("
");
                            var value = "";
 							for (var j = 0; j < configPlateau.board[i].length; j++) {
 								var border = flatArray(Object.keys(configPlateau.board[i][j]));
                                var classBorder = "";
                                if(border=="g"){
                                    classBorder = "bord_gauche";
                                }else if(border=="d"){
                                    classBorder = "bord_droit";
                                }else if(border=="b"){
                                    classBorder = "bord_bas";
                                }else if(border=="h"){
                                    classBorder = "bord_haut";
                                }else if(border=="gh" || border=="hg"){
                                    classBorder = "angle_haut_gauche";
                                }else if(border=="dh" || border=="hd"){
                                    classBorder = "angle_haut_droit";
                                }else if(border=="gb" || border=="bg"){
                                    classBorder = "angle_bas_gauche";
                                }else if(border=="db" || border=="bd"){
                                    classBorder = "angle_bas_droit";
                                }
 								value +="	";
 							};
 							$("#board").append("
"+value+"
");
 						};

                        var posRobot = new Array();
                        posRobot = configPlateau.robots;

                        for(var k = 0; k<posRobot.length; k++){
                            $(".ligne"+posRobot[k].line+" "+".colonne"+posRobot[k].column).html("

");
                            $(".ligne"+posRobot[k].line+" "+".colonne"+posRobot[k].column).attr('onclick','').unbind('click');
                        }

                        var posTarget = configPlateau.target;
                        $("#targetColor").val(posTarget.t);
                        $(".ligne"+posTarget.l+" "+".colonne"+posTarget.c).html("

");

                        var line = posRobot[0].line;

                        for(var l = posRobot[0].column+1; l<configPlateau.board[0].length ; l++){
                            var border = flatArray(Object.keys(configPlateau.board[line][l]));

// $(".ligne"+line+" "+".colonne"+(l)).addClass("case_deplacement");
                        }
                }

var solutions = {};

function init(idGame,idPlayer) {
	// Connect to the SocketIO server to retrieve ongoing games.
    generatePlateau(idGame);

	socket = io.connect();
	socket.on('participants', function(data) {
		var ul = document.getElementById('lesParticipants');
		ul.innerHTML = '';
		for (p in data.participants) {
			var li = document.createElement('li');
			ul.appendChild(li);
			li.appendChild(document.createTextNode(data.participants[p]));
		}
	});
	socket.on('FinalCountDown', function(data) {
        var ms = data.FinalCountDown;
        finalCountDown(ms/1000,ms/1000);
	});
	socket.on('TerminateGame', function(data) {
        endGame=true;
        if(endGame && solutions.solutions.length>0){
            determineWinner(idPlayer);
        }
	});
	socket.on('solutions', function(data) {
        console.log("solution ", data);
        solutions=data;
		var ul = document.getElementById('lesSolutions');
		ul.innerHTML = '';
		for (s in data.solutions) {
			var li = document.createElement('li');
			ul.appendChild(li);
			li.appendChild(document.createTextNode(data.solutions[s]));
		}
		console.log("Solutions are :\n" + JSON.stringify(data.solutions));
        if(endGame){
            determineWinner(idPlayer);
        }
	});
	socket.emit('identification', {
		login : document.getElementById('login').value,
		idGame : document.getElementById('idGame').value
	});
}

function determineWinner(idPlayer){
    $('#sendSolution').prop('disabled', true);
    $('#resetSolution').prop('disabled', true);
    var nameWinner = [];
    var propMin = 10000000;
    var propositionAnimate;

    for(var i = 0; i<solutions.solutions.length; i++){
        if(solutions.solutions[i].proposition.length<=propMin){
            propMin=solutions.solutions[i].proposition.length;
            propositionAnimate=solutions.solutions[i].proposition;
            nameWinner[nameWinner.length] = solutions.solutions[i].player;
        }
    }

    animateBestSolution(propositionAnimate);

    var winnerYou = false;

    $('#modal-victoire').modal('show');

    if(nameWinner.length==1){
        winnerYou = winnerOrNot(nameWinner[0],idPlayer);
        if(winnerYou){
            $('.modal-body').html("Vous gagnez la partie.");
        }else{
            $('.modal-body').html(nameWinner[0]+" a gagné la partie.");
        }

    }else{
        var firstEx=true;
        var stringEx="";
        console.log("Ex eaquo ");
        for(var j = 0; j<nameWinner.length; j++){
            winnerYou = winnerOrNot(nameWinner[j],idPlayer);
            if(!winnerYou){
                if(firstEx){
                    stringEx = nameWinner[j];
                }else{
                    firstEx=false;
                    stringEx +=", "+nameWinner[j];
                }
            }
        }
        if(winnerYou){
            $('.modal-body').html("Vous gagnez la partie.");
            $('.modal-body').append("
Ainsi que "+stringEx);
        }else{
            $('.modal-body').html(stringEx+" ont gagnez la partie.");
        }
    }
    h1 = document.querySelector('body > header > h1');
    h1.innerHTML += ' est terminée !';
}

function animateBestSolution(propositionAnimate){
    var selector;
    for(var i = 0; i<propositionAnimate.length; i++){
        if(propositionAnimate[i].command=="select"){
            selector = $(".robot_"+propositionAnimate[i].robot);
        }else if (propositionAnimate[i].command=="move"){
            console.log(selector.parent().attr('class'));
        }
    }
}

function winnerOrNot(playerWin, playerId){
    if(playerWin==playerId){
        console.log("You are the winner");
        return true;
    }
    return false;
}

function finalCountDown(time,all){
    if(!waitingOther){
            if(time>=0){
                $("#barre").css("width",((time*100)/all)+"%");
                $(".zone-nb-temps").html(time + "s");
            }
            if(time>0){
                time--;
                setTimeout("finalCountDown("+time+","+all+")", 1000);
            }else{
                //LOCK GAME
            }
    }else{
        $(".zone-nb-temps").html("En attente des autres joueurs");
    }

}

/**
 * Show the list of "participants"
 */
function showParticipants() {
	socket = io.connect();
	socket.on('participants', function(data) {
		var ul = document.getElementById('lesParticipants');
		ul.innerHTML = '';
		for (p in data.participants) {
			var li = document.createElement('li');
			ul.appendChild(li);
			li.appendChild(document.createTextNode(data.participants[p]));
		}
	});
	socket.emit('identification', {
		login : document.getElementById('login').value,
		idGame : document.getElementById('idGame').value
	});

}

/**
 * Propose a move for a robot
 */
function proposition(){
  var loginValue = document.getElementById('login').value;
  var idGameValue = document.getElementById('idGame').value;
  var jsonProposition = '['+document.getElementById('jsonProposition').value+']';

  XHR( "POST"
           , "/proposition"
           ,   {
           onload : function() {
             var reponseServer = JSON.parse(this.responseText);
             receivePropositionResponse(reponseServer);
               console.log(reponseServer);
               if(reponseServer.state=="SUCCESS"){
                    waitingOther = true;
                    $('#sendSolution').prop('disabled', true);
                    $('#resetSolution').prop('disabled', true);
               }

           }
           , variables : {
             login : loginValue
             , idGame : idGameValue
             , proposition : jsonProposition
           }
           }
     );
}

/**
 * Propose a single movement.
 * @param robotColor the color of the robot.
 * @param lineDestination the destination line.
 * @param columnDestination the destination column.
 */
function proposeSingleMovement(robotColor,lineDestination,columnDestination){
	  var loginValue = document.getElementById('login').value;
	  var idGameValue = document.getElementById('idGame').value;
	  var proposition = '[' +'{"command": "select" , "robot": "'+robotColor+'"} , {"command": "move" , "line": '+lineDestination+', "column": '+columnDestination+'}]';
	  XHR( "POST"
	           , "/proposition"
	           ,   {
	           onload : function() {
	             var reponseServer = JSON.parse(this.responseText);
	             receivePropositionResponse(reponseServer);

	           }
	           , variables : {
	             login : loginValue
	             , idGame : idGameValue
	             , proposition : proposition
	           }
	           }
	     );
}

/**
 * Reset the game
 */
function reset(){
	var idGame = $("#idGame").val();
	init(idGame);
	$("#moveState").text("");
    //$(".zone-nb-temps").html('<object xmlns="http://www.w3.org/1999/xhtml" data="medias/images-svg/infinity-icon.svg" type="image/svg+xml">infini</object>');
	$("#selectedRobotLine").val("");
	$("#selectedRobotColumn").val("");
	$("#selectedRobot").text("");
	$("#jsonProposition").val("");
	$("#nombreCoups").val("0");
	$(".zone-nb-coups").text("0");

}

/**
 * Manage the proposition response from the server.
 *
 * @param reponseServer
 *            the response from the server.
 */
function receivePropositionResponse(reponseServer){
	$("#jsonPropositionResponse").val(reponseServer.state);
	switch (reponseServer.state) {
	case "INVALID_EMPTY":
		document.getElementById('moveState').innerHTML = "Aucune proposition envoyée.";
		break;
	case "SUCCESS":
		document.getElementById('moveState').innerHTML = "Proposition valide !";
		break;
	case "INCOMPLETE":
		document.getElementById('moveState').innerHTML = "Proposition incomplète.";
		break;
	case "INVALID_MOVE":
		document.getElementById('moveState').innerHTML = "Un robot doit bouger le long d'une ligne ou d'une colonne jusqu'à ce qu'il rencontre un autre robot ou un mur.";
		break;
	case "INVALID_SELECT":
		document.getElementById('moveState').innerHTML = "Vous ne pouvez pas bouger un robot après l'avoir relaché.";
		break;
	default:
		document.getElementById('moveState').innerHTML = reponseServer.state;
		break;
	}
}
<|endoftext|>