<commit_before>module.exports = {
	roles: ["@everyone"],
	descr: "Te asigna o elimina de un rol.",
	exec: (message, args) => {
		message.delete();
		//Si no se ha usado el comando correctamente, avisa al usuario de manera privada
		if(!args[1] || !args[2]){
			message.author.sendMessage("Uso: !rol join/leave [nombre]");
			return;
		}
		let roleName = args.splice(2).join(' ');
		let rol = roleName ? message.guild.roles.findKey("name", roleName) : "";
		//Si el rol no existe o no es auto asignable
		//avisa al usuario de manera privada
		if(!rol || !global.config.roles.includes(roleName)){
			message.author.sendMessage("Ese rol no existe o no es auto asignable :thinking:\nrevisa que lo hayas escrito correctamente.");
			return;
		}
		//Si el rol es auto asignable
		//busca que el argumento sea "leave" o "join"
		if (args[1] == "join") {
			message.member.addRole(rol).then(member =>
				message.author.sendMessage(`Te has unido a \`${roleName}\``)
			).catch(err => {
				message.author.sendMessage(`Se ha producido un error.`);
				console.log(err.message);
			});
			return;
		} else if (args[1] == "leave") {
			message.member.removeRole(rol).then(member =>
				message.author.sendMessage(`Has salido de \`${roleName}\``)
			).catch(err => {
				message.author.sendMessage(`Se ha producido un error.`);
				console.log(err.message);
			});
			return;
		}
		//Si el arugumento no es "leave" o "join", avisa al usuario de manera privada
		message.author.sendMessage("Uso: !rol join/leave [nombre].");
	}
}
<commit_msg>Fixed - !rol<commit_after>module.exports = {
	roles: ["@everyone"],
	descr: "Te asigna o elimina de un rol.",
	exec: (message, args) => {
		message.delete();
		//Si no se ha usado el comando correctamente, avisa al usuario de manera privada
		if(!args[1] || !args[2]){
			message.author.send("Uso: !rol join/leave [nombre]");
			return;
		}
		let roleName = args.splice(2).join(' ');
		let rol = roleName ? message.guild.roles.findKey("name", roleName) : "";
		//Si el rol no existe o no es auto asignable
		//avisa al usuario de manera privada
		if(!rol || !global.config.roles.includes(roleName)){
			message.author.send("Ese rol no existe o no es auto asignable :thinking:\nrevisa que lo hayas escrito correctamente.");
			return;
		}
		//Si el rol es auto asignable
		//busca que el argumento sea "leave" o "join"
		if (args[1] === "join") {
			message.member.addRole(rol).then(member =>
				message.author.send(`Te has unido a \`${roleName}\``)
			).catch(err => {
				message.author.send(`Se ha producido un error.`);
				console.log(err.message);
			});
			return;
		} else if (args[1] === "leave") {
			message.member.removeRole(rol).then(member =>
				message.author.send(`Has salido de \`${roleName}\``)
			).catch(err => {
				message.author.send(`Se ha producido un error.`);
				console.log(err.message);
			});
			return;
		}
		//Si el arugumento no es "leave" o "join", avisa al usuario de manera privada
		message.author.send("Uso: !rol join/leave [nombre].");
	}
}
<|endoftext|>


<commit_before>
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
const settings = require('./../../settings.json');
const createMute = require('./../lib/createMute');

async function command(params, message) {
    let muted = message.guild.roles.find(function (r) {
        if (r.name.toLowerCase().includes('mute')) return r
    })
    if (!muted)
        return muted = await createMute(guild);

    if (!(message.member.highestRole.position > muted.position)) {
        message.channel.send("You aren't Worthy\nhttps://media.tenor.com/images/c472d1ee8c75a50f700bd028cc1b10b9/tenor.gif");
        return;
    }

    let user = message.mentions.users.first();
    await message.guild.member(user).removeRole(muted);
    message.reply("unmuted");
}
/**
 * description of the command
 */
const description = "Adds a role to a user. \nSyntax: add <mention> to role";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<commit_msg>Update unmute.js<commit_after>
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
const settings = require('./../../settings.json');
const createMute = require('./../lib/createMute');

async function command(params, message) {
    let muted = message.guild.roles.find(function (r) {
        if (r.name.toLowerCase().includes('mute')) return r
    })
    if (!muted)
        return muted = await createMute(guild);

    if (!(message.member.highestRole.position > muted.position)) {
        message.channel.send("You aren't Worthy\nhttps://media.tenor.com/images/c472d1ee8c75a50f700bd028cc1b10b9/tenor.gif");
        return;
    }

    let user = message.mentions.users.first();
    await message.guild.member(user).removeRole(muted);
    message.reply("unmuted");
}
/**
 * description of the command
 */
const description = "unmutes a user";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<|endoftext|>


<commit_before>var irc = require('irc');
var config = require('./config.js');

var bot;
var commands;

var channel_blocks = {
	private_chat: {
		blocked: false,
		kudos_minus: false,
		kudos_plus: false,
		ultrachord: false,
	},
	main_chat: {
		blocked: false,
		// XXX merge these into identify
		botbrname: false,
		botbrpass: false,
		botbrsync: false,
		kudos_minus: false,
		kudos_plus: false,
		update_ip: false,
	}
};

var commands_aliases = {
	b: 'battle',
	chord: 'ultrachord',
	compo: 'battle',
	g: 'google',
	gi: 'image',
	gif: 'giphy',
	h: 'help',
	i: 'imdb',
	images: 'image',
	img: 'imgur',
	imgr: 'imgur',
	l: 'lyceum',
	ohc: 'ohb',
	pic: 'pix',
	uc: 'ultrachord',
	up: 'uptime',
	w: 'wikipedia',
	wiki: 'wikipedia',
	y: 'youtube',
	yt: 'youtube',
};

var commands_alias_filters = {
	'kudos_minus': /^(.+)\-{2}$/i,
	'kudos_plus': /^(.+)\+{2}$/i,
};

alias_check = function(command) {
	if (typeof commands_aliases[command] !== 'undefined') {
		command = commands_aliases[command];
	}
	return command;
};

command_check = function(channel_type, command) {
	if (channel_blocks[channel_type][command] === false) {
		return false;
	}
	if (typeof commands[command] === 'undefined') {
		return false;
	}
	return true;
};

command_parser = function(from, to, text, info) {

	var command = '';

	// break text into words
	var words = text.split(' ').filter(e => e !== '');

	// supplement info
	info.from = from;
	info.command_prefix = config.command_prefix;
	info.words = words;

	// interpret solicitor
	var channel;
	if (to === config.bot_name) {
		console.log('PM <' + from + '> ' + text);
		channel = 'private_chat';
		info.channel = from;
		info.channel_type = channel;
	}
	else if (config.irc.channels.indexOf(to) != -1) {
		console.log(to + ' <' + from + '> ' + text);
		channel = 'main_chat';
		info.channel = info.args[0];
		info.channel_type = channel;
	}

	// check alias filters (command override)
	for (var key in commands_alias_filters) {
		filter = commands_alias_filters[key];
		if (filter.test(text)) {
			commands[key](info, words);
			return;
		}
	};

	// check for command prefix
	if (words[0].substr(0, 1) !== config.command_prefix) {
		if (to === config.bot_name) {
			// XXX something is fukt here
			if (from === config.bot_name) {
				console.log('STOP MESSAGING YERSELF!!');
				return false;
			}
			info.channel = from;
			commands.unknown(info, words);
		}
		return false;
	}

	// remove command prefix
	var command = words[0].substr(1);

	// abort if command is empty or non-alphabetic (likely an emoticon)
	if (command === '' || !command.match(/^[a-zA-Z]/)) {
		return false;
	}

	// check if the command is an alias
	command = alias_check(command);

	// check channel's blocked commands
	if (command_check(channel, command) === false) {
		commands.blocked(info, words);
		console.log('"' + command + '" in #' + channel + ' blocked');
		return false;
	}

	// check for command and call
	if (typeof commands[command] === "function") {
		try {
			var response = commands[command](info, words);
		} catch(err) {
			module.exports.say(info.channel, 'an error hath occured :X');
			console.log(err);
		}
	}
};

module.exports = {

	alias_check: function(command) {
		return alias_check(command);
	},

	alias_find: function(command) {
		var alias_list = [];
		for (alias in commands_aliases) {
			if (commands_aliases[alias] === command) {
				alias_list.push(alias);
			}
		}
		return alias_list;
	},

	command_check: function(command, channel_type) {
		return command_check(command, channel_type);
	},

	command_list: function(channel_type) {
		var command_list = [];
		for (command in commands) {
			if (command_check(channel_type, command)) {
				command_list.push(command);
			}
		}
		return command_list;
	},

	initialize: function() {
		bot = new irc.Client(config.irc.server, config.bot_name, {
			debug: config.irc.debug,
			autoRejoin: config.irc.autoRejoin,
			channels: config.irc.channels
		});

		//commands.init(this);
		commands = require('./irc_commands.js');

		bot.addListener('error', function(message) {
			console.log('IRC error: ' + message);
		});

		bot.addListener('join', function(channel, who) {
			console.log(who + ' has joined ' + channel);
		});

		bot.addListener('part', function(channel, who) {
			console.log(who + ' has parted ' + channel);
		});

		bot.addListener('quit', function(channel, who) {
			console.log(who + ' has quit ' + channel);
		});

		bot.addListener('message', function(from, to, text, info) {
			command_parser(from, to, text, info);
		});
	},

	say: function(channel, text) {
		function irc_push(channel, text) {
			text = config.irc.text_color + ' ' + text + config.irc.text_color + ' ';
			console.log(channel + " <" + config.bot_name + "> " + text)
			bot.say(channel, text);
		}
		// is it an array?
		if (Array.isArray(text)) {
			text.forEach(function(line) {
				irc_push(channel, line);
			});
			return;
		}
		// is it just text?
		irc_push(channel, text);
	}
}
<commit_msg>Set userName and realName based on bot_name<commit_after>var irc = require('irc');
var config = require('./config.js');

var bot;
var commands;

var channel_blocks = {
	private_chat: {
		blocked: false,
		kudos_minus: false,
		kudos_plus: false,
		ultrachord: false,
	},
	main_chat: {
		blocked: false,
		// XXX merge these into identify
		botbrname: false,
		botbrpass: false,
		botbrsync: false,
		kudos_minus: false,
		kudos_plus: false,
		update_ip: false,
	}
};

var commands_aliases = {
	b: 'battle',
	chord: 'ultrachord',
	compo: 'battle',
	g: 'google',
	gi: 'image',
	gif: 'giphy',
	h: 'help',
	i: 'imdb',
	images: 'image',
	img: 'imgur',
	imgr: 'imgur',
	l: 'lyceum',
	ohc: 'ohb',
	pic: 'pix',
	uc: 'ultrachord',
	up: 'uptime',
	w: 'wikipedia',
	wiki: 'wikipedia',
	y: 'youtube',
	yt: 'youtube',
};

var commands_alias_filters = {
	'kudos_minus': /^(.+)\-{2}$/i,
	'kudos_plus': /^(.+)\+{2}$/i,
};

alias_check = function(command) {
	if (typeof commands_aliases[command] !== 'undefined') {
		command = commands_aliases[command];
	}
	return command;
};

command_check = function(channel_type, command) {
	if (channel_blocks[channel_type][command] === false) {
		return false;
	}
	if (typeof commands[command] === 'undefined') {
		return false;
	}
	return true;
};

command_parser = function(from, to, text, info) {

	var command = '';

	// break text into words
	var words = text.split(' ').filter(e => e !== '');

	// supplement info
	info.from = from;
	info.command_prefix = config.command_prefix;
	info.words = words;

	// interpret solicitor
	var channel;
	if (to === config.bot_name) {
		console.log('PM <' + from + '> ' + text);
		channel = 'private_chat';
		info.channel = from;
		info.channel_type = channel;
	}
	else if (config.irc.channels.indexOf(to) != -1) {
		console.log(to + ' <' + from + '> ' + text);
		channel = 'main_chat';
		info.channel = info.args[0];
		info.channel_type = channel;
	}

	// check alias filters (command override)
	for (var key in commands_alias_filters) {
		filter = commands_alias_filters[key];
		if (filter.test(text)) {
			commands[key](info, words);
			return;
		}
	};

	// check for command prefix
	if (words[0].substr(0, 1) !== config.command_prefix) {
		if (to === config.bot_name) {
			// XXX something is fukt here
			if (from === config.bot_name) {
				console.log('STOP MESSAGING YERSELF!!');
				return false;
			}
			info.channel = from;
			commands.unknown(info, words);
		}
		return false;
	}

	// remove command prefix
	var command = words[0].substr(1);

	// abort if command is empty or non-alphabetic (likely an emoticon)
	if (command === '' || !command.match(/^[a-zA-Z]/)) {
		return false;
	}

	// check if the command is an alias
	command = alias_check(command);

	// check channel's blocked commands
	if (command_check(channel, command) === false) {
		commands.blocked(info, words);
		console.log('"' + command + '" in #' + channel + ' blocked');
		return false;
	}

	// check for command and call
	if (typeof commands[command] === "function") {
		try {
			var response = commands[command](info, words);
		} catch(err) {
			module.exports.say(info.channel, 'an error hath occured :X');
			console.log(err);
		}
	}
};

module.exports = {

	alias_check: function(command) {
		return alias_check(command);
	},

	alias_find: function(command) {
		var alias_list = [];
		for (alias in commands_aliases) {
			if (commands_aliases[alias] === command) {
				alias_list.push(alias);
			}
		}
		return alias_list;
	},

	command_check: function(command, channel_type) {
		return command_check(command, channel_type);
	},

	command_list: function(channel_type) {
		var command_list = [];
		for (command in commands) {
			if (command_check(channel_type, command)) {
				command_list.push(command);
			}
		}
		return command_list;
	},

	initialize: function() {
		bot = new irc.Client(config.irc.server, config.bot_name, {
			userName: config.bot_name.toLowerCase(),
			realName: config.bot_name + ' IRC bot',
			debug: config.irc.debug,
			autoRejoin: config.irc.autoRejoin,
			channels: config.irc.channels
		});

		//commands.init(this);
		commands = require('./irc_commands.js');

		bot.addListener('error', function(message) {
			console.log('IRC error: ' + message);
		});

		bot.addListener('join', function(channel, who) {
			console.log(who + ' has joined ' + channel);
		});

		bot.addListener('part', function(channel, who) {
			console.log(who + ' has parted ' + channel);
		});

		bot.addListener('quit', function(channel, who) {
			console.log(who + ' has quit ' + channel);
		});

		bot.addListener('message', function(from, to, text, info) {
			command_parser(from, to, text, info);
		});
	},

	say: function(channel, text) {
		function irc_push(channel, text) {
			text = config.irc.text_color + ' ' + text + config.irc.text_color + ' ';
			console.log(channel + " <" + config.bot_name + "> " + text)
			bot.say(channel, text);
		}
		// is it an array?
		if (Array.isArray(text)) {
			text.forEach(function(line) {
				irc_push(channel, line);
			});
			return;
		}
		// is it just text?
		irc_push(channel, text);
	}
}
<|endoftext|>


<commit_before>// implementation of object "process" in ceylon.language
function languageClass() {
    var lang = new languageClass.$$;
    Basic(lang);
    return lang;
}
languageClass.$$metamodel$$={$nm:'languageClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','language']};
initTypeProto(languageClass, "ceylon.language::language", $init$Basic());
var lang$proto=languageClass.$$.prototype;
defineAttr(lang$proto, 'version', function() {
    return String$("0.6.1",3);
},undefined,{$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','version']});
defineAttr(lang$proto, 'majorVersion', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersion']});
defineAttr(lang$proto, 'minorVersion', function(){ return 6; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersion']});
defineAttr(lang$proto, 'releaseVersion', function(){ return 1; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','releaseVersion']});
defineAttr(lang$proto, 'versionName', function(){ return String$("Transmogrifier",14); },undefined,
  {$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','versionName']});
defineAttr(lang$proto, 'majorVersionBinary', function(){ return 5; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersionBinary']});
defineAttr(lang$proto, 'minorVersionBinary', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersionBinary']});
var languageString = String$("language", 8);
defineAttr(lang$proto, 'string', function() {
    return languageString;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});

var language$ = languageClass();
function getLanguage() { return language$; }
exports.getLanguage=getLanguage;

function processClass() {
    var proc = new processClass.$$;
    Basic(proc);
    return proc;
}
processClass.$$metamodel$$={$nm:'processClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','process']};
initTypeProto(processClass, "ceylon.language::process", $init$Basic());
var process$proto = processClass.$$.prototype;

var argv = getEmpty();
var namedArgs = {};
if ((typeof process !== "undefined") && (process.argv !== undefined)) {
    // parse command line arguments
    if (process.argv.length > 1) {
        var args = process.argv.slice(1);
        for (var i=0; i<args.length; ++i) {
            var arg = args[i];
            if (arg.charAt(0) == '-') {
                var pos = 1;
                if (arg.charAt(1) == '-') { pos = 2; }
                arg = arg.substr(pos);
                pos = arg.indexOf('=');
                if (pos >= 0) {
                    namedArgs[arg.substr(0, pos)] = String$(arg.substr(pos+1));
                } else {
                    var value = args[i+1];
                    if ((value !== undefined) && (value.charAt(0) != '-')) {
                        namedArgs[arg] = String$(value);
                        ++i;
                    } else {
                        namedArgs[arg] = null;
                    }
                }
            }
            args[i] = String$(args[i]);
        }
        argv = ArraySequence(args, {Element:{t:String$}});
    }
} else if (typeof window !== "undefined") {
    // parse URL parameters
    var parts = window.location.search.substr(1).replace('+', ' ').split('&');
    if ((parts.length > 1) || ((parts.length > 0) && (parts[0].length > 0))) {
        var argStrings = new Array(parts.length);
        //can't do "for (i in parts)" anymore because of the added stuff to arrays
        var i;
        for (i=0; i<parts.length; i++) { argStrings[i] = String$(parts[i]); }
        argv = ArraySequence(argStrings, {Element:{t:String$}});

        for (i=0; i < parts.length; i++) {
            var part = parts[i];
            var pos = part.indexOf('=');
            if (pos >= 0) {
                var value = decodeURIComponent(part.substr(pos+1));
                namedArgs[part.substr(0, pos)] = String$(value);
            } else {
                namedArgs[part] = null;
            }
        }
    }
}
defineAttr(process$proto, 'arguments', function(){ return argv; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','arguments']});
process$proto.namedArgumentPresent = function(name) {
    return (name in namedArgs);
}
process$proto.namedArgumentValue = function(name) {
    var value = namedArgs[name];
    return (value !== undefined) ? value : null;
}

var properties = {};
if (typeof navigator !== "undefined") {
    if (navigator.language !== undefined) {
        properties["user.language"] = String$(navigator.language);
    }
    if (navigator.platform !== undefined) {
        properties["os.name"] = String$(navigator.platform);
    }
    if (navigator.userLanguage||navigator.browserLanguage||navigator.language) {
        properties["user.locale"]=String$(navigator.userLanguage||navigator.browserLanguage||navigator.language);
    }
}
if (typeof process !== "undefined") {
    if (process.platform !== undefined) {
        properties["os.name"] = String$(process.platform);
    }
    if (process.arch !== undefined) {
        properties["os.arch"] = String$(process.arch);
    }
}
if (typeof document !== "undefined") {
    if (document.defaultCharset !== undefined) {
        properties["file.encoding"] = String$(document.defaultCharset);
    }
}

var linesep = String$('\n', 1);
var filesep = String$('/', 1);
var pathsep = String$(':', 1);
var osname = properties["os.name"];
if ((osname !== undefined) && (osname.search(/windows/i) >= 0)) {
    linesep = String$("\r\n", 2);
    filesep = String$('\\', 1);
    pathsep = String$(';', 1);
}
properties["line.separator"] = linesep;
properties["file.separator"] = filesep;
properties["path.separator"] = pathsep;

process$proto.propertyValue = function(name) {
    var value = properties[name];
    return (value !== undefined) ? value : null;
}

defineAttr(process$proto, 'newline', function(){ return linesep; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','newline']});

if ((typeof process !== "undefined") && (process.stdout !== undefined)) {
    process$proto.write = function(string) {
        process.stdout.write(string.valueOf());
    }
    process$proto.writeLine = function(line) {
        this.write(line.valueOf());
        this.write(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.log !== undefined)) {
    process$proto.writeLine = function(line) {
        console.log(line.valueOf());
    }
    process$proto.write = process$proto.writeLine;
} else {
    process$proto.write = function() {};
    process$proto.writeLine = function() {};
}

if ((typeof process !== "undefined") && (process.stderr !== undefined)) {
    process$proto.writeError = function(string) {
        process.stderr.write(string.valueOf());
    }
    process$proto.writeErrorLine = function(line) {
        this.writeError(line.valueOf());
        this.writeError(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.error !== undefined)) {
    process$proto.writeErrorLine = function(line) {
        console.error(line.valueOf());
    }
    process$proto.writeError = process$proto.writeErrorLine;
} else {
    process$proto.writeError = process$proto.write;
    process$proto.writeErrorLine = process$proto.writeLine;
}

process$proto.readLine = function() {
    return String$("", 0);//TODO
}

defineAttr(process$proto, 'milliseconds', function() {
    return Date.now();
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','milliseconds']});
defineAttr(process$proto, 'nanoseconds', function() {
    return Date.now()*1000000;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','nanoseconds']});

if ((typeof process !== "undefined") && (process.exit !== undefined)) {
    process$proto.exit = function(code) {
        process.exit(code);
    }
} else {
    process$proto.exit = function() {}
}

var processString = String$("process", 7);
defineAttr(process$proto, 'string', function() {
    return processString;
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});
defineAttr(process$proto, 'vm', function() {
    if (typeof process !== "undefined" && process.execPath && process.execPath.match(/node(\.exe)?$/)) {
        return String$("node.js", 7);
    } else if (typeof window === 'object') {
        return String$("Browser", 7);
    }
    return String$("Unknown JavaScript environment", 30);
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vm']});
defineAttr(process$proto, 'vmVersion', function() {
    if (typeof process !== "undefined" && typeof process.version === 'string') {
        return String$(process.version);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vmVersion']});
defineAttr(process$proto, 'os',function() {
    if (typeof process !== "undefined" && typeof process.platform === 'string') {
        return String$(process.platform);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','os']});
defineAttr(process$proto, 'osVersion', function() {
    return String$("Unknown");
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','osVersion']});
defineAttr(process$proto, 'timezoneOffset', function(){
  return new Date().getTimezoneOffset()*60000;
},undefined,{$t:{t:Integer}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','timezoneOffset']});
defineAttr(process$proto, 'locale', function(){
  return properties["user.locale"] || String$("Unknown",7);
},undefined,{$t:{t:String$}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','locale']});

var process$ = processClass();
function getProcess() { return process$; }
exports.getProcess=getProcess;
<commit_msg>Fixed Ceylon release name and reset the binary version numbers<commit_after>// implementation of object "process" in ceylon.language
function languageClass() {
    var lang = new languageClass.$$;
    Basic(lang);
    return lang;
}
languageClass.$$metamodel$$={$nm:'languageClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','language']};
initTypeProto(languageClass, "ceylon.language::language", $init$Basic());
var lang$proto=languageClass.$$.prototype;
defineAttr(lang$proto, 'version', function() {
    return String$("0.6.1",3);
},undefined,{$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','version']});
defineAttr(lang$proto, 'majorVersion', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersion']});
defineAttr(lang$proto, 'minorVersion', function(){ return 6; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersion']});
defineAttr(lang$proto, 'releaseVersion', function(){ return 1; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','releaseVersion']});
defineAttr(lang$proto, 'versionName', function(){ return String$("Virtual Boy",11); },undefined,
  {$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','versionName']});
defineAttr(lang$proto, 'majorVersionBinary', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersionBinary']});
defineAttr(lang$proto, 'minorVersionBinary', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersionBinary']});
var languageString = String$("language", 8);
defineAttr(lang$proto, 'string', function() {
    return languageString;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});

var language$ = languageClass();
function getLanguage() { return language$; }
exports.getLanguage=getLanguage;

function processClass() {
    var proc = new processClass.$$;
    Basic(proc);
    return proc;
}
processClass.$$metamodel$$={$nm:'processClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','process']};
initTypeProto(processClass, "ceylon.language::process", $init$Basic());
var process$proto = processClass.$$.prototype;

var argv = getEmpty();
var namedArgs = {};
if ((typeof process !== "undefined") && (process.argv !== undefined)) {
    // parse command line arguments
    if (process.argv.length > 1) {
        var args = process.argv.slice(1);
        for (var i=0; i<args.length; ++i) {
            var arg = args[i];
            if (arg.charAt(0) == '-') {
                var pos = 1;
                if (arg.charAt(1) == '-') { pos = 2; }
                arg = arg.substr(pos);
                pos = arg.indexOf('=');
                if (pos >= 0) {
                    namedArgs[arg.substr(0, pos)] = String$(arg.substr(pos+1));
                } else {
                    var value = args[i+1];
                    if ((value !== undefined) && (value.charAt(0) != '-')) {
                        namedArgs[arg] = String$(value);
                        ++i;
                    } else {
                        namedArgs[arg] = null;
                    }
                }
            }
            args[i] = String$(args[i]);
        }
        argv = ArraySequence(args, {Element:{t:String$}});
    }
} else if (typeof window !== "undefined") {
    // parse URL parameters
    var parts = window.location.search.substr(1).replace('+', ' ').split('&');
    if ((parts.length > 1) || ((parts.length > 0) && (parts[0].length > 0))) {
        var argStrings = new Array(parts.length);
        //can't do "for (i in parts)" anymore because of the added stuff to arrays
        var i;
        for (i=0; i<parts.length; i++) { argStrings[i] = String$(parts[i]); }
        argv = ArraySequence(argStrings, {Element:{t:String$}});

        for (i=0; i < parts.length; i++) {
            var part = parts[i];
            var pos = part.indexOf('=');
            if (pos >= 0) {
                var value = decodeURIComponent(part.substr(pos+1));
                namedArgs[part.substr(0, pos)] = String$(value);
            } else {
                namedArgs[part] = null;
            }
        }
    }
}
defineAttr(process$proto, 'arguments', function(){ return argv; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','arguments']});
process$proto.namedArgumentPresent = function(name) {
    return (name in namedArgs);
}
process$proto.namedArgumentValue = function(name) {
    var value = namedArgs[name];
    return (value !== undefined) ? value : null;
}

var properties = {};
if (typeof navigator !== "undefined") {
    if (navigator.language !== undefined) {
        properties["user.language"] = String$(navigator.language);
    }
    if (navigator.platform !== undefined) {
        properties["os.name"] = String$(navigator.platform);
    }
    if (navigator.userLanguage||navigator.browserLanguage||navigator.language) {
        properties["user.locale"]=String$(navigator.userLanguage||navigator.browserLanguage||navigator.language);
    }
}
if (typeof process !== "undefined") {
    if (process.platform !== undefined) {
        properties["os.name"] = String$(process.platform);
    }
    if (process.arch !== undefined) {
        properties["os.arch"] = String$(process.arch);
    }
}
if (typeof document !== "undefined") {
    if (document.defaultCharset !== undefined) {
        properties["file.encoding"] = String$(document.defaultCharset);
    }
}

var linesep = String$('\n', 1);
var filesep = String$('/', 1);
var pathsep = String$(':', 1);
var osname = properties["os.name"];
if ((osname !== undefined) && (osname.search(/windows/i) >= 0)) {
    linesep = String$("\r\n", 2);
    filesep = String$('\\', 1);
    pathsep = String$(';', 1);
}
properties["line.separator"] = linesep;
properties["file.separator"] = filesep;
properties["path.separator"] = pathsep;

process$proto.propertyValue = function(name) {
    var value = properties[name];
    return (value !== undefined) ? value : null;
}

defineAttr(process$proto, 'newline', function(){ return linesep; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','newline']});

if ((typeof process !== "undefined") && (process.stdout !== undefined)) {
    process$proto.write = function(string) {
        process.stdout.write(string.valueOf());
    }
    process$proto.writeLine = function(line) {
        this.write(line.valueOf());
        this.write(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.log !== undefined)) {
    process$proto.writeLine = function(line) {
        console.log(line.valueOf());
    }
    process$proto.write = process$proto.writeLine;
} else {
    process$proto.write = function() {};
    process$proto.writeLine = function() {};
}

if ((typeof process !== "undefined") && (process.stderr !== undefined)) {
    process$proto.writeError = function(string) {
        process.stderr.write(string.valueOf());
    }
    process$proto.writeErrorLine = function(line) {
        this.writeError(line.valueOf());
        this.writeError(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.error !== undefined)) {
    process$proto.writeErrorLine = function(line) {
        console.error(line.valueOf());
    }
    process$proto.writeError = process$proto.writeErrorLine;
} else {
    process$proto.writeError = process$proto.write;
    process$proto.writeErrorLine = process$proto.writeLine;
}

process$proto.readLine = function() {
    return String$("", 0);//TODO
}

defineAttr(process$proto, 'milliseconds', function() {
    return Date.now();
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','milliseconds']});
defineAttr(process$proto, 'nanoseconds', function() {
    return Date.now()*1000000;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','nanoseconds']});

if ((typeof process !== "undefined") && (process.exit !== undefined)) {
    process$proto.exit = function(code) {
        process.exit(code);
    }
} else {
    process$proto.exit = function() {}
}

var processString = String$("process", 7);
defineAttr(process$proto, 'string', function() {
    return processString;
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});
defineAttr(process$proto, 'vm', function() {
    if (typeof process !== "undefined" && process.execPath && process.execPath.match(/node(\.exe)?$/)) {
        return String$("node.js", 7);
    } else if (typeof window === 'object') {
        return String$("Browser", 7);
    }
    return String$("Unknown JavaScript environment", 30);
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vm']});
defineAttr(process$proto, 'vmVersion', function() {
    if (typeof process !== "undefined" && typeof process.version === 'string') {
        return String$(process.version);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vmVersion']});
defineAttr(process$proto, 'os',function() {
    if (typeof process !== "undefined" && typeof process.platform === 'string') {
        return String$(process.platform);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','os']});
defineAttr(process$proto, 'osVersion', function() {
    return String$("Unknown");
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','osVersion']});
defineAttr(process$proto, 'timezoneOffset', function(){
  return new Date().getTimezoneOffset()*60000;
},undefined,{$t:{t:Integer}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','timezoneOffset']});
defineAttr(process$proto, 'locale', function(){
  return properties["user.locale"] || String$("Unknown",7);
},undefined,{$t:{t:String$}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','locale']});

var process$ = processClass();
function getProcess() { return process$; }
exports.getProcess=getProcess;
<|endoftext|>


<commit_before>(function () {

    var directive = function () {
        return {
            restrict: "EA",
            bindToController: {},
            controllerAs: 'vm',
            scope: {},
            templateUrl: 'js/feed-details/details/feed-nifi-properties.html',
            controller: "FeedNifiPropertiesController",
            link: function ($scope, element, attrs, controller) {

            }

        };
    }

    var controller = function ($scope, AccessControlService, FeedService, EditFeedNifiPropertiesService, FeedInputProcessorOptionsFactory, FeedDetailsProcessorRenderingHelper) {

        var self = this;

        /**
         * Indicates if the feed NiFi properties may be edited.
         * @type {boolean}
         */
        self.allowEdit = false;

        this.model = FeedService.editFeedModel;
        this.editModel = {};
        this.editableSection = false;
        this.INCREMENTAL_DATE_PROPERTY_KEY = 'Date Field';

        $scope.$watch(function () {
            return FeedService.editFeedModel;
        }, function (newVal) {
            //only update the model if it is not set yet
            if (self.model == null) {
                self.model = angular.copy(FeedService.editFeedModel);

            }
            //tell the ui what properties to show/hide
            var renderGetTableData = FeedDetailsProcessorRenderingHelper.updateGetTableDataRendering(self.model.inputProcessor, self.model.nonInputProcessors);
            var renderSqoop = FeedDetailsProcessorRenderingHelper.updateSqoopProcessorRendering(self.model.inputProcessor, self.model.nonInputProcessors);
        })

        var inputProcessorIdWatch = $scope.$watch(function () {
            return self.editModel.inputProcessorId;
        }, function (newVal) {
            updateInputProcessor(newVal);
            //validate();
        });

        function setInputProcessorFeedPropertiesUrl(processor) {

            if (processor.feedPropertiesUrl == undefined) {
                processor.feedPropertiesUrl = null;
            }
            if (processor.feedPropertiesUrl == null) {
                processor.feedPropertiesUrl = FeedInputProcessorOptionsFactory.templateForProcessor(processor, 'edit');
            }
        }

        function updateInputProcessor(newVal) {
            angular.forEach(self.editModel.inputProcessors, function (processor) {
                if (processor.processorId == newVal) {
                    //check the type and return the custom form if there is one via a factory
                    var renderGetTableData = FeedDetailsProcessorRenderingHelper.updateGetTableDataRendering(processor, self.editModel.nonInputProcessors);
                    //   var renderSqoop = FeedDetailsProcessorRenderingHelper.updateSqoopProcessorRendering(processor, self.editModel.nonInputProcessors);
                    if (renderGetTableData) {
                        self.model.table.method = 'EXISTING_TABLE';
                    }
                    else {
                        self.model.table.method = 'MANUAL';
                    }

                    self.editModel.inputProcessor = processor;
                    self.editModel.inputProcessorType = processor.type;
                    //  setInputProcessorFeedPropertiesUrl(processor);
                    return false;
                }
            })
        }

        function findIncrementalDateFieldProperty() {
            return findProperty(self.INCREMENTAL_DATE_PROPERTY_KEY);
        }

        function findProperty(key) {
            return _.find(self.model.inputProcessor.properties, function (property) {
                //return property.key = 'Source Database Connection';
                return property.key == key;
            });
        }

        this.onEdit = function () {
            //copy the model
            var inputProcessors = angular.copy(FeedService.editFeedModel.inputProcessors);
            var nonInputProcessors = angular.copy(FeedService.editFeedModel.nonInputProcessors);
            self.editModel = {};

            var allInputProperties = _.filter(self.model.properties, function (property) {
                return property.inputProperty == true;
            });

            var allInputProcessorProperties = _.groupBy(allInputProperties, function (property) {
                return property.processorId;
            })

            var allInputProcessorProperties = angular.copy(allInputProcessorProperties);
            self.editModel.allInputProcessorProperties = allInputProcessorProperties;
            self.editModel.inputProcessors = inputProcessors;
            self.editModel.nonInputProcessors = nonInputProcessors;
            //NEED TO COPY IN TABLE PROPS HERE
            self.editModel.table = angular.copy(FeedService.editFeedModel.table);
            EditFeedNifiPropertiesService.editFeedModel = self.editModel;
            if (angular.isDefined(self.model.inputProcessor)) {
                updateInputProcessor(self.model.inputProcessor.processorId);
                self.editModel.inputProcessorId = self.model.inputProcessor.processorId;
            }
        };

        this.onCancel = function () {

        }
        this.onSave = function (ev) {
            FeedService.showFeedSavingDialog(ev, "Saving Feed " + self.model.feedName, self.model.feedName);
            var copy = angular.copy(FeedService.editFeedModel);

            copy.inputProcessors = self.editModel.inputProcessors;
            copy.nonInputProcessors = self.editModel.nonInputProcessors;
            copy.inputProcessorId = self.editModel.inputProcessorId;
            copy.inputProcessor = self.editModel.inputProcessor;
            copy.inputProcessorType = self.editModel.inputProcessorType;
            copy.userProperties = null;

            //table type is edited here so need tup update that prop as well
            copy.table.tableType = self.editModel.table.tableType

            if (copy.table.incrementalDateField) {
                findIncrementalDateFieldProperty().value = self.editModel.table.incrementalDateField;
                copy.table.incrementalDateField = self.editModel.table.incrementalDateField;
            }

            //update the db properties

            FeedService.saveFeedModel(copy).then(function (response) {
                FeedService.hideFeedSavingDialog();
                self.editableSection = false;

                self.model.inputProcessors = self.editModel.inputProcessors;
                self.model.nonInputProcessors = self.editModel.nonInputProcessors;
                self.model.inputProcessorId = self.editModel.inputProcessorId;
                self.model.inputProcessor = self.editModel.inputProcessor;
                self.model.table.tableType = self.editModel.table.tableType;
                self.model.table.incrementalDateField = self.editModel.table.incrementalDateField;
                self.model.inputProcessorType = self.editModel.inputProcessorType;

            }, function (response) {
                FeedService.hideFeedSavingDialog();
                console.log('ERRORS were found ', response)
                FeedService.buildErrorData(self.model.feedName, response.data);
                FeedService.showFeedErrorsDialog();
                //make it editable
                self.editableSection = true;
            });
        };

        // Fetch the allowed actions
        AccessControlService.getAllowedActions()
                .then(function(actionSet) {
                    self.allowEdit = AccessControlService.hasAction(AccessControlService.FEEDS_EDIT, actionSet.actions);
                });
    };

    angular.module(MODULE_FEED_MGR).controller('FeedNifiPropertiesController', controller);

    angular.module(MODULE_FEED_MGR)
        .directive('thinkbigFeedNifiProperties', directive);

})();
<commit_msg>sqoop processor rendering fix<commit_after>(function () {

    var directive = function () {
        return {
            restrict: "EA",
            bindToController: {},
            controllerAs: 'vm',
            scope: {},
            templateUrl: 'js/feed-details/details/feed-nifi-properties.html',
            controller: "FeedNifiPropertiesController",
            link: function ($scope, element, attrs, controller) {

            }

        };
    }

    var controller = function ($scope, AccessControlService, FeedService, EditFeedNifiPropertiesService, FeedInputProcessorOptionsFactory, FeedDetailsProcessorRenderingHelper) {

        var self = this;

        /**
         * Indicates if the feed NiFi properties may be edited.
         * @type {boolean}
         */
        self.allowEdit = false;

        this.model = FeedService.editFeedModel;
        this.editModel = {};
        this.editableSection = false;
        this.INCREMENTAL_DATE_PROPERTY_KEY = 'Date Field';

        $scope.$watch(function () {
            return FeedService.editFeedModel;
        }, function (newVal) {
            //only update the model if it is not set yet
            if (self.model == null) {
                self.model = angular.copy(FeedService.editFeedModel);

            }
            //tell the ui what properties to show/hide
            var renderGetTableData = FeedDetailsProcessorRenderingHelper.updateGetTableDataRendering(self.model.inputProcessor, self.model.nonInputProcessors);
            //   var renderSqoop = FeedDetailsProcessorRenderingHelper.updateSqoopProcessorRendering(self.model.inputProcessor, self.model.nonInputProcessors);
        })

        var inputProcessorIdWatch = $scope.$watch(function () {
            return self.editModel.inputProcessorId;
        }, function (newVal) {
            updateInputProcessor(newVal);
            //validate();
        });

        function setInputProcessorFeedPropertiesUrl(processor) {

            if (processor.feedPropertiesUrl == undefined) {
                processor.feedPropertiesUrl = null;
            }
            if (processor.feedPropertiesUrl == null) {
                processor.feedPropertiesUrl = FeedInputProcessorOptionsFactory.templateForProcessor(processor, 'edit');
            }
        }

        function updateInputProcessor(newVal) {
            angular.forEach(self.editModel.inputProcessors, function (processor) {
                if (processor.processorId == newVal) {
                    //check the type and return the custom form if there is one via a factory
                    var renderGetTableData = FeedDetailsProcessorRenderingHelper.updateGetTableDataRendering(processor, self.editModel.nonInputProcessors);
                    //   var renderSqoop = FeedDetailsProcessorRenderingHelper.updateSqoopProcessorRendering(processor, self.editModel.nonInputProcessors);
                    if (renderGetTableData) {
                        self.model.table.method = 'EXISTING_TABLE';
                    }
                    else {
                        self.model.table.method = 'MANUAL';
                    }

                    self.editModel.inputProcessor = processor;
                    self.editModel.inputProcessorType = processor.type;
                    //  setInputProcessorFeedPropertiesUrl(processor);
                    return false;
                }
            })
        }

        function findIncrementalDateFieldProperty() {
            return findProperty(self.INCREMENTAL_DATE_PROPERTY_KEY);
        }

        function findProperty(key) {
            return _.find(self.model.inputProcessor.properties, function (property) {
                //return property.key = 'Source Database Connection';
                return property.key == key;
            });
        }

        this.onEdit = function () {
            //copy the model
            var inputProcessors = angular.copy(FeedService.editFeedModel.inputProcessors);
            var nonInputProcessors = angular.copy(FeedService.editFeedModel.nonInputProcessors);
            self.editModel = {};

            var allInputProperties = _.filter(self.model.properties, function (property) {
                return property.inputProperty == true;
            });

            var allInputProcessorProperties = _.groupBy(allInputProperties, function (property) {
                return property.processorId;
            })

            var allInputProcessorProperties = angular.copy(allInputProcessorProperties);
            self.editModel.allInputProcessorProperties = allInputProcessorProperties;
            self.editModel.inputProcessors = inputProcessors;
            self.editModel.nonInputProcessors = nonInputProcessors;
            //NEED TO COPY IN TABLE PROPS HERE
            self.editModel.table = angular.copy(FeedService.editFeedModel.table);
            EditFeedNifiPropertiesService.editFeedModel = self.editModel;
            if (angular.isDefined(self.model.inputProcessor)) {
                updateInputProcessor(self.model.inputProcessor.processorId);
                self.editModel.inputProcessorId = self.model.inputProcessor.processorId;
            }
        };

        this.onCancel = function () {

        }
        this.onSave = function (ev) {
            FeedService.showFeedSavingDialog(ev, "Saving Feed " + self.model.feedName, self.model.feedName);
            var copy = angular.copy(FeedService.editFeedModel);

            copy.inputProcessors = self.editModel.inputProcessors;
            copy.nonInputProcessors = self.editModel.nonInputProcessors;
            copy.inputProcessorId = self.editModel.inputProcessorId;
            copy.inputProcessor = self.editModel.inputProcessor;
            copy.inputProcessorType = self.editModel.inputProcessorType;
            copy.userProperties = null;

            //table type is edited here so need tup update that prop as well
            copy.table.tableType = self.editModel.table.tableType

            if (copy.table.incrementalDateField) {
                findIncrementalDateFieldProperty().value = self.editModel.table.incrementalDateField;
                copy.table.incrementalDateField = self.editModel.table.incrementalDateField;
            }

            //update the db properties

            FeedService.saveFeedModel(copy).then(function (response) {
                FeedService.hideFeedSavingDialog();
                self.editableSection = false;

                self.model.inputProcessors = self.editModel.inputProcessors;
                self.model.nonInputProcessors = self.editModel.nonInputProcessors;
                self.model.inputProcessorId = self.editModel.inputProcessorId;
                self.model.inputProcessor = self.editModel.inputProcessor;
                self.model.table.tableType = self.editModel.table.tableType;
                self.model.table.incrementalDateField = self.editModel.table.incrementalDateField;
                self.model.inputProcessorType = self.editModel.inputProcessorType;

            }, function (response) {
                FeedService.hideFeedSavingDialog();
                console.log('ERRORS were found ', response)
                FeedService.buildErrorData(self.model.feedName, response.data);
                FeedService.showFeedErrorsDialog();
                //make it editable
                self.editableSection = true;
            });
        };

        // Fetch the allowed actions
        AccessControlService.getAllowedActions()
                .then(function(actionSet) {
                    self.allowEdit = AccessControlService.hasAction(AccessControlService.FEEDS_EDIT, actionSet.actions);
                });
    };

    angular.module(MODULE_FEED_MGR).controller('FeedNifiPropertiesController', controller);

    angular.module(MODULE_FEED_MGR)
        .directive('thinkbigFeedNifiProperties', directive);

})();
<|endoftext|>


<commit_before>const express = require('express');
const logger = require('logger').logger;
const recursive = require('recursive-fs');
const path = require('path');
const Api = require('./Api');
const Controller = require('./Controller');
const CONTROLLER_REG = /^((.*[\/\\])(.)(.*))(Ctrl|Controller)(\.js)$/i;
const JS_EXT_REG = /\.js$/i;
const cache = require('./cache');
const ExpressBasics = require('express-basics');
const environment = require('environment');
const exec = require('child_process').exec;
const SKIP_COMPASS = environment.argument('SKIP_COMPASS', false);
const COMPASS = environment.argument('COMPASS', 'compass');
const COMPASS_CMD = COMPASS +
  ' compile --relative-assets --output-style=expanded ' +
  '--css-dir=css --sass-dir=scss --images-dir=images --trace';
const CSS_REG = /\.css(\?.*)?$/;
const fs = require('fs-plus');

class ExpressMvc {

  /**
   * @param {string=} directory The directory of the mvc sources.
   * @param {express=} expressVersion The express instance to be used.
   */
  constructor(directory, expressVersion) {

    /**
     * The express version we'll be using.
     * @type {*}
     * @private
     */
    const expr = expressVersion || express;

    /**
     * The directory where we'll be looking for controllers and apis.
     */
    this._directory = path.normalize(process.cwd() + '/' + (directory || ''));

    /**
     * The express instance.
     */
    this.expressBasics = new ExpressBasics(expr());

    /**
     * Obtains all the js files.
     *
     * @type {Promise}
     */
    const allJsFiles = new Promise((resolve, reject) => {
      recursive.readdirr(this._directory, (e, dirs, files) => {
        if (e) {
          logger.error(e);
          return reject(e);
        }
        logger.debug(files);
        resolve(files);
      });
    });

    /**
     * The apis found in the directory.
     * @type {Promise.<Api[]>}
     * @private
     */
    this._apis = allJsFiles
      .then(files => files.filter(file => /Api\.js$/.test(file))
        .map(file => {
          try {

            const apiKey = path.basename(file).replace(JS_EXT_REG, '');
            const SubApi = require(file.toString());
            const subApi = new SubApi();
            cache.getLibrary('apis').add(apiKey, subApi);
            this._bindApi(subApi, file);
            return subApi;

          } catch (e) {
            logger.error(file.toString() + ' is not an Api');
            return null;
          }
        })
        .filter(ctrl => ctrl instanceof Api));

    /**
     * The controllers found in the directory.
     * @type {Promise.<Controller[]>}
     * @private
     */
    this._controllers = allJsFiles
      .then(files => files
        .filter(file => CONTROLLER_REG.test(file))
        .map(file => {
          file = file.toString();
          try {

            const matches = file.match(CONTROLLER_REG);
            const modelName = matches[3].toLowerCase() + matches[4] + 'Model';
            let viewFile = matches[1] + 'View.hbs';

            let Model;
            try {
              const modelFile = matches[1] + 'Model.js';
              logger.debug('Looking for model ' + modelFile);
              Model = require(modelFile);
            } catch (e) {
              logger.warn('No model found for controller ' + file);
              viewFile = null;
              Model = null;
            }

            const Ctrl = require(file);
            const ctrl = new Ctrl(viewFile, Model, modelName);
            const ctrlKey = path.basename(file).replace(JS_EXT_REG, '');

            cache.getLibrary('controllers').add(ctrlKey, ctrl);

            this._bindController(ctrl, file);

            return ctrl;

          } catch (e) {
            logger.error(e);
            return null;
          }
        })
        .filter(ctrl => ctrl instanceof Controller));

    // Bind the node modules.
    this._bindNodeModules(this._directory);

  }

  /**
   * Binds a controller to the express application.
   * @param {Controller} controller The controller to bind.
   * @param {string=} file The file.
   * @private
   */
  _bindController(controller, file) {

    this._bindControllerAssets(file);

    const handler = basics => cache.getLibrary('assets')
      .getOrElse(file, () => {
        return this._getAssets(file)
          .then(assets => {
            logger.debug({title: 'Assets', message: assets});
            return assets;
          });
      }, environment.development ? 100 : 0)
      .then(assets => {
        controller.doRequest(Object.assign(basics, {assets}));
      });

    const context = this._getAbsPath(path.dirname(file));

    if (context) {
      this.expressBasics.use('/' + context, handler);
    } else {
      this.expressBasics.use(handler);
    }

    logger.debug('Controller bound to express on route: ' + (context || '/'));
  }

  /**
   * Obtains the assets dynamically.
   * @param {string} file The file to obtain assets from.
   * @returns {Promise.<Array[]>}
   * @private
   */
  _getAssets(file) {
    const {assetsDir, configFile} = this._getControllerAssetNames(file);

    return fs.existsPromise(assetsDir)
      .then(exists => {

        if (!exists) {
          logger.warn(`No assets found ${assetsDir}`);
          return {js: [], css: []};
        }

        logger.debug('Looking for assets in ' + assetsDir);

        let promise = environment.development ?
          this._getDevelopmentAssets(assetsDir) :
          this._getProductionAssets(assetsDir);

        return promise.then(([css, js]) => this._getConfiguration(configFile)
          .then(cnf => {
            (cnf.dependencies || []).forEach(dependency => {
              if (CSS_REG.test(dependency)) {
                css.unshift(dependency);
              } else {
                js.unshift(dependency);
              }
            });
            logger.debug({title: 'Assets', message: {js, css}});
            return {js, css};
          }));

      });
  }

  /**
   * Obtains the configuration.
   * @param configFile
   * @returns {Promise.<Object>}
   * @private
   */
  _getConfiguration(configFile) {
    return cache.getLibrary('configurations')
      .getOrElse(configFile, () => fs.readFilePromise(configFile)
        .then(
          config => {
            config = JSON.parse(config.toString());
            if (config[environment.name]) {
              Object.assign(config, config[environment.name]);
              delete config[environment.name];
            }
            logger.debug({title: 'Controller Config', message: config});
            return config;
          },
          e => {
            logger.warn(e);
            return {};
          }
        ), environment.development ? 100 : 0);
  }

  /**
   * Obtains the development assets.
   * @param {string} assetsDir The assets directory.
   * @returns {Promise.<Array[]>}
   * @private
   */
  _getDevelopmentAssets(assetsDir) {
    return Promise.all([
      new Promise(resolve => {
        recursive.readdirr(path.normalize(assetsDir + '/scss/'),
          (e, dirs, files) => {
            if (e) {
              logger.error(e);
              return resolve([]);
            }
            resolve(files.filter(file =>
            /\.scss/.test(file) && !/[\/\\]_.*/.test(file))
              .map(file => this._getAbsPath(file)
                .replace(/scss/g, 'css')));
          });
      }),
      new Promise(resolve => {
        recursive.readdirr(path.normalize(assetsDir + '/js/'),
          (e, dirs, files) => {
            if (e) {
              logger.error(e);
              return resolve([]);
            }
            resolve(files
              .filter(file => /\.js/.test(file) && !/\.min\./.test(file))
              .map(file => this._getAbsPath(file)));
          });
      })
    ]);
  }

  /**
   * Obtains the production assets.
   * @param {string} assetsDir The assets directory.
   * @returns {Promise.<Array[]>}
   * @private
   */
  _getProductionAssets(assetsDir) {
    return Promise.all([
      new Promise(resolve => {
        recursive.readdirr(path.normalize(assetsDir + '/css/'),
          (e, dirs, files) => {
            if (e) {
              logger.error(e);
              return resolve([]);
            }
            resolve(files.filter(file => /\.min\.css$/.test(file))
              .map(file => '/' + path.relative(this._directory, file)
                .replace(/\\/g, '/')));
          });
      }),
      new Promise(resolve => {
        recursive.readdirr(path.normalize(assetsDir + '/js/'),
          (e, dirs, files) => {
            if (e) {
              logger.error(e);
              return resolve([]);
            }
            resolve(files.filter(file => /\.min\.js/.test(file))
              .map(file => '/' + path.relative(this._directory, file)
                .replace(/\\/g, '/')));
          });
      })
    ]);
  }

  /**
   * Binds the assets to the controller.
   * @param {string} file The file.
   * @private
   */
  _bindControllerAssets(file) {
    const {assetsDir} = this._getControllerAssetNames(file);
    this._bindCompass(assetsDir);
    this._bindStaticAssets(assetsDir);
  }

  /**
   * Binds the static assets to the application.
   * @param {string} dir The directory of the assets.
   * @private
   */
  _bindStaticAssets(dir) {
    const context = this._getAbsPath(dir) + '/';
    this.express
      .use(['/:version' + context, context], express.static(dir));
    logger.debug('Static assets bound to route: ' +
      context + ' & /:version' + context + ' on directory ' + dir);
  }

  /**
   * Binds the node modules as a static resource.
   * @private
   */
  _bindNodeModules(dir) {
    const context = this._getAbsPath(dir + '/node_modules') + '/';
    this.express.use(['/:version' + context, context],
      express.static(environment.nodeModules));
    logger.debug('Node modules bound to route: ' + context +
      ' & /:version' + context +
      ' on directory ' + environment.nodeModules);
  }

  /**
   * Binds compass on the static assets.
   * @param {string} dir The directory of the assets.
   * @private
   */
  _bindCompass(dir) {
    const context = this._getAbsPath(dir) + '/';
    if (environment.development && !SKIP_COMPASS) {
      this.expressBasics.use(['/:version' + context, context], basics => {
        if (!CSS_REG.test(basics.request.originalUrl)) {
          return basics.next();
        }
        exec(COMPASS_CMD, {cwd: dir}, (e, output) => {
          if (e) {
            logger.error({title: 'Compass', message: e});
          } else if (output) {
            logger.debug({title: 'Compass', message: output});
          }
          basics.next();
        });

      });
      logger.debug('Compass compilation bound to route: ' +
        context + ' & ' + '/:version' + context);
    }
  }

  /**
   * Obtains the name of the assets directory based on a file path.
   * @param {string} file The file name.
   * @returns {{assetsDir:string,configFile:string,rootDir:string}}
   * @private
   */
  _getControllerAssetNames(file) {
    const matches = file.match(CONTROLLER_REG);
    const prefix = matches[2] + matches[3].toLowerCase() + matches[4];
    return {
      rootDir: matches[2],
      assetsDir: prefix + 'Assets',
      configFile: prefix + 'Config.json'
    };
  }

  /**
   * Gets a relative path to a destination based on controller directory.
   * @param {string} destination The destination.
   * @returns {string}
   * @private
   */
  _getAbsPath(destination) {
    return '/' +
      path.relative(this._directory, path.normalize(destination))
        .replace(/\\/g, '/');
  }

  /**
   * Binds an api to the express application.
   * @param {Api} api The controller to bind.
   * @param {string=} file The file.
   * @private
   */
  _bindApi(api, file) {
    const context = path.dirname(this._getAbsPath(file)) + '/' +
      path.basename(file)
        .replace(/^(.)(.*)Api\.js$/i, (a, b, c) => b.toLowerCase() + c);
    this.expressBasics.use(context, basics => api.doRequest(basics));
    logger.debug('Api bound to express on route: ' + (context || '/'));
  }

  /**
   * Obtains the list of apis.
   * @returns {Promise.<Api[]>}
   */
  get apis() {
    return this._apis;
  }

  /**
   * Obtains the list of controllers.
   * @returns {Promise.<Controller[]>}
   */
  get controllers() {
    return this._controllers;
  }

  /**
   * Gets the controller.
   * @param {String} name The name of the controller.
   * @returns {Promise.<Controller>}}
   */
  getController(name) {
    return this._controllers
      .then(() => cache.getLibrary('controllers').get(name));
  }

  /**
   * Gets the api.
   * @param {String} name The name of the api.
   * @returns {Promise.<Api>}}
   */
  getApi(name) {
    return this._apis.then(() => cache.getLibrary('apis').get(name));
  }

  /**
   * Forwards the request to the listen method.
   * @param {*} args The arguments to send.
   * @returns {Promise.<express>}
   */
  listen(...args) {
    return Promise.all([this._controllers, this._apis])
      .then(() => {
        this.expressBasics.use(basics => basics.response.status(404).end());
        this.expressBasics.listen.apply(this.expressBasics, args);
        logger.highlight({
          title: 'SERVER',
          message: `Listening on port ${args[0]}`
        });
        return this.express;
      }, e => {
        logger.error(e);
        return this.express;
      });
  }

  /**
   * Simple getter of the express instance.
   * @returns {express}
   */
  get express() {
    return this.expressBasics.express;
  }

  /**
   * Forwards the request to the use method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  use(...args) {
    return this.expressBasics.use.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the get method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  get(...args) {
    return this.expressBasics.get.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the put method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  put(...args) {
    return this.expressBasics.put.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the post method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  post(...args) {
    return this.expressBasics.post.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the patch method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  patch(...args) {
    return this.expressBasics.patch.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the delete method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  delete(...args) {
    return this.expressBasics.delete.apply(this.expressBasics, args);
  }

}

module
  .exports = ExpressMvc;
<commit_msg>Fixing the normalization of the directory<commit_after>const express = require('express');
const logger = require('logger').logger;
const recursive = require('recursive-fs');
const path = require('path');
const Api = require('./Api');
const Controller = require('./Controller');
const CONTROLLER_REG = /^((.*[\/\\])(.)(.*))(Ctrl|Controller)(\.js)$/i;
const JS_EXT_REG = /\.js$/i;
const cache = require('./cache');
const ExpressBasics = require('express-basics');
const environment = require('environment');
const exec = require('child_process').exec;
const SKIP_COMPASS = environment.argument('SKIP_COMPASS', false);
const COMPASS = environment.argument('COMPASS', 'compass');
const COMPASS_CMD = COMPASS +
  ' compile --relative-assets --output-style=expanded ' +
  '--css-dir=css --sass-dir=scss --images-dir=images --trace';
const CSS_REG = /\.css(\?.*)?$/;
const fs = require('fs-plus');

class ExpressMvc {

  /**
   * @param {string=} directory The directory of the mvc sources.
   * @param {express=} expressVersion The express instance to be used.
   */
  constructor(directory, expressVersion) {

    /**
     * The express version we'll be using.
     * @type {*}
     * @private
     */
    const expr = expressVersion || express;

    /**
     * The directory where we'll be looking for controllers and apis.
     */
    this._directory = path.normalize(directory);

    /**
     * The express instance.
     */
    this.expressBasics = new ExpressBasics(expr());

    /**
     * Obtains all the js files.
     *
     * @type {Promise}
     */
    const allJsFiles = new Promise((resolve, reject) => {
      recursive.readdirr(this._directory, (e, dirs, files) => {
        if (e) {
          logger.error(e);
          return reject(e);
        }
        logger.debug(files);
        resolve(files);
      });
    });

    /**
     * The apis found in the directory.
     * @type {Promise.<Api[]>}
     * @private
     */
    this._apis = allJsFiles
      .then(files => files.filter(file => /Api\.js$/.test(file))
        .map(file => {
          try {

            const apiKey = path.basename(file).replace(JS_EXT_REG, '');
            const SubApi = require(file.toString());
            const subApi = new SubApi();
            cache.getLibrary('apis').add(apiKey, subApi);
            this._bindApi(subApi, file);
            return subApi;

          } catch (e) {
            logger.error(file.toString() + ' is not an Api');
            return null;
          }
        })
        .filter(ctrl => ctrl instanceof Api));

    /**
     * The controllers found in the directory.
     * @type {Promise.<Controller[]>}
     * @private
     */
    this._controllers = allJsFiles
      .then(files => files
        .filter(file => CONTROLLER_REG.test(file))
        .map(file => {
          file = file.toString();
          try {

            const matches = file.match(CONTROLLER_REG);
            const modelName = matches[3].toLowerCase() + matches[4] + 'Model';
            let viewFile = matches[1] + 'View.hbs';

            let Model;
            try {
              const modelFile = matches[1] + 'Model.js';
              logger.debug('Looking for model ' + modelFile);
              Model = require(modelFile);
            } catch (e) {
              logger.warn('No model found for controller ' + file);
              viewFile = null;
              Model = null;
            }

            const Ctrl = require(file);
            const ctrl = new Ctrl(viewFile, Model, modelName);
            const ctrlKey = path.basename(file).replace(JS_EXT_REG, '');

            cache.getLibrary('controllers').add(ctrlKey, ctrl);

            this._bindController(ctrl, file);

            return ctrl;

          } catch (e) {
            logger.error(e);
            return null;
          }
        })
        .filter(ctrl => ctrl instanceof Controller));

    // Bind the node modules.
    this._bindNodeModules(this._directory);

  }

  /**
   * Binds a controller to the express application.
   * @param {Controller} controller The controller to bind.
   * @param {string=} file The file.
   * @private
   */
  _bindController(controller, file) {

    this._bindControllerAssets(file);

    const handler = basics => cache.getLibrary('assets')
      .getOrElse(file, () => {
        return this._getAssets(file)
          .then(assets => {
            logger.debug({title: 'Assets', message: assets});
            return assets;
          });
      }, environment.development ? 100 : 0)
      .then(assets => {
        controller.doRequest(Object.assign(basics, {assets}));
      });

    const context = this._getAbsPath(path.dirname(file));

    if (context) {
      this.expressBasics.use('/' + context, handler);
    } else {
      this.expressBasics.use(handler);
    }

    logger.debug('Controller bound to express on route: ' + (context || '/'));
  }

  /**
   * Obtains the assets dynamically.
   * @param {string} file The file to obtain assets from.
   * @returns {Promise.<Array[]>}
   * @private
   */
  _getAssets(file) {
    const {assetsDir, configFile} = this._getControllerAssetNames(file);

    return fs.existsPromise(assetsDir)
      .then(exists => {

        if (!exists) {
          logger.warn(`No assets found ${assetsDir}`);
          return {js: [], css: []};
        }

        logger.debug('Looking for assets in ' + assetsDir);

        let promise = environment.development ?
          this._getDevelopmentAssets(assetsDir) :
          this._getProductionAssets(assetsDir);

        return promise.then(([css, js]) => this._getConfiguration(configFile)
          .then(cnf => {
            (cnf.dependencies || []).forEach(dependency => {
              if (CSS_REG.test(dependency)) {
                css.unshift(dependency);
              } else {
                js.unshift(dependency);
              }
            });
            logger.debug({title: 'Assets', message: {js, css}});
            return {js, css};
          }));

      });
  }

  /**
   * Obtains the configuration.
   * @param configFile
   * @returns {Promise.<Object>}
   * @private
   */
  _getConfiguration(configFile) {
    return cache.getLibrary('configurations')
      .getOrElse(configFile, () => fs.readFilePromise(configFile)
        .then(
          config => {
            config = JSON.parse(config.toString());
            if (config[environment.name]) {
              Object.assign(config, config[environment.name]);
              delete config[environment.name];
            }
            logger.debug({title: 'Controller Config', message: config});
            return config;
          },
          e => {
            logger.warn(e);
            return {};
          }
        ), environment.development ? 100 : 0);
  }

  /**
   * Obtains the development assets.
   * @param {string} assetsDir The assets directory.
   * @returns {Promise.<Array[]>}
   * @private
   */
  _getDevelopmentAssets(assetsDir) {
    return Promise.all([
      new Promise(resolve => {
        recursive.readdirr(path.normalize(assetsDir + '/scss/'),
          (e, dirs, files) => {
            if (e) {
              logger.error(e);
              return resolve([]);
            }
            resolve(files.filter(file =>
            /\.scss/.test(file) && !/[\/\\]_.*/.test(file))
              .map(file => this._getAbsPath(file)
                .replace(/scss/g, 'css')));
          });
      }),
      new Promise(resolve => {
        recursive.readdirr(path.normalize(assetsDir + '/js/'),
          (e, dirs, files) => {
            if (e) {
              logger.error(e);
              return resolve([]);
            }
            resolve(files
              .filter(file => /\.js/.test(file) && !/\.min\./.test(file))
              .map(file => this._getAbsPath(file)));
          });
      })
    ]);
  }

  /**
   * Obtains the production assets.
   * @param {string} assetsDir The assets directory.
   * @returns {Promise.<Array[]>}
   * @private
   */
  _getProductionAssets(assetsDir) {
    return Promise.all([
      new Promise(resolve => {
        recursive.readdirr(path.normalize(assetsDir + '/css/'),
          (e, dirs, files) => {
            if (e) {
              logger.error(e);
              return resolve([]);
            }
            resolve(files.filter(file => /\.min\.css$/.test(file))
              .map(file => '/' + path.relative(this._directory, file)
                .replace(/\\/g, '/')));
          });
      }),
      new Promise(resolve => {
        recursive.readdirr(path.normalize(assetsDir + '/js/'),
          (e, dirs, files) => {
            if (e) {
              logger.error(e);
              return resolve([]);
            }
            resolve(files.filter(file => /\.min\.js/.test(file))
              .map(file => '/' + path.relative(this._directory, file)
                .replace(/\\/g, '/')));
          });
      })
    ]);
  }

  /**
   * Binds the assets to the controller.
   * @param {string} file The file.
   * @private
   */
  _bindControllerAssets(file) {
    const {assetsDir} = this._getControllerAssetNames(file);
    this._bindCompass(assetsDir);
    this._bindStaticAssets(assetsDir);
  }

  /**
   * Binds the static assets to the application.
   * @param {string} dir The directory of the assets.
   * @private
   */
  _bindStaticAssets(dir) {
    const context = this._getAbsPath(dir) + '/';
    this.express
      .use(['/:version' + context, context], express.static(dir));
    logger.debug('Static assets bound to route: ' +
      context + ' & /:version' + context + ' on directory ' + dir);
  }

  /**
   * Binds the node modules as a static resource.
   * @private
   */
  _bindNodeModules(dir) {
    const context = this._getAbsPath(dir + '/node_modules') + '/';
    this.express.use(['/:version' + context, context],
      express.static(environment.nodeModules));
    logger.debug('Node modules bound to route: ' + context +
      ' & /:version' + context +
      ' on directory ' + environment.nodeModules);
  }

  /**
   * Binds compass on the static assets.
   * @param {string} dir The directory of the assets.
   * @private
   */
  _bindCompass(dir) {
    const context = this._getAbsPath(dir) + '/';
    if (environment.development && !SKIP_COMPASS) {
      this.expressBasics.use(['/:version' + context, context], basics => {
        if (!CSS_REG.test(basics.request.originalUrl)) {
          return basics.next();
        }
        exec(COMPASS_CMD, {cwd: dir}, (e, output) => {
          if (e) {
            logger.error({title: 'Compass', message: e});
          } else if (output) {
            logger.debug({title: 'Compass', message: output});
          }
          basics.next();
        });

      });
      logger.debug('Compass compilation bound to route: ' +
        context + ' & ' + '/:version' + context);
    }
  }

  /**
   * Obtains the name of the assets directory based on a file path.
   * @param {string} file The file name.
   * @returns {{assetsDir:string,configFile:string,rootDir:string}}
   * @private
   */
  _getControllerAssetNames(file) {
    const matches = file.match(CONTROLLER_REG);
    const prefix = matches[2] + matches[3].toLowerCase() + matches[4];
    return {
      rootDir: matches[2],
      assetsDir: prefix + 'Assets',
      configFile: prefix + 'Config.json'
    };
  }

  /**
   * Gets a relative path to a destination based on controller directory.
   * @param {string} destination The destination.
   * @returns {string}
   * @private
   */
  _getAbsPath(destination) {
    return '/' +
      path.relative(this._directory, path.normalize(destination))
        .replace(/\\/g, '/');
  }

  /**
   * Binds an api to the express application.
   * @param {Api} api The controller to bind.
   * @param {string=} file The file.
   * @private
   */
  _bindApi(api, file) {
    const context = path.dirname(this._getAbsPath(file)) + '/' +
      path.basename(file)
        .replace(/^(.)(.*)Api\.js$/i, (a, b, c) => b.toLowerCase() + c);
    this.expressBasics.use(context, basics => api.doRequest(basics));
    logger.debug('Api bound to express on route: ' + (context || '/'));
  }

  /**
   * Obtains the list of apis.
   * @returns {Promise.<Api[]>}
   */
  get apis() {
    return this._apis;
  }

  /**
   * Obtains the list of controllers.
   * @returns {Promise.<Controller[]>}
   */
  get controllers() {
    return this._controllers;
  }

  /**
   * Gets the controller.
   * @param {String} name The name of the controller.
   * @returns {Promise.<Controller>}}
   */
  getController(name) {
    return this._controllers
      .then(() => cache.getLibrary('controllers').get(name));
  }

  /**
   * Gets the api.
   * @param {String} name The name of the api.
   * @returns {Promise.<Api>}}
   */
  getApi(name) {
    return this._apis.then(() => cache.getLibrary('apis').get(name));
  }

  /**
   * Forwards the request to the listen method.
   * @param {*} args The arguments to send.
   * @returns {Promise.<express>}
   */
  listen(...args) {
    return Promise.all([this._controllers, this._apis])
      .then(() => {
        this.expressBasics.use(basics => basics.response.status(404).end());
        this.expressBasics.listen.apply(this.expressBasics, args);
        logger.highlight({
          title: 'SERVER',
          message: `Listening on port ${args[0]}`
        });
        return this.express;
      }, e => {
        logger.error(e);
        return this.express;
      });
  }

  /**
   * Simple getter of the express instance.
   * @returns {express}
   */
  get express() {
    return this.expressBasics.express;
  }

  /**
   * Forwards the request to the use method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  use(...args) {
    return this.expressBasics.use.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the get method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  get(...args) {
    return this.expressBasics.get.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the put method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  put(...args) {
    return this.expressBasics.put.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the post method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  post(...args) {
    return this.expressBasics.post.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the patch method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  patch(...args) {
    return this.expressBasics.patch.apply(this.expressBasics, args);
  }

  /**
   * Forwards the request to the delete method.
   * @param {*} args The arguments to send.
   * @returns {express}
   */
  delete(...args) {
    return this.expressBasics.delete.apply(this.expressBasics, args);
  }

}

module
  .exports = ExpressMvc;
<|endoftext|>


<commit_before>import animate;
import device;
import ui.View;
import ui.ImageView;
import ui.TextView;

import src.Match3Core as Core;
import src.Utils as Utils;
var Chance = require('chance');

//Some constants
var CoreGame = new Core();
var level = new Core();
var chance = new Chance();
/* The Game Screen code.
 * The child of the main application in
 * the game.  Everything else is a child
 * of game so it is all visible.
 */

exports = Class(ui.View, function(supr) {
    this.init = function(opts) {
        opts = merge(opts, {
            x: 0,
            y: 0,
            width: 576,
            height: 1024,
            backgroundColor: '#37b34a'
        });

        supr(this, 'init', [opts]);

        this.build();
    };

    this.build = function() {
        this.on('app:start', start_game_flow.bind(this));
    };
});

function ReadyGame() {
    CoreGame.InitializeBoard();
    CoreGame.CreateLevel();

    //Find Initial Moves and Clusters
    CoreGame.FindMoves();
    CoreGame.FindClusters();
}

// Starts the game
function start_game_flow() {
	ReadyGame();
	play_game(this);
}

// Game play
function play_game() {
	if(CoreGame.moves.length === 0) {
		end_game_flow.call(this);
	}
}

// function tick() {}
// function update_countdown() {}

// Game End
function end_game_flow() {
	//slight delay before allowing a tap reset
	setTimeout(emit_endgame_event.bind(this), 2000);
}

function emit_endgame_event() {
	this.once('InputSelect', function() {
		this.emit('gamescreen:end');
		reset_game.call(this);
	});
}

function reset_game() {}
<commit_msg>Update GameScreen.js<commit_after>import animate;
import device;
import ui.View;
import ui.ImageView;
import ui.TextView;

import src.Match3Core as Core;
import src.Utils as Utils;
//var Chance = require('chance');

//Some constants
var CoreGame = new Core();
var level = new Core();
//var chance = new Chance();
/* The Game Screen code.
 * The child of the main application in
 * the game.  Everything else is a child
 * of game so it is all visible.
 */

exports = Class(ui.View, function(supr) {
    this.init = function(opts) {
        opts = merge(opts, {
            x: 0,
            y: 0,
            width: 576,
            height: 1024,
            backgroundColor: '#37b34a'
        });

        supr(this, 'init', [opts]);

        this.build();
    };

    this.build = function() {
        this.on('app:start', start_game_flow.bind(this));
    };
});

function ReadyGame() {
    CoreGame.InitializeBoard();
    CoreGame.CreateLevel();

    //Find Initial Moves and Clusters
    CoreGame.FindMoves();
    CoreGame.FindClusters();
}

// Starts the game
function start_game_flow() {
	ReadyGame();
	play_game(this);
}

// Game play
function play_game() {
	if(CoreGame.moves.length === 0) {
		end_game_flow.call(this);
	}
}

// function tick() {}
// function update_countdown() {}

// Game End
function end_game_flow() {
	//slight delay before allowing a tap reset
	setTimeout(emit_endgame_event.bind(this), 2000);
}

function emit_endgame_event() {
	this.once('InputSelect', function() {
		this.emit('gamescreen:end');
		reset_game.call(this);
	});
}

function reset_game() {}
<|endoftext|>