<commit_before>"use strict";
var net = require("net");
var util=require("util");
var URL=require("url");
var DNS=require("dns");
var tls = require('tls');
var fs = require('fs');
var log = require("./log").instance;
var optparser = require("./optparser");
var BufferManager=require('./buffermanager').BufferManager;
var local_request=require('./request').local_request;
var remote_response=require('./response').remote_response;
var dataLogger=require('./front').dataLogger;
var config=require("./config");
var matchAutoResponder=require("./auto_responder").matchAutoResponder;

var SERVER_CMD_START=[0x00,0x01];
var SERVER_CMD_END=[0xfe,0xff];
var DNSCache=config.DNSCache;
//DNSCache['www.baidu.com']={addresses:['127.0.0.1']};

var httpsOptions = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),

  // This is necessary only if using the client certificate authentication.
  //requestCert: false,

  // This is necessary only if the client uses the self-signed certificate.
  //ca: [ fs.readFileSync('server-cert.pem') ]
};

function connectTo(socket,hostname,port){
    if(net.isIP(hostname)){
        socket.connect(port,hostname);
    }else{
        if(typeof DNSCache[hostname]!='undefined'){
            hostname=DNSCache[hostname].addresses[0];
            socket.connect(port,hostname);
        }else{
            DNS.resolve4(hostname,function(err,addresses){
                if (err) {
                    //throw new Error(hostname+" can't be resolved to ip");
                    //close remote socket
                    //clean_remote_socket(socket);
                    return;
                }
                DNSCache[hostname]={addresses:addresses};
                socket.connect(port,addresses[0]);
            });
        }
    }
}
var remote_connection_pool={};
function get_cached_remote_connection(url){
    var key=url.hostname+":"+(url.port?url.port:80);
    if(!remote_connection_pool[key]){
        return false;
    }else{
        log.debug("re use keepalive connection: "+key);
        return remote_connection_pool[key].pop();
    }
}
function release_connection(remote_socket){
    var url=remote_socket.url;
    var key=url.hostname+":"+(url.port?url.port:80);
    if(typeof(remote_connection_pool[key])=='undefined'){
        remote_connection_pool[key]=[];
    }
    log.debug("release keepalive connection: "+key);
    remote_connection_pool[key].push(remote_socket);
}
function delete_from_connection_pool(remote_socket){
    var k,i,tmp;
    for(k in remote_connection_pool){
        tmp=[];
        for(i=0;i<remote_connection_pool[k].length;i++){
            if(remote_connection_pool[k][i]!==remote_socket){
                tmp.push(remote_connection_pool[k][i]);
            }else{
                log.debug("delete remote connection from pool");
            }
        }
        remote_connection_pool[k]=tmp;
    }
}

function create_remote_connecton(request,socket,netType) {
    var url=request.getUrl();
    var port;
    if(!url.port){
        if(url.protocol=='https:'){
            port=443;
        }else{
            port=80;
        }
    }else{
        port=url.port;
    }
    var hostname= url.hostname;
    if(request.getMethod()=='CONNECT'&&port=='443'&&config.delegate_https_hosts.indexOf(hostname)!=-1){
        log.info("delegate https request to 127.0.0.1");
        hostname=config.listen_host;
        port=config.listen_https_port;
    }
    //console.log(url);
    var remote_socket;
    //socket = net.createConnection(port, hostname);
    if(remote_socket=get_cached_remote_connection(url)){
        remote_socket.socket=socket;
        remote_socket.request=request;
        log.debug("restore remote connection from pool");
        remote_socket_on_connect.apply(remote_socket);
        log.info("write to cached connection:"+remote_socket.request.getUrl().href);
        return remote_socket;
    }
    remote_socket = new net.Socket();
    remote_socket.request=request;

    if(netType===tls){
        var options={
            isServer:false,
            key: httpsOptions.key,
            cert: httpsOptions.cert
        }
        remote_socket=new tls.TLSSocket(remote_socket, options);
        remote_socket.isTLS=true;
    }
    remote_socket.socket=socket;

    try{
        connectTo(remote_socket,hostname,port);
    }catch(e){
        log.error("remote connection fail:"+e);
    }
    remote_socket.url=url;
    if(netType===tls){
        remote_socket.on("secureConnection", function() {
            log.debug("secure connect successful: " + hostname + ":" + port);
        });
        remote_socket.on("clientError", function(e) {
            log.error("secure connection error: " + hostname + ":" + port+"  "+e);
            clean_remote_socket(this);
            clean_client_socket(this.socket);
        });
    }else{
        remote_socket.on("connect", function() {
            log.debug("connect successful: " + hostname + ":" + port);
        });
    }

    remote_socket.on("error", function(e) {
        log.error("connection error: " + hostname + ":" + port+"  "+e);
        clean_remote_socket(this);
        clean_client_socket(this.socket);
    });
    var response;
    remote_socket.on('data',function(buf){
        log.info("recv remote data length:"+buf.length+":"+this.request.getUrl().href);
        if(!this.bm){
            this.bm=new BufferManager();
        }
        var bm=this.bm;
        try{
            this.socket.write(buf);
        }catch(e){
            this.destroy();
            this.socket.destroy();
        }
        bm.add(buf);
        if(!response){
            response=remote_response(bm);
        }
        dataLogger.data(this.request,"responseCode",response.getResponseCode());
        if(response
            && response.getResponseCode()<200//100－199都是报状态的，响应还没结束
            && response.getResponseCode()>=100
            ){
            log.info("recv 1xx response:"+response.getResponseCode());
            response=false;
            return;
        }

        if(response
            && response.responseIsEnd(bm)
            ){
            dataLogger.data(this.request,"responseHeader",response.getRawHeader());
            dataLogger.data(this.request,"response",response.getBody().toString());
            log.info("response end:"+response.getResponseCode()+":"+this.request.getUrl().href);

            if(response.isKeepAlive()){
                release_connection(this);
            }
            response=false;
            bm.clear();
            delete this.bm;
        }
    });
    remote_socket.on("close",function(had_error){
        log.debug("remote connection has been closed");
        if (had_error) {
            this.destroy();
        }
        clean_remote_socket(this);
        clean_client_socket(this.socket);
    });
    remote_socket.once("connect",remote_socket_on_connect);
    function remote_socket_on_connect(){
        try{
            log.debug("remote connection established");
            log.debug("send:\n"+this.request.getSendHeader());
            this.write(this.request.getSendHeader());
            this.write(this.request.getBody());
        }catch(e){
            clean_remote_socket(remote_socket);
            log.error("can't write to cached connection");
            log.error(e);
            throw e;
        }
    }
    return remote_socket;
}

function clean_remote_socket(remote_socket) {
    delete_from_connection_pool(remote_socket);
    if(!remote_socket){
        return;
    }
    remote_socket.removeAllListeners("data");
    remote_socket.removeAllListeners("error");
    remote_socket.removeAllListeners("close");
    remote_socket.removeAllListeners("connect");
    delete remote_socket.bm;
    if(remote_socket.socket){
        delete remote_socket.socket.remote_socket;
        clean_client_socket(remote_socket.socket);
        delete remote_socket.socket;
    }
    remote_socket.end();
    remote_socket.destroy();
}

function clean_client_socket(socket) {
    if(!socket){
        return;
    }
    socket.removeAllListeners("data");
    socket.removeAllListeners("error");
    socket.removeAllListeners("close");
    socket.removeAllListeners("connect");
    delete socket.bm;
    if(socket.remote_socket){
        delete socket.remote_socket.socket;
        clean_remote_socket(socket.remote_socket);
        delete socket.remote_socket;
    }
    socket.end();
    socket.destroy();
}

function parse_server_cmd(bm){
    var start=bm.indexOf(SERVER_CMD_START),
        end=bm.indexOf(SERVER_CMD_END);
    if(start!=0 || end==-1){
        return null;
    }
    var cmd=bm.slice(SERVER_CMD_START.length,end-SERVER_CMD_END.length).toString();
    bm.delete(end+SERVER_CMD_END.length);
    log.debug('recieved server command:'+cmd);
    return cmd;
}

//TODO
var COMMAND_TABLE={
    list:function(){
         },
    info:function(){
         },
    loadconf:function(){
        },
    dnsshow:function(){
        },
    dnsclean:function(){
        }
}

function process_server_cmd(cmd,socket){
    var tokens=cmd.split(/\s+/);
    var cmd_type=tokens[0].toLowerCase();
    if(COMMAND_TABLE.hasOwnProperty(cmd_type)){
        result=COMMAND_TABLE[cmd_type](tokens.slice(1));
    }else{
        log.error('not implement: "'+cmd+'"');
        result='not implement';
    }
    var bm=new BufferManager(
            new Buffer(SERVER_CMD_START),
            new Buffer(JSON.stringify(result)),
            new Buffer(SERVER_CMD_END)
            );
    socket.write(bm.toBuffer());
}

function createServerCallbackFunc(netType){//netType is tls or net
    return function(socket) {
        //socket.on("connect", function() {
        if(netType===tls){
            socket.isTLS=true;
        }

        log.debug("local connection established: " + socket.remoteAddress);
        //});
        socket.on("end", function() {
            log.debug("local connection closed: " + this.remoteAddress);
            clean_client_socket(this);
            //log.debug("client end " + this.remoteAddress);
        });
        socket.on("data", function(buf) {
            log.debug("recievied local length: "+buf.length);
            if(!this.bm){
                var bm=this.bm=new BufferManager();
            }else{
                var bm=this.bm;
            }
            bm.add(buf);

            var server_cmd=parse_server_cmd(bm);
            if(server_cmd){
                log.debug(server_cmd);
            }
            if(server_cmd){
                process_server_cmd(server_cmd,this);
                return;
            }
            var request=local_request(bm,netType);

            if(request===null){
                log.debug("not full request");
                return;
            }

            if(request){
                log.info("recieve:"+request.getUrl().href);
                if(request.getMethod()!="CONNECT"){
                    //透传的请求就不用往下走了
                    dataLogger.data(request,"url",request.getUrl().href);
                    dataLogger.data(request,"requestHeader",request.getSendHeader());
                }
                if(matchAutoResponder(request,socket)===true){
                    return;
                }
            }

            var remote_socket=this.remote_socket=create_remote_connecton(request,socket,netType);

            if(request&&request.getMethod()=='CONNECT'){
                remote_socket.removeAllListeners("connect");
                remote_socket.removeAllListeners("data");
                log.info("http connect, create http channel");
                remote_socket.on("connect",function(){
                    socket.removeAllListeners("data");
                    socket.write('HTTP/1.1 200 Connection Established\r\n' +
                            'Proxy-agent: Node-Proxy\r\n' +
                            '\r\n');
                    remote_socket.write(bm.toBuffer());
                    remote_socket.pipe(socket);
                    socket.pipe(remote_socket);
                });
            }

        });

        socket.on("close", function() {
            clean_client_socket(this);
            log.debug("local connection closed: " + this.remoteAddress);
        });
        socket.on("error", function() {
            clean_client_socket(this);
            log.error("client error");
        });
    }
}

var httpServer=net.createServer(
    createServerCallbackFunc(net)
);
httpServer.maxConnections=config.max_connections;
httpServer.listen(config.listen_port,config.listen_host);

var httpsServer=tls.createServer(httpsOptions,
    createServerCallbackFunc(tls)
);
httpsServer.maxConnections=config.max_connections;
httpsServer.listen(config.listen_https_port,config.listen_host);

///////////http config server/////////////////////
<commit_msg>little fix<commit_after>"use strict";
var net = require("net");
var util=require("util");
var URL=require("url");
var DNS=require("dns");
var tls = require('tls');
var fs = require('fs');
var log = require("./log").instance;
var optparser = require("./optparser");
var BufferManager=require('./buffermanager').BufferManager;
var local_request=require('./request').local_request;
var remote_response=require('./response').remote_response;
var dataLogger=require('./front').dataLogger;
var config=require("./config");
var matchAutoResponder=require("./auto_responder").matchAutoResponder;

var SERVER_CMD_START=[0x00,0x01];
var SERVER_CMD_END=[0xfe,0xff];
var DNSCache=config.DNSCache;
//DNSCache['www.baidu.com']={addresses:['127.0.0.1']};

var httpsOptions = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),

  // This is necessary only if using the client certificate authentication.
  //requestCert: false,

  // This is necessary only if the client uses the self-signed certificate.
  //ca: [ fs.readFileSync('server-cert.pem') ]
};

function connectTo(socket,hostname,port){
    if(net.isIP(hostname)){
        socket.connect(port,hostname);
    }else{
        if(typeof DNSCache[hostname]!='undefined'){
            hostname=DNSCache[hostname].addresses[0];
            socket.connect(port,hostname);
        }else{
            DNS.resolve4(hostname,function(err,addresses){
                if (err) {
                    //throw new Error(hostname+" can't be resolved to ip");
                    //close remote socket
                    //clean_remote_socket(socket);
                    return;
                }
                DNSCache[hostname]={addresses:addresses};
                socket.connect(port,addresses[0]);
            });
        }
    }
}
var remote_connection_pool={};
function get_cached_remote_connection(url){
    var key=url.hostname+":"+(url.port?url.port:80);
    if(!remote_connection_pool[key]){
        return false;
    }else{
        log.debug("re use keepalive connection: "+key);
        return remote_connection_pool[key].pop();
    }
}
function release_connection(remote_socket){
    var url=remote_socket.url;
    var key=url.hostname+":"+(url.port?url.port:80);
    if(typeof(remote_connection_pool[key])=='undefined'){
        remote_connection_pool[key]=[];
    }
    log.debug("release keepalive connection: "+key);
    remote_connection_pool[key].push(remote_socket);
}
function delete_from_connection_pool(remote_socket){
    var k,i,tmp;
    for(k in remote_connection_pool){
        tmp=[];
        for(i=0;i<remote_connection_pool[k].length;i++){
            if(remote_connection_pool[k][i]!==remote_socket){
                tmp.push(remote_connection_pool[k][i]);
            }else{
                log.debug("delete remote connection from pool");
            }
        }
        remote_connection_pool[k]=tmp;
    }
}

function create_remote_connecton(request,socket,netType) {
    var url=request.getUrl();
    var port;
    if(!url.port){
        if(url.protocol=='https:'){
            port=443;
        }else{
            port=80;
        }
    }else{
        port=url.port;
    }
    var hostname= url.hostname;
    if(request.getMethod()=='CONNECT'&&port=='443'&&config.delegate_https_hosts.indexOf(hostname)!=-1){
        log.info("delegate https request to 127.0.0.1");
        hostname=config.listen_host;
        port=config.listen_https_port;
    }
    //console.log(url);
    var remote_socket;
    //socket = net.createConnection(port, hostname);
    if(remote_socket=get_cached_remote_connection(url)){
        remote_socket.socket=socket;
        remote_socket.request=request;
        log.debug("restore remote connection from pool");
        remote_socket_on_connect.apply(remote_socket);
        log.info("write to cached connection:"+remote_socket.request.getUrl().href);
        return remote_socket;
    }
    remote_socket = new net.Socket();
    remote_socket.request=request;

    if(netType===tls){
        var options={
            isServer:false,
            key: httpsOptions.key,
            cert: httpsOptions.cert
        }
        remote_socket=new tls.TLSSocket(remote_socket, options);
        remote_socket.isTLS=true;
    }
    remote_socket.socket=socket;

    try{
        connectTo(remote_socket,hostname,port);
    }catch(e){
        log.error("remote connection fail:"+e);
    }
    remote_socket.url=url;
    if(netType===tls){
        remote_socket.on("secureConnection", function() {
            log.debug("secure connect successful: " + hostname + ":" + port);
        });
        remote_socket.on("clientError", function(e) {
            log.error("secure connection error: " + hostname + ":" + port+"  "+e);
            clean_remote_socket(this);
            clean_client_socket(this.socket);
        });
    }else{
        remote_socket.on("connect", function() {
            log.debug("connect successful: " + hostname + ":" + port);
        });
    }

    remote_socket.on("error", function(e) {
        log.error("connection error: " + hostname + ":" + port+"  "+e);
        clean_remote_socket(this);
        clean_client_socket(this.socket);
    });
    var response;
    remote_socket.on('data',function(buf){
        log.info("recv remote data length:"+buf.length+":"+this.request.getUrl().href);
        if(!this.bm){
            this.bm=new BufferManager();
        }
        var bm=this.bm;
        try{
            this.socket.write(buf);
        }catch(e){
            this.destroy();
            this.socket.destroy();
        }
        bm.add(buf);
        if(!response){
            response=remote_response(bm);
        }
        if(response){
            dataLogger.data(this.request,"responseCode",response.getResponseCode());
        }
        if(response
            && response.getResponseCode()<200//100－199都是报状态的，响应还没结束
            && response.getResponseCode()>=100
            ){
            log.info("recv 1xx response:"+response.getResponseCode());
            response=false;
            return;
        }

        if(response
            && response.responseIsEnd(bm)
            ){
            dataLogger.data(this.request,"responseHeader",response.getRawHeader());
            dataLogger.data(this.request,"response",response.getBody().toString());
            log.info("response end:"+response.getResponseCode()+":"+this.request.getUrl().href);

            if(response.isKeepAlive()){
                release_connection(this);
            }
            response=false;
            bm.clear();
            delete this.bm;
        }
    });
    remote_socket.on("close",function(had_error){
        log.debug("remote connection has been closed");
        if (had_error) {
            this.destroy();
        }
        clean_remote_socket(this);
        clean_client_socket(this.socket);
    });
    remote_socket.once("connect",remote_socket_on_connect);
    function remote_socket_on_connect(){
        try{
            log.debug("remote connection established");
            log.debug("send:\n"+this.request.getSendHeader());
            this.write(this.request.getSendHeader());
            this.write(this.request.getBody());
        }catch(e){
            clean_remote_socket(remote_socket);
            log.error("can't write to cached connection");
            log.error(e);
            throw e;
        }
    }
    return remote_socket;
}

function clean_remote_socket(remote_socket) {
    delete_from_connection_pool(remote_socket);
    if(!remote_socket){
        return;
    }
    remote_socket.removeAllListeners("data");
    remote_socket.removeAllListeners("error");
    remote_socket.removeAllListeners("close");
    remote_socket.removeAllListeners("connect");
    delete remote_socket.bm;
    if(remote_socket.socket){
        delete remote_socket.socket.remote_socket;
        clean_client_socket(remote_socket.socket);
        delete remote_socket.socket;
    }
    remote_socket.end();
    remote_socket.destroy();
}

function clean_client_socket(socket) {
    if(!socket){
        return;
    }
    socket.removeAllListeners("data");
    socket.removeAllListeners("error");
    socket.removeAllListeners("close");
    socket.removeAllListeners("connect");
    delete socket.bm;
    if(socket.remote_socket){
        delete socket.remote_socket.socket;
        clean_remote_socket(socket.remote_socket);
        delete socket.remote_socket;
    }
    socket.end();
    socket.destroy();
}

function parse_server_cmd(bm){
    var start=bm.indexOf(SERVER_CMD_START),
        end=bm.indexOf(SERVER_CMD_END);
    if(start!=0 || end==-1){
        return null;
    }
    var cmd=bm.slice(SERVER_CMD_START.length,end-SERVER_CMD_END.length).toString();
    bm.delete(end+SERVER_CMD_END.length);
    log.debug('recieved server command:'+cmd);
    return cmd;
}

//TODO
var COMMAND_TABLE={
    list:function(){
         },
    info:function(){
         },
    loadconf:function(){
        },
    dnsshow:function(){
        },
    dnsclean:function(){
        }
}

function process_server_cmd(cmd,socket){
    var tokens=cmd.split(/\s+/);
    var cmd_type=tokens[0].toLowerCase();
    if(COMMAND_TABLE.hasOwnProperty(cmd_type)){
        result=COMMAND_TABLE[cmd_type](tokens.slice(1));
    }else{
        log.error('not implement: "'+cmd+'"');
        result='not implement';
    }
    var bm=new BufferManager(
            new Buffer(SERVER_CMD_START),
            new Buffer(JSON.stringify(result)),
            new Buffer(SERVER_CMD_END)
            );
    socket.write(bm.toBuffer());
}

function createServerCallbackFunc(netType){//netType is tls or net
    return function(socket) {
        //socket.on("connect", function() {
        if(netType===tls){
            socket.isTLS=true;
        }

        log.debug("local connection established: " + socket.remoteAddress);
        //});
        socket.on("end", function() {
            log.debug("local connection closed: " + this.remoteAddress);
            clean_client_socket(this);
            //log.debug("client end " + this.remoteAddress);
        });
        socket.on("data", function(buf) {
            log.debug("recievied local length: "+buf.length);
            if(!this.bm){
                var bm=this.bm=new BufferManager();
            }else{
                var bm=this.bm;
            }
            bm.add(buf);

            var server_cmd=parse_server_cmd(bm);
            if(server_cmd){
                log.debug(server_cmd);
            }
            if(server_cmd){
                process_server_cmd(server_cmd,this);
                return;
            }
            var request=local_request(bm,netType);

            if(request===null){
                log.debug("not full request");
                return;
            }

            if(request){
                log.info("recieve:"+request.getUrl().href);
                if(request.getMethod()!="CONNECT"){
                    //透传的请求就不用往下走了
                    dataLogger.data(request,"url",request.getUrl().href);
                    dataLogger.data(request,"requestHeader",request.getSendHeader());
                }
                if(matchAutoResponder(request,socket)===true){
                    return;
                }
            }

            var remote_socket=this.remote_socket=create_remote_connecton(request,socket,netType);

            if(request&&request.getMethod()=='CONNECT'){
                remote_socket.removeAllListeners("connect");
                remote_socket.removeAllListeners("data");
                log.info("http connect, create http channel");
                remote_socket.on("connect",function(){
                    socket.removeAllListeners("data");
                    socket.write('HTTP/1.1 200 Connection Established\r\n' +
                            'Proxy-agent: Node-Proxy\r\n' +
                            '\r\n');
                    remote_socket.write(bm.toBuffer());
                    remote_socket.pipe(socket);
                    socket.pipe(remote_socket);
                });
            }

        });

        socket.on("close", function() {
            clean_client_socket(this);
            log.debug("local connection closed: " + this.remoteAddress);
        });
        socket.on("error", function() {
            clean_client_socket(this);
            log.error("client error");
        });
    }
}

var httpServer=net.createServer(
    createServerCallbackFunc(net)
);
httpServer.maxConnections=config.max_connections;
httpServer.listen(config.listen_port,config.listen_host);

var httpsServer=tls.createServer(httpsOptions,
    createServerCallbackFunc(tls)
);
httpsServer.maxConnections=config.max_connections;
httpsServer.listen(config.listen_https_port,config.listen_host);

///////////http config server/////////////////////
<|endoftext|>


<commit_before>var PassportFacebook = require('passport-facebook').Strategy;
var passport = require('passport');

var _ = require('underscore');

module.exports = (function () {
	'use strict';

	function FacebookLogin (config) {

		this.config = _.extend({}, config);

	}

	FacebookLogin.prototype.passportStrategy = PassportFacebook;

	FacebookLogin.prototype.name = 'facebook-login';

	FacebookLogin.prototype.stateIn = [
		'registered'
	];

	FacebookLogin.prototype.stateOut = 'registered';

	FacebookLogin.prototype.steps = [
		'findOrCreateUserByOAuthId',

		'addFacebookAccount',

		'createToken',
		'hashToken',
		'addBearerAccount',
		'removeInvalidTokens',

		'updateState',

		'saveUser'
	];

	FacebookLogin.prototype.mapper = function (accessToken, refreshToken, rawResponse, profile, callback) {
		var mixin = {
			user: null,
			specs: {
				stateIn: this.stateIn,
				stateOut: this.stateOut
			},
			data: {
				oauthId: profile.id,
				profile: profile,
				expiration: rawResponse.expires_in,
				accessToken: rawResponse.accessToken,
				refreshToken: rawResponse.refreshToken
			},
			accounts: []
		};

		return callback(null, mixin);
	};

	return FacebookLogin;

})();
<commit_msg>Same as google.<commit_after>var PassportFacebook = require('passport-facebook').Strategy;
var passport = require('passport');

var _ = require('underscore');

module.exports = (function () {
	'use strict';

	function FacebookLogin (config) {

		this.config = _.extend({}, config);

	}

	FacebookLogin.prototype.passportStrategy = PassportFacebook;

	FacebookLogin.prototype.name = 'facebook-login';

	FacebookLogin.prototype.stateIn = [
		'registered'
	];

	FacebookLogin.prototype.stateOut = 'registered';

	FacebookLogin.prototype.steps = [
		'findOrCreateUserByOAuthId',

		'addFacebookAccount',

		'createToken',
		'hashToken',
		'addBearerAccount',
		'removeInvalidTokens',

		'updateState',

		'saveUser'
	];

	FacebookLogin.prototype.mapper = function (accessToken, refreshToken, rawResponse, callback) {
		var mixin = {
			user: null,
			specs: {
				stateIn: this.stateIn,
				stateOut: this.stateOut
			},
			data: {
				oauthId: rawResponse.id,
				profile: rawResponse,
				accessToken: accessToken,
			},
			accounts: []
		};

		return callback(null, mixin);
	};

	return FacebookLogin;

})();
<|endoftext|>


<commit_before>'use strict';

const rpad = require('right-pad');
const lpad = require('pad-left');
const BaseEmbed = require('./BaseEmbed.js');

/**
 * Generates enemy embeds
 */
class WhatsinEmbed extends BaseEmbed {
  /**
   * @param {Genesis} bot - An instance of Genesis
   * @param {Object} details details to derive data from
   * @param {string} tier Relic tier
   * @param {string} type Relic type
   */
  constructor(bot, details, tier, type) {
    super();
    const transformedRewards = {};
    const rewards = [details.rewards.Intact, details.rewards.Exceptional,
      details.rewards.Flawless, details.rewards.Radiant];
    rewards.forEach((rewardTier) => {
      rewardTier.forEach((reward) => {
        if (!transformedRewards[reward.itemName]) {
          transformedRewards[reward.itemName] = [];
        }
        if (!transformedRewards[reward.itemName][rewards.indexOf(rewardTier)]) {
          transformedRewards[reward.itemName][rewards.indexOf(rewardTier)] = reward.chance;
        }
      });
    });

    const longest = Object.keys(transformedRewards).reduce((a, b) => (a.length > b.length ? a : b));
    const tokens = [];
    Object.keys(transformedRewards).forEach((rewardName) => {
      const reward = transformedRewards[rewardName];
      const qualities = [];
      reward.forEach((quality) => {
        const wrappedQuality = lpad(`${quality.toFixed(2)}`, 6, ' ').substring(0, 5);
        qualities.push(wrappedQuality);
      });
      tokens.push(`${rpad(rewardName, longest.length + 1, ' ')} ${qualities.join('/')}%`);
    });

    this.title = `${tier} ${type}`;
    this.color = 0x3498db;
    this.type = 'rich';
    this.fields = [
      {
        name: '_ _',
        value: `\`\`\`tokens.join('\n')\`\`\``,
      },
    ];
  }
}

module.exports = WhatsinEmbed;
<commit_msg>template notation is important<commit_after>'use strict';

const rpad = require('right-pad');
const lpad = require('pad-left');
const BaseEmbed = require('./BaseEmbed.js');

/**
 * Generates enemy embeds
 */
class WhatsinEmbed extends BaseEmbed {
  /**
   * @param {Genesis} bot - An instance of Genesis
   * @param {Object} details details to derive data from
   * @param {string} tier Relic tier
   * @param {string} type Relic type
   */
  constructor(bot, details, tier, type) {
    super();
    const transformedRewards = {};
    const rewards = [details.rewards.Intact, details.rewards.Exceptional,
      details.rewards.Flawless, details.rewards.Radiant];
    rewards.forEach((rewardTier) => {
      rewardTier.forEach((reward) => {
        if (!transformedRewards[reward.itemName]) {
          transformedRewards[reward.itemName] = [];
        }
        if (!transformedRewards[reward.itemName][rewards.indexOf(rewardTier)]) {
          transformedRewards[reward.itemName][rewards.indexOf(rewardTier)] = reward.chance;
        }
      });
    });

    const longest = Object.keys(transformedRewards).reduce((a, b) => (a.length > b.length ? a : b));
    const tokens = [];
    Object.keys(transformedRewards).forEach((rewardName) => {
      const reward = transformedRewards[rewardName];
      const qualities = [];
      reward.forEach((quality) => {
        const wrappedQuality = lpad(`${quality.toFixed(2)}`, 6, ' ').substring(0, 5);
        qualities.push(wrappedQuality);
      });
      tokens.push(`${rpad(rewardName, longest.length + 1, ' ')} ${qualities.join('/')}%`);
    });

    this.title = `${tier} ${type}`;
    this.color = 0x3498db;
    this.type = 'rich';
    this.fields = [
      {
        name: '_ _',
        value: `\`\`\`${tokens.join('\n')}\`\`\``,
      },
    ];
  }
}

module.exports = WhatsinEmbed;
<|endoftext|>


<commit_before>var isProblem = require( '../utils/isProblem' );
var Problem = require( '../models/Problem' );
var functionName = require( '../utils/fnName' );
var namedFn = require( '../utils/namedFn' );
var betterThrow = require( '../utils/betterThrow' );
var stringifyWithFnName = require( '../utils/stringifyWithFnName' );

function fclauseWalker( clause, walkFn ) {
  var { args: argsClause, ret: retClause, fn: validateFn } = clause.opts;

  return {
    trailblaze: fclauseTrailblaze,
    reconstruct: fclauseReconstruct,
  };

  function fclauseTrailblaze( fn ) {
    return fn;
  }

  function fclauseReconstruct( fn, walkOpts ) {
    if ( fn ) {
      var { conform, instrument } = walkOpts;

      if ( conform && instrument ) {
        return instrumentConformed( fn, walkOpts );
      } else if ( instrument ) {
        return _instrument( fn, walkOpts );
      }
    } else {
      throw new Error( 'A function must be clauseified for instrumentation.' );
    }
  }

  function _instrument( fn, walkOpts ) {
    var fnName = functionName( fn );
    var instrumentedFn = getInstrumentedFn( fnName, fn, walkOpts );
    var namedClauseedFn = namedFn( fnName, instrumentedFn, '__instrumented' );
    return namedClauseedFn;
  }

  function instrumentConformed( fn, walkOpts ) {
    var fnName = functionName( fn );
    var argConformedFn = getArgConformedInstrumentedFn( fnName, fn, walkOpts );
    var namedArgConformedFn = namedFn( fnName, argConformedFn, '__conformed' );

    return namedArgConformedFn;
  }

  function getInstrumentedFn( fnName, fn ) {
    return function __instrumented() {
      var args = Array.prototype.slice.call( arguments );
      var instrumentedArgs = checkArgs( fn, fnName, args );
      var retVal = fn.apply( this, instrumentedArgs );
      var instrumentedRetVal = checkRet( fn, fnName, retVal );

      // TODO optimize
      var conformedArgs =
      argsClause ?
        walkFn( argsClause, args, { conform: true, instrument: true } ) :
        args;
      let conformedRetVal;
      if ( retClause ) {
        conformedRetVal = walkFn( retClause, retVal, { conform: true, instrument: true } );
      } else {
        conformedRetVal = retVal;
      }

      checkFnRelation( fnName, fn, validateFn, conformedArgs, conformedRetVal );
      return instrumentedRetVal;
    };
  }

  function checkFnRelation( fnName, fn, validateFn, conformedArgs, retVal ) {
    if ( validateFn ) {
      var r = validateFn.call( null, conformedArgs, retVal );
      if ( !r ) {
        var p = new Problem( fn, clause, [],
          `Function ${fnName} failed valiation on argument-return value relation` );
        betterThrow( p );
      }
    }
  }

  function checkArgs( fn, fnName, args ) {
    const displayFnName = fnName || '<anonymous>';
    if ( argsClause ) {
      var instrumentedArgs = walkFn( argsClause, args, { phase: 'trailblaze' } );
      if ( isProblem( instrumentedArgs ) ) {
        var p = new Problem( args, clause, [ instrumentedArgs ], `Arguments for function ${displayFnName}() is not valid` );
        betterThrow( p );
      } else {
        return walkFn( argsClause, instrumentedArgs, { phase: 'reconstruct', conform: false, instrument: true } );
      }
    } else {
      return args;
    }
  }

  function checkRet( fn, fnName, retVal ) {
    const displayFnName = fnName || '<anonymous>';

    if ( retClause ) {
      var instrumentedRetVal = walkFn( retClause, retVal, { phase: 'trailblaze' } );
      if ( isProblem( instrumentedRetVal ) ) {
        var p = new Problem( retVal, clause, [ instrumentedRetVal ], 'Return value for function ' + displayFnName + '() is not valid' );
        betterThrow( p );
      } else {
        var r = walkFn( retClause, instrumentedRetVal, { phase: 'reconstruct', instrument: true, conform: false } );
        return r;
      }
    } else {
      return retVal;
    }
  }

  function getArgConformedInstrumentedFn( fnName, fn ) {
    const displayFnName = fnName || '<anonymous>';

    return function __instrumentConformed() {
      var args = Array.prototype.slice.call( arguments );

      var conformedArgs = walkFn( argsClause, args, { conform: true, instrument: true } );
      if ( isProblem( conformedArgs ) ) {
        var p = new Problem( args, argsClause, [ conformedArgs ], `Arguments for function ${displayFnName} is not valid` );
        betterThrow( p );
      }

      var retVal = fn.call( this, conformedArgs );

      checkRet( fn, fnName, retVal );

      if ( validateFn ) {
        var conformedRetVal;
        if ( retClause ) {
          conformedRetVal = walkFn( retClause, retVal, { conform: true, instrument: true } );
        } else {
          conformedRetVal = retVal;
        }
        checkFnRelation( fnName, fn, validateFn, conformedArgs, conformedRetVal );
      }

      return retVal;
    };
  }

}

module.exports = fclauseWalker;
<commit_msg>correct problem value for fn check<commit_after>var isProblem = require( '../utils/isProblem' );
var Problem = require( '../models/Problem' );
var functionName = require( '../utils/fnName' );
var namedFn = require( '../utils/namedFn' );
var betterThrow = require( '../utils/betterThrow' );
var stringifyWithFnName = require( '../utils/stringifyWithFnName' );

function fclauseWalker( clause, walkFn ) {
  var { args: argsClause, ret: retClause, fn: validateFn } = clause.opts;

  return {
    trailblaze: fclauseTrailblaze,
    reconstruct: fclauseReconstruct,
  };

  function fclauseTrailblaze( fn ) {
    return fn;
  }

  function fclauseReconstruct( fn, walkOpts ) {
    if ( fn ) {
      var { conform, instrument } = walkOpts;

      if ( conform && instrument ) {
        return instrumentConformed( fn, walkOpts );
      } else if ( instrument ) {
        return _instrument( fn, walkOpts );
      }
    } else {
      throw new Error( 'A function must be clauseified for instrumentation.' );
    }
  }

  function _instrument( fn, walkOpts ) {
    var fnName = functionName( fn );
    var instrumentedFn = getInstrumentedFn( fnName, fn, walkOpts );
    var namedClauseedFn = namedFn( fnName, instrumentedFn, '__instrumented' );
    return namedClauseedFn;
  }

  function instrumentConformed( fn, walkOpts ) {
    var fnName = functionName( fn );
    var argConformedFn = getArgConformedInstrumentedFn( fnName, fn, walkOpts );
    var namedArgConformedFn = namedFn( fnName, argConformedFn, '__conformed' );

    return namedArgConformedFn;
  }

  function getInstrumentedFn( fnName, fn ) {
    return function __instrumented() {
      var args = Array.prototype.slice.call( arguments );
      var instrumentedArgs = checkArgs( fn, fnName, args );
      var retVal = fn.apply( this, instrumentedArgs );
      var instrumentedRetVal = checkRet( fn, fnName, retVal );

      // TODO optimize
      var conformedArgs =
      argsClause ?
        walkFn( argsClause, args, { conform: true, instrument: true } ) :
        args;
      let conformedRetVal;
      if ( retClause ) {
        conformedRetVal = walkFn( retClause, retVal, { conform: true, instrument: true } );
      } else {
        conformedRetVal = retVal;
      }

      checkFnRelation( fnName, fn, validateFn, conformedArgs, conformedRetVal );
      return instrumentedRetVal;
    };
  }

  function checkFnRelation( fnName, fn, validateFn, conformedArgs, retVal ) {
    if ( validateFn ) {
      var r = validateFn.call( null, conformedArgs, retVal );
      if ( !r ) {
        var p = new Problem( { args: conformedArgs, ret: retVal }, clause, [],
          `Function ${fnName} failed valiation on argument-return value relation` );
        betterThrow( p );
      }
    }
  }

  function checkArgs( fn, fnName, args ) {
    const displayFnName = fnName || '<anonymous>';
    if ( argsClause ) {
      var instrumentedArgs = walkFn( argsClause, args, { phase: 'trailblaze' } );
      if ( isProblem( instrumentedArgs ) ) {
        var p = new Problem( args, clause, [ instrumentedArgs ], `Arguments for function ${displayFnName}() is not valid` );
        betterThrow( p );
      } else {
        return walkFn( argsClause, instrumentedArgs, { phase: 'reconstruct', conform: false, instrument: true } );
      }
    } else {
      return args;
    }
  }

  function checkRet( fn, fnName, retVal ) {
    const displayFnName = fnName || '<anonymous>';

    if ( retClause ) {
      var instrumentedRetVal = walkFn( retClause, retVal, { phase: 'trailblaze' } );
      if ( isProblem( instrumentedRetVal ) ) {
        var p = new Problem( retVal, clause, [ instrumentedRetVal ], 'Return value for function ' + displayFnName + '() is not valid' );
        betterThrow( p );
      } else {
        var r = walkFn( retClause, instrumentedRetVal, { phase: 'reconstruct', instrument: true, conform: false } );
        return r;
      }
    } else {
      return retVal;
    }
  }

  function getArgConformedInstrumentedFn( fnName, fn ) {
    const displayFnName = fnName || '<anonymous>';

    return function __instrumentConformed() {
      var args = Array.prototype.slice.call( arguments );

      var conformedArgs = walkFn( argsClause, args, { conform: true, instrument: true } );
      if ( isProblem( conformedArgs ) ) {
        var p = new Problem( args, argsClause, [ conformedArgs ], `Arguments for function ${displayFnName} is not valid` );
        betterThrow( p );
      }

      var retVal = fn.call( this, conformedArgs );

      checkRet( fn, fnName, retVal );

      if ( validateFn ) {
        var conformedRetVal;
        if ( retClause ) {
          conformedRetVal = walkFn( retClause, retVal, { conform: true, instrument: true } );
        } else {
          conformedRetVal = retVal;
        }
        checkFnRelation( fnName, fn, validateFn, conformedArgs, conformedRetVal );
      }

      return retVal;
    };
  }

}

module.exports = fclauseWalker;
<|endoftext|>


<commit_before>/*globals define*/
/*
 * @author brollb / https://github/brollb
 */
//This is the connection highlight updater
define(['./SnapEditorWidget.Constants.js'], function (SNAP_CONSTANTS) {

    "use strict";

    var SnapEditorWidgetHighlightUpdater,
        ITEM_TAG = "current_droppable_item";

    SnapEditorWidgetHighlightUpdater = function () {
    };

    SnapEditorWidgetHighlightUpdater.prototype.registerDraggingItem = function (ui) {
        var i;

        this._ui = ui;
        this._underItems = [];
        this._draggedIds = [];

        i = this._ui.children().length;
        while (i--){
            this._draggedIds.push(this._ui.children()[i].id);
        }
    };

    SnapEditorWidgetHighlightUpdater.prototype.unregisterDraggingItem = function () {
        this._ui = null;
        this._underItems = null;
    };

    SnapEditorWidgetHighlightUpdater.prototype.registerUnderItem = function (underItem) {
        if (this._underItems !== null){
            this._underItems.push(underItem);

            if (this._underItems.length === 1){
                this._updateHighlights(this);
            }
        }
    };

    SnapEditorWidgetHighlightUpdater.prototype.unregisterUnderItem = function (item) {
        var i = this._underItems.indexOf(item),
            ui = this._ui;

        if (i !== -1){
            this._underItems.splice(i,1);
            if (ui.data(ITEM_TAG) === item.id){
                item.deactivateConnectionAreas();
                this.dropFocus = SNAP_CONSTANTS.BACKGROUND;

                //Remove data from dragged ui
                ui.removeData(ITEM_TAG);
            }
        }
    };

    SnapEditorWidgetHighlightUpdater.prototype._updateHighlights = function (self) {
        var items = self._underItems.slice(),
            draggedUI = self._ui,
            selector = '#' + draggedUI.attr('id') + '.' + draggedUI.attr('class'),
            draggedId = draggedUI.attr('id'),
            dragged = self.items[draggedId],
            draggedIds = [],
            pos,
            connectionInfo,
            connectionDistance,
            otherItemId,
            minDistance = null,
            closestItem = null,
            closestArea = null,
            j;

        if (items.length){
            pos = $(selector).position();
            pos.left -= items[0].$el.parent().offset().left;
            pos.top -= items[0].$el.parent().offset().top;

            //Update the highlight
            for (j = items.length-1; j >= 0; j--){
                if(draggedIds.indexOf(items[j].id) === -1){//If it isn't hovering over itself
                    connectionInfo = items[j].getClosestConnectionArea(dragged, pos);
                    connectionDistance = connectionInfo.distance;

                    if (connectionInfo.area && //there is a compatible match
                        (minDistance === null || connectionDistance < minDistance)){

                        closestItem = items[j];
                        closestArea = connectionInfo.area;
                        minDistance = closestArea;
                    }

                }
            }
            self.logger.debug("Hovering over " + items.join(","));

            if (closestItem){
                //Deactivate the previous connection area
                if (draggedUI.data(ITEM_TAG)){
                    otherItemId = draggedUI.data(ITEM_TAG);
                    self.items[otherItemId].deactivateConnectionAreas();
                }

                //set the closest item
                closestItem.setActiveConnectionArea(closestArea);
                self.dropFocus = SNAP_CONSTANTS.ITEM;

                //Store the data in the dragged object
                draggedUI.data(ITEM_TAG, closestItem.id);
            }

            if (self._ui !== null){
                setTimeout(self._updateHighlights, 100, self);
            }
        }
    };

    return SnapEditorWidgetHighlightUpdater;
});
<commit_msg>Minor changes<commit_after>/*globals define*/
/*
 * @author brollb / https://github/brollb
 */
//This is the connection highlight updater
define(['./SnapEditorWidget.Constants.js'], function (SNAP_CONSTANTS) {

    "use strict";

    var SnapEditorWidgetHighlightUpdater,
        ITEM_TAG = "current_droppable_item";

    SnapEditorWidgetHighlightUpdater = function () {
    };

    SnapEditorWidgetHighlightUpdater.prototype.registerDraggingItem = function (ui) {
        var i;

        this._ui = ui;
        this._underItems = [];
        this._draggedIds = [];

        i = this._ui.children().length;
        while (i--){
            this._draggedIds.push(this._ui.children()[i].id);
        }
    };

    SnapEditorWidgetHighlightUpdater.prototype.unregisterDraggingItem = function () {
        this._ui = null;
        this._underItems = null;
    };

    SnapEditorWidgetHighlightUpdater.prototype.registerUnderItem = function (underItem) {
        if (this._underItems !== null){
            this._underItems.push(underItem);

            if (this._underItems.length === 1){
                this._updateHighlights(this);
            }
        }
    };

    SnapEditorWidgetHighlightUpdater.prototype.unregisterUnderItem = function (item) {
        var i = this._underItems.indexOf(item),
            ui = this._ui;

        if (i !== -1){
            this._underItems.splice(i,1);
            if (ui.data(ITEM_TAG) === item.id){
                item.deactivateConnectionAreas();
                this.dropFocus = SNAP_CONSTANTS.BACKGROUND;

                //Remove data from dragged ui
                ui.removeData(ITEM_TAG);
            }
        }
    };

    SnapEditorWidgetHighlightUpdater.prototype._updateHighlights = function (self) {
        var items,
            closestArea,
            closestItem,
            connectionDistance,
            connectionInfo,
            draggedUI,
            draggedId,
            dragged,
            draggedIds,
            pos,
            otherItemId,
            minDistance,
            selector,
            j;

        if (self._underItems && self._underItems.length){

            items = self._underItems.slice();
            draggedUI = self._ui;
            selector = '#' + draggedUI.attr('id') + '.' + draggedUI.attr('class');
            draggedId = draggedUI.attr('id');
            dragged = self.items[draggedId];
            draggedIds = [];
            minDistance = null;
            closestItem = null;
            closestArea = null;

            pos = $(selector).position();
            pos.left -= items[0].$el.parent().offset().left;
            pos.top -= items[0].$el.parent().offset().top;

            //Update the highlight
            for (j = items.length-1; j >= 0; j--){
                if(draggedIds.indexOf(items[j].id) === -1){//If it isn't hovering over itself
                    connectionInfo = items[j].getClosestConnectionArea(dragged, pos);
                    connectionDistance = connectionInfo.distance;

                    if (connectionInfo.area && //there is a compatible match
                        (minDistance === null || connectionDistance < minDistance)){

                        closestItem = items[j];
                        closestArea = connectionInfo.area;
                        minDistance = closestArea;
                    }

                }
            }
            self.logger.debug("Hovering over " + items.join(","));

            if (closestItem){
                //Deactivate the previous connection area
                if (draggedUI.data(ITEM_TAG)){
                    otherItemId = draggedUI.data(ITEM_TAG);
                    self.items[otherItemId].deactivateConnectionAreas();
                }

                //set the closest item
                closestItem.setActiveConnectionArea(closestArea);
                self.dropFocus = SNAP_CONSTANTS.ITEM;

                //Store the data in the dragged object
                draggedUI.data(ITEM_TAG, closestItem.id);
            }

            if (self._ui !== null){
                setTimeout(self._updateHighlights, 100, self);
            }
        }
    };

    return SnapEditorWidgetHighlightUpdater;
});
<|endoftext|>


<commit_before>/* Like Python's |range|, but without |step|. */
function range(start, stop) {
  if (stop === undefined) {
    stop = start;
    start = 0;
  }

  var result = new Array(Math.max(0, stop - start));
  for (var i = 0, j = start; j < stop; i++, j++) {
    result[i] = j;
  }
  return result;
}

function contains(array, value) {
  /*
   * Stupid IE does not have Array.prototype.indexOf, otherwise this function
   * would be a one-liner.
   */
  var length = array.length;
  for (var i = 0; i < length; i++) {
    if (array[i] === value) {
      return true;
    }
  }
  return false;
}

function each(array, callback) {
  var length = array.length;
  for (var i = 0; i < length; i++) {
    callback(array[i], i);
  }
}

function map(array, callback) {
  var result = [];
  var length = array.length;
  for (var i = 0; i < length; i++) {
    result[i] = callback(array[i], i);
  }
  return result;
}

/*
 * Returns a string padded on the left to a desired length with a character.
 *
 * The code needs to be in sync with the code template in the compilation
 * function for "action" nodes.
 */
function padLeft(input, padding, length) {
  var result = input;

  var padLength = length - input.length;
  for (var i = 0; i < padLength; i++) {
    result = padding + result;
  }

  return result;
}

/*
 * Returns an escape sequence for given character. Uses \x for characters <=
 * 0xFF to save space, \u for the rest.
 *
 * The code needs to be in sync with the code template in the compilation
 * function for "action" nodes.
 */
function escape(ch) {
  var charCode = ch.charCodeAt(0);
  var escapeChar;
  var length;

  if (charCode <= 0xFF) {
    escapeChar = 'x';
    length = 2;
  } else {
    escapeChar = 'u';
    length = 4;
  }

  return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}

/*
 * Surrounds the string with quotes and escapes characters inside so that the
 * result is a valid JavaScript string.
 *
 * The code needs to be in sync with the code template in the compilation
 * function for "action" nodes.
 */
function quote(s) {
  /*
   * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a string
   * literal except for the closing quote character, backslash, carriage return,
   * line separator, paragraph separator, and line feed. Any character may
   * appear in the form of an escape sequence.
   *
   * For portability, we also escape escape all control and non-ASCII
   * characters. Note that "\0" and "\v" escape sequences are not used because
   * JSHint does not like the first and IE the second.
   */
  return '"' + s
    .replace(/\\/g, '\\\\')  // backslash
    .replace(/"/g, '\\"')    // closing quote character
    .replace(/\x08/g, '\\b') // backspace
    .replace(/\t/g, '\\t')   // horizontal tab
    .replace(/\n/g, '\\n')   // line feed
    .replace(/\f/g, '\\f')   // form feed
    .replace(/\r/g, '\\r')   // carriage return
    .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
    + '"';
}

/*
 * Escapes characters inside the string so that it can be used as a list of
 * characters in a character class of a regular expression.
 */
function quoteForRegexpClass(s) {
  /*
   * Based on ECMA-262, 5th ed., 7.8.5 & 15.10.1.
   *
   * For portability, we also escape escape all control and non-ASCII
   * characters.
   */
  return s
    .replace(/\\/g, '\\\\')  // backslash
    .replace(/\//g, '\\/')   // closing slash
    .replace(/\]/g, '\\]')   // closing bracket
    .replace(/-/g, '\\-')    // dash
    .replace(/\0/g, '\\0')   // null, IE needs this
    .replace(/\t/g, '\\t')   // horizontal tab
    .replace(/\n/g, '\\n')   // line feed
    .replace(/\v/g, '\\x0B') // vertical tab
    .replace(/\f/g, '\\f')   // form feed
    .replace(/\r/g, '\\r')   // carriage return
    .replace(/[\x01-\x08\x0E-\x1F\x80-\uFFFF]/g, escape);
}

/*
 * Builds a node visitor -- a function which takes a node and any number of
 * other parameters, calls an appropriate function according to the node type,
 * passes it all its parameters and returns its value. The functions for various
 * node types are passed in a parameter to |buildNodeVisitor| as a hash.
 */
function buildNodeVisitor(functions) {
  return function(node) {
    return functions[node.type].apply(null, arguments);
  };
}
<commit_msg>Remove comment about IE in |quoteForRegexpClass|<commit_after>/* Like Python's |range|, but without |step|. */
function range(start, stop) {
  if (stop === undefined) {
    stop = start;
    start = 0;
  }

  var result = new Array(Math.max(0, stop - start));
  for (var i = 0, j = start; j < stop; i++, j++) {
    result[i] = j;
  }
  return result;
}

function contains(array, value) {
  /*
   * Stupid IE does not have Array.prototype.indexOf, otherwise this function
   * would be a one-liner.
   */
  var length = array.length;
  for (var i = 0; i < length; i++) {
    if (array[i] === value) {
      return true;
    }
  }
  return false;
}

function each(array, callback) {
  var length = array.length;
  for (var i = 0; i < length; i++) {
    callback(array[i], i);
  }
}

function map(array, callback) {
  var result = [];
  var length = array.length;
  for (var i = 0; i < length; i++) {
    result[i] = callback(array[i], i);
  }
  return result;
}

/*
 * Returns a string padded on the left to a desired length with a character.
 *
 * The code needs to be in sync with the code template in the compilation
 * function for "action" nodes.
 */
function padLeft(input, padding, length) {
  var result = input;

  var padLength = length - input.length;
  for (var i = 0; i < padLength; i++) {
    result = padding + result;
  }

  return result;
}

/*
 * Returns an escape sequence for given character. Uses \x for characters <=
 * 0xFF to save space, \u for the rest.
 *
 * The code needs to be in sync with the code template in the compilation
 * function for "action" nodes.
 */
function escape(ch) {
  var charCode = ch.charCodeAt(0);
  var escapeChar;
  var length;

  if (charCode <= 0xFF) {
    escapeChar = 'x';
    length = 2;
  } else {
    escapeChar = 'u';
    length = 4;
  }

  return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}

/*
 * Surrounds the string with quotes and escapes characters inside so that the
 * result is a valid JavaScript string.
 *
 * The code needs to be in sync with the code template in the compilation
 * function for "action" nodes.
 */
function quote(s) {
  /*
   * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a string
   * literal except for the closing quote character, backslash, carriage return,
   * line separator, paragraph separator, and line feed. Any character may
   * appear in the form of an escape sequence.
   *
   * For portability, we also escape escape all control and non-ASCII
   * characters. Note that "\0" and "\v" escape sequences are not used because
   * JSHint does not like the first and IE the second.
   */
  return '"' + s
    .replace(/\\/g, '\\\\')  // backslash
    .replace(/"/g, '\\"')    // closing quote character
    .replace(/\x08/g, '\\b') // backspace
    .replace(/\t/g, '\\t')   // horizontal tab
    .replace(/\n/g, '\\n')   // line feed
    .replace(/\f/g, '\\f')   // form feed
    .replace(/\r/g, '\\r')   // carriage return
    .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
    + '"';
}

/*
 * Escapes characters inside the string so that it can be used as a list of
 * characters in a character class of a regular expression.
 */
function quoteForRegexpClass(s) {
  /*
   * Based on ECMA-262, 5th ed., 7.8.5 & 15.10.1.
   *
   * For portability, we also escape escape all control and non-ASCII
   * characters.
   */
  return s
    .replace(/\\/g, '\\\\')  // backslash
    .replace(/\//g, '\\/')   // closing slash
    .replace(/\]/g, '\\]')   // closing bracket
    .replace(/-/g, '\\-')    // dash
    .replace(/\0/g, '\\0')   // null
    .replace(/\t/g, '\\t')   // horizontal tab
    .replace(/\n/g, '\\n')   // line feed
    .replace(/\v/g, '\\x0B') // vertical tab
    .replace(/\f/g, '\\f')   // form feed
    .replace(/\r/g, '\\r')   // carriage return
    .replace(/[\x01-\x08\x0E-\x1F\x80-\uFFFF]/g, escape);
}

/*
 * Builds a node visitor -- a function which takes a node and any number of
 * other parameters, calls an appropriate function according to the node type,
 * passes it all its parameters and returns its value. The functions for various
 * node types are passed in a parameter to |buildNodeVisitor| as a hash.
 */
function buildNodeVisitor(functions) {
  return function(node) {
    return functions[node.type].apply(null, arguments);
  };
}
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular.module('documents')
        .component('scientillaDocument', {
            templateUrl: 'partials/scientillaDocument.html',
            controller: scientillaDocument,
            controllerAs: 'vm',
            bindings: {
                document: "<",
                showPrivateTags: "<?",
                checkDuplicates: '<?'
            }
        });

    scientillaDocument.$inject = [
        'ModalService',
        'config',
        'DocumentLabels',
        'context'
    ];

    function scientillaDocument(ModalService, config, DocumentLabels, context) {
        var vm = this;
        vm.openDetails = openDetails;
        vm.hasMainGroupAffiliation = hasMainGroupAffiliation;
        vm.editTags = editTags;
        vm.isSynchronized = isSynchronized;

        const researchEntity = context.getResearchEntity();
        if (_.isNil(vm.checkDuplicates))
            vm.checkDuplicates = true;

        vm.$onInit = function () {
            vm.showPrivateTags = vm.showPrivateTags || false;
            vm.verifiedCount = getVerifiedCount();
            if (vm.checkDuplicates)
                checkDuplicate();

            addLabels();
        };

        function checkDuplicate() {
            function isSuggested(doc) {
                const f = researchEntity.getType() === 'user' ? 'authors' : 'groups';
                return !doc[f].some(re => re.id === researchEntity.id);
            }

            if (!vm.document.duplicates || !vm.document.duplicates.length)
                return;
            let documentLabel;
            //verified and duplicated
            if (vm.document.kind === 'v' && !isSuggested(vm.document) && vm.document.duplicates.some(d => d.duplicateKind === 'v'))
                documentLabel = DocumentLabels.DUPLICATE;
            //verified and duplicates in drafts (no real duplicates)
            else if (vm.document.kind === 'v' && !isSuggested(vm.document) && vm.document.duplicates.every(d => d.duplicateKind === 'd'))
                ;
            //draft and duplicated
            else if (vm.document.kind === 'd' && vm.document.duplicates.every(d => d.duplicateKind === 'd'))
                documentLabel = DocumentLabels.DUPLICATE;
            //draft and already verified
            else if (vm.document.kind === 'd' && vm.document.duplicates.some(d => d.duplicateKind === 'v'))
                documentLabel = DocumentLabels.ALREADY_VERIFIED;
            //external and already verified
            else if (vm.document.kind === 'e' && vm.document.duplicates.some(d => d.duplicateKind === 'v'))
                documentLabel = DocumentLabels.ALREADY_VERIFIED;
            //external and already in drafts
            else if (vm.document.kind === 'e' && vm.document.duplicates.every(d => d.duplicateKind === 'd'))
                documentLabel = DocumentLabels.ALREADY_IN_DRAFTS;
            //suggested and already verified
            else if (vm.document.kind === 'v' && isSuggested(vm.document) && vm.document.duplicates.some(d => d.duplicateKind === 'v'))
                documentLabel = DocumentLabels.ALREADY_VERIFIED;
            //suggested and already in drafts
            else if (vm.document.kind === 'v' && isSuggested(vm.document) && vm.document.duplicates.every(d => d.duplicateKind === 'd'))
                documentLabel = DocumentLabels.ALREADY_IN_DRAFTS;
            if (documentLabel)
                vm.document.addLabel(documentLabel);
        }

        function addLabels() {
            console.log(vm.document.createdAt);
            if (vm.document.kind === 'd' && (new Date(vm.document.createdAt)).toDateString() === (new Date()).toDateString())
                vm.document.addLabel(DocumentLabels.NEW);
        }

        function openDetails() {
            ModalService
                .openScientillaDocumentDetails(vm.document);
        }

        function hasMainGroupAffiliation() {
            return _.some(vm.document.affiliations, function (a) {
                return a.institute === config.mainInstitute.id;
            });
        }

        function editTags() {
            ModalService.openScientillaTagForm(vm.document);
        }

        function getVerifiedCount() {
            return vm.document.authorships.filter(a => a.researchEntity)
                .concat(vm.document.groupAuthorships).length;
        }

        function isSynchronized() {
            return vm.document.synchronized && vm.document.origin === 'scopus';
        }
    }

})();<commit_msg>Removed console.log<commit_after>(function () {
    'use strict';

    angular.module('documents')
        .component('scientillaDocument', {
            templateUrl: 'partials/scientillaDocument.html',
            controller: scientillaDocument,
            controllerAs: 'vm',
            bindings: {
                document: "<",
                showPrivateTags: "<?",
                checkDuplicates: '<?'
            }
        });

    scientillaDocument.$inject = [
        'ModalService',
        'config',
        'DocumentLabels',
        'context'
    ];

    function scientillaDocument(ModalService, config, DocumentLabels, context) {
        var vm = this;
        vm.openDetails = openDetails;
        vm.hasMainGroupAffiliation = hasMainGroupAffiliation;
        vm.editTags = editTags;
        vm.isSynchronized = isSynchronized;

        const researchEntity = context.getResearchEntity();
        if (_.isNil(vm.checkDuplicates))
            vm.checkDuplicates = true;

        vm.$onInit = function () {
            vm.showPrivateTags = vm.showPrivateTags || false;
            vm.verifiedCount = getVerifiedCount();
            if (vm.checkDuplicates)
                checkDuplicate();

            addLabels();
        };

        function checkDuplicate() {
            function isSuggested(doc) {
                const f = researchEntity.getType() === 'user' ? 'authors' : 'groups';
                return !doc[f].some(re => re.id === researchEntity.id);
            }

            if (!vm.document.duplicates || !vm.document.duplicates.length)
                return;
            let documentLabel;
            //verified and duplicated
            if (vm.document.kind === 'v' && !isSuggested(vm.document) && vm.document.duplicates.some(d => d.duplicateKind === 'v'))
                documentLabel = DocumentLabels.DUPLICATE;
            //verified and duplicates in drafts (no real duplicates)
            else if (vm.document.kind === 'v' && !isSuggested(vm.document) && vm.document.duplicates.every(d => d.duplicateKind === 'd'))
                ;
            //draft and duplicated
            else if (vm.document.kind === 'd' && vm.document.duplicates.every(d => d.duplicateKind === 'd'))
                documentLabel = DocumentLabels.DUPLICATE;
            //draft and already verified
            else if (vm.document.kind === 'd' && vm.document.duplicates.some(d => d.duplicateKind === 'v'))
                documentLabel = DocumentLabels.ALREADY_VERIFIED;
            //external and already verified
            else if (vm.document.kind === 'e' && vm.document.duplicates.some(d => d.duplicateKind === 'v'))
                documentLabel = DocumentLabels.ALREADY_VERIFIED;
            //external and already in drafts
            else if (vm.document.kind === 'e' && vm.document.duplicates.every(d => d.duplicateKind === 'd'))
                documentLabel = DocumentLabels.ALREADY_IN_DRAFTS;
            //suggested and already verified
            else if (vm.document.kind === 'v' && isSuggested(vm.document) && vm.document.duplicates.some(d => d.duplicateKind === 'v'))
                documentLabel = DocumentLabels.ALREADY_VERIFIED;
            //suggested and already in drafts
            else if (vm.document.kind === 'v' && isSuggested(vm.document) && vm.document.duplicates.every(d => d.duplicateKind === 'd'))
                documentLabel = DocumentLabels.ALREADY_IN_DRAFTS;
            if (documentLabel)
                vm.document.addLabel(documentLabel);
        }

        function addLabels() {
            if (vm.document.kind === 'd' && (new Date(vm.document.createdAt)).toDateString() === (new Date()).toDateString())
                vm.document.addLabel(DocumentLabels.NEW);
        }

        function openDetails() {
            ModalService
                .openScientillaDocumentDetails(vm.document);
        }

        function hasMainGroupAffiliation() {
            return _.some(vm.document.affiliations, function (a) {
                return a.institute === config.mainInstitute.id;
            });
        }

        function editTags() {
            ModalService.openScientillaTagForm(vm.document);
        }

        function getVerifiedCount() {
            return vm.document.authorships.filter(a => a.researchEntity)
                .concat(vm.document.groupAuthorships).length;
        }

        function isSynchronized() {
            return vm.document.synchronized && vm.document.origin === 'scopus';
        }
    }

})();<|endoftext|>


<commit_before>
/* eslint-disable max-len */

import {describe} from 'ava-spec';

const jssm = require('../../../build/jssm.es5.js');

describe('compile/1', async _parse_it => {

  describe('a->b;', async it => {
    const a_to_b_str = `a->b;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(a_to_b_str));
    }) );
  });

  describe('a->b->c;', async it => {
    const a_to_b_to_c_str = `a->b->c;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(a_to_b_to_c_str));
    }) );
  });

  describe('template tokens', async it => {
    const a_through_e_token_str = `a->${'b'}->c->${'d'}->e;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(a_through_e_token_str));
    }) );
  });

  describe('all arrows', async it => {
    const all_arrows = `a -> b => c ~> d <-> e <=> f <~> g <-=> h <=-> i <~-> j <-~> k <=~> l <~=> m <- n <= o <~ p;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(all_arrows));
    }) );
  });

  describe('all unicode arrows', async it => {
    const all_arrows = `a ← b ⇐ c ↚ d → e ⇒ f ↛ g ↔ h ⇔ i ↮ j ←⇒ k ⇐→ l ←↛ m ↚→ n ⇐↛ o ↚⇒ p;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(all_arrows));
    }) );
  });

});

describe('error catchery', async _parse_it => {

  describe('unknown rule', async it => {
    it('throws', t => t.throws( () => {
      jssm.compile( [{"key":"FAKE_RULE","from":"a","se":{"kind":"->","to":"b"}}] );
    } ));
  });

});

// stochable
<commit_msg>get coverage back<commit_after>
/* eslint-disable max-len */

import {describe} from 'ava-spec';

const jssm = require('../../../build/jssm.es5.js');

describe('compile/1', async _parse_it => {

  describe('a->b;', async it => {
    const a_to_b_str = `a->b;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(a_to_b_str));
    }) );
  });

  describe('a->b->c;', async it => {
    const a_to_b_to_c_str = `a->b->c;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(a_to_b_to_c_str));
    }) );
  });

  describe('template tokens', async it => {
    const a_through_e_token_str = `a->${'b'}->c->${'d'}->e;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(a_through_e_token_str));
    }) );
  });

  describe('all arrows', async it => {
    const all_arrows = `a -> b => c ~> d <-> e <=> f <~> g <-=> h <=-> i <~-> j <-~> k <=~> l <~=> m <- n <= o <~ p;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(all_arrows));
    }) );
  });

  describe('all unicode arrows', async it => {
    const all_arrows = `a ← b ⇐ c ↚ d → e ⇒ f ↛ g ↔ h ⇔ i ↮ j ←⇒ k ⇐→ l ←↛ m ↚→ n ⇐↛ o ↚⇒ p;`;
    it('doesn\'t throw', t => t.notThrows(() => {
      jssm.compile(jssm.parse(all_arrows));
    }) );
  });

});

describe('error catchery', async _parse_it => {

  describe('unknown rule', async it => {
    it('throws', t => t.throws( () => {
      jssm.compile( [{"key":"FAKE_RULE","from":"a","se":{"kind":"->","to":"b"}}] );
    } ));
  });

  describe('unnamed state_declaration', async it => {
    it('throws', t => t.throws( () => {
      jssm.compile( [{"key":"state_declaration"}] );
    } ));
  });

});

// stochable
<|endoftext|>


<commit_before>/**
 * Directive for handling new buttons added
 * TODO 1.) support to backend and saving
 * TODO 2.) Fix refreshing issue
 * 2.) can be fixed when we tie this to the backend since we will look for issues added by
 * the community and look to the database to populate the frontend issues
 */
app.directive("issuenew", function($compile) {
    var count = 0;  //in case we want to limit the amount of issues that can be added
    var link = function (scope) {
        scope.populateissue = function () {
            if (count >= 3) {
                console.log("limit reached");
            } else {
            angular.element(document.getElementById('space-for-issues'))
                .append($compile("

" +
                "<button class='btn btn-primary btn-block'>{{issue.new_title}}</button>" +
                "

{{issue.new_description}}

")(scope));
                count++;
            }
        };
    };
    return {
        restrict: "E",
        link: link,
        template: "<button ng-click='populateissue()' type='button' class='btn btn-success'>Add New Issue</button>"
    }
});

/**
 * D3 directive that is embedded in explore-controller.
 */
app.directive("bars", function () {
    return {
        restrict: 'E',
        replace: true,
        template: '

',
        link: function (scope, element, attrs) {
            var chart = c3.generate({
                data: {
                    columns: [
                        ['strongly disagree', 30, 200, 200, 400, 150, 250],
                        ['disagree', 130, 100, 100, 200, 150, 50],
                        ['no opinion', 230, 200, 200, 300, 250, 250],
                        ['agree', 75, 100, 450, 0, 300, 200],
                        ['strongly agree', 250, 300, 20, 85, 430, 500],
                        ['you', 75, 50, 320, 100, 750, 175]

                    ],
                    type: 'bar',
                    types: {
                        you: 'scatter'
                    },
                    order: null,
                    colors: {
                      'strongly disagree': '#920000',
                      disagree: '#ec1b1b',
                      'no opinion': '#dbd9d9' ,
                      agree: '#0087d8',
                      'strongly agree': '095983',
                      you: '#000000'

                    },
                    groups: [
                        ['strongly disagree', 'disagree', 'no opinion', 'agree', 'strongly agree', 'you']
                    ]
                },
                axis: {
                    rotated: true,
                    y:{
                        max: 1300,
                        min: -200
                    },
                },
                grid: {
                    x2: {
                        show: true
                    }
                }
            });

            /*
                Animation stuff, may or may not be useful
             */
            //setTimeout(function () {
            //    chart.load({
            //        columns: [['fly_in', 50, 20, 400, 30, 600, 50]]
            //    });
            //}, 1500);
            //
            //setTimeout(function () {
            //    chart.groups([['strongly disagree', 'disagree', 'no opinion', 'agree', 'strongly agree', 'you', 'fly_in']])
            //}, 2000);
        }
    };
});<commit_msg>forgot a '#'<commit_after>/**
 * Directive for handling new buttons added
 * TODO 1.) support to backend and saving
 * TODO 2.) Fix refreshing issue
 * 2.) can be fixed when we tie this to the backend since we will look for issues added by
 * the community and look to the database to populate the frontend issues
 */
app.directive("issuenew", function($compile) {
    var count = 0;  //in case we want to limit the amount of issues that can be added
    var link = function (scope) {
        scope.populateissue = function () {
            if (count >= 3) {
                console.log("limit reached");
            } else {
            angular.element(document.getElementById('space-for-issues'))
                .append($compile("

" +
                "<button class='btn btn-primary btn-block'>{{issue.new_title}}</button>" +
                "

{{issue.new_description}}

")(scope));
                count++;
            }
        };
    };
    return {
        restrict: "E",
        link: link,
        template: "<button ng-click='populateissue()' type='button' class='btn btn-success'>Add New Issue</button>"
    }
});

/**
 * D3 directive that is embedded in explore-controller.
 */
app.directive("bars", function () {
    return {
        restrict: 'E',
        replace: true,
        template: '

',
        link: function (scope, element, attrs) {
            var chart = c3.generate({
                data: {
                    columns: [
                        ['strongly disagree', 30, 200, 200, 400, 150, 250],
                        ['disagree', 130, 100, 100, 200, 150, 50],
                        ['no opinion', 230, 200, 200, 300, 250, 250],
                        ['agree', 75, 100, 450, 0, 300, 200],
                        ['strongly agree', 250, 300, 20, 85, 430, 500],
                        ['you', 75, 50, 320, 100, 750, 175]

                    ],
                    type: 'bar',
                    types: {
                        you: 'scatter'
                    },
                    order: null,
                    colors: {
                      'strongly disagree': '#920000',
                      disagree: '#ec1b1b',
                      'no opinion': '#dbd9d9' ,
                      agree: '#0087d8',
                      'strongly agree': '#095983',
                      you: '#000000'

                    },
                    groups: [
                        ['strongly disagree', 'disagree', 'no opinion', 'agree', 'strongly agree', 'you']
                    ]
                },
                axis: {
                    rotated: true,
                    y:{
                        max: 1300,
                        min: -200
                    },
                },
                grid: {
                    x2: {
                        show: true
                    }
                }
            });

            /*
                Animation stuff, may or may not be useful
             */
            //setTimeout(function () {
            //    chart.load({
            //        columns: [['fly_in', 50, 20, 400, 30, 600, 50]]
            //    });
            //}, 1500);
            //
            //setTimeout(function () {
            //    chart.groups([['strongly disagree', 'disagree', 'no opinion', 'agree', 'strongly agree', 'you', 'fly_in']])
            //}, 2000);
        }
    };
});<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  var TabDataTable = require('utils/tab-datatable');
  var VMsTableUtils = require('./utils/datatable-common');
  var OpenNebulaVM = require('opennebula/vm');
  var SunstoneConfig = require('sunstone-config');
  var Locale = require('utils/locale');
  var StateActions = require('./utils/state-actions');
  var Sunstone = require('sunstone');
  var Vnc = require('utils/vnc');
  var Spice = require('utils/spice');
  var Notifier = require('utils/notifier');

  /*
    CONSTANTS
   */

  var RESOURCE = "VM";
  var XML_ROOT = "VM";
  var TAB_NAME = require('./tabId');

  /*
    CONSTRUCTOR
   */

  function Table(dataTableId, conf) {
    this.conf = conf || {};
    this.tabId = TAB_NAME;
    this.dataTableId = dataTableId;
    this.resource = RESOURCE;
    this.xmlRoot = XML_ROOT;

    this.dataTableOptions = {
      "bAutoWidth": false,
      "bSortClasses" : false,
      "bDeferRender": true,
      "aoColumnDefs": [
          {"bSortable": false, "aTargets": ["check", 6, 7, 11]},
          {"sWidth": "35px", "aTargets": [0]},
          {"bVisible": true, "aTargets": SunstoneConfig.tabTableColumns(TAB_NAME)},
          {"bVisible": false, "aTargets": ['_all']}
      ]
    }

    this.columns = VMsTableUtils.columns;

    this.selectOptions = {
      "id_index": 1,
      "name_index": 4,
      "select_resource": Locale.tr("Please select a VM from the list"),
      "you_selected": Locale.tr("You selected the following VM:"),
      "select_resource_multiple": Locale.tr("Please select one or more VMs from the list"),
      "you_selected_multiple": Locale.tr("You selected the following VMs:")
    };

    this.totalVms = 0;
    this.activeVms = 0;
    this.pendingVms = 0;
    this.failedVms = 0;
    this.offVms = 0;

    TabDataTable.call(this);
  };

  Table.prototype = Object.create(TabDataTable.prototype);
  Table.prototype.constructor = Table;
  Table.prototype.elementArray = _elementArray;
  Table.prototype.initialize = _initialize;
  Table.prototype.preUpdateView = _preUpdateView;
  Table.prototype.postUpdateView = _postUpdateView;

  return Table;

  /*
    FUNCTION DEFINITIONS
   */

  function _elementArray(element_json) {
    var element = element_json[XML_ROOT];
    var state = parseInt(element.STATE);

    this.totalVms++;
    switch (state) {
      case OpenNebulaVM.STATES.INIT:
      case OpenNebulaVM.STATES.PENDING:
      case OpenNebulaVM.STATES.HOLD:
        this.pendingVms++;
        break;
      case OpenNebulaVM.STATES.ACTIVE:
        if (OpenNebulaVM.isFailureState(element.LCM_STATE)) {
          this.failedVms++;
        } else {
          this.activeVms++;
        }
        break;
      case OpenNebulaVM.STATES.STOPPED:
      case OpenNebulaVM.STATES.SUSPENDED:
      case OpenNebulaVM.STATES.POWEROFF:
        this.offVms++;
        break;
      default:
        break;
    }

    return VMsTableUtils.elementArray(element_json);
  }

  function _preUpdateView() {
    StateActions.disableAllStateActions();

    this.totalVms = 0;
    this.activeVms = 0;
    this.pendingVms = 0;
    this.failedVms = 0;
    this.offVms = 0;
  }

  function _postUpdateView() {
    $(".total_vms").text(this.totalVms);
    $(".active_vms").text(this.activeVms);
    $(".pending_vms").text(this.pendingVms);
    $(".failed_vms").text(this.failedVms);
    $(".off_vms").text(this.offVms);
  }

  function _initialize(opts) {
    var that = this;

    TabDataTable.prototype.initialize.call(this, opts);

    $('#' + this.dataTableId).on("click", '.vnc', function() {
      var vmId = $(this).attr('vm_id');

      if (!Vnc.lockStatus()) {
        Vnc.lock();
        Sunstone.runAction("VM.startvnc_action", vmId);
      } else {
        Notifier.notifyError(Locale.tr("VNC Connection in progress"))
      }

      return false;
    });

    $('#' + this.dataTableId).on("click", '.spice', function() {
      var vmId = $(this).attr('vm_id');

      if (!Spice.lockStatus()) {
        Spice.lock();
        Sunstone.runAction("VM.startspice_action", vmId);
      } else {
        Notifier.notifyError(Locale.tr("SPICE Connection in progress"))
      }

      return false;
    });

    $('#' + this.dataTableId).on("change", 'tbody input.check_item', function() {
      if ($(this).is(":checked")){
        StateActions.enableStateActions($(this).attr("state"), $(this).attr("lcm_state"));
      } else {
        // First disable all actions
        StateActions.disableAllStateActions();

        // Enable actions available to any of the selected VMs
        var nodes = $('tr', that.dataTable); //visible nodes only
        $.each($('input.check_item:checked', nodes), function(){
          StateActions.enableStateActions($(this).attr("state"), $(this).attr("lcm_state"));
        });

      }

      return true;
    });

  }
});
<commit_msg>Bug #4025: Prevent race condition in call to disableAllStateActions<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  var TabDataTable = require('utils/tab-datatable');
  var VMsTableUtils = require('./utils/datatable-common');
  var OpenNebulaVM = require('opennebula/vm');
  var SunstoneConfig = require('sunstone-config');
  var Locale = require('utils/locale');
  var StateActions = require('./utils/state-actions');
  var Sunstone = require('sunstone');
  var Vnc = require('utils/vnc');
  var Spice = require('utils/spice');
  var Notifier = require('utils/notifier');

  /*
    CONSTANTS
   */

  var RESOURCE = "VM";
  var XML_ROOT = "VM";
  var TAB_NAME = require('./tabId');

  /*
    CONSTRUCTOR
   */

  function Table(dataTableId, conf) {
    this.conf = conf || {};
    this.tabId = TAB_NAME;
    this.dataTableId = dataTableId;
    this.resource = RESOURCE;
    this.xmlRoot = XML_ROOT;

    this.dataTableOptions = {
      "bAutoWidth": false,
      "bSortClasses" : false,
      "bDeferRender": true,
      "aoColumnDefs": [
          {"bSortable": false, "aTargets": ["check", 6, 7, 11]},
          {"sWidth": "35px", "aTargets": [0]},
          {"bVisible": true, "aTargets": SunstoneConfig.tabTableColumns(TAB_NAME)},
          {"bVisible": false, "aTargets": ['_all']}
      ]
    }

    this.columns = VMsTableUtils.columns;

    this.selectOptions = {
      "id_index": 1,
      "name_index": 4,
      "select_resource": Locale.tr("Please select a VM from the list"),
      "you_selected": Locale.tr("You selected the following VM:"),
      "select_resource_multiple": Locale.tr("Please select one or more VMs from the list"),
      "you_selected_multiple": Locale.tr("You selected the following VMs:")
    };

    this.totalVms = 0;
    this.activeVms = 0;
    this.pendingVms = 0;
    this.failedVms = 0;
    this.offVms = 0;

    TabDataTable.call(this);
  };

  Table.prototype = Object.create(TabDataTable.prototype);
  Table.prototype.constructor = Table;
  Table.prototype.elementArray = _elementArray;
  Table.prototype.initialize = _initialize;
  Table.prototype.preUpdateView = _preUpdateView;
  Table.prototype.postUpdateView = _postUpdateView;

  return Table;

  /*
    FUNCTION DEFINITIONS
   */

  function _elementArray(element_json) {
    var element = element_json[XML_ROOT];
    var state = parseInt(element.STATE);

    this.totalVms++;
    switch (state) {
      case OpenNebulaVM.STATES.INIT:
      case OpenNebulaVM.STATES.PENDING:
      case OpenNebulaVM.STATES.HOLD:
        this.pendingVms++;
        break;
      case OpenNebulaVM.STATES.ACTIVE:
        if (OpenNebulaVM.isFailureState(element.LCM_STATE)) {
          this.failedVms++;
        } else {
          this.activeVms++;
        }
        break;
      case OpenNebulaVM.STATES.STOPPED:
      case OpenNebulaVM.STATES.SUSPENDED:
      case OpenNebulaVM.STATES.POWEROFF:
        this.offVms++;
        break;
      default:
        break;
    }

    return VMsTableUtils.elementArray(element_json);
  }

  function _preUpdateView() {
    var tab = $('#' + TAB_NAME);
    if (!Sunstone.rightInfoVisible(tab)){
      StateActions.disableAllStateActions();
    }

    this.totalVms = 0;
    this.activeVms = 0;
    this.pendingVms = 0;
    this.failedVms = 0;
    this.offVms = 0;
  }

  function _postUpdateView() {
    $(".total_vms").text(this.totalVms);
    $(".active_vms").text(this.activeVms);
    $(".pending_vms").text(this.pendingVms);
    $(".failed_vms").text(this.failedVms);
    $(".off_vms").text(this.offVms);
  }

  function _initialize(opts) {
    var that = this;

    TabDataTable.prototype.initialize.call(this, opts);

    $('#' + this.dataTableId).on("click", '.vnc', function() {
      var vmId = $(this).attr('vm_id');

      if (!Vnc.lockStatus()) {
        Vnc.lock();
        Sunstone.runAction("VM.startvnc_action", vmId);
      } else {
        Notifier.notifyError(Locale.tr("VNC Connection in progress"))
      }

      return false;
    });

    $('#' + this.dataTableId).on("click", '.spice', function() {
      var vmId = $(this).attr('vm_id');

      if (!Spice.lockStatus()) {
        Spice.lock();
        Sunstone.runAction("VM.startspice_action", vmId);
      } else {
        Notifier.notifyError(Locale.tr("SPICE Connection in progress"))
      }

      return false;
    });

    $('#' + this.dataTableId).on("change", 'tbody input.check_item', function() {
      if ($(this).is(":checked")){
        StateActions.enableStateActions($(this).attr("state"), $(this).attr("lcm_state"));
      } else {
        // First disable all actions
        StateActions.disableAllStateActions();

        // Enable actions available to any of the selected VMs
        var nodes = $('tr', that.dataTable); //visible nodes only
        $.each($('input.check_item:checked', nodes), function(){
          StateActions.enableStateActions($(this).attr("state"), $(this).attr("lcm_state"));
        });

      }

      return true;
    });

  }
});
<|endoftext|>


<commit_before>// Test for examples included in README.md
var helpers = require('./global-setup')
var path = require('path')

var describe = global.describe
var it = global.it
var beforeEach = global.beforeEach
var afterEach = global.afterEach

describe('example application launch', function () {
  helpers.setupTimeout(this)

  var app = null

  beforeEach(function () {
    return helpers.startApplication({
      args: [path.join(__dirname, 'fixtures', 'example')]
    }).then(function (startedApp) { app = startedApp })
  })

  afterEach(function () {
    return helpers.stopApplication(app)
  })

  it('opens a window', function () {
    return app.client.waitUntilWindowLoaded()
      .getWindowCount().should.eventually.equal(1)
      .browserWindow.isMinimized().should.eventually.be.false
      .browserWindow.isDevToolsOpened().should.eventually.be.false
      .browserWindow.isVisible().should.eventually.be.true
      .browserWindow.isFocused().should.eventually.be.true
      .browserWindow.getBounds().should.eventually.have.property('width', 800)
      .browserWindow.getBounds().should.eventually.have.property('height', 400)
  })

  describe('when the make larger button is clicked', function () {
    it('increases the window height and width by 10 pixels', function () {
      return app.client.waitUntilWindowLoaded()
        .getWindowHeight().should.eventually.equal(400)
        .getWindowWidth().should.eventually.equal(800)
        .click('.btn-make-bigger')
        .pause(1000)
        .getWindowHeight().should.eventually.equal(410)
        .getWindowWidth().should.eventually.equal(810)
    })
  })

  describe('when the make smaller button is clicked', function () {
    it('decreases the window height and width by 10 pixels', function () {
      return app.client.waitUntilWindowLoaded()
        .getWindowHeight().should.eventually.equal(400)
        .getWindowWidth().should.eventually.equal(800)
        .click('.btn-make-smaller')
        .pause(1000)
        .getWindowHeight().should.eventually.equal(390)
        .getWindowWidth().should.eventually.equal(790)
    })
  })
})
<commit_msg>Use browserWindow for more assertions<commit_after>// Test for examples included in README.md
var helpers = require('./global-setup')
var path = require('path')

var describe = global.describe
var it = global.it
var beforeEach = global.beforeEach
var afterEach = global.afterEach

describe('example application launch', function () {
  helpers.setupTimeout(this)

  var app = null

  beforeEach(function () {
    return helpers.startApplication({
      args: [path.join(__dirname, 'fixtures', 'example')]
    }).then(function (startedApp) { app = startedApp })
  })

  afterEach(function () {
    return helpers.stopApplication(app)
  })

  it('opens a window', function () {
    return app.client.waitUntilWindowLoaded()
      .getWindowCount().should.eventually.equal(1)
      .browserWindow.isMinimized().should.eventually.be.false
      .browserWindow.isDevToolsOpened().should.eventually.be.false
      .browserWindow.isVisible().should.eventually.be.true
      .browserWindow.isFocused().should.eventually.be.true
      .browserWindow.getBounds().should.eventually.have.property('width', 800)
      .browserWindow.getBounds().should.eventually.have.property('height', 400)
  })

  describe('when the make larger button is clicked', function () {
    it('increases the window height and width by 10 pixels', function () {
      return app.client.waitUntilWindowLoaded()
        .browserWindow.getBounds().should.eventually.have.property('width', 800)
        .browserWindow.getBounds().should.eventually.have.property('height', 400)
        .click('.btn-make-bigger')
        .pause(1000)
        .browserWindow.getBounds().should.eventually.have.property('width', 810)
        .browserWindow.getBounds().should.eventually.have.property('height', 410)
    })
  })

  describe('when the make smaller button is clicked', function () {
    it('decreases the window height and width by 10 pixels', function () {
      return app.client.waitUntilWindowLoaded()
        .browserWindow.getBounds().should.eventually.have.property('width', 800)
        .browserWindow.getBounds().should.eventually.have.property('height', 400)
        .click('.btn-make-smaller')
        .pause(1000)
        .browserWindow.getBounds().should.eventually.have.property('width', 790)
        .browserWindow.getBounds().should.eventually.have.property('height', 390)
    })
  })
})
<|endoftext|>