<commit_before>'use strict';

module.exports = {
	app: {
		title: 'georate',
		description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
		keywords: 'MongoDB, Express, AngularJS, Node.js'
	},
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'MEAN',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.css',
				'public/lib/leaflet/dist/leaflet.css',
				'public/lib/leaflet.draw/dist/leaflet.draw.css',
				'public/lib/ngDialog/css/ngDialog.css',
				'public/lib/ngDialog/css/ngDialog-theme-default.css',
				'public/lib/fontawesome/css/font-awesome.css'
			],
			js: [
				'public/lib/angular/angular.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/leaflet/dist/leaflet.js',
				'public/lib/angular-leaflet/dist/angular-leaflet-directive.min.js',
				'public/lib/leaflet.draw/dist/leaflet.draw.js',
				'public/lib/ngDialog/js/ngDialog.js'
			]
		},
		css: [
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};<commit_msg>Changed Port for node-server to port 80<commit_after>'use strict';

module.exports = {
	app: {
		title: 'georate',
		description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
		keywords: 'MongoDB, Express, AngularJS, Node.js'
	},
	port: process.env.PORT || 80,
	templateEngine: 'swig',
	sessionSecret: 'MEAN',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.css',
				'public/lib/leaflet/dist/leaflet.css',
				'public/lib/leaflet.draw/dist/leaflet.draw.css',
				'public/lib/ngDialog/css/ngDialog.css',
				'public/lib/ngDialog/css/ngDialog-theme-default.css',
				'public/lib/fontawesome/css/font-awesome.css'
			],
			js: [
				'public/lib/angular/angular.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/leaflet/dist/leaflet.js',
				'public/lib/angular-leaflet/dist/angular-leaflet-directive.min.js',
				'public/lib/leaflet.draw/dist/leaflet.draw.js',
				'public/lib/ngDialog/js/ngDialog.js'
			]
		},
		css: [
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};<|endoftext|>


<commit_before>var express = require('express');
var load = require('express-load');

module.exports = function() {
	var app = express();

	app.set('port', 3000);

	app.use(express.static('./public'));

	app.set('view engine', 'ejs');
	app.set('views', './app/views');

	load('models', {cwd: 'app'})
		.then('controllers')
		.then('routes')
		.into(app);

	return app;

};

<commit_msg>adicionando body-parser e method-override<commit_after>var express = require('express');

var load = require('express-load');

var bodyParser = require('body-parser');

module.exports = function() {
	var app = express();

	app.set('port', 3000);
	app.use(express.static('./public'));
	app.set('view engine', 'ejs');
	app.set('views', './app/views');

	app.use(bodyParser.urlencoded({extended: true}));
	app.use(bodyParser.json());
	app.use(require('method-override')());

	load('models', {cwd: 'app'})
		.then('controllers')
		.then('routes')
		.into(app);

	return app;

};

<|endoftext|>


<commit_before>

"use strict";
var
  OS = require('os'),
  Net = require('net'),
  CPP = require('childprocess-promise');
class Main{
  constructor(Port){
    this.Port = Number(Port);
    this.Server = null;
    this.Children = [];
    this.Database = new Map();
  }
  Run(){
    let NumCPUs = OS.cpus().length;
    let SupportedEvents = [];

    for(let Name in Main){
      if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action')
        SupportedEvents.push(Name.substr(6));
    }
    for(var i = 0; i < NumCPUs; ++i){
      let Child = new CPP(__dirname + '/../Main.js');
      SupportedEvents.forEach(function(Child, Event){
        Child.on(Event, function(Request, Message){
          try {
            Message.Result = Main['Action' + Event].call(this, Request, Child, Message);
          } catch(error){
            Message.Result = {Type: 'Error', Message: error.message};
          }
          Child.Finished(Message);
        }.bind(this));
      }.bind(this, Child));
      Child.Send('SupportedEvents', SupportedEvents);
      this.Children.push(Child);
    }
    let Server = this.Server = Net.createServer();
    this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){
      Child.Target.send('Server', Server);
    }));
  }

  static NormalizeType(Value){
    let ValueInt = Value;
    if(!isNaN(ValueInt) && ValueInt.toString() === Value){
      return ValueInt;
    }
    return Value;
  }
  static Validate(Type, Action, Value){
    if(Type === Main.VAL_NUMERIC){
      if(typeof Value !== 'number')
        throw new Error("Cant ${Action} Non-Numeric Item");
    } else if(Type === Main.VAL_STRINGISH){
      if(typeof Value !== 'string' && typeof Value !== 'number')
        throw new Error("Cant ${Action} Non-Stringish Item");
    } else if(Type === Main.VAL_HASH){
      if(typeof Value !== 'object')
        throw new Error("Cant ${Action} Non-Hash Item");
    } else if(Type === Main.VAL_LIST){
      if(typeof Value !== 'object' || !Value.constructor || !Value.constructor.name === 'Array')
        throw new Error("Cant ${Action} Non-List Item");
    }
    return Value;
  }
  static ValidateArguments(TypeOrLength, Length){
    if(typeof TypeOrLength === 'string'){
      let IsOdd = Length % 2;
      if(TypeOrLength === Main.ARGS_EVEN && IsOdd)
        throw new Error(Main.MSG_ARGS_INVALID + '; Expected Even');
      else if(TypeOrLength === Main.ARGS_ODD && !IsOdd){
        throw new Error(Main.MSG_ARGS_INVALID + '; Expected Odd');
      }
    } else{
      if(TypeOrLength > Length){
        throw new Error(Main.MSG_ARGS_MORE);
      } else if(TypeOrLength < Length){
        throw new Error(Main.MSG_ARGS_LESS);
      }
    }
  }
}

Main.VAL_NUMERIC = 'VAL_NUMERIC';
Main.VAL_STRINGISH = 'VAL_STRING';
Main.VAL_HASH = 'VAL_HASH';
Main.VAL_LIST = 'VAL_LIST';

Main.MSG_ARGS_MORE = 'Too Many Arguments';
Main.MSG_ARGS_LESS = 'Too less Arguments';
Main.MSG_ARGS_INVALID = 'Invalid Number of Arguments';

Main.ARGS_EVEN = 'EVEN';
Main.ARGS_ODD = 'ODD';

Main.Timeouts = {};

module.exports = Main;

// Load the functions
require('./Methods_Basic');<commit_msg>:art: Include Methods_Hash in Main<commit_after>

"use strict";
var
  OS = require('os'),
  Net = require('net'),
  CPP = require('childprocess-promise');
class Main{
  constructor(Port){
    this.Port = Number(Port);
    this.Server = null;
    this.Children = [];
    this.Database = new Map();
  }
  Run(){
    let NumCPUs = OS.cpus().length;
    let SupportedEvents = [];

    for(let Name in Main){
      if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action')
        SupportedEvents.push(Name.substr(6));
    }
    for(var i = 0; i < NumCPUs; ++i){
      let Child = new CPP(__dirname + '/../Main.js');
      SupportedEvents.forEach(function(Child, Event){
        Child.on(Event, function(Request, Message){
          try {
            Message.Result = Main['Action' + Event].call(this, Request, Child, Message);
          } catch(error){
            Message.Result = {Type: 'Error', Message: error.message};
          }
          Child.Finished(Message);
        }.bind(this));
      }.bind(this, Child));
      Child.Send('SupportedEvents', SupportedEvents);
      this.Children.push(Child);
    }
    let Server = this.Server = Net.createServer();
    this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){
      Child.Target.send('Server', Server);
    }));
  }

  static NormalizeType(Value){
    let ValueInt = Value;
    if(!isNaN(ValueInt) && ValueInt.toString() === Value){
      return ValueInt;
    }
    return Value;
  }
  static Validate(Type, Action, Value){
    if(Type === Main.VAL_NUMERIC){
      if(typeof Value !== 'number')
        throw new Error("Cant ${Action} Non-Numeric Item");
    } else if(Type === Main.VAL_STRINGISH){
      if(typeof Value !== 'string' && typeof Value !== 'number')
        throw new Error("Cant ${Action} Non-Stringish Item");
    } else if(Type === Main.VAL_HASH){
      if(typeof Value !== 'object')
        throw new Error("Cant ${Action} Non-Hash Item");
    } else if(Type === Main.VAL_LIST){
      if(typeof Value !== 'object' || !Value.constructor || !Value.constructor.name === 'Array')
        throw new Error("Cant ${Action} Non-List Item");
    }
    return Value;
  }
  static ValidateArguments(TypeOrLength, Length){
    if(typeof TypeOrLength === 'string'){
      let IsOdd = Length % 2;
      if(TypeOrLength === Main.ARGS_EVEN && IsOdd)
        throw new Error(Main.MSG_ARGS_INVALID + '; Expected Even');
      else if(TypeOrLength === Main.ARGS_ODD && !IsOdd){
        throw new Error(Main.MSG_ARGS_INVALID + '; Expected Odd');
      }
    } else{
      if(TypeOrLength > Length){
        throw new Error(Main.MSG_ARGS_MORE);
      } else if(TypeOrLength < Length){
        throw new Error(Main.MSG_ARGS_LESS);
      }
    }
  }
}

Main.VAL_NUMERIC = 'VAL_NUMERIC';
Main.VAL_STRINGISH = 'VAL_STRING';
Main.VAL_HASH = 'VAL_HASH';
Main.VAL_LIST = 'VAL_LIST';

Main.MSG_ARGS_MORE = 'Too Many Arguments';
Main.MSG_ARGS_LESS = 'Too less Arguments';
Main.MSG_ARGS_INVALID = 'Invalid Number of Arguments';

Main.ARGS_EVEN = 'EVEN';
Main.ARGS_ODD = 'ODD';

Main.Timeouts = {};

module.exports = Main;

// Load the functions
require('./Methods_Basic');
require('./Methods_Hash');<|endoftext|>


<commit_before>var GENERATE_TO = process.argv.slice(2);
var sequence = [0, 1];

for (var i = 0; i < GENERATE_TO; i++) {
    sequence.push(sequence[0] + sequence[1]);
    sequence.splice(0, 1);
    console.log(sequence[1]);
}
<commit_msg>Added npm configuration code<commit_after>'use strict';

module.exports = function (generateTo) {
    var GENERATE_TO = generateTo || process.argv.slice(2);
    var sequence = [0, 1];

    for (var i = 0; i < GENERATE_TO; i++) {
        sequence.push(sequence[0] + sequence[1]);
        sequence.splice(0, 1);
        console.log(sequence[1]);
    }
}
<|endoftext|>


<commit_before>/**
 * (c) 2012 Spredfast, Inc. BSD Licensed; see LICENSE.txt
 */
steal("jquery","jquery/lang/string","jquery/model","mustache",function() {

	var toString = Object.prototype.toString;

	var _ = {
		map: function(obj,iterator,context) {
			return $.map(obj,function(value,key) {
				return iterator.call(context,value,key);
			});
		},
		keys: function(obj) {
			return _.map(obj,function(v,key) {
				return key;
			});
		},
		isFunction: function(obj) {
			return toString.call(obj) == '[object Function]';
		},
		isString: function(obj) {
			return toString.call(obj) == '[object String]';
		},
		find: function(obj,iterator) {
			for(var i = 0, l = obj.length; i < l; i++) {
				if(iterator(obj[i])) {
					return obj[i];
				}
			}
		}
	};

	_.each = _.map;

	var TMPL = /\{([^\s\{\}]+)\}/g,
		PREFIX = 'data-live-hookup',
		// XXX jQuery does strange things with data keys, so test how it maps PREFIX
		DATA_KEY = _.keys($('
').data())[0],
		hookups = {},
		lists = {},
		id = 0,
		listId = 0;

	// allows multiple hookups per element
	// $.View.hookup will only work for the first hookup on an element, but we may have multiple
	function addHookup(fn) {
		hookups[++id] = fn;
		return new Handlebars.SafeString(
			$.View.hook(runHookups) +
		'" '+PREFIX+id);
	}

	function bindings(obj,el,createBinder) {
		var model = this;
		_.map(obj,function(value,key,obj) {
			var binding = createBinder.call(this,value,key,obj),
				observed = binding[0],
				binder = binding[1];
			_.each(observed,function(o) {
				o.obj.bind(o.attr,binder);
			});
			el.bind('destroyed',function() {
				_.each(observed,function(o) {
					o.obj.unbind(o.attr,binder);
				});
			});
			return binder;
		});
	}

	// takes a simple string that may have substitutions and figures out what
	// attributes it depends on
	function parseEvents(bindTo) {
		var attrs = [];
		if(_.isString(bindTo) && bindTo.match(TMPL)) {
			bindTo.replace(TMPL,function(match,attr) {
				attrs.push(attr);
			});
			return {attrs:attrs};
		} else {
			return bindTo;
		}
	}

	function getValue(obj,attr) {
		var attrs = parseEvents(attr);
		if(attrs.attrs) {
			var results = {};
			_.each(attrs.attrs,function(attr) {
				results[attr] = getValue(obj,attr);
			});
			return results;
		} else if(_.isFunction(obj[attrs])) {
			return obj[attrs]();
		} else if(_.isFunction(attr)) {
			return attr.call(obj);
		} else {
			return obj.attr(attrs);
		}
	}

	function trapObserved(update) {
		var observed = [], old = can.Observe.__reading;
		can.Observe.__reading = function(obj,attr) {
			observed.push({obj:obj,attr:attr});
		};
		update();
		can.Observe.__reading = old;
		return observed;
	}

	// add a binding based on doing substitions on the value for each name="value" pair
	// in the options hash
	// either ctx or this is bound to, depending on who has a bind function
	function bindMany(ctx,options,update) {
		if(!ctx.bind) {
			options = ctx;
			ctx = this;
		}
		return addHookup(bindingsSetup(ctx,options.hash,update));
	}

	function bindingsSetup(ctx,options,update) {
		return function(el) {
			bindings.call(ctx,options,el,function(bindTo,key) {
				var length, not, tmpl;
				if( _.isString(bindTo) ) {
					tmpl = bindTo.match(TMPL);
					not = !tmpl && bindTo.charAt(0) === '!';
					bindTo = not ? bindTo.substring(1) : bindTo;
					length = !tmpl && bindTo.charAt(0) === '#';
					bindTo = length ? bindTo.substring(1) : bindTo;
				}
				function simpleUpdate() {
					var value = getValue(ctx,bindTo);
					if(length) {
						value = value && value.length;
					}
					update.call(ctx,el,
						tmpl ? $.String.sub(bindTo,value) :
							not ? !value : value,
						key);
				}
				var bound = trapObserved(simpleUpdate);
				// if it's the length, add a binding to update on add & remove
				if(length) {
					var list = getValue(ctx,bindTo);
					if(!list) {
						throw new Error(bindTo+' is not defined.');
					}
					bound.push({
						obj: list,
						attr: 'add remove'
					});
				}
				return [bound,simpleUpdate];
			});
		};
	}

	// bind to a single attribute change
	function bindOne(attr,options,update) {
		var ctx = options.hash.context || this;
		return bindMany.call(this,ctx,{hash:{attr:attr}},update);
	}

	// run all the hookups attached to el
	function runHookups(el) {
		el = $(el);
		_.each(el.data(),function(value,key) {
			var id;
			if(key.indexOf(DATA_KEY) === 0) {
				id = +(key.substring(DATA_KEY.length));
				hookups[id](el);
				delete hookups[id];
				el.removeData(key);
			}
		},this);
	}

	Handlebars.registerHelper('bindAttr',function(ctx,options) {
		return bindMany.call(this,ctx,options,function(el,value,attr) {
			el.attr(attr,""+value);
		});
	});

	Handlebars.registerHelper('bindClass',function(ctx,options) {
		return bindMany.call(this,ctx,options,function(el,condition,className) {
			el.toggleClass(""+className,!!condition);
		});
	});

	Handlebars.registerHelper('bindHtml',function(attr,options) {
		return bindOne.call(this,attr,options,function(el,html) {
			el.html(""+html);
		});
	});

	Handlebars.registerHelper('bindIf',function(attr,options) {
		var ctx = options.hash.context || this,
			templateContext = this;
		return '<span ' + addHookup(function(el) {
			var parent = $(el).parent(),
				bind = {_changed:attr},
				content = $(el);
			if(!parent.length) {
				throw new Error('Cannot use bindIf without a wrapper element.');
			}
			bindingsSetup(ctx,bind,function(parent,condition) {
				var newContent = $('
').
					html( (condition ? options.fn : options.inverse)(templateContext) ).
					children();

				if(!newContent.length) {
					newContent = $('');
				}

				content.replaceWith(newContent);
				content = newContent;
			})(parent);
		}) +'>';
	});

	Handlebars.registerHelper('bindList',function(ctx,options) {
		if(!ctx.bind) {
			options = ctx;
			ctx = this;
		}
		lists[++listId] = {};
		var id = listId, ns = '',
			sort = options.hash.sortBy;
		var sortBy = sort ? _.isFunction(sort) ? sort : function(model) {
			return model && model.attr(sort);
		} : false;
		if(options.hash.namespace) {
			ns = '.' + options.hash.namespace;
		}
		function findBefore(model,el) {
			if(!sortBy) return;

			var value = sortBy(model);
			var before = _.find(ctx.elements(el),function(item) {
				return sortBy($(item).model(model.constructor)) > value;
			});
			return before && $(before);
		}
		return addHookup(function(el) {
			function add(ev,models) {
				_.each(models,function(model) {
					var config = {
						appendTo: el,
						before: findBefore(model,el),
						item: $(lists[id].tmpl(model))
					};
					el.trigger('beforeAdd'+ns,config);
					if(config.before) {
						config.before.before( config.item );
					} else {
						config.appendTo.append( config.item );
					}
					model.hookup(config.item[0]);
					config.item.trigger('add'+ns);
				});
			}
			function remove(ev,models) {
				_.each(models,function(model) {
					// remove any descendant of el for this model
					model.elements(el).remove();
				});
			}
			ctx.bind('add',add);
			ctx.bind('remove',remove);
			el.bind('destroyed',function() {
				ctx.unbind('add',add);
				ctx.unbind('remove',remove);
				delete lists[id];
			});
			// add all the existing models
			add(null,ctx);
		});
	});

	// just saves the item template for the current list
	Handlebars.registerHelper('bindItem',function(ctx,options) {
		lists[listId].tmpl = (options || ctx).fn;
		return '';
	});

	Handlebars.registerHelper('bindProp',function(ctx,options) {
		return bindMany.call(this,ctx,options,function(el,value,prop) {
			el.prop(prop,value);
		});
	});

	Handlebars.registerHelper('bindText',function(attr,options) {
		return bindOne.call(this,attr,options,function(el,text) {
			el.text(""+text);
		});
	});

	Handlebars.registerHelper('bindTruncatedText',function(attr,options) {
		var len = options.hash.length,
			ellipsis = options.hash.ellipsis;
		return bindOne.call(this,attr,options,function(el,text) {
			el.text(""+Spredfast.truncate(text,len,ellipsis));
		});
	});

	Handlebars.registerHelper('bindVal',function(attr,options) {
		var def = options && options.hash && options.hash['default'];
		return bindOne.call(this,attr,options,function(el,val) {
			var old = el.val();
			if(old !== val) {
				// the default value comes into play if val is undefined
				// or null (hence ==) because 0 or the empty string is OK
				/*jshint eqnull:true */
				el.val(""+((val == null && def != null) ? def : val));
			}
		});
	});

	Handlebars.registerHelper('bindSelect',function(attr,options) {
		return bindOne.call(this,attr,options,function(el,val) {
			el.find('option').filter(function() {
				return String($(this).val()) === String(val);
			}).prop('selected',true);
		});
	});

	// HACK have to overwrite hookupModel because it doesn't support multiple hookups
	Handlebars.registerHelper('hookupModel',function(ctx,options) {
		var model = ctx && ctx.bind && ctx || this;
		return addHookup(function(el) {
			model.hookup(el[0]);
		});
	});

});
<commit_msg>remove invalid helper<commit_after>/**
 * (c) 2012 Spredfast, Inc. BSD Licensed; see LICENSE.txt
 */
steal("jquery","jquery/lang/string","jquery/model","mustache",function() {

	var toString = Object.prototype.toString;

	var _ = {
		map: function(obj,iterator,context) {
			return $.map(obj,function(value,key) {
				return iterator.call(context,value,key);
			});
		},
		keys: function(obj) {
			return _.map(obj,function(v,key) {
				return key;
			});
		},
		isFunction: function(obj) {
			return toString.call(obj) == '[object Function]';
		},
		isString: function(obj) {
			return toString.call(obj) == '[object String]';
		},
		find: function(obj,iterator) {
			for(var i = 0, l = obj.length; i < l; i++) {
				if(iterator(obj[i])) {
					return obj[i];
				}
			}
		}
	};

	_.each = _.map;

	var TMPL = /\{([^\s\{\}]+)\}/g,
		PREFIX = 'data-live-hookup',
		// XXX jQuery does strange things with data keys, so test how it maps PREFIX
		DATA_KEY = _.keys($('
').data())[0],
		hookups = {},
		lists = {},
		id = 0,
		listId = 0;

	// allows multiple hookups per element
	// $.View.hookup will only work for the first hookup on an element, but we may have multiple
	function addHookup(fn) {
		hookups[++id] = fn;
		return new Handlebars.SafeString(
			$.View.hook(runHookups) +
		'" '+PREFIX+id);
	}

	function bindings(obj,el,createBinder) {
		var model = this;
		_.map(obj,function(value,key,obj) {
			var binding = createBinder.call(this,value,key,obj),
				observed = binding[0],
				binder = binding[1];
			_.each(observed,function(o) {
				o.obj.bind(o.attr,binder);
			});
			el.bind('destroyed',function() {
				_.each(observed,function(o) {
					o.obj.unbind(o.attr,binder);
				});
			});
			return binder;
		});
	}

	// takes a simple string that may have substitutions and figures out what
	// attributes it depends on
	function parseEvents(bindTo) {
		var attrs = [];
		if(_.isString(bindTo) && bindTo.match(TMPL)) {
			bindTo.replace(TMPL,function(match,attr) {
				attrs.push(attr);
			});
			return {attrs:attrs};
		} else {
			return bindTo;
		}
	}

	function getValue(obj,attr) {
		var attrs = parseEvents(attr);
		if(attrs.attrs) {
			var results = {};
			_.each(attrs.attrs,function(attr) {
				results[attr] = getValue(obj,attr);
			});
			return results;
		} else if(_.isFunction(obj[attrs])) {
			return obj[attrs]();
		} else if(_.isFunction(attr)) {
			return attr.call(obj);
		} else {
			return obj.attr(attrs);
		}
	}

	function trapObserved(update) {
		var observed = [], old = can.Observe.__reading;
		can.Observe.__reading = function(obj,attr) {
			observed.push({obj:obj,attr:attr});
		};
		update();
		can.Observe.__reading = old;
		return observed;
	}

	// add a binding based on doing substitions on the value for each name="value" pair
	// in the options hash
	// either ctx or this is bound to, depending on who has a bind function
	function bindMany(ctx,options,update) {
		if(!ctx.bind) {
			options = ctx;
			ctx = this;
		}
		return addHookup(bindingsSetup(ctx,options.hash,update));
	}

	function bindingsSetup(ctx,options,update) {
		return function(el) {
			bindings.call(ctx,options,el,function(bindTo,key) {
				var length, not, tmpl;
				if( _.isString(bindTo) ) {
					tmpl = bindTo.match(TMPL);
					not = !tmpl && bindTo.charAt(0) === '!';
					bindTo = not ? bindTo.substring(1) : bindTo;
					length = !tmpl && bindTo.charAt(0) === '#';
					bindTo = length ? bindTo.substring(1) : bindTo;
				}
				function simpleUpdate() {
					var value = getValue(ctx,bindTo);
					if(length) {
						value = value && value.length;
					}
					update.call(ctx,el,
						tmpl ? $.String.sub(bindTo,value) :
							not ? !value : value,
						key);
				}
				var bound = trapObserved(simpleUpdate);
				// if it's the length, add a binding to update on add & remove
				if(length) {
					var list = getValue(ctx,bindTo);
					if(!list) {
						throw new Error(bindTo+' is not defined.');
					}
					bound.push({
						obj: list,
						attr: 'add remove'
					});
				}
				return [bound,simpleUpdate];
			});
		};
	}

	// bind to a single attribute change
	function bindOne(attr,options,update) {
		var ctx = options.hash.context || this;
		return bindMany.call(this,ctx,{hash:{attr:attr}},update);
	}

	// run all the hookups attached to el
	function runHookups(el) {
		el = $(el);
		_.each(el.data(),function(value,key) {
			var id;
			if(key.indexOf(DATA_KEY) === 0) {
				id = +(key.substring(DATA_KEY.length));
				hookups[id](el);
				delete hookups[id];
				el.removeData(key);
			}
		},this);
	}

	Handlebars.registerHelper('bindAttr',function(ctx,options) {
		return bindMany.call(this,ctx,options,function(el,value,attr) {
			el.attr(attr,""+value);
		});
	});

	Handlebars.registerHelper('bindClass',function(ctx,options) {
		return bindMany.call(this,ctx,options,function(el,condition,className) {
			el.toggleClass(""+className,!!condition);
		});
	});

	Handlebars.registerHelper('bindHtml',function(attr,options) {
		return bindOne.call(this,attr,options,function(el,html) {
			el.html(""+html);
		});
	});

	Handlebars.registerHelper('bindIf',function(attr,options) {
		var ctx = options.hash.context || this,
			templateContext = this;
		return '<span ' + addHookup(function(el) {
			var parent = $(el).parent(),
				bind = {_changed:attr},
				content = $(el);
			if(!parent.length) {
				throw new Error('Cannot use bindIf without a wrapper element.');
			}
			bindingsSetup(ctx,bind,function(parent,condition) {
				var newContent = $('
').
					html( (condition ? options.fn : options.inverse)(templateContext) ).
					children();

				if(!newContent.length) {
					newContent = $('');
				}

				content.replaceWith(newContent);
				content = newContent;
			})(parent);
		}) +'>';
	});

	Handlebars.registerHelper('bindList',function(ctx,options) {
		if(!ctx.bind) {
			options = ctx;
			ctx = this;
		}
		lists[++listId] = {};
		var id = listId, ns = '',
			sort = options.hash.sortBy;
		var sortBy = sort ? _.isFunction(sort) ? sort : function(model) {
			return model && model.attr(sort);
		} : false;
		if(options.hash.namespace) {
			ns = '.' + options.hash.namespace;
		}
		function findBefore(model,el) {
			if(!sortBy) return;

			var value = sortBy(model);
			var before = _.find(ctx.elements(el),function(item) {
				return sortBy($(item).model(model.constructor)) > value;
			});
			return before && $(before);
		}
		return addHookup(function(el) {
			function add(ev,models) {
				_.each(models,function(model) {
					var config = {
						appendTo: el,
						before: findBefore(model,el),
						item: $(lists[id].tmpl(model))
					};
					el.trigger('beforeAdd'+ns,config);
					if(config.before) {
						config.before.before( config.item );
					} else {
						config.appendTo.append( config.item );
					}
					model.hookup(config.item[0]);
					config.item.trigger('add'+ns);
				});
			}
			function remove(ev,models) {
				_.each(models,function(model) {
					// remove any descendant of el for this model
					model.elements(el).remove();
				});
			}
			ctx.bind('add',add);
			ctx.bind('remove',remove);
			el.bind('destroyed',function() {
				ctx.unbind('add',add);
				ctx.unbind('remove',remove);
				delete lists[id];
			});
			// add all the existing models
			add(null,ctx);
		});
	});

	// just saves the item template for the current list
	Handlebars.registerHelper('bindItem',function(ctx,options) {
		lists[listId].tmpl = (options || ctx).fn;
		return '';
	});

	Handlebars.registerHelper('bindProp',function(ctx,options) {
		return bindMany.call(this,ctx,options,function(el,value,prop) {
			el.prop(prop,value);
		});
	});

	Handlebars.registerHelper('bindText',function(attr,options) {
		return bindOne.call(this,attr,options,function(el,text) {
			el.text(""+text);
		});
	});

	Handlebars.registerHelper('bindVal',function(attr,options) {
		var def = options && options.hash && options.hash['default'];
		return bindOne.call(this,attr,options,function(el,val) {
			var old = el.val();
			if(old !== val) {
				// the default value comes into play if val is undefined
				// or null (hence ==) because 0 or the empty string is OK
				/*jshint eqnull:true */
				el.val(""+((val == null && def != null) ? def : val));
			}
		});
	});

	Handlebars.registerHelper('bindSelect',function(attr,options) {
		return bindOne.call(this,attr,options,function(el,val) {
			el.find('option').filter(function() {
				return String($(this).val()) === String(val);
			}).prop('selected',true);
		});
	});

	// HACK have to overwrite hookupModel because it doesn't support multiple hookups
	Handlebars.registerHelper('hookupModel',function(ctx,options) {
		var model = ctx && ctx.bind && ctx || this;
		return addHookup(function(el) {
			model.hookup(el[0]);
		});
	});

});
<|endoftext|>


<commit_before>$("#home_call").on ("click", function () {
		$("#pageContent").load("pages/home-view.html", function () {
			$(this).enhanceWithin(); /* apply styles */
		});
	});
$("#proprety_call").on ("click", function () {
	$("#pageContent").load("pages/property-view.html", function () {
		$(this).enhanceWithin(); /* apply styles */
	});
});

$(".current-title").text ("Customer View");
$(".left").on ("click", function () {
	loadPage ("pages/customer-view.html"); // "pages/splash-view.html"
});
<commit_msg>new js to prefill form<commit_after>$("#home_call").on ("click", function () {
		$("#pageContent").load("pages/home-view.html", function () {
			$(this).enhanceWithin(); /* apply styles */
		});
	});
$("#proprety_call").on ("click", function () {
	$("#pageContent").load("pages/property-view.html", function () {
		$(this).enhanceWithin(); /* apply styles */
	});
});

$(".current-title").text ("Customer View");
$(".left").on ("click", function () {
	loadPage ("pages/customer-view.html"); // "pages/splash-view.html"
});

autoFill{

data = {
	        "Title": "Mr",
	        "First_name": "Rachid",
	        "Last_name": "Mahmoudi",
	        "Nationality": "Morrocan",
	        "Email": "az@gmail.com",
	        "Mobile":"(212)-6757657 676545",
	        "Monthly_income":"60000",
	        "personal_loans":"Yes",
	        "MP_personal_loans":"3000",
	        "car_loans":"Yes",
	        "MP_car_loans":"2000",
	        "existing_mortgages":"Yes",
	        "MP_existing_mortgages":"4000",
	        "Existing_debit_card":"Yes",
	        "Existing_credit_card":"No"

	};

	// reset form values from json object
	function resetForm(){
		$.each(data, function (name, val) {
	    var $el = $('[name="' + name + '"]'),
	        type = $el.attr('type');

	    switch (type) {
	        case 'checkbox':
	            $el.attr('checked', 'checked');
	            break;
	        case 'radio':
	            $el.filter('[value="' + val + '"]').attr('checked', 'checked');
	            break;
	        default:
	            $el.val(val);
	    }
	})}
}

 resetForm();<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 */
// repaint
function Repaint(){
    $("#whiteboard").resize(function(){
        jsPlumb.repaintEverything();
    });
}
// drag
function DragEl(el){
    jsPlumb.draggable($(el) ,{
        containment:"#whiteboard"
    });
}

// JsPlumb Config
var color = "gray",
    exampleColor = "#00f",
    arrowCommon = { foldback:0.7, fillStyle:color, width:14 };

jsPlumb.importDefaults({
    Connector : [ "Bezier", { curviness:63 } ]
});

var nodeDropOptions = {
    activeClass:"dragActive"
};

var bottomConnectorOptions = {
    endpoint:"Rectangle",
    paintStyle:{ width:25, height:21, fillStyle:'#666' },
    isSource:true,
    connectorStyle : { strokeStyle:"#666" },
    isTarget:false,
    maxConnections:20
};

var endpointOptions = {
    isTarget:true,
    endpoint:"Dot",
    paintStyle:{
        fillStyle:"gray"
    },
    dropOptions: nodeDropOptions,
    maxConnections:1
};

var groupOptions = {
    isTarget:true,
    endpoint:"Dot",
    paintStyle:{
        fillStyle:"gray"
    },
    dropOptions: nodeDropOptions,
    maxConnections:1
};

var generatedCartridgeEndpointOptions = {
    isTarget:false,
    endpoint:"Dot",
    paintStyle:{
        fillStyle:"gray"
    },
    dropOptions: '',
    maxConnections:1
};

var generatedGroupOptions = {
    isTarget:false,
    endpoint:"Dot",
    paintStyle:{
        fillStyle:"gray"
    },
    dropOptions: nodeDropOptions,
    maxConnections:1
};

function dagrePosition(){
    // construct dagre graph from JsPlumb graph
    var g = new dagre.graphlib.Graph();
    g.setGraph({ranksep:'80'});
    g.setDefaultEdgeLabel(function() { return {}; });
    var nodes = $(".stepnode");

    for (var i = 0; i < nodes.length; i++) {
        var n = nodes[i];
        g.setNode(n.id, {width: 52, height: 52});
    }
    var edges = jsPlumb.getAllConnections();
    for (var i = 0; i < edges.length; i++) {
        var c = edges[i];
        g.setEdge(c.source.id,c.target.id );
    }
    // calculate the layout (i.e. node positions)
    dagre.layout(g);

    // Applying the calculated layout
    g.nodes().forEach(function(v) {
        $("#" + v).css("left", g.node(v).x + "px");
        $("#" + v).css("top", g.node(v).y + "px");
    });
    jsPlumb.repaintEverything();
}
//add group to editor
var cartridgeCounter =0;
//add group to editor
function addJsplumbGroup(groupJSON, cartridgeCounter){

    var divRoot = $('
').attr({'id':cartridgeCounter+'-'+groupJSON.alias,'data-type':'group','data-ctype':groupJSON.alias})
        .text(groupJSON.alias)
        .addClass('input-false')
        .addClass('stepnode')
        .attr('data-toggle', 'tooltip')
        .attr('title',groupJSON.alias )
        .appendTo('#whiteboard');
    jsPlumb.addEndpoint($(divRoot), {
        anchor:"BottomCenter"
    }, bottomConnectorOptions);

    DragEl($(divRoot));
    if(groupJSON['components']['cartridges']) {
        genJsplumbCartridge(groupJSON['components']['cartridges'], divRoot, groupJSON.alias);
    }
    if(groupJSON['components']['groups']){
        genJsplumbGroups(groupJSON['components']['groups'], divRoot, groupJSON.alias);
    }

    function genJsplumbCartridge(item, currentParent, parentName){
        for (var prop in item) {
            var id = item[prop].type;
            var divCartridge = $('
').attr({'id':cartridgeCounter+'-'+parentName+'-'+item[prop].type, 'data-type':'cartridge',
                'data-calias':item[prop]['subscribableInfo']['alias']} )
                .text(item[prop].type)
                .addClass('input-false')
                .addClass('stepnode')
                .attr('data-toggle', 'tooltip')
                .attr('title',item[prop].type )
                .appendTo('#whiteboard');
            $(divCartridge).append('

');
            jsPlumb.addEndpoint($(divCartridge), {
                anchor: "TopCenter"
            }, generatedCartridgeEndpointOptions);

            //add connection options
            jsPlumb.connect({
                source:$(currentParent),
                target:$(divCartridge),
                paintStyle:{strokeStyle:"blue", lineWidth:1 },
                Connector : [ "Bezier", { curviness:63 } ],
                anchors:["BottomCenter", "TopCenter"],
                endpoint:"Dot"
            });

            DragEl($(divCartridge));
        }
    }

    function genJsplumbGroups(item, currentParent, parentName) {
        for (var prop in item) {
            var divGroup = $('
').attr({'id':cartridgeCounter+'-'+parentName+'-'+item[prop]['name'],'data-type':'group','data-ctype':item[prop]['name'] })
                .text(item[prop]['name'])
                .addClass('stepnode')
                .attr('data-toggle', 'tooltip')
                .attr('title',item[prop]['name'] )
                .addClass('input-false')
                .appendTo('#whiteboard');
            //$(divGroup).append('

');
            jsPlumb.addEndpoint($(divGroup), {
                anchor:"BottomCenter"
            }, bottomConnectorOptions);

            jsPlumb.addEndpoint($(divGroup), {
                anchor: "TopCenter"
            }, generatedGroupOptions);

            //add connection options
            jsPlumb.connect({
                source:$(currentParent),
                target:$(divGroup),
                paintStyle:{strokeStyle:"blue", lineWidth:1 },
                Connector : [ "Bezier", { curviness:63 } ],
                anchors:["BottomCenter", "TopCenter"],
                endpoint:"Dot"
            });

            DragEl($(divGroup));

            if(item[prop].hasOwnProperty('cartridges')) {
                genJsplumbCartridge(item[prop].cartridges, divGroup, parentName+'-'+item[prop]['name'] );
            }
            if(item[prop].hasOwnProperty('groups')) {
                genJsplumbGroups(item[prop].groups, divGroup, parentName+'-'+item[prop]['name'])
            }
        }
    }

}

jsPlumb.bind("ready", function() {
    addJsplumbGroup(applicationJSON, cartridgeCounter);
    //reposition after group add
    dagrePosition();
});

var signupBlockTemplate = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "root",
    "type": "object",
    "title": " ",
    "options": {
        "disable_properties": true,
        "disable_collapse": true
    },
    "properties": {
        "alias": {
            "id": "root/alias",
            "title": "Cartridge Alias: ",
            "type": "string"
        },
        "privateRepo": {
            "id": "root/privateRepo",
            "title": "Is private repository: ",
            "type": "boolean"
        },
        "repoUrl": {
            "id": "root/repoUrl",
            "title": "Repository URL: ",
            "type": "string"
        },
        "repoUsername": {
            "id": "root/repoUsername",
            "title": "Repository User Name: ",
            "type": "string"
        },
        "repoPassword": {
            "id": "root/repoPassword",
            "title": "Repository Password: ",
            "type": "string"
        }
    }
};

var signupBlockDefault = {
    "alias": "php",
    "privateRepo": false,
    "repoUrl": "https://github.com/imesh/stratos-php-applications.git",
    "repoUsername": "",
    "repoPassword": ""
};

// Document ready events
$(document).ready(function(){
    //handled Ajax base session expire issue
    $(document).ajaxError(function (e, xhr, settings) {
        window.location.href = '../';
    });

    //*******************Adding JSON editor *************//
    JSONEditor.defaults.theme = 'bootstrap3';
    JSONEditor.defaults.iconlib = 'fontawesome4';
    JSONEditor.defaults.show_errors = "always";
    var editor,blockId;

    $('#whiteboard').on('click', '.stepnode', function(){
        $('.signup-details').show();
        $('.signup-default').hide();
        $('.stepnode').removeClass("highlightme");
        $(this).addClass('highlightme');
        tabData($(this));
    });

    function tabData(node){

        blockId = node.attr('id');
        var blockType = node.attr('data-type');
        var startval;
        var calias = node.attr('data-calias');

        if(blockType == 'cartridge'){
            startval = signupBlockDefault;
            startval['alias'] = calias;
        }

        if(node.attr('data-generated')) {
            startval = JSON.parse(decodeURIComponent(node.attr('data-generated')));
        }
        $('#signup-details').html('');

        switch (blockType){
            case 'cartridge':
                generateHtmlBlock(signupBlockTemplate, startval);
                break;
        }
    }

    function generateHtmlBlock(schema, startval){
        // Initialize the editor
        editor = new JSONEditor(document.getElementById('signup-details'), {
            ajax: false,
            disable_edit_json: true,
            schema: schema,
            format: "grid",
            startval: startval
        });

        if(editor.getEditor('root.alias')){
            editor.getEditor('root.alias').disable();
        }

    }

    //get component JSON data
    $('#component-info-update').on('click', function(){
        $('#'+blockId).attr('data-generated', encodeURIComponent(JSON.stringify(editor.getValue())));
        $('#'+blockId).removeClass('input-false');
        $('#'+blockId).find('div>i').removeClass('fa-exclamation-circle').addClass('fa-check-circle-o').css('color','#2ecc71');
    });

    $('#signup').on('click', function(){
        var btn = $(this);
        var appid = btn.attr('data-appid');
        var signupJSON = {"artifactRepositories":[]};
        //generate raw data tree from connections
        $.each(jsPlumb.getConnections(), function (idx, connection) {
           var dataGen = $('#'+connection.targetId).attr('data-generated');
            if(dataGen!=undefined){
                var jsonContent = JSON.parse(decodeURIComponent(dataGen));
                signupJSON['artifactRepositories'].push(jsonContent);
            }

        });

        var formtype = 'signupapplication';
        btn.html(" Adding...");
        $.ajax({
            type: "POST",
            url: caramel.context + "/controllers/applications/application_requests.jag",
            dataType: 'json',
            data: { "formPayload": JSON.stringify(signupJSON), "formtype": formtype, "applicationId": appid },
            success: function (data) {
                if (data.status == 'error') {
                    var n = noty({text: data.message, layout: 'bottomRight', type: 'error'});
                } else if (data.status == 'warning') {
                    var n = noty({text: data.message, layout: 'bottomRight', type: 'warning'});
                } else {
                    var n = noty({text: data.message, layout: 'bottomRight', type: 'success'});
                    window.setTimeout(function(){
                        window.location.href = '../';
                    }, 1500);
                }
            }
        })
            .always(function () {
                btn.html('Add Signup');
            });

    });

});<commit_msg>Updating default signup git repository URL<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 */
// repaint
function Repaint(){
    $("#whiteboard").resize(function(){
        jsPlumb.repaintEverything();
    });
}
// drag
function DragEl(el){
    jsPlumb.draggable($(el) ,{
        containment:"#whiteboard"
    });
}

// JsPlumb Config
var color = "gray",
    exampleColor = "#00f",
    arrowCommon = { foldback:0.7, fillStyle:color, width:14 };

jsPlumb.importDefaults({
    Connector : [ "Bezier", { curviness:63 } ]
});

var nodeDropOptions = {
    activeClass:"dragActive"
};

var bottomConnectorOptions = {
    endpoint:"Rectangle",
    paintStyle:{ width:25, height:21, fillStyle:'#666' },
    isSource:true,
    connectorStyle : { strokeStyle:"#666" },
    isTarget:false,
    maxConnections:20
};

var endpointOptions = {
    isTarget:true,
    endpoint:"Dot",
    paintStyle:{
        fillStyle:"gray"
    },
    dropOptions: nodeDropOptions,
    maxConnections:1
};

var groupOptions = {
    isTarget:true,
    endpoint:"Dot",
    paintStyle:{
        fillStyle:"gray"
    },
    dropOptions: nodeDropOptions,
    maxConnections:1
};

var generatedCartridgeEndpointOptions = {
    isTarget:false,
    endpoint:"Dot",
    paintStyle:{
        fillStyle:"gray"
    },
    dropOptions: '',
    maxConnections:1
};

var generatedGroupOptions = {
    isTarget:false,
    endpoint:"Dot",
    paintStyle:{
        fillStyle:"gray"
    },
    dropOptions: nodeDropOptions,
    maxConnections:1
};

function dagrePosition(){
    // construct dagre graph from JsPlumb graph
    var g = new dagre.graphlib.Graph();
    g.setGraph({ranksep:'80'});
    g.setDefaultEdgeLabel(function() { return {}; });
    var nodes = $(".stepnode");

    for (var i = 0; i < nodes.length; i++) {
        var n = nodes[i];
        g.setNode(n.id, {width: 52, height: 52});
    }
    var edges = jsPlumb.getAllConnections();
    for (var i = 0; i < edges.length; i++) {
        var c = edges[i];
        g.setEdge(c.source.id,c.target.id );
    }
    // calculate the layout (i.e. node positions)
    dagre.layout(g);

    // Applying the calculated layout
    g.nodes().forEach(function(v) {
        $("#" + v).css("left", g.node(v).x + "px");
        $("#" + v).css("top", g.node(v).y + "px");
    });
    jsPlumb.repaintEverything();
}
//add group to editor
var cartridgeCounter =0;
//add group to editor
function addJsplumbGroup(groupJSON, cartridgeCounter){

    var divRoot = $('
').attr({'id':cartridgeCounter+'-'+groupJSON.alias,'data-type':'group','data-ctype':groupJSON.alias})
        .text(groupJSON.alias)
        .addClass('input-false')
        .addClass('stepnode')
        .attr('data-toggle', 'tooltip')
        .attr('title',groupJSON.alias )
        .appendTo('#whiteboard');
    jsPlumb.addEndpoint($(divRoot), {
        anchor:"BottomCenter"
    }, bottomConnectorOptions);

    DragEl($(divRoot));
    if(groupJSON['components']['cartridges']) {
        genJsplumbCartridge(groupJSON['components']['cartridges'], divRoot, groupJSON.alias);
    }
    if(groupJSON['components']['groups']){
        genJsplumbGroups(groupJSON['components']['groups'], divRoot, groupJSON.alias);
    }

    function genJsplumbCartridge(item, currentParent, parentName){
        for (var prop in item) {
            var id = item[prop].type;
            var divCartridge = $('
').attr({'id':cartridgeCounter+'-'+parentName+'-'+item[prop].type, 'data-type':'cartridge',
                'data-calias':item[prop]['subscribableInfo']['alias']} )
                .text(item[prop].type)
                .addClass('input-false')
                .addClass('stepnode')
                .attr('data-toggle', 'tooltip')
                .attr('title',item[prop].type )
                .appendTo('#whiteboard');
            $(divCartridge).append('

');
            jsPlumb.addEndpoint($(divCartridge), {
                anchor: "TopCenter"
            }, generatedCartridgeEndpointOptions);

            //add connection options
            jsPlumb.connect({
                source:$(currentParent),
                target:$(divCartridge),
                paintStyle:{strokeStyle:"blue", lineWidth:1 },
                Connector : [ "Bezier", { curviness:63 } ],
                anchors:["BottomCenter", "TopCenter"],
                endpoint:"Dot"
            });

            DragEl($(divCartridge));
        }
    }

    function genJsplumbGroups(item, currentParent, parentName) {
        for (var prop in item) {
            var divGroup = $('
').attr({'id':cartridgeCounter+'-'+parentName+'-'+item[prop]['name'],'data-type':'group','data-ctype':item[prop]['name'] })
                .text(item[prop]['name'])
                .addClass('stepnode')
                .attr('data-toggle', 'tooltip')
                .attr('title',item[prop]['name'] )
                .addClass('input-false')
                .appendTo('#whiteboard');
            //$(divGroup).append('

');
            jsPlumb.addEndpoint($(divGroup), {
                anchor:"BottomCenter"
            }, bottomConnectorOptions);

            jsPlumb.addEndpoint($(divGroup), {
                anchor: "TopCenter"
            }, generatedGroupOptions);

            //add connection options
            jsPlumb.connect({
                source:$(currentParent),
                target:$(divGroup),
                paintStyle:{strokeStyle:"blue", lineWidth:1 },
                Connector : [ "Bezier", { curviness:63 } ],
                anchors:["BottomCenter", "TopCenter"],
                endpoint:"Dot"
            });

            DragEl($(divGroup));

            if(item[prop].hasOwnProperty('cartridges')) {
                genJsplumbCartridge(item[prop].cartridges, divGroup, parentName+'-'+item[prop]['name'] );
            }
            if(item[prop].hasOwnProperty('groups')) {
                genJsplumbGroups(item[prop].groups, divGroup, parentName+'-'+item[prop]['name'])
            }
        }
    }

}

jsPlumb.bind("ready", function() {
    addJsplumbGroup(applicationJSON, cartridgeCounter);
    //reposition after group add
    dagrePosition();
});

var signupBlockTemplate = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "root",
    "type": "object",
    "title": " ",
    "options": {
        "disable_properties": true,
        "disable_collapse": true
    },
    "properties": {
        "alias": {
            "id": "root/alias",
            "title": "Cartridge Alias: ",
            "type": "string"
        },
        "privateRepo": {
            "id": "root/privateRepo",
            "title": "Is private repository: ",
            "type": "boolean"
        },
        "repoUrl": {
            "id": "root/repoUrl",
            "title": "Repository URL: ",
            "type": "string"
        },
        "repoUsername": {
            "id": "root/repoUsername",
            "title": "Repository User Name: ",
            "type": "string"
        },
        "repoPassword": {
            "id": "root/repoPassword",
            "title": "Repository Password: ",
            "type": "string"
        }
    }
};

var signupBlockDefault = {
    "alias": "php",
    "privateRepo": false,
    "repoUrl": "https://hostname/repository.git",
    "repoUsername": "",
    "repoPassword": ""
};

// Document ready events
$(document).ready(function(){
    //handled Ajax base session expire issue
    $(document).ajaxError(function (e, xhr, settings) {
        window.location.href = '../';
    });

    //*******************Adding JSON editor *************//
    JSONEditor.defaults.theme = 'bootstrap3';
    JSONEditor.defaults.iconlib = 'fontawesome4';
    JSONEditor.defaults.show_errors = "always";
    var editor,blockId;

    $('#whiteboard').on('click', '.stepnode', function(){
        $('.signup-details').show();
        $('.signup-default').hide();
        $('.stepnode').removeClass("highlightme");
        $(this).addClass('highlightme');
        tabData($(this));
    });

    function tabData(node){

        blockId = node.attr('id');
        var blockType = node.attr('data-type');
        var startval;
        var calias = node.attr('data-calias');

        if(blockType == 'cartridge'){
            startval = signupBlockDefault;
            startval['alias'] = calias;
        }

        if(node.attr('data-generated')) {
            startval = JSON.parse(decodeURIComponent(node.attr('data-generated')));
        }
        $('#signup-details').html('');

        switch (blockType){
            case 'cartridge':
                generateHtmlBlock(signupBlockTemplate, startval);
                break;
        }
    }

    function generateHtmlBlock(schema, startval){
        // Initialize the editor
        editor = new JSONEditor(document.getElementById('signup-details'), {
            ajax: false,
            disable_edit_json: true,
            schema: schema,
            format: "grid",
            startval: startval
        });

        if(editor.getEditor('root.alias')){
            editor.getEditor('root.alias').disable();
        }

    }

    //get component JSON data
    $('#component-info-update').on('click', function(){
        $('#'+blockId).attr('data-generated', encodeURIComponent(JSON.stringify(editor.getValue())));
        $('#'+blockId).removeClass('input-false');
        $('#'+blockId).find('div>i').removeClass('fa-exclamation-circle').addClass('fa-check-circle-o').css('color','#2ecc71');
    });

    $('#signup').on('click', function(){
        var btn = $(this);
        var appid = btn.attr('data-appid');
        var signupJSON = {"artifactRepositories":[]};
        //generate raw data tree from connections
        $.each(jsPlumb.getConnections(), function (idx, connection) {
           var dataGen = $('#'+connection.targetId).attr('data-generated');
            if(dataGen!=undefined){
                var jsonContent = JSON.parse(decodeURIComponent(dataGen));
                signupJSON['artifactRepositories'].push(jsonContent);
            }

        });

        var formtype = 'signupapplication';
        btn.html(" Adding...");
        $.ajax({
            type: "POST",
            url: caramel.context + "/controllers/applications/application_requests.jag",
            dataType: 'json',
            data: { "formPayload": JSON.stringify(signupJSON), "formtype": formtype, "applicationId": appid },
            success: function (data) {
                if (data.status == 'error') {
                    var n = noty({text: data.message, layout: 'bottomRight', type: 'error'});
                } else if (data.status == 'warning') {
                    var n = noty({text: data.message, layout: 'bottomRight', type: 'warning'});
                } else {
                    var n = noty({text: data.message, layout: 'bottomRight', type: 'success'});
                    window.setTimeout(function(){
                        window.location.href = '../';
                    }, 1500);
                }
            }
        })
            .always(function () {
                btn.html('Add Signup');
            });

    });

});<|endoftext|>


<commit_before>'use strict';

var CronJob = require('cron').CronJob,
  rank_user = require('../jobs/rank-user');

var test_job = new CronJob({
  cronTime: '* * * * *',
  onTick: function() {
    rank_user.excute();
  },
  start: false,
  timeZone: 'Asia/Tokyo'
});
var rank_user_job = new CronJob({
  cronTime: '0 0 * * *', //every 24hours (every midnight)
  onTick: function() {
    rank_user.excute();
  },
  start: false,
  timeZone: 'Asia/Tokyo'
});
function start() {
  test_job.start();
}
exports.start = start;
<commit_msg>Commited from lenh at Mon, Aug 28, 2017 11:01:16 AM<commit_after>'use strict';

var CronJob = require('cron').CronJob,
  rank_user = require('../jobs/rank-user');

var test_job = new CronJob({
  cronTime: '* * * * *',
  onTick: function() {
    // rank_user.excute();
  },
  start: false,
  timeZone: 'Asia/Tokyo'
});
var rank_user_job = new CronJob({
  cronTime: '0 0 * * *', //every 24hours (every midnight)
  onTick: function() {
    rank_user.excute();
  },
  start: false,
  timeZone: 'Asia/Tokyo'
});
function start() {
  rank_user_job.start();
}
exports.start = start;
<|endoftext|>


<commit_before>var express = require('express');
var debug = require('debug')('raml-serve');

var path = require('path');

// creates dist-override/index.html
var fs = require('fs');
var indexFile = fs.readFileSync(path.join(__dirname, 'node_modules/api-designer/dist/index.html'), 'utf8');
indexFile = indexFile.replace(/<\/body\>/g, '');
fs.writeFileSync('dist-override/index.html', indexFile, 'utf8');

function serveOverride (req, res, next) {
  if (req.url === '/index.html' || req.url === '/') {
    return res.sendFile('/index.html', { root: 'dist-override' });
  }
  if (req.url === '/angular-persistence.js') {
    return res.sendFile('/angular-persistence.js', { root: 'dist-override' });
  }
  var requestedFile = req.url.replace(/\?.*/, '');
  debug('requested:', requestedFile);
  res.sendFile(requestedFile, { root: 'node_modules/api-designer/dist' }, function (err) {
    if (!!err && err.code === 'ENOENT') return res.sendStatus(404);
    if (!!err) {
      console.log('unexpected error happened');
      console.log(err.stack);
      return res.sendStatus(500);
    }
  });
}

var ramlServe;
module.exports = ramlServe = function (ramlPath) {
  var router = express.Router();
  var bodyParser = require('body-parser');
  // quick n dirty = setup RAML_DATAPATH without refactoring files.js
  if (!!ramlPath) {
    process.env.RAML_DATAPATH = ramlPath;
  }
  var files = require('./routes/files');

  router.use(bodyParser.json());
  router.get('/files/*', files.findAll);
  router.post('/files/*', files.addFile);
  router.put('/files/*', files.updateFile);
  router.delete('/files/*', files.deleteFile);
  router.use('/', serveOverride);
  return router;
};

if (module.parent === null) {
  var app = express();
  app.use('/', ramlServe());

  var server = app.listen(process.env.PORT || 3000, function() {
    console.log('Express server listening on ' + server.address().address + ':' + server.address().port + '/');
  });
}
<commit_msg>critical fix :)<commit_after>var express = require('express');
var debug = require('debug')('raml-serve');

var path = require('path');

// creates dist-override/index.html
var fs = require('fs');
var indexFile = fs.readFileSync(path.join(__dirname, 'node_modules/api-designer/dist/index.html'), 'utf8');
indexFile = indexFile.replace(/<\/body\>/g, '');
fs.writeFileSync(path.join(__dirname, 'dist-override/index.html'), indexFile, 'utf8');

function serveOverride (req, res, next) {
  if (req.url === '/index.html' || req.url === '/') {
    return res.sendFile('/index.html', { root: path.join(__dirname, 'dist-override') });
  }
  if (req.url === '/angular-persistence.js') {
    return res.sendFile('/angular-persistence.js', { root: path.join(__dirname, 'dist-override') });
  }
  var requestedFile = req.url.replace(/\?.*/, '');
  debug('requested:', requestedFile);
  res.sendFile(requestedFile, { root: 'node_modules/api-designer/dist' }, function (err) {
    if (!!err && err.code === 'ENOENT') return res.sendStatus(404);
    if (!!err) {
      console.log('unexpected error happened');
      console.log(err.stack);
      return res.sendStatus(500);
    }
  });
}

var ramlServe;
module.exports = ramlServe = function (ramlPath) {
  var router = express.Router();
  var bodyParser = require('body-parser');
  // quick n dirty = setup RAML_DATAPATH without refactoring files.js
  if (!!ramlPath) {
    process.env.RAML_DATAPATH = ramlPath;
  }
  var files = require('./routes/files');

  router.use(bodyParser.json());
  router.get('/files/*', files.findAll);
  router.post('/files/*', files.addFile);
  router.put('/files/*', files.updateFile);
  router.delete('/files/*', files.deleteFile);
  router.use('/', serveOverride);
  return router;
};

if (module.parent === null) {
  var app = express();
  app.use('/', ramlServe());

  var server = app.listen(process.env.PORT || 3000, function() {
    console.log('Express server listening on ' + server.address().address + ':' + server.address().port + '/');
  });
}
<|endoftext|>


<commit_before>var Gaffa = require('gaffa'),
    crel = require('crel'),
    doc = require('doc-js');

function setValue(event){
    var input = event.target,
        viewModel = input.parentElement.viewModel,
        files = Array.prototype.slice.call(input.files);

    for (var i = files.length - 1; i >= 0; i--) {
        var file = files[i];
        if(viewModel.maxSize.value && file.size / 1024 / 1024 > viewModel.maxSize.value){
            window.teabag(file.name + ' is too large to upload. The maximum file size accepted is ' + viewModel.maxSize.value + 'MB', 'alert', true);
            files.splice(i,1);
            i--;
        }
    };

    viewModel.files.set(files);
    viewModel.inputElement.value = null;
}

function FileInput(){}
FileInput = Gaffa.createSpec(FileInput, Gaffa.View);
FileInput.prototype.type = 'fileInput';
FileInput.prototype.render = function(){
    var input,
        renderedElement = crel('span', {'class':'fileInput'},
            input = crel('input', {'type':'file'}),
            crel('span', {'class':'icon-upload'}),
            crel('label', {'class':'fileInputLabel'})
        );

    doc.on("change", input, setValue);

    this.inputElement = input;

    this.renderedElement = renderedElement;

    this.__super__.render.apply(this, arguments);
};
FileInput.prototype.multiple = new Gaffa.Property(function(viewModel, value){
    var input = doc.find(viewModel.renderedElement, 'input')[0];
    if (value){
        input.setAttribute('multiple', null);
    }else{
        input.removeAttribute('multiple');
    }
});
FileInput.prototype.files = new Gaffa.Property();
FileInput.prototype.maxSize = new Gaffa.Property();
FileInput.prototype.accept = new Gaffa.Property(function(viewModel, value){
    var input = doc.find(viewModel.renderedElement, 'input')[0];
    if (value){
        input.setAttribute('accept', value);
    }else{
        input.removeAttribute('accept');
    }
});
FileInput.prototype.enabled = new Gaffa.Property({
    update: function(viewModel, value){
        var input = viewModel.inputElement;
        if (!value){
            input.setAttribute('disabled', 'disabled');
        }else{
            input.removeAttribute('disabled');
        }
    },
    value: true
});
FileInput.prototype.text = new Gaffa.Property(function(viewModel, value){
    doc.find(viewModel.renderedElement, 'label')[0].textContent = value ? value : '';
});

module.exports = FileInput;
<commit_msg>removed old code<commit_after>var Gaffa = require('gaffa'),
    crel = require('crel'),
    doc = require('doc-js');

function setValue(event){
    var input = event.target,
        viewModel = input.parentElement.viewModel,
        files = Array.prototype.slice.call(input.files);

    viewModel.files.set(files);
    viewModel.inputElement.value = null;
}

function FileInput(){}
FileInput = Gaffa.createSpec(FileInput, Gaffa.View);
FileInput.prototype.type = 'fileInput';
FileInput.prototype.render = function(){
    var input,
        renderedElement = crel('span', {'class':'fileInput'},
            input = crel('input', {'type':'file'}),
            crel('span', {'class':'icon-upload'}),
            crel('label', {'class':'fileInputLabel'})
        );

    doc.on("change", input, setValue);

    this.inputElement = input;

    this.renderedElement = renderedElement;

    this.__super__.render.apply(this, arguments);
};
FileInput.prototype.multiple = new Gaffa.Property(function(viewModel, value){
    var input = doc.find(viewModel.renderedElement, 'input')[0];
    if (value){
        input.setAttribute('multiple', null);
    }else{
        input.removeAttribute('multiple');
    }
});
FileInput.prototype.files = new Gaffa.Property();
FileInput.prototype.maxSize = new Gaffa.Property();
FileInput.prototype.accept = new Gaffa.Property(function(viewModel, value){
    var input = doc.find(viewModel.renderedElement, 'input')[0];
    if (value){
        input.setAttribute('accept', value);
    }else{
        input.removeAttribute('accept');
    }
});
FileInput.prototype.enabled = new Gaffa.Property({
    update: function(viewModel, value){
        var input = viewModel.inputElement;
        if (!value){
            input.setAttribute('disabled', 'disabled');
        }else{
            input.removeAttribute('disabled');
        }
    },
    value: true
});
FileInput.prototype.text = new Gaffa.Property(function(viewModel, value){
    doc.find(viewModel.renderedElement, 'label')[0].textContent = value ? value : '';
});

module.exports = FileInput;
<|endoftext|>


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

    var FlowchartEditorStepView;
    var _ = require('underscore');
    var FlowchartViewerStepView = require('../viewer/step-view');

    FlowchartEditorStepView = FlowchartViewerStepView.extend({
        template: require('tpl!oroworkflow/templates/flowchart/editor/step.html'),

        className: function() {
            var classNames = [FlowchartEditorStepView.__super__.className.call(this)];
            if (!this.model.get('_is_start')) {
                classNames.push('dropdown');
            }
            return classNames.join(' ');
        },

        events: {
            'dblclick': 'triggerEditStep',
            'click .jsplumb-source': 'triggerAddStep',
            'click .workflow-step-edit': 'triggerEditStep',
            'click .workflow-step-clone': 'triggerCloneStep',
            'click .workflow-step-delete': 'triggerRemoveStep'
        },

        /**
         * @inheritDoc
         */
        constructor: function FlowchartEditorStepView() {
            FlowchartEditorStepView.__super__.constructor.apply(this, arguments);
        },

        connect: function() {
            var instance = this.areaView.jsPlumbInstance;
            // add element as source to jsPlumb
            if (this.model.get('draggable') !== false) {
                instance.draggable(this.$el, {
                    start: function(obj) {
                        instance.eventBus.trigger('step:drag-start', obj, this.model);
                    }.bind(this),
                    stop: function(obj) {
                        // update model position when dragging stops
                        this.model.set({position: obj.pos});
                        instance.eventBus.trigger('step:drag-stop', obj, this.model);
                    }.bind(this)
                });
            }
            FlowchartEditorStepView.__super__.connect.apply(this, arguments);
        },

        triggerEditStep: function(e) {
            e.preventDefault();
            this.areaView.model.trigger('requestEditStep', this.model);
        },

        triggerRemoveStep: function(e) {
            e.preventDefault();
            this.areaView.model.trigger('requestRemoveStep', this.model);
        },

        triggerCloneStep: function(e) {
            e.preventDefault();
            this.areaView.model.trigger('requestCloneStep', this.model);
        },

        triggerAddStep: function() {
            this.areaView.model.trigger('requestAddTransition', this.model);
        },

        render: function() {
            FlowchartEditorStepView.__super__.render.call(this);
            this.$el.toggleClass('final-step', Boolean(this.model.get('is_final')));
        }
    });

    return FlowchartEditorStepView;
});
<commit_msg>BAP-18428: Hide workflow graph if there are too many transitions to render<commit_after>define(function(require) {
    'use strict';

    var FlowchartEditorStepView;
    var FlowchartViewerStepView = require('../viewer/step-view');

    FlowchartEditorStepView = FlowchartViewerStepView.extend({
        template: require('tpl!oroworkflow/templates/flowchart/editor/step.html'),

        className: function() {
            var classNames = [FlowchartEditorStepView.__super__.className.call(this)];
            if (!this.model.get('_is_start')) {
                classNames.push('dropdown');
            }
            return classNames.join(' ');
        },

        events: {
            'dblclick': 'triggerEditStep',
            'click .jsplumb-source': 'triggerAddStep',
            'click .workflow-step-edit': 'triggerEditStep',
            'click .workflow-step-clone': 'triggerCloneStep',
            'click .workflow-step-delete': 'triggerRemoveStep'
        },

        /**
         * @inheritDoc
         */
        constructor: function FlowchartEditorStepView() {
            FlowchartEditorStepView.__super__.constructor.apply(this, arguments);
        },

        connect: function() {
            var instance = this.areaView.jsPlumbInstance;
            // add element as source to jsPlumb
            if (this.model.get('draggable') !== false) {
                instance.draggable(this.$el, {
                    start: function(obj) {
                        instance.eventBus.trigger('step:drag-start', obj, this.model);
                    }.bind(this),
                    stop: function(obj) {
                        // update model position when dragging stops
                        this.model.set({position: obj.pos});
                        instance.eventBus.trigger('step:drag-stop', obj, this.model);
                    }.bind(this)
                });
            }
            FlowchartEditorStepView.__super__.connect.apply(this, arguments);
        },

        triggerEditStep: function(e) {
            e.preventDefault();
            this.areaView.model.trigger('requestEditStep', this.model);
        },

        triggerRemoveStep: function(e) {
            e.preventDefault();
            this.areaView.model.trigger('requestRemoveStep', this.model);
        },

        triggerCloneStep: function(e) {
            e.preventDefault();
            this.areaView.model.trigger('requestCloneStep', this.model);
        },

        triggerAddStep: function() {
            this.areaView.model.trigger('requestAddTransition', this.model);
        },

        render: function() {
            FlowchartEditorStepView.__super__.render.call(this);
            this.$el.toggleClass('final-step', Boolean(this.model.get('is_final')));
        }
    });

    return FlowchartEditorStepView;
});
<|endoftext|>


<commit_before>/*
   Azure Mobile Services - Recipe Core Module

    Copyright 2013 Mimi Xu

   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.

 */
var exec = require('child_process').exec;
var async = require('async');
var recipe = require('./recipeUtils.js');
var fs = require('fs');
var scripty = require('azure-scripty');

module.exports.init = function (cli) {
    var mobile = cli.category('mobile');
    var log = cli.output;
    var mobileRecipe = mobile.category('recipe');

    mobileRecipe.description('Commands to use Mobile Services Recipes');

    /*
     * list all globally installed recipes
     */

    mobileRecipe.command('list')
        .description('List the installed recipes')
        .execute(function (recipename, options, callback) {

            var file_list = fs.readdirSync(__dirname + '/../');
            var recipe_list = [];

            for (var i in file_list) {
                // find azuremobile-recipename
                if ((file_list[i].substring(0, 12) === "azuremobile-") && (file_list[i] !== "azuremobile-recipe")) {
                    recipe_list.push(file_list[i].slice(12));
                }
            }

            console.log("\nInstalled Azure Mobile Services Recipes:");
            for (var i in recipe_list) {
                console.log(' -' + recipe_list[i]);
            }
        });

    /*
     * download to user directory recipe templates
     */

    mobileRecipe.command('create [recipename]')
        .usage('[recipename] [options]')
        .description('Retrieve template files for creating a new recipe')
        .execute(function (recipename, options, callback) {

            var folder = './new_recipe';
            var new_folder = '';
            var azure_recipe = '';

            async.series([

                /***** recipe name error handling *****/

                function (callback) {
                    // error check: recipename
                    if (!recipename) {
                        recipe.ask("\nRecipe name", recipe.REGEXP, function (name) {
                            recipename = name;
                            callback(null, 'one');
                        });
                    } else
                        callback(null, 'one');
                },
                function (callback) {
                    // error check: recipename/command conflicts
                    if ((recipename === 'create') || (recipename === 'list')) {
                        throw new Error('Azure Mobile Recipe contains the command ' + recipename);
                    } else {
                        azure_recipe = 'azuremobile-' + recipename;
                        new_folder = './' + azure_recipe;
                        callback(null, 'two');
                    }
                },
                function (callback) {
                    // check if recipe exists in npm directory
                    var child = exec('npm owner ls azuremobile-' + recipename, function (error, stdout, stderr) {
                        if (!error) {
                            throw new Error('Recipe name azuremobile-' + recipename + ' already exists in npm directory');
                        }
                        callback(null, 'three');
                    });
                },

                /***** new recipe directories *****/

                function (callback) {
                    var curdir = process.cwd();
                    var clientdir = curdir + '/' + azure_recipe;
                    // create recipename directory
                    fs.exists(clientdir, function (exists) {
                        if (!exists) {
                            fs.mkdir(clientdir, function (err) {
                                if (err)
                                    throw err;
                                callback(null, 'client dir');
                            });
                        } else
                            callback(null, 'client dir');
                    });
                },
                function (callback) {
                    var curdir = process.cwd();
                    var clientdir = curdir + '/' + azure_recipe + '/client_files';
                    // create client_files directory
                    fs.exists(clientdir, function (exists) {
                        if (!exists) {
                            fs.mkdir(clientdir, function (err) {
                                if (err)
                                    throw err;
                                callback(null, 'client dir');
                            });
                        } else
                            callback(null, 'client dir');
                    });
                },
                function (callback) {
                    var curdir = process.cwd();
                    var clientdir = curdir + '/' + azure_recipe + '/server_files';
                    // create server_files directory
                    fs.exists(clientdir, function (exists) {
                        if (!exists) {
                            fs.mkdir(clientdir, function (err) {
                                if (err)
                                    throw err;
                                callback(null, 'client dir');
                            });
                        } else
                            callback(null, 'client dir');
                    });
                },
                function (callback) {
                    var curdir = process.cwd();
                    var clientdir = curdir + '/' + azure_recipe + '/server_files/api';
                    // create api directory
                    fs.exists(clientdir, function (exists) {
                        if (!exists) {
                            fs.mkdir(clientdir, function (err) {
                                if (err)
                                    throw err;
                                callback(null, 'client dir');
                            });
                        } else
                            callback(null, 'client dir');
                    });
                },
                function (callback) {
                    var curdir = process.cwd();
                    var clientdir = curdir + '/' + azure_recipe + '/server_files/table';
                    // create table directory
                    fs.exists(clientdir, function (exists) {
                        if (!exists) {
                            fs.mkdir(clientdir, function (err) {
                                if (err)
                                    throw err;
                                callback(null, 'client dir');
                            });
                        } else
                            callback(null, 'client dir');
                    });
                },
                function (callback) {
                    var curdir = process.cwd();
                    var clientdir = curdir + '/' + azure_recipe + '/server_files/shared';
                    // create shared directory
                    fs.exists(clientdir, function (exists) {
                        if (!exists) {
                            fs.mkdir(clientdir, function (err) {
                                if (err)
                                    throw err;
                                callback(null, 'client dir');
                            });
                        } else
                            callback(null, 'client dir');
                    });
                },

                /***** retrieve and download template files *****/

                function (callback) {
                    recipe.downloadRecipeFile([folder, new_folder], ['package.json'], ['\\$'], [recipename],
                        function (err) {
                            if (err)
                                throw err;
                            callback(err, 'template file download');
                        });
                },
                function (callback) {
                    recipe.downloadRecipeFile([folder, new_folder], ['README.md'], ['\\$'], [recipename],
                        function (err) {
                            if (err)
                                throw err;
                            callback(err, 'template file download');
                        });
                },
                function (callback) {
                    recipe.downloadRecipeFile([folder, new_folder], ['new_recipe.js', recipename + '.js'], ['\\$'], [recipename],
                        function (err) {
                            if (err)
                                throw err;
                            callback(err, 'template file download');
                        });
                },
                function (callback) {
                    recipe.downloadRecipeFile([folder, new_folder], ['LICENSE.txt'], ['\\$'], [recipename],
                        function (err) {
                            if (err)
                                throw err;
                            callback(err, 'template file download');
                        });
                },
                function () {
                    process.exit(1);
                }
            ]);
        });

    /*
     * use recipes
     */

    mobileRecipe.command('use [recipename] [servicename]')
        .usage('[recipename] [servicename] [options]')
        .description('Use a mobile service recipe')
        .execute(function (recipename, servicename, options, callback) {

            async.series([
                function (callback) {
                    // error check: recipename
                    if (!recipename) {
                        recipe.ask("\nRecipe name", recipe.REGEXP, function (name) {
                            recipename = name;
                            callback(null, 'one');
                        });
                    } else
                        callback(null, 'one');
                },
                function (callback) {
                    // error check: servicename
                    if (!servicename) {
                        recipe.ask("\nMobile Service name", recipe.REGEXP, function (name) {
                            servicename = name;
                            callback(null, 'one');
                        });
                    } else
                        callback(null, 'one');
                },
                function (callback) {
                    // error check: service exists
                    console.log('Validating mobile service ' + servicename + '...');
                    scripty.invoke('mobile show ' + servicename, function (err, results) {
                        if (err)
                            throw err;
                        console.log('Validated.\n');
                        callback(err, results);
                    });
                },
                function (callback) {
                    // call recipe
                    var recipe_path = __dirname + '/../azuremobile-' + recipename + '/' + recipename + '.js';
                    var recipe_name = require(recipe_path);

                    recipe_name.use(servicename);
                },
                function () {
                    callback(null);
                }
            ]);

        });
};<commit_msg>command info update<commit_after>/*
   Azure Mobile Services - Recipe Core Module

    Copyright 2013 Mimi Xu

   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.

 */

var exec = require('child_process').exec;
var async = require('async');
var scripty = require('azure-scripty');
var fs = require('fs');
var path = require('path');
var recipe = require('./recipeUtils.js');

module.exports.init = function (cli) {
    var mobile = cli.category('mobile');
    var log = cli.output;
    var mobileRecipe = mobile.category('recipe');

    mobileRecipe.description('Commands to use Mobile Services Recipes');

    /*
     * list all globally installed recipes
     */

    mobileRecipe.command('list')
        .description('List the installed recipes')
        .execute(function (recipename, options, callback) {

            var file_list = fs.readdirSync(path.join(__dirname,'..'));
            var recipe_list = [];
            for (var i in file_list) {
                // find azuremobile-recipename
                if ((file_list[i].substring(0, 12) === "azuremobile-") && (file_list[i] !== "azuremobile-recipe")) {
                    recipe_list.push(file_list[i].slice(12));
                }
            }

            console.log("\nInstalled Azure Mobile Services Recipes:");
            for (var i in recipe_list) {
                console.log(' -' + recipe_list[i]);
            }

            callback();
        });

    /*
     * download to user directory recipe templates
     */

    mobileRecipe.command('create [recipename]')
        .usage('[recipename] [options]')
        .description('Retrieve template files for creating a new recipe')
        .execute(function (recipename, options, callback) {

            var azure_recipe = '';
            async.series([
                function (callback) {
                    // error check: recipename
                    if (!recipename) {
                        recipe.ask("\nRecipe name", recipe.REGEXP, function (name) {
                            recipename = name;
                            callback();
                        });
                    } else callback();
                },
                function (callback) {
                    azure_recipe = 'azuremobile-' + recipename;
                    // check if recipe exists in npm directory
                    var child = exec('npm owner ls ' + azure_recipe, function (error, stdout, stderr) {
                        if (!error) {
                            throw new Error('Recipe name ' + azure_recipe + ' already exists in npm directory');
                        }
                        callback();
                    });
                },
                function (callback) {
                    // retrieve and download template files
                    original = ['\\$'];
                    replacement = [recipename];

                    // find all new recipe files
                    recipe.readPath(path.join(__dirname, 'new_recipe'), function (err, results) {
                        if (err) return callback(err);
                        files = results;
                        callback(err, results);
                    });
                },
                function (callback) {
                    // download all client files and create directories
                    async.forEachSeries(
                        files,
                        function (file, done) {
                            if (file.file === 'new_recipe.js')
                            {
                                recipe.downloadRecipeFile([file.dir.replace(__dirname,''), azure_recipe], [file.file, recipename+'.js'], original, replacement,
                                    function (err) {
                                        if (err) return callback(err);
                                        done(err);
                                    });
                            }
                            else {
                                recipe.downloadRecipeFile([file.dir.replace(__dirname,''), azure_recipe], [file.file], original, replacement,
                                    function (err) {
                                        if (err) return callback(err);
                                        done(err);
                                    });
                            }
                        },
                        function (err) {
                            if (err) return callback(err);
                            callback();
                        });
                },
                function (callback) {
                    // new recipe client_files directory
                    var clientdir = path.join(process.cwd(), azure_recipe, 'client_files');
                    // create client_files directory
                    fs.stat(clientdir, function (err,stat) {
                        if (!(stat && stat.isDirectory())) {
                            fs.mkdir(clientdir, function (err) {
                                if (err) return callback(err);
                                callback();
                            });
                        }
                        else
                            callback();
                    });
                },
                function () {
                    callback();
                }
            ]);
        });

    /*
     * use recipes
     */

    mobileRecipe.command('use [recipename] [servicename]')
        .usage('[recipename] [servicename] [options]')
        .description('Use a mobile service recipe')
        .execute(function (recipename, servicename, options, callback) {

            async.series([
                function (callback) {
                    // error check: recipename
                    if (!recipename) {
                        recipe.ask("\nRecipe name", recipe.REGEXP, function (name) {
                            recipename = name;
                            callback();
                        });
                    } else
                        callback();
                },
                function (callback) {
                    // error check: servicename
                    if (!servicename) {
                        recipe.ask("\nMobile Service name", recipe.REGEXP, function (name) {
                            servicename = name;
                            callback();
                        });
                    } else
                        callback();
                },
                function (callback) {
                    // error check: service exists
                    console.log('Validating mobile service ' + servicename + '...');
                    scripty.invoke('mobile show ' + servicename, function (err, results) {
                        if (err) return callback(err);
                        console.log('Validated.\n');
                        callback();
                    });
                },
                function (callback) {
                    // call recipe
                    var recipe_path = path.join(__dirname, '..', 'azuremobile-'+recipename, recipename+'.js');
                    var recipe_name = require(recipe_path);
                    recipe_name.use(servicename, function (err){
                        if (err) return callback(err);
                        callback();
                    });
                },
                function () {
                    callback();
                }
            ]);

        });
};<|endoftext|>