<commit_before>// TESTING: Get user object for name and create it if it doesn't exist
function ensureUser(name) {
	if (!name) {name = 'Serverscriptttt'};
	var email = (name.replace(' ', '')+"@openki.example").toLowerCase()

	while (true) {
		var user = Meteor.users.findOne({ "emails.address": email})
		if (user) return user;

		user = Meteor.users.findOne({username: name})
		if (user) return user;

		var id = Accounts.createUser({
			username: name,
			email: email,
			profile: {name : name},
		});

		var age = Math.floor(Random.fraction()*100000000000)
		Meteor.users.update({ _id: id },{$set:{
			services : {"password" : {"bcrypt" : "$2a$10$pMiVQDN4hfJNUk6ToyFXQugg2vJnsMTd0c.E0hrRoqYqnq70mi4Jq"}},  //every password is set to "greg". cause creating passwords takes too long
			createdAt: new Date(new Date().getTime()-age),
			lastLogin: new Date(new Date().getTime()-age/30)
		}});

		console.log("   Added user: "+name)

	}
}

function ensureRegion(name) {
	while (true) {
		var region = Regions.findOne({name: name})
		if (region) return region._id;

		var id = Regions.insert({
			name: name,
			timezone: "UTC+"+Math.floor(Random.fraction()*12)+":00"
		});

		console.log("Added region: "+name+" "+id)
	}
}

createCoursesIfNone = function(scale) {
	if (Courses.find().count() === 0) {
		createCourses(scale);
	}
}

function createCourses(scale) {

	// Make a number that looks like a human chose it, favouring 2 and 5
	function humandistrib() {
		var factors = [0,0,1,2,2,3,5,5]
		return factors[Math.floor(Random.fraction()*factors.length)] * (Random.fraction() > 0.7 ? humandistrib() : 1) + (Random.fraction() > 0.5 ? humandistrib() : 0)
	}

	_.each(testcourses, function(course) {
		if (!course.createdby) return; // Don't create courses that don't have a creator name

		/* Replace user name with ID */
		_.each(course.members, function(member) {
			member.user = ensureUser(member.user)._id
		})
		course.createdby = ensureUser(course.createdby)._id
		var name = course.name
		for (var n = 0; n < scale; n++) {
			course.name = name + (n > 0 ? ' (' + n + ')' : '');
			course.slug = getSlug(name + ' (' + n + ')');

			// TESTING: always use same id for same course to avoid broken urls while testing
			var crypto = Npm.require('crypto'), m5 = crypto.createHash('md5');
			m5.update(course.name);
			m5.update(course.description);
			course._id = m5.digest('hex').substring(0, 8)

			course.subscribers_min = Random.fraction() > 0.3 ? undefined : humandistrib()
			course.subscribers_max = Random.fraction() > 0.5 ? undefined : course.subscribers_min + Math.floor(course.subscribers_min*Random.fraction())
			course.date = Random.fraction() > 0.50 ? new Date(new Date().getTime()+((Random.fraction()-0.25)*8000000000)) : false
			var age = Math.floor(Random.fraction()*80000000000)
			course.time_created = new Date(new Date().getTime()-age)
			course.time_lastedit = new Date(new Date().getTime()-age*0.25)
			course.time_lastenrol = new Date(new Date().getTime()-age*0.15)
			if (course.region) {
				course.region = ensureRegion(course.region)
			} else {
				/* place in random test region, Spilistan or Testistan */
				course.region = Random.fraction() > 0.85 ? '9JyFCoKWkxnf8LWPh' : 'EZqQLGL4PtFCxCNrp'
			}
			course.groups = _.map(course.groups, ensureGroup)
			var id = Courses.insert(course)
			console.log("Added course: "+course.name)
		}
	})
}

/////////////////////////////// TESTING: Create Locations if non in db

createLocationsIfNone = function(){
 	if (Locations.find().count() === 0) {
		createLocations();
	}
}

function ensureLocationCategory(name){
	var category_prototype = {name: name}
	var category
	while (!(category = LocationCategories.findOne(category_prototype))) { // Legit
		LocationCategories.insert(category_prototype)
	}
	return category
}

// TESTING:
function createLocations(){

	_.each(testlocations, function(location) {
		if (!location.name) return; // Don't create locations that don't have a name

		// TESTING: always use same id for same location to avoid broken urls while testing
		var crypto = Npm.require('crypto'), m5 = crypto.createHash('md5');
		m5.update(location.name);
//		m5.update(location.description);
		location._id = m5.digest('hex').substring(0, 8)

		var category_names = location.categories
		location.categories = []
		for (var i=0; category_names && i < category_names.length; i++) {
			location.categories.push(ensureLocationCategory(category_names[i]))
		}

		if (location.roles === undefined) location.roles = {}
		_.each(location.roles, function(role) {
			_.each(role.subscribed, function(subscriber, i) {
				role.subscribed[i] = ensureUser(subscriber)._id
			})
		})

		location.createdby = ensureUser(location.createdby)._id
//		location.hosts.noContact = ensureUser(location.hosts.noContact)._id
		if (!location.hosts) location.hosts = []
		location.hosts = [ensureUser(location.hosts[0])._id]

//		location.maxWorkplaces = Random.fraction() > 0.3 ? undefined : humandistrib()
//		location.maxPeople = Random.fraction() > 0.5 ? undefined : location.subscribers_min + Math.floor(location.maxWorkplaces*Random.fraction())

		var age = Math.floor(Random.fraction()*80000000000)
		location.time_created = new Date(new Date().getTime()-age)
		location.time_lastedit = new Date(new Date().getTime()-age*0.25)
		location.region = Random.fraction() > 0.85 ? '9JyFCoKWkxnf8LWPh' : 'EZqQLGL4PtFCxCNrp'
		Locations.insert(location)
	})
}

/////////////////////////////// TESTING: Create generic events if not in db

createEventsIfNone = function(){
	//Events.remove({});
	if (Events.find().count() === 0) {
		Courses.find().forEach(function(course) {
			var event_count =  Math.floor(Math.pow(Math.random() * 1.6, 6));
			for (var n = 0; n < event_count; n++) {
				var event = {};
				var description = course.description;
				if (!description) description = "No description"; // :-(
				var words = _.shuffle(description.split(' '));
				event.region = course.region;
				var random = Random.fraction();
				if (random < 0.4) event.location = random < 0.2 ? 'Haus am See' : 'Kongresszentrum';
				else if (random < 0.7) event.location = random < 0.5 ? 'Volkshaus' : 'SQ131';
				else if (random < 0.8) event.location = random < 0.75 ? 'Caffee Zähringer' : 'Restaurant Krone';
				else if (random < 0.9) event.location = random < 0.85 ? 'Hischengraben 3' : 'SQ125';
				else event.location = random < 0.95 ? 'Hub' : 'ASZ';
				event.course_id = course._id;
				event.title = course.name + ' ' + _.sample(words);
				event.description =  words.slice(0, 10 + Math.floor(Math.random() * 30)).join(' ');
				event.mentors = []
				event.host = []

				var spread = 1000*60*60*24*365*1.2					// cause it's millis  1.2 Years
				var timeToGo = Random.fraction()-0.7 				// put 70% in the past
				if (timeToGo >= 0.05) {								// 75% of the remaining in future
					timeToGo = Math.pow((timeToGo-0.05)*5, 2)		// exponential function in order to decrease occurrence in time
				}
				timeToGo = Math.floor(timeToGo*spread);
				var date = new Date(new Date().getTime() + timeToGo);
				var hour = date.getHours();
				if (Random.fraction() > 0.2 && hour < 8 || hour > 21) date.setHours(hour + 12);
				if (Random.fraction() > 0.05) date.setMinutes(Math.floor((date.getMinutes()) / 15) * 15); // quarter-hours' precision
				event.start = date;
				event.end = new Date(date.getTime() + (1000*60*60*2));
				event.createdby = 'ServerScript'
				var age = Math.floor(Random.fraction() * 10000000000)
				event.time_created = new Date(new Date().getTime() - age)
				event.time_lastedit = new Date(new Date().getTime() - age * 0.25)
				Events.insert(event)
				console.log('Added generic event ('+ n +'/' + event_count +'):  "' + event.title + '"');
			}
		});
	}
}

/////////////////////////////// TESTING: Create generic comments if non in db

createCommentsIfNone = function(){
	//Events.remove({});
	if (CourseDiscussions.find().count() === 0) {
		Courses.find().forEach(function(course) {
			var comment_count =  Math.floor(Math.pow(Math.random() * 2, 4));
			for (var n = 0; n < comment_count; n++) {
				var comment = {};
				var description = course.description;
				if (!description) description = "No description"; // :-(
				var words = _.shuffle(description.split(' '));
				var random = Random.fraction();

				comment.course_id = course._id;
				comment.title = _.sample(words) + ' ' + _.sample(words) + ' ' + _.sample(words);
				comment.text =  words.slice(0, 10 + Math.floor(Math.random() * 30)).join(' ');

				var spread = new Date(new Date().getTime() - course.time_created)
				var age = Random.fraction()
				age = Math.floor(age*spread);
				var date = new Date(new Date().getTime() - age);
				comment.time_created = date;
				comment.time_updated = date + age * 0.77

				comment.createdby = 'ServerScript' + n
				CourseDiscussions.insert(comment)
				console.log('Added '+ n +' of '+ comment_count +' generic comments:  "' + comment.title + '"');
			}
		});
	}
}

/////////////////////////////// TESTING: load the events from file server/data/testing.events.js
/////////////////////////////// most of these don't have a parent course

loadTestEvents = function(){
	var dateOffset = 0
	_.each(testevents, function(event) {
		if (!event.createdBy) return; // Don't create events that don't have a creator name
		if (Events.findOne({_id: event._id})) return; //Don't create events that exist already

		event.createdBy = ensureUser(event.createdby)._id  // Replace user name with ID

		/* Create the events around the current Day.
		First loaded event gets moved to current day. All events stay at original hour */
		if (dateOffset == 0){
			var toDay = new Date();
			toDay.setHours(0); toDay.setMinutes(0); toDay.setSeconds(0);
			var DayOfFirstEvent = new Date(event.start.$date)
			DayOfFirstEvent.setHours(0); DayOfFirstEvent.setMinutes(0); DayOfFirstEvent.setSeconds(0);
			dateOffset = toDay.getTime()-DayOfFirstEvent.getTime()
			console.log("   Loading events, Date Offset is: "+moment.duration(dateOffset).humanize());
			console.log("   which is "+dateOffset+" milliseconds, right?");
			console.log("   becouse toDay is: "+toDay+", and day of first loaded event is: "+DayOfFirstEvent);
		}

		event.start = new Date(event.start.$date+dateOffset);
		event.end = new Date(event.end.$date+dateOffset);
		event.time_created = new Date(event.time_created.$date);
		event.time_lastedit = new Date(event.time_lastedit.$date);
		var id = Events.insert(event);
		console.log("Added event:  "+event.title);
	})
}

createGroupsIfNone = function(){
	if (Groups.find().count() === 0) {
		_.each (testgroups, function (group){
			if (!group.name) return;
			group.createdby = 'ServerScript_loadingTestgroups'
			var age = Math.floor(Random.fraction()*10000000000)
			group.time_created = new Date(new Date().getTime()-age)
			group.time_lastedit = new Date(new Date().getTime()-age*0.25)
				// TESTING: always use same id for same group to avoid broken urls while testing
			var crypto = Npm.require('crypto'), m5 = crypto.createHash('md5');
			m5.update(group.name);
			m5.update(group.description);
			group._id = m5.digest('hex').substring(0, 8)
			group.members = _.map(group.members, function (name){
				return ensureUser(name)._id
			});
			Groups.insert(group)
			console.log("Added Testgroup:   "+group.name)
		})
	}
}

function ensureGroup(short) {
	while (true) {
		var group = Groups.findOne({short: short})
		if (group) return group._id;

		var id = Groups.insert({
			name: short,
			short: short,
			createdby: 'ServerScript_from_TestCouses',
			description: 'Automaticaly created group by server'
		});
		console.log("Added group from TestCouses: "+name+"    id: "+id)
	}
}

/////////////////////////////// TESTING: Create Regions if non in db

createTestRegionsIfNone = function(){
	if (Meteor.isServer && Regions.find().count() == 0) {
		_.each(regions, function(region){
			if (region.loc) {
				region.loc = region.loc.reverse()			//latitude first !!?!
				region.loc = { "type": "Point", "coordinates": region.loc } //2dsphere
			}
			Regions.insert(region)
			console.log('*Added region: '+region.name)
		})
		Regions._ensureIndex({loc : "2dsphere"});
	}
}
<commit_msg>correcting amount of generated events upwards<commit_after>// TESTING: Get user object for name and create it if it doesn't exist
function ensureUser(name) {
	if (!name) {name = 'Serverscriptttt'};
	var email = (name.replace(' ', '')+"@openki.example").toLowerCase()

	while (true) {
		var user = Meteor.users.findOne({ "emails.address": email})
		if (user) return user;

		user = Meteor.users.findOne({username: name})
		if (user) return user;

		var id = Accounts.createUser({
			username: name,
			email: email,
			profile: {name : name},
		});

		var age = Math.floor(Random.fraction()*100000000000)
		Meteor.users.update({ _id: id },{$set:{
			services : {"password" : {"bcrypt" : "$2a$10$pMiVQDN4hfJNUk6ToyFXQugg2vJnsMTd0c.E0hrRoqYqnq70mi4Jq"}},  //every password is set to "greg". cause creating passwords takes too long
			createdAt: new Date(new Date().getTime()-age),
			lastLogin: new Date(new Date().getTime()-age/30)
		}});

		console.log("   Added user: "+name)

	}
}

function ensureRegion(name) {
	while (true) {
		var region = Regions.findOne({name: name})
		if (region) return region._id;

		var id = Regions.insert({
			name: name,
			timezone: "UTC+"+Math.floor(Random.fraction()*12)+":00"
		});

		console.log("Added region: "+name+" "+id)
	}
}

createCoursesIfNone = function(scale) {
	if (Courses.find().count() === 0) {
		createCourses(scale);
	}
}

function createCourses(scale) {

	// Make a number that looks like a human chose it, favouring 2 and 5
	function humandistrib() {
		var factors = [0,0,1,2,2,3,5,5]
		return factors[Math.floor(Random.fraction()*factors.length)] * (Random.fraction() > 0.7 ? humandistrib() : 1) + (Random.fraction() > 0.5 ? humandistrib() : 0)
	}

	_.each(testcourses, function(course) {
		if (!course.createdby) return; // Don't create courses that don't have a creator name

		/* Replace user name with ID */
		_.each(course.members, function(member) {
			member.user = ensureUser(member.user)._id
		})
		course.createdby = ensureUser(course.createdby)._id
		var name = course.name
		for (var n = 0; n < scale; n++) {
			course.name = name + (n > 0 ? ' (' + n + ')' : '');
			course.slug = getSlug(name + ' (' + n + ')');

			// TESTING: always use same id for same course to avoid broken urls while testing
			var crypto = Npm.require('crypto'), m5 = crypto.createHash('md5');
			m5.update(course.name);
			m5.update(course.description);
			course._id = m5.digest('hex').substring(0, 8)

			course.subscribers_min = Random.fraction() > 0.3 ? undefined : humandistrib()
			course.subscribers_max = Random.fraction() > 0.5 ? undefined : course.subscribers_min + Math.floor(course.subscribers_min*Random.fraction())
			course.date = Random.fraction() > 0.50 ? new Date(new Date().getTime()+((Random.fraction()-0.25)*8000000000)) : false
			var age = Math.floor(Random.fraction()*80000000000)
			course.time_created = new Date(new Date().getTime()-age)
			course.time_lastedit = new Date(new Date().getTime()-age*0.25)
			course.time_lastenrol = new Date(new Date().getTime()-age*0.15)
			if (course.region) {
				course.region = ensureRegion(course.region)
			} else {
				/* place in random test region, Spilistan or Testistan */
				course.region = Random.fraction() > 0.85 ? '9JyFCoKWkxnf8LWPh' : 'EZqQLGL4PtFCxCNrp'
			}
			course.groups = _.map(course.groups, ensureGroup)
			var id = Courses.insert(course)
			console.log("Added course: "+course.name)
		}
	})
}

/////////////////////////////// TESTING: Create Locations if non in db

createLocationsIfNone = function(){
 	if (Locations.find().count() === 0) {
		createLocations();
	}
}

function ensureLocationCategory(name){
	var category_prototype = {name: name}
	var category
	while (!(category = LocationCategories.findOne(category_prototype))) { // Legit
		LocationCategories.insert(category_prototype)
	}
	return category
}

// TESTING:
function createLocations(){

	_.each(testlocations, function(location) {
		if (!location.name) return; // Don't create locations that don't have a name

		// TESTING: always use same id for same location to avoid broken urls while testing
		var crypto = Npm.require('crypto'), m5 = crypto.createHash('md5');
		m5.update(location.name);
//		m5.update(location.description);
		location._id = m5.digest('hex').substring(0, 8)

		var category_names = location.categories
		location.categories = []
		for (var i=0; category_names && i < category_names.length; i++) {
			location.categories.push(ensureLocationCategory(category_names[i]))
		}

		if (location.roles === undefined) location.roles = {}
		_.each(location.roles, function(role) {
			_.each(role.subscribed, function(subscriber, i) {
				role.subscribed[i] = ensureUser(subscriber)._id
			})
		})

		location.createdby = ensureUser(location.createdby)._id
//		location.hosts.noContact = ensureUser(location.hosts.noContact)._id
		if (!location.hosts) location.hosts = []
		location.hosts = [ensureUser(location.hosts[0])._id]

//		location.maxWorkplaces = Random.fraction() > 0.3 ? undefined : humandistrib()
//		location.maxPeople = Random.fraction() > 0.5 ? undefined : location.subscribers_min + Math.floor(location.maxWorkplaces*Random.fraction())

		var age = Math.floor(Random.fraction()*80000000000)
		location.time_created = new Date(new Date().getTime()-age)
		location.time_lastedit = new Date(new Date().getTime()-age*0.25)
		location.region = Random.fraction() > 0.85 ? '9JyFCoKWkxnf8LWPh' : 'EZqQLGL4PtFCxCNrp'
		Locations.insert(location)
	})
}

/////////////////////////////// TESTING: Create generic events if not in db

createEventsIfNone = function(){
	//Events.remove({});
	if (Events.find().count() === 0) {
		Courses.find().forEach(function(course) {
			var event_count =  Math.floor(Math.pow(Math.random() * 1.6, 10));
			for (var n = 0; n < event_count; n++) {
				var event = {};
				var description = course.description;
				if (!description) description = "No description"; // :-(
				var words = _.shuffle(description.split(' '));
				event.region = course.region;
				var random = Random.fraction();
				if (random < 0.4) event.location = random < 0.2 ? 'Haus am See' : 'Kongresszentrum';
				else if (random < 0.7) event.location = random < 0.5 ? 'Volkshaus' : 'SQ131';
				else if (random < 0.8) event.location = random < 0.75 ? 'Caffee Zähringer' : 'Restaurant Krone';
				else if (random < 0.9) event.location = random < 0.85 ? 'Hischengraben 3' : 'SQ125';
				else event.location = random < 0.95 ? 'Hub' : 'ASZ';
				event.course_id = course._id;
				event.title = course.name + ' ' + _.sample(words);
				event.description =  words.slice(0, 10 + Math.floor(Math.random() * 30)).join(' ');
				event.mentors = []
				event.host = []

				var spread = 1000*60*60*24*365*1.2					// cause it's millis  1.2 Years
				var timeToGo = Random.fraction()-0.7 				// put 70% in the past
				if (timeToGo >= 0.05) {								// 75% of the remaining in future
					timeToGo = Math.pow((timeToGo-0.05)*5, 2)		// exponential function in order to decrease occurrence in time
				}
				timeToGo = Math.floor(timeToGo*spread);
				var date = new Date(new Date().getTime() + timeToGo);
				var hour = date.getHours();
				if (Random.fraction() > 0.2 && hour < 8 || hour > 21) date.setHours(hour + 12);
				if (Random.fraction() > 0.05) date.setMinutes(Math.floor((date.getMinutes()) / 15) * 15); // quarter-hours' precision
				event.start = date;
				event.end = new Date(date.getTime() + (1000*60*60*2));
				event.createdby = 'ServerScript'
				var age = Math.floor(Random.fraction() * 10000000000)
				event.time_created = new Date(new Date().getTime() - age)
				event.time_lastedit = new Date(new Date().getTime() - age * 0.25)
				Events.insert(event)
				console.log('Added generic event ('+ n +'/' + event_count +'):  "' + event.title + '"');
			}
		});
	}
}

/////////////////////////////// TESTING: Create generic comments if non in db

createCommentsIfNone = function(){
	//Events.remove({});
	if (CourseDiscussions.find().count() === 0) {
		Courses.find().forEach(function(course) {
			var comment_count =  Math.floor(Math.pow(Math.random() * 2, 4));
			for (var n = 0; n < comment_count; n++) {
				var comment = {};
				var description = course.description;
				if (!description) description = "No description"; // :-(
				var words = _.shuffle(description.split(' '));
				var random = Random.fraction();

				comment.course_id = course._id;
				comment.title = _.sample(words) + ' ' + _.sample(words) + ' ' + _.sample(words);
				comment.text =  words.slice(0, 10 + Math.floor(Math.random() * 30)).join(' ');

				var spread = new Date(new Date().getTime() - course.time_created)
				var age = Random.fraction()
				age = Math.floor(age*spread);
				var date = new Date(new Date().getTime() - age);
				comment.time_created = date;
				comment.time_updated = date + age * 0.77

				comment.createdby = 'ServerScript' + n
				CourseDiscussions.insert(comment)
				console.log('Added '+ n +' of '+ comment_count +' generic comments:  "' + comment.title + '"');
			}
		});
	}
}

/////////////////////////////// TESTING: load the events from file server/data/testing.events.js
/////////////////////////////// most of these don't have a parent course

loadTestEvents = function(){
	var dateOffset = 0
	_.each(testevents, function(event) {
		if (!event.createdBy) return; // Don't create events that don't have a creator name
		if (Events.findOne({_id: event._id})) return; //Don't create events that exist already

		event.createdBy = ensureUser(event.createdby)._id  // Replace user name with ID

		/* Create the events around the current Day.
		First loaded event gets moved to current day. All events stay at original hour */
		if (dateOffset == 0){
			var toDay = new Date();
			toDay.setHours(0); toDay.setMinutes(0); toDay.setSeconds(0);
			var DayOfFirstEvent = new Date(event.start.$date)
			DayOfFirstEvent.setHours(0); DayOfFirstEvent.setMinutes(0); DayOfFirstEvent.setSeconds(0);
			dateOffset = toDay.getTime()-DayOfFirstEvent.getTime()
			console.log("   Loading events, Date Offset is: "+moment.duration(dateOffset).humanize());
			console.log("   which is "+dateOffset+" milliseconds, right?");
			console.log("   becouse toDay is: "+toDay+", and day of first loaded event is: "+DayOfFirstEvent);
		}

		event.start = new Date(event.start.$date+dateOffset);
		event.end = new Date(event.end.$date+dateOffset);
		event.time_created = new Date(event.time_created.$date);
		event.time_lastedit = new Date(event.time_lastedit.$date);
		var id = Events.insert(event);
		console.log("Added event:  "+event.title);
	})
}

createGroupsIfNone = function(){
	if (Groups.find().count() === 0) {
		_.each (testgroups, function (group){
			if (!group.name) return;
			group.createdby = 'ServerScript_loadingTestgroups'
			var age = Math.floor(Random.fraction()*10000000000)
			group.time_created = new Date(new Date().getTime()-age)
			group.time_lastedit = new Date(new Date().getTime()-age*0.25)
				// TESTING: always use same id for same group to avoid broken urls while testing
			var crypto = Npm.require('crypto'), m5 = crypto.createHash('md5');
			m5.update(group.name);
			m5.update(group.description);
			group._id = m5.digest('hex').substring(0, 8)
			group.members = _.map(group.members, function (name){
				return ensureUser(name)._id
			});
			Groups.insert(group)
			console.log("Added Testgroup:   "+group.name)
		})
	}
}

function ensureGroup(short) {
	while (true) {
		var group = Groups.findOne({short: short})
		if (group) return group._id;

		var id = Groups.insert({
			name: short,
			short: short,
			createdby: 'ServerScript_from_TestCouses',
			description: 'Automaticaly created group by server'
		});
		console.log("Added group from TestCouses: "+name+"    id: "+id)
	}
}

/////////////////////////////// TESTING: Create Regions if non in db

createTestRegionsIfNone = function(){
	if (Meteor.isServer && Regions.find().count() == 0) {
		_.each(regions, function(region){
			if (region.loc) {
				region.loc = region.loc.reverse()			//latitude first !!?!
				region.loc = { "type": "Point", "coordinates": region.loc } //2dsphere
			}
			Regions.insert(region)
			console.log('*Added region: '+region.name)
		})
		Regions._ensureIndex({loc : "2dsphere"});
	}
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var _ = require('lodash');
var request = require('superagent');
var moment = require('moment');

var openfisca = require('../simulation/openfisca');
var config = require('../config/config');

var Situation = mongoose.model('Situation');

exports.situation = function(req, res, next, id) {
    Situation.findById(id, function(err, situation) {
        if (err) return next(err);
        if (!situation) return res.send(404);
        req.situation = situation;
        next();
    });
};

exports.show = function(req, res) {
    res.send(req.situation);
};

exports.update = function(req, res, next) {
    req.situation
        .set('_updated', Date.now())
        .set(_.omit(req.body, 'status', 'token'))
        .save(function(err) {
            if (err) return next(err);
            res.send(req.situation);
        });
};

exports.submit = function(req, res, next) {
    req.situation.submit(function(err) {
        if (err) return next(err);
        res.send(req.situation);
    });
};

exports.create = function(req, res, next) {
    Situation.create(_.omit(req.body, 'status', 'token'), function(err, situation) {
        if (err) return next(err);
        res.cookie('situation_' + situation.id, situation.token, { maxAge: 7 * 24 * 3600, httpOnly: true });
        res.send(situation);
    });
};

exports.simulation = function(req, res, next) {
    openfisca.simulate(req.situation, function(err, result) {
        if (err) next(err);
        res.send(result);
    });
};

exports.cerfa = function(req, res) {
    var situation = req.situation.toObject();

    var convertDate = function(object, key) {
        if (object[key]) {
            object[key] = moment(object[key]).format('DD/MM/YYYY');
        }
    };

    situation.individus.forEach(function(individu) {
        convertDate(individu, 'dateDeNaissance');
        convertDate(individu, 'dateArriveeFoyer');
        convertDate(individu, 'dateSituationFamiliale');
    });

    convertDate(situation.logement, 'dateArrivee');

    request
        .post(config.cerfaFormFillerApi + '/form/' + req.params.cerfaId)
        .send(situation)
        .pipe(res);
};

exports.openfiscaRequest = function(req, res) {
    res.send(openfisca.buildRequest(req.situation, true));
};

exports.openfiscaResponse = function(req, res, next) {
    openfisca.calculate(req.situation, true, function(err, result) {
        if (err) next(err);
        res.send(result);
    });
};
<commit_msg>Rallonge la durée du jeton<commit_after>var mongoose = require('mongoose');
var _ = require('lodash');
var request = require('superagent');
var moment = require('moment');

var openfisca = require('../simulation/openfisca');
var config = require('../config/config');

var Situation = mongoose.model('Situation');

exports.situation = function(req, res, next, id) {
    Situation.findById(id, function(err, situation) {
        if (err) return next(err);
        if (!situation) return res.send(404);
        req.situation = situation;
        next();
    });
};

exports.show = function(req, res) {
    res.send(req.situation);
};

exports.update = function(req, res, next) {
    req.situation
        .set('_updated', Date.now())
        .set(_.omit(req.body, 'status', 'token'))
        .save(function(err) {
            if (err) return next(err);
            res.send(req.situation);
        });
};

exports.submit = function(req, res, next) {
    req.situation.submit(function(err) {
        if (err) return next(err);
        res.send(req.situation);
    });
};

exports.create = function(req, res, next) {
    Situation.create(_.omit(req.body, 'status', 'token'), function(err, situation) {
        if (err) return next(err);
        res.cookie('situation_' + situation.id, situation.token, { maxAge: 7 * 24 * 3600 * 1000, httpOnly: true });
        res.send(situation);
    });
};

exports.simulation = function(req, res, next) {
    openfisca.simulate(req.situation, function(err, result) {
        if (err) next(err);
        res.send(result);
    });
};

exports.cerfa = function(req, res) {
    var situation = req.situation.toObject();

    var convertDate = function(object, key) {
        if (object[key]) {
            object[key] = moment(object[key]).format('DD/MM/YYYY');
        }
    };

    situation.individus.forEach(function(individu) {
        convertDate(individu, 'dateDeNaissance');
        convertDate(individu, 'dateArriveeFoyer');
        convertDate(individu, 'dateSituationFamiliale');
    });

    convertDate(situation.logement, 'dateArrivee');

    request
        .post(config.cerfaFormFillerApi + '/form/' + req.params.cerfaId)
        .send(situation)
        .pipe(res);
};

exports.openfiscaRequest = function(req, res) {
    res.send(openfisca.buildRequest(req.situation, true));
};

exports.openfiscaResponse = function(req, res, next) {
    openfisca.calculate(req.situation, true, function(err, result) {
        if (err) next(err);
        res.send(result);
    });
};
<|endoftext|>


<commit_before>// Creates reverse { value: master } map for provided keyPath

'use strict';

var ensureArray      = require('es5-ext/array/valid-array')
  , diff             = require('es5-ext/array/#/diff')
  , ensureString     = require('es5-ext/object/validate-stringifiable-value')
  , endsWith         = require('es5-ext/string/#/ends-with')
  , deferred         = require('deferred')
  , Map              = require('es6-map')
  , ensureStorage    = require('dbjs-persistence/ensure-storage')
  , resolveEventKeys = require('dbjs-persistence/lib/resolve-event-keys')

  , isArray = Array.isArray;

module.exports = function (storage, keyPath/*, options*/) {
	var map, storages, options = Object(arguments[2])
	  , recordType = (options.recordType === 'computed') ? 'computed' : 'direct';

	if (isArray(storage)) storages = storage.map(ensureStorage);
	else storages = [ensureStorage(storage)];
	ensureString(keyPath);

	map = new Map();
	return deferred.map(storages, function (storage) {
		storage.on('key:' + keyPath, function (event) {
			var old, nu;
			if (event.type !== recordType) return;
			if (event.old && event.old.value && (event.old.value !== '0')) {
				if (event.path !== event.keyPath) {
					if (event.old.value === '11') old = event.path.slice(keyPath.length + 1);
				} else {
					old = event.old.value;
				}
			}
			if (event.data.value && (event.data.value !== '0')) {
				if (event.path !== event.keyPath) {
					if (event.data.value === '11') nu = event.path.slice(keyPath.length + 1);
				} else {
					nu = event.data.value;
				}
			}
			if (isArray(old)) {
				nu = resolveEventKeys(ensureArray(nu));
				old = resolveEventKeys(old);
				diff.call(old, nu).forEach(map.delete, map);
				diff.call(nu, old).forEach(function (nu) { map.set(nu, event.ownerId); });
				return;
			}
			if (old === nu) return;
			if (old) map.delete(old);
			if (nu) map.set(nu, event.ownerId);
		}.bind(this));
		if (recordType === 'direct') {
			return storage.search({ keyPath: keyPath }, function (id, data) {
				var ownerId;
				if (endsWith.call(id, '/' + keyPath)) {
					if (data.value && (data.value !== '0')) map.set(data.value, id.split('/', 1)[0]);
				} else {
					ownerId = id.split('/', 1)[0];
					if (data.value === '11') map.set(id.slice(ownerId.length + keyPath.length + 2), ownerId);
				}
			});
		}
		return storage.searchComputed({ keyPath: keyPath }, function (id, data) {
			var ownerId = id.split('/', 1)[0];
			if (isArray(data.value)) {
				resolveEventKeys(data.value).forEach(function (nu) { map.set(nu, ownerId); });
			} else {
				if (data.value && (data.value !== '0')) map.set(data.value, ownerId);
			}
		});
	})(map);
};
<commit_msg>Mark reverse map<commit_after>// Creates reverse { value: master } map for provided keyPath

'use strict';

var ensureArray      = require('es5-ext/array/valid-array')
  , diff             = require('es5-ext/array/#/diff')
  , ensureString     = require('es5-ext/object/validate-stringifiable-value')
  , endsWith         = require('es5-ext/string/#/ends-with')
  , d                = require('d')
  , deferred         = require('deferred')
  , Map              = require('es6-map')
  , ensureStorage    = require('dbjs-persistence/ensure-storage')
  , resolveEventKeys = require('dbjs-persistence/lib/resolve-event-keys')

  , isArray = Array.isArray;

module.exports = function (storage, keyPath/*, options*/) {
	var map, storages, options = Object(arguments[2])
	  , recordType = (options.recordType === 'computed') ? 'computed' : 'direct';

	if (isArray(storage)) storages = storage.map(ensureStorage);
	else storages = [ensureStorage(storage)];
	ensureString(keyPath);

	map = Object.defineProperty(new Map(), 'isReverseMap', d(true));
	return deferred.map(storages, function (storage) {
		storage.on('key:' + keyPath, function (event) {
			var old, nu;
			if (event.type !== recordType) return;
			if (event.old && event.old.value && (event.old.value !== '0')) {
				if (event.path !== event.keyPath) {
					if (event.old.value === '11') old = event.path.slice(keyPath.length + 1);
				} else {
					old = event.old.value;
				}
			}
			if (event.data.value && (event.data.value !== '0')) {
				if (event.path !== event.keyPath) {
					if (event.data.value === '11') nu = event.path.slice(keyPath.length + 1);
				} else {
					nu = event.data.value;
				}
			}
			if (isArray(old)) {
				nu = resolveEventKeys(ensureArray(nu));
				old = resolveEventKeys(old);
				diff.call(old, nu).forEach(map.delete, map);
				diff.call(nu, old).forEach(function (nu) { map.set(nu, event.ownerId); });
				return;
			}
			if (old === nu) return;
			if (old) map.delete(old);
			if (nu) map.set(nu, event.ownerId);
		}.bind(this));
		if (recordType === 'direct') {
			return storage.search({ keyPath: keyPath }, function (id, data) {
				var ownerId;
				if (endsWith.call(id, '/' + keyPath)) {
					if (data.value && (data.value !== '0')) map.set(data.value, id.split('/', 1)[0]);
				} else {
					ownerId = id.split('/', 1)[0];
					if (data.value === '11') map.set(id.slice(ownerId.length + keyPath.length + 2), ownerId);
				}
			});
		}
		return storage.searchComputed({ keyPath: keyPath }, function (id, data) {
			var ownerId = id.split('/', 1)[0];
			if (isArray(data.value)) {
				resolveEventKeys(data.value).forEach(function (nu) { map.set(nu, ownerId); });
			} else {
				if (data.value && (data.value !== '0')) map.set(data.value, ownerId);
			}
		});
	})(map);
};
<|endoftext|>


<commit_before>import gulp from 'gulp';
import gulpIf from 'gulp-if';
import minifyCss from 'gulp-minify-css';
import minifyHtml from 'gulp-minify-html';
import path from 'path';
import webpack from 'webpack';
import SplitByPathPlugin from 'webpack-split-by-path';
import webpackStream from 'webpack-stream';
import postcss from 'gulp-postcss';
import sourcemaps from 'gulp-sourcemaps';
import autoprefixer from 'autoprefixer-core';
import del from 'del';

const COMPOSE_FILE = process.env.COMPOSE_FILE || '';
const ENVIRONMENT = process.env.ENVIRONMENT
  || (COMPOSE_FILE.match(/production/) ? 'production' : 'development');
const DEBUG = ENVIRONMENT !== 'production';

const paths = {
  styles: 'src/*.css',
  html: 'src/index.html',
  src: path.resolve(__dirname, 'src'),
  build: path.resolve(__dirname, 'build'),
  node_modules: path.resolve(__dirname, 'node_modules'),
};

const webpackConfig = {
  resolve: {
    root: paths.src,
    extensions: ['', '.js', '.jsx'],
    alias: {
      app: 'scripts',
    },
  },
  externals: {
    primus: 'Primus',
  },
  entry: {
    app: 'app',
  },
  output: {
    path: paths.build,
    filename: '[name].js',
    chunkFilename: '[name].js',
  },
  plugins: [
    new SplitByPathPlugin([
      {
        path: paths.node_modules,
        name: 'vendor',
      },
    ]),
    new webpack.DefinePlugin({
      DEBUG: JSON.stringify(DEBUG),
      'process.env.NODE_ENV': JSON.stringify(process.env.ENVIRONMENT),
    }),
    !DEBUG && new webpack.optimize.DedupePlugin(),
    !DEBUG && new webpack.optimize.OccurenceOrderPlugin(),
    !DEBUG && new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
    }),
  ].filter(Boolean),
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel?stage=1',
        include: paths.src,
      },
    ],
  },
  devtool: DEBUG && 'inline-source-map',
};

function scriptsTask(watch) {
  return () => gulp.src([])
    .pipe(webpackStream({
      ...webpackConfig,
      colors: true,
      watch: watch,
    }))
    .pipe(gulp.dest(paths.build));
}

gulp.task('build:scripts', scriptsTask(false));
gulp.task('watch:scripts', scriptsTask(true));

gulp.task('build:styles', () => {
  return gulp.src(paths.styles)
    .pipe(gulpIf(DEBUG, sourcemaps.init()))
    .pipe(postcss([
      autoprefixer({
        browsers: ['last 2 versions'],
      }),
    ]))
    .pipe(gulpIf(!DEBUG, minifyCss()))
    .pipe(gulpIf(DEBUG, sourcemaps.write()))
    .pipe(gulp.dest(paths.build));
});

gulp.task('watch:styles', ['build:styles'], () => {
  gulp.watch(paths.styles, ['build:styles']);
});

gulp.task('build:html', () => {
  return gulp.src(paths.html)
    .pipe(gulpIf(!DEBUG, minifyHtml()))
    .pipe(gulp.dest(paths.build));
});

gulp.task('build', ['build:scripts', 'build:styles', 'build:html']);
gulp.task('watch', ['watch:scripts', 'watch:styles']);
gulp.task('default', ['build']);
<commit_msg>client: add gulp watch:html task<commit_after>import gulp from 'gulp';
import gulpIf from 'gulp-if';
import minifyCss from 'gulp-minify-css';
import minifyHtml from 'gulp-minify-html';
import path from 'path';
import webpack from 'webpack';
import SplitByPathPlugin from 'webpack-split-by-path';
import webpackStream from 'webpack-stream';
import postcss from 'gulp-postcss';
import sourcemaps from 'gulp-sourcemaps';
import autoprefixer from 'autoprefixer-core';
import del from 'del';

const COMPOSE_FILE = process.env.COMPOSE_FILE || '';
const ENVIRONMENT = process.env.ENVIRONMENT
  || (COMPOSE_FILE.match(/production/) ? 'production' : 'development');
const DEBUG = ENVIRONMENT !== 'production';

const paths = {
  styles: 'src/*.css',
  html: 'src/index.html',
  src: path.resolve(__dirname, 'src'),
  build: path.resolve(__dirname, 'build'),
  node_modules: path.resolve(__dirname, 'node_modules'),
};

const webpackConfig = {
  resolve: {
    root: paths.src,
    extensions: ['', '.js', '.jsx'],
    alias: {
      app: 'scripts',
    },
  },
  externals: {
    primus: 'Primus',
  },
  entry: {
    app: 'app',
  },
  output: {
    path: paths.build,
    filename: '[name].js',
    chunkFilename: '[name].js',
  },
  plugins: [
    new SplitByPathPlugin([
      {
        path: paths.node_modules,
        name: 'vendor',
      },
    ]),
    new webpack.DefinePlugin({
      DEBUG: JSON.stringify(DEBUG),
      'process.env.NODE_ENV': JSON.stringify(process.env.ENVIRONMENT),
    }),
    !DEBUG && new webpack.optimize.DedupePlugin(),
    !DEBUG && new webpack.optimize.OccurenceOrderPlugin(),
    !DEBUG && new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
    }),
  ].filter(Boolean),
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel?stage=1',
        include: paths.src,
      },
    ],
  },
  devtool: DEBUG && 'inline-source-map',
};

function scriptsTask(watch) {
  return () => gulp.src([])
    .pipe(webpackStream({
      ...webpackConfig,
      colors: true,
      watch: watch,
    }))
    .pipe(gulp.dest(paths.build));
}

gulp.task('build:scripts', scriptsTask(false));
gulp.task('watch:scripts', scriptsTask(true));

gulp.task('build:styles', () => {
  return gulp.src(paths.styles)
    .pipe(gulpIf(DEBUG, sourcemaps.init()))
    .pipe(postcss([
      autoprefixer({
        browsers: ['last 2 versions'],
      }),
    ]))
    .pipe(gulpIf(!DEBUG, minifyCss()))
    .pipe(gulpIf(DEBUG, sourcemaps.write()))
    .pipe(gulp.dest(paths.build));
});

gulp.task('watch:styles', ['build:styles'], () => {
  gulp.watch(paths.styles, ['build:styles']);
});

gulp.task('build:html', () => {
  return gulp.src(paths.html)
    .pipe(gulpIf(!DEBUG, minifyHtml()))
    .pipe(gulp.dest(paths.build));
});

gulp.task('watch:html', ['build:html'], () => {
  gulp.watch(paths.html, ['build:html']);
});

gulp.task('build', ['build:scripts', 'build:styles', 'build:html']);
gulp.task('watch', ['watch:scripts', 'watch:styles', 'watch:html']);
gulp.task('default', ['build']);
<|endoftext|>


<commit_before>var Promise = require("nodegit-promise");
var promisify = require("promisify-node");
var fse = promisify("fs-extra");
var zlib = require("zlib");
var cp = require("child_process");
var path = require("path");

var local = path.join.bind(path, __dirname);
var rooted = path.join.bind(path, __dirname, "..");

var check = require(local("checkPrepared")).checkVendor;
var pkg = require(rooted("package"));
var tar;
var request;

var NODE_VERSION = Number(process.version.match(/^v(\d+\.\d+)/)[1]);

module.exports = function retrieveExternalDependencies() {
  tar = require("tar");
  request = require("request");
  return Promise.all([
    getVendorLib("libgit2", "https://github.com/libgit2/libgit2/tarball/" + pkg.libgit2.sha),
    getVendorLib("libssh2", pkg.libssh2.url),
    getVendorLib("http_parser", pkg.http_parser.url)
  ])
};

function getVendorLib(name, url) {
  var vendorPath = "vendor/" + name + "/";
  var vendorPackage = pkg[name];
  if (NODE_VERSION === 0.1 && vendorPackage["0.10"]) {
    vendorPackage = vendorPackage["0.10"];
  }

  var version = vendorPackage.sha || vendorPackage.version;

  console.info("[nodegit] Detecting " + vendorPath + ".");
  return check(name)
    .then(function(exists) {
      if (exists) {
        console.info("[nodegit] " + vendorPath + " already exists.");
        return Promise.resolve();
      }
      else {
        return check(name, true)
          .then(function(exists) {
            if (exists) {
              console.info("[nodegit] Removing outdated " + vendorPath + ".");
              return fse.remove(rooted(vendorPath));
            }
            else {
              console.info("[nodegit] " + vendorPath + " not found.");
              return Promise.resolve();
            }
          })
          .then(function() {
            return new Promise(function (resolve, reject) {
              console.info("[nodegit] Retrieving " + vendorPath + ".");

              var extract = tar.Extract({
                path: rooted("vendor/" + name + "/"),
                strip: true
              });

              request.get(url)
                .pipe(zlib.createUnzip())
                .pipe(extract)
                .on("error", reject)
                .on("end", resolve);
            });

          })
          .then(function() {
            return fse.writeFile(rooted(vendorPath + version), "");
          })
          .then(function() {
            if ((name == "libssh2") && (process.platform !== "win32")) {
              return new Promise(function(resolve, reject) {
                console.info("[nodegit] Configuring libssh2.");
                cp.exec(rooted(vendorPath) + "configure", {cwd: rooted(vendorPath)}, function(err, stdout, stderr) {
                  if (err) {
                    console.error(err);
                    console.error(stderr);
                    reject(err, stderr);
                  }
                  else {
                    resolve(stdout);
                  }
                })
              });
            }
            else {
              return Promise.resolve();
            }
          })
          .then(function() {
            console.info("[nodegit] Successfully updated " + vendorPath + ".");
          });
      }
    });

}

// Called on the command line
if (require.main === module) {
  module.exports();
}
<commit_msg>debug info<commit_after>var Promise = require("nodegit-promise");
var promisify = require("promisify-node");
var fse = promisify("fs-extra");
var zlib = require("zlib");
var cp = require("child_process");
var path = require("path");

var local = path.join.bind(path, __dirname);
var rooted = path.join.bind(path, __dirname, "..");

var check = require(local("checkPrepared")).checkVendor;
var pkg = require(rooted("package"));
var tar;
var request;

var NODE_VERSION = Number(process.version.match(/^v(\d+\.\d+)/)[1]);

module.exports = function retrieveExternalDependencies() {
  tar = require("tar");
  request = require("request");
  return Promise.all([
    getVendorLib("libgit2", "https://github.com/libgit2/libgit2/tarball/" + pkg.libgit2.sha),
    getVendorLib("libssh2", pkg.libssh2.url),
    getVendorLib("http_parser", pkg.http_parser.url)
  ])
};

function getVendorLib(name, url) {
  var vendorPath = "vendor/" + name + "/";
  var vendorPackage = pkg[name];
  if (NODE_VERSION === 0.1 && vendorPackage["0.10"]) {
    vendorPackage = vendorPackage["0.10"];
  }

  var version = vendorPackage.sha || vendorPackage.version;

  console.info("[nodegit] Detecting " + vendorPath + version + ".");
  return check(name)
    .then(function(exists) {
      if (exists) {
        console.info("[nodegit] " + vendorPath + version + " already exists.");
        return Promise.resolve();
      }
      else {
        return check(name, true)
          .then(function(exists) {
            if (exists) {
              console.info("[nodegit] Removing outdated " + vendorPath + ".");
              return fse.remove(rooted(vendorPath));
            }
            else {
              console.info("[nodegit] " + vendorPath + " not found.");
              return Promise.resolve();
            }
          })
          .then(function() {
            return new Promise(function (resolve, reject) {
              console.info("[nodegit] Retrieving " + vendorPath + ".");

              var extract = tar.Extract({
                path: rooted("vendor/" + name + "/"),
                strip: true
              });

              request.get(url)
                .pipe(zlib.createUnzip())
                .pipe(extract)
                .on("error", reject)
                .on("end", resolve);
            });

          })
          .then(function() {
            return fse.writeFile(rooted(vendorPath + version), "");
          })
          .then(function() {
            if ((name == "libssh2") && (process.platform !== "win32")) {
              return new Promise(function(resolve, reject) {
                console.info("[nodegit] Configuring libssh2.");
                cp.exec(rooted(vendorPath) + "configure", {cwd: rooted(vendorPath)}, function(err, stdout, stderr) {
                  if (err) {
                    console.error(err);
                    console.error(stderr);
                    reject(err, stderr);
                  }
                  else {
                    resolve(stdout);
                  }
                })
              });
            }
            else {
              return Promise.resolve();
            }
          })
          .then(function() {
            console.info("[nodegit] Successfully updated " + vendorPath + version + ".");
          });
      }
    });

}

// Called on the command line
if (require.main === module) {
  module.exports();
}
<|endoftext|>


<commit_before>var Project = Backbone.Model.extend({
    SRS_DEFAULT: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs',
    STYLESHEET_DEFAULT: [{
        id: 'style.mss',
        data: "Map {\n  map-bgcolor: #fff;\n}\n\n#world {\n  polygon-fill: #eee;\n  line-color: #ccc;\n  line-width: 0.5;\n}"
    }],
    LAYER_DEFAULT: [{
        id: 'world',
        srs: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs',
        Datasource: {
            file: 'http://tilemill-data.s3.amazonaws.com/world_borders_merc.zip',
            type: 'shape',
            estimate_extent: 'id',
            id: 'world',
        }
    }],
    initialize: function(attributes) {
        if (!this.get('srs')) {
            this.set({'srs': this.SRS_DEFAULT});
        }
        if (!this.get('Stylesheet')) {
            this.set({'Stylesheet': new StylesheetList(this.STYLESHEET_DEFAULT, { parent: this })});
        }
        if (!this.get('Layer')) {
            this.set({'Layer': new LayerList(this.LAYER_DEFAULT, { parent:this })});
        }
    },
    parse: function(response) {
        var self = this;
        // Instantiate StylesheetList and LayerList collections from JSON lists
        // of plain JSON objects.
        response.Stylesheet = new StylesheetList(response.Stylesheet ? response.Stylesheet : [], {parent:this});
        response.Layer = new LayerList(response.Layer ? response.Layer : [], {parent:this});
        return response;
    },
    // Override url() method for convenience so we don't always need a
    // collection reference around for CRUD operations on a single model.
    url: function() {
        return '/api/project/' + this.id;
    },
    /**
     * Layer URL based on the model URL.
     */
    layerURL: function() {
        var mmlb64 = Base64.urlsafe_encode(window.location.origin + this.url());
        return window.location.origin + '/tile/' + mmlb64 + '/${z}/${x}/${y}.png'
    },
    validate: function(attributes) {
        // Trigger a validation event.
        this.trigger('validate');

        if (/^[a-z0-9\-_]+$/i.test(this.id) === false) {
            return 'Name must contain only letters, numbers, dashes, and underscores.';
        }
    }
});

var ProjectList = Backbone.Collection.extend({
    model: Project,
    url: '/api/project'
});

var ProjectListView = Backbone.View.extend({
    id: 'ProjectListView',
    tagName: 'div',
    className: 'column',
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.bind('all', this.render);
        this.collection.fetch();
    },
    render: function() {
        var self = this;
        $(this.el).html(ich.ProjectListView());
        this.collection.each(function(project) {
            var projectRow = new ProjectRowView({
                model: project,
                collection: this.collection
            });
            $('ul', self.el).append(projectRow.el);
        });
        return this;
    },
    events: {
        'click input.submit': 'add'
    },
    add: function() {
        // @TODO: this code is considerably more complicated than it should be
        // because this.collection.create() does not appear to stop itself from
        // saving a project even if its validation fails.
        // See: https://github.com/documentcloud/backbone/issues#issue/66
        window.app.loading();
        var projectId = $('input.text', this.el).val();
        var project = new Project({id: projectId});
        var self = this;
        project.save(project, {
            success: function() {
                self.collection.add(project);
                window.app.done();
            },
            error: function(project, error) {
                window.app.done();
                window.app.message('Error', error);
            }
        });
        return false;
    }
});

var ProjectRowView = Backbone.View.extend({
    tagName: 'li',
    className: 'clearfix',
    initialize: function () {
        _.bindAll(this, 'render');
        this.render();
    },
    render: function () {
        $(this.el).html(ich.ProjectRowView(this.model));
        return this;
    },
    events: {
        'click .file-delete': 'del'
    },
    del: function() {
        window.app.loading();
        if (confirm('Are you sure you want to delete this project?')) {
            this.model.destroy({
                success: function() {
                    window.app.done();
                },
                error: function() {
                    window.app.done();
                    window.app.message('Error', 'The project could not be deleted.');
                }
            });
        }
        else {
            window.app.done();
        }
        return false;
    }
});

var ProjectView = Backbone.View.extend({
    events: {
        'click #header a.save': 'saveProject',
        'click #header a.info': 'projectInfo',
        'click #header a.minimal': 'minimal',
        'click #header a.home': 'home'
    },
    initialize: function () {
        _.bindAll(this, 'render', 'saveProject', 'projectInfo', 'home', 'minimal', 'changed');
        this.model.view = this;
        this.model.bind('change', this.changed);
        this.model.fetch({ success: this.render, error: this.render});
    },
    render: function() {
        $(this.el).html(ich.ProjectView(this.model));

        var layers = new LayerListView({collection: this.model.get('Layer')});
        var stylesheets = new StylesheetListView({collection: this.model.get('Stylesheet')});
        var map = new MapView({model: this.model});

        $('#sidebar', this.el).append(layers.el);
        $('#sidebar', this.el).append(map.el);
        $('#main', this.el).append(stylesheets.el);

        window.app.el.html(this.el);
        window.app.trigger('ready');
        return this;
    },
    saveProject: function() {
        this.model.save(this.model, {
            success: function() {
                $('#header a.save', this.el).removeClass('changed');
            },
            error: function(err) {
                window.app.message('Error', err);
            }
        });
        return false;
    },
    projectInfo: function() {
        window.app.message('Project Info', {'tilelive_url': this.model.layerURL(), 'mml_url': window.location.origin + this.model.url()}, 'projectInfo');
        return false;
    },
    home: function() {
        return (!$('#header a.save', this.el).is('.changed') || confirm('You have unsaved changes. Are you sure you want to close this project?'));
    },
    minimal: function() {
        $('a.minimal', this.el).toggleClass('active');
        if ($('a.minimal', this.el).is('.active')) {
            $('#main').hide();
            $('a.home').hide();
            $('a.save').hide();
            $('#sidebar').css('width', '100%');
            // @TODO.
            // TileMill.project_watcher = setInterval(TileMill.project.watch, 1000);
        }
        else {
            $('#main').show();
            $('a.home').show();
            $('a.save').show();
            $('#sidebar').css('width', '30%');
            // @TODO
            // window.clearInterval(TileMill.project_watcher);
        }
        return false;
    },
    changed: function() {
        $('#header a.save', this.el).addClass('changed');
    }
});

/**
 * Router controller: Project page.
TileMill.bind('project', function() {
  var id = $.bbq.getState('id');
  TileMill.backend.get('project/' + id + '/' + id + '.mml', function(mml) {
    // Bail if MML was not valid.
    if (typeof mml != 'string') {
      TileMill.errorPage(mml.data);
      return false;
    }

    // Store current project data.
    TileMill.data.mml = mml;
    TileMill.data.id = id;
    TileMill.data.type = 'project';
    TileMill.data.filename = 'project/' + id + '/' + id + '.mml';

    // Set the unique query string.
    TileMill.data.uniq = (new Date().getTime());

    // Parse MML.
    var parsed = TileMill.mml.parseMML(mml);

    TileMill.show(ich.project({id: id}));

    var layers = TileMill.mml.init();
    var inspector = TileMill.inspector.init();
    var stylesheets = TileMill.stylesheet.init();
    var map = TileMill.map.init();
    var color = TileMill.colors.init();

    $('#sidebar').append(layers);
    $('#sidebar').append(inspector);
    $('#sidebar').append(map).addClass('with-map');
    $('#main').append(stylesheets);
    $('#main').append(color);

    // Init elements which require DOM presence.
    TileMill.colors.initFarb(color);
    // TODO: actually configure map, don't pretend to
    TileMill.map.initOL(map, TileMill.backend.servers(TileMill.mml.url()), {
        navigation: 1,
        fullscreen: 1,
        zoom: 1,
        panzoombar: 0
    }, parsed.metadata.mapCenter);

    $(document).bind('keypress', function(event) {
      if (event.charCode == 19) {
        TileMill.project.save();
        return false;
      }
    });

    // Hide inspector to start.
    inspector.hide();
    $('a.inspector-close').click(function() {
      $('#layers').show();
      $('#inspector').hide();
      return false;
    });

    setInterval(TileMill.project.status, 10000);
  });
});

// TileMill.project = {};

/**
 * Mark this project as changed (and needing to be saved).
TileMill.project.changed = function() {
  $('div#header a.save').addClass('changed');
};

TileMill.project.checkStale = function(data) {
  $('#tabs a.tab').each(function() {
    if (($.url.setUrl($(this).data('tilemill').src)
            .param('filename') == data.filename) &&
      ($(this).data('tilemill').mtime != data.mtime)) {
      TileMill.inspector.load();
      TileMill.data.uniq = (new Date().getTime());
      TileMill.map.reload(
          $('#map-preview'),
          TileMill.backend.servers(TileMill.mml.url()));
      $('div#header a.save').removeClass('changed');
      $(this).data('tilemill').mtime = data.mtime;
    }
  });
};

TileMill.project.status = function() {
  TileMill.backend.status(function(status) {
    if (status) {
        $('.status').removeClass('offline');
    } else {
        $('.status').text('tile server offline');
        $('.status').addClass('offline');
    }
  });
};

TileMill.project.watch = function() {
  $('#tabs a.tab').each(function() {
    TileMill.stylesheet.setCode($('#tabs a.active'), true);
    TileMill.stylesheet.mtime(
      $.url.setUrl($(this).data('tilemill').src).param('filename'),
      TileMill.project.checkStale);
  });
};

/**
 * Save a project from its current DOM state.
TileMill.project.save = function() {
  // Refresh storage of active stylesheet before saving.
  TileMill.stylesheet.setCode($('#tabs a.active'), true);

  var id = TileMill.data.id,
      queue = new TileMill.queue();
  queue.add(function(id, next) {
    var mml = {
      metadata: {
        mapCenter: TileMill.map.getCenter($('#map-preview'))
      },
      stylesheets: [],
      layers: []
    };

    $('#tabs a.tab').each(function() {
      mml.stylesheets.push(
          TileMill.backend.url($.url.setUrl($(this).data('tilemill').src)
              .param('filename')) + '&c=' + TileMill.data.uniq);
      TileMill.stylesheet.save(
          $.url.setUrl($(this).data('tilemill').src).param('filename'),
          $('input', this).val());
    });
    $('#layers ul.sidebar-content li').reverse().each(function() {
      var layer = $(this).data('tilemill');
      if (layer) {
        layer.status = !!$(this).find('input[type=checkbox]').is(':checked');
        mml.layers.push(layer);
      }
    });
    mml = TileMill.mml.generate(mml);
    TileMill.backend.post('project/' + id + '/' + id + '.mml', mml, next);
  }, [id]);
  queue.add(function() {
    TileMill.inspector.load();
    TileMill.data.uniq = (new Date().getTime());
    TileMill.map.reload(
        $('#map-preview'),
        TileMill.backend.servers(TileMill.mml.url()));
    $('div#header a.save').removeClass('changed');
  });
  queue.execute();
};

/**
 * Add a new project.
TileMill.project.add = function(name) {
  $('body').append(ich.loading({}));

  var queue = new TileMill.queue();
  queue.add(function(name, next) {
    var self = this;
    TileMill.backend.list('project', function(projects) {
      if ($.inArray(name, projects) !== -1) {
        $('body div.loading').remove();
        TileMill.message('Error', 'A project with the name <em>' +
            name + '</em> already exists. Please choose another name.',
            'error');
        self.reset();
      }
      else {
        next();
      }
    });
  }, [name]);
  queue.add(function(name, next) {
    TileMill.backend.post('project/' + name + '/' + name + '.mss',
      TileMill.mss.generate({
        'Map': {
          'map-bgcolor': '#fff'
        },
        '#world': {
          'polygon-fill': '#eee',
          'line-color': '#ccc',
          'line-width': '0.5'
        }
      }),
      next);
  }, [name]);
  queue.add(function(name, next) {
    var mss = 'project/' + name + '/' + name + '.mss';
    var mml = 'project/' + name + '/' + name + '.mml';
    var data = TileMill.mml.generate({
      stylesheets: [TileMill.backend.url(mss)],
      layers: [{
        id: 'world',
        srs: '&srs900913;',
        // TODO: make configurable
        file: 'http://tilemill-data.s3.amazonaws.com/world_borders_merc.zip',
        type: 'shape'
      }]
    });
    TileMill.backend.post(mml, data, next);
  }, [name]);
  queue.add(function(name) {
    $.bbq.pushState({ 'action': 'project', 'id': name });
  }, [name]);
  queue.execute();
};
*/
<commit_msg>Remove map bgcolor styles.<commit_after>var Project = Backbone.Model.extend({
    SRS_DEFAULT: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs',
    STYLESHEET_DEFAULT: [{
        id: 'style.mss',
        data: "#world {\n  polygon-fill: #eee;\n  line-color: #ccc;\n  line-width: 0.5;\n}"
    }],
    LAYER_DEFAULT: [{
        id: 'world',
        srs: '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs',
        Datasource: {
            file: 'http://tilemill-data.s3.amazonaws.com/world_borders_merc.zip',
            type: 'shape',
            estimate_extent: 'id',
            id: 'world',
        }
    }],
    initialize: function(attributes) {
        if (!this.get('srs')) {
            this.set({'srs': this.SRS_DEFAULT});
        }
        if (!this.get('Stylesheet')) {
            this.set({'Stylesheet': new StylesheetList(this.STYLESHEET_DEFAULT, { parent: this })});
        }
        if (!this.get('Layer')) {
            this.set({'Layer': new LayerList(this.LAYER_DEFAULT, { parent:this })});
        }
    },
    parse: function(response) {
        var self = this;
        // Instantiate StylesheetList and LayerList collections from JSON lists
        // of plain JSON objects.
        response.Stylesheet = new StylesheetList(response.Stylesheet ? response.Stylesheet : [], {parent:this});
        response.Layer = new LayerList(response.Layer ? response.Layer : [], {parent:this});
        return response;
    },
    // Override url() method for convenience so we don't always need a
    // collection reference around for CRUD operations on a single model.
    url: function() {
        return '/api/project/' + this.id;
    },
    /**
     * Layer URL based on the model URL.
     */
    layerURL: function() {
        var mmlb64 = Base64.urlsafe_encode(window.location.origin + this.url());
        return window.location.origin + '/tile/' + mmlb64 + '/${z}/${x}/${y}.png'
    },
    validate: function(attributes) {
        // Trigger a validation event.
        this.trigger('validate');

        if (/^[a-z0-9\-_]+$/i.test(this.id) === false) {
            return 'Name must contain only letters, numbers, dashes, and underscores.';
        }
    }
});

var ProjectList = Backbone.Collection.extend({
    model: Project,
    url: '/api/project'
});

var ProjectListView = Backbone.View.extend({
    id: 'ProjectListView',
    tagName: 'div',
    className: 'column',
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.bind('all', this.render);
        this.collection.fetch();
    },
    render: function() {
        var self = this;
        $(this.el).html(ich.ProjectListView());
        this.collection.each(function(project) {
            var projectRow = new ProjectRowView({
                model: project,
                collection: this.collection
            });
            $('ul', self.el).append(projectRow.el);
        });
        return this;
    },
    events: {
        'click input.submit': 'add'
    },
    add: function() {
        // @TODO: this code is considerably more complicated than it should be
        // because this.collection.create() does not appear to stop itself from
        // saving a project even if its validation fails.
        // See: https://github.com/documentcloud/backbone/issues#issue/66
        window.app.loading();
        var projectId = $('input.text', this.el).val();
        var project = new Project({id: projectId});
        var self = this;
        project.save(project, {
            success: function() {
                self.collection.add(project);
                window.app.done();
            },
            error: function(project, error) {
                window.app.done();
                window.app.message('Error', error);
            }
        });
        return false;
    }
});

var ProjectRowView = Backbone.View.extend({
    tagName: 'li',
    className: 'clearfix',
    initialize: function () {
        _.bindAll(this, 'render');
        this.render();
    },
    render: function () {
        $(this.el).html(ich.ProjectRowView(this.model));
        return this;
    },
    events: {
        'click .file-delete': 'del'
    },
    del: function() {
        window.app.loading();
        if (confirm('Are you sure you want to delete this project?')) {
            this.model.destroy({
                success: function() {
                    window.app.done();
                },
                error: function() {
                    window.app.done();
                    window.app.message('Error', 'The project could not be deleted.');
                }
            });
        }
        else {
            window.app.done();
        }
        return false;
    }
});

var ProjectView = Backbone.View.extend({
    events: {
        'click #header a.save': 'saveProject',
        'click #header a.info': 'projectInfo',
        'click #header a.minimal': 'minimal',
        'click #header a.home': 'home'
    },
    initialize: function () {
        _.bindAll(this, 'render', 'saveProject', 'projectInfo', 'home', 'minimal', 'changed');
        this.model.view = this;
        this.model.bind('change', this.changed);
        this.model.fetch({ success: this.render, error: this.render});
    },
    render: function() {
        $(this.el).html(ich.ProjectView(this.model));

        var layers = new LayerListView({collection: this.model.get('Layer')});
        var stylesheets = new StylesheetListView({collection: this.model.get('Stylesheet')});
        var map = new MapView({model: this.model});

        $('#sidebar', this.el).append(layers.el);
        $('#sidebar', this.el).append(map.el);
        $('#main', this.el).append(stylesheets.el);

        window.app.el.html(this.el);
        window.app.trigger('ready');
        return this;
    },
    saveProject: function() {
        this.model.save(this.model, {
            success: function() {
                $('#header a.save', this.el).removeClass('changed');
            },
            error: function(err) {
                window.app.message('Error', err);
            }
        });
        return false;
    },
    projectInfo: function() {
        window.app.message('Project Info', {'tilelive_url': this.model.layerURL(), 'mml_url': window.location.origin + this.model.url()}, 'projectInfo');
        return false;
    },
    home: function() {
        return (!$('#header a.save', this.el).is('.changed') || confirm('You have unsaved changes. Are you sure you want to close this project?'));
    },
    minimal: function() {
        $('a.minimal', this.el).toggleClass('active');
        if ($('a.minimal', this.el).is('.active')) {
            $('#main').hide();
            $('a.home').hide();
            $('a.save').hide();
            $('#sidebar').css('width', '100%');
            // @TODO.
            // TileMill.project_watcher = setInterval(TileMill.project.watch, 1000);
        }
        else {
            $('#main').show();
            $('a.home').show();
            $('a.save').show();
            $('#sidebar').css('width', '30%');
            // @TODO
            // window.clearInterval(TileMill.project_watcher);
        }
        return false;
    },
    changed: function() {
        $('#header a.save', this.el).addClass('changed');
    }
});

/**
 * Router controller: Project page.
TileMill.bind('project', function() {
  var id = $.bbq.getState('id');
  TileMill.backend.get('project/' + id + '/' + id + '.mml', function(mml) {
    // Bail if MML was not valid.
    if (typeof mml != 'string') {
      TileMill.errorPage(mml.data);
      return false;
    }

    // Store current project data.
    TileMill.data.mml = mml;
    TileMill.data.id = id;
    TileMill.data.type = 'project';
    TileMill.data.filename = 'project/' + id + '/' + id + '.mml';

    // Set the unique query string.
    TileMill.data.uniq = (new Date().getTime());

    // Parse MML.
    var parsed = TileMill.mml.parseMML(mml);

    TileMill.show(ich.project({id: id}));

    var layers = TileMill.mml.init();
    var inspector = TileMill.inspector.init();
    var stylesheets = TileMill.stylesheet.init();
    var map = TileMill.map.init();
    var color = TileMill.colors.init();

    $('#sidebar').append(layers);
    $('#sidebar').append(inspector);
    $('#sidebar').append(map).addClass('with-map');
    $('#main').append(stylesheets);
    $('#main').append(color);

    // Init elements which require DOM presence.
    TileMill.colors.initFarb(color);
    // TODO: actually configure map, don't pretend to
    TileMill.map.initOL(map, TileMill.backend.servers(TileMill.mml.url()), {
        navigation: 1,
        fullscreen: 1,
        zoom: 1,
        panzoombar: 0
    }, parsed.metadata.mapCenter);

    $(document).bind('keypress', function(event) {
      if (event.charCode == 19) {
        TileMill.project.save();
        return false;
      }
    });

    // Hide inspector to start.
    inspector.hide();
    $('a.inspector-close').click(function() {
      $('#layers').show();
      $('#inspector').hide();
      return false;
    });

    setInterval(TileMill.project.status, 10000);
  });
});

// TileMill.project = {};

/**
 * Mark this project as changed (and needing to be saved).
TileMill.project.changed = function() {
  $('div#header a.save').addClass('changed');
};

TileMill.project.checkStale = function(data) {
  $('#tabs a.tab').each(function() {
    if (($.url.setUrl($(this).data('tilemill').src)
            .param('filename') == data.filename) &&
      ($(this).data('tilemill').mtime != data.mtime)) {
      TileMill.inspector.load();
      TileMill.data.uniq = (new Date().getTime());
      TileMill.map.reload(
          $('#map-preview'),
          TileMill.backend.servers(TileMill.mml.url()));
      $('div#header a.save').removeClass('changed');
      $(this).data('tilemill').mtime = data.mtime;
    }
  });
};

TileMill.project.status = function() {
  TileMill.backend.status(function(status) {
    if (status) {
        $('.status').removeClass('offline');
    } else {
        $('.status').text('tile server offline');
        $('.status').addClass('offline');
    }
  });
};

TileMill.project.watch = function() {
  $('#tabs a.tab').each(function() {
    TileMill.stylesheet.setCode($('#tabs a.active'), true);
    TileMill.stylesheet.mtime(
      $.url.setUrl($(this).data('tilemill').src).param('filename'),
      TileMill.project.checkStale);
  });
};

/**
 * Save a project from its current DOM state.
TileMill.project.save = function() {
  // Refresh storage of active stylesheet before saving.
  TileMill.stylesheet.setCode($('#tabs a.active'), true);

  var id = TileMill.data.id,
      queue = new TileMill.queue();
  queue.add(function(id, next) {
    var mml = {
      metadata: {
        mapCenter: TileMill.map.getCenter($('#map-preview'))
      },
      stylesheets: [],
      layers: []
    };

    $('#tabs a.tab').each(function() {
      mml.stylesheets.push(
          TileMill.backend.url($.url.setUrl($(this).data('tilemill').src)
              .param('filename')) + '&c=' + TileMill.data.uniq);
      TileMill.stylesheet.save(
          $.url.setUrl($(this).data('tilemill').src).param('filename'),
          $('input', this).val());
    });
    $('#layers ul.sidebar-content li').reverse().each(function() {
      var layer = $(this).data('tilemill');
      if (layer) {
        layer.status = !!$(this).find('input[type=checkbox]').is(':checked');
        mml.layers.push(layer);
      }
    });
    mml = TileMill.mml.generate(mml);
    TileMill.backend.post('project/' + id + '/' + id + '.mml', mml, next);
  }, [id]);
  queue.add(function() {
    TileMill.inspector.load();
    TileMill.data.uniq = (new Date().getTime());
    TileMill.map.reload(
        $('#map-preview'),
        TileMill.backend.servers(TileMill.mml.url()));
    $('div#header a.save').removeClass('changed');
  });
  queue.execute();
};

/**
 * Add a new project.
TileMill.project.add = function(name) {
  $('body').append(ich.loading({}));

  var queue = new TileMill.queue();
  queue.add(function(name, next) {
    var self = this;
    TileMill.backend.list('project', function(projects) {
      if ($.inArray(name, projects) !== -1) {
        $('body div.loading').remove();
        TileMill.message('Error', 'A project with the name <em>' +
            name + '</em> already exists. Please choose another name.',
            'error');
        self.reset();
      }
      else {
        next();
      }
    });
  }, [name]);
  queue.add(function(name, next) {
    TileMill.backend.post('project/' + name + '/' + name + '.mss',
      TileMill.mss.generate({
        'Map': {
          'map-bgcolor': '#fff'
        },
        '#world': {
          'polygon-fill': '#eee',
          'line-color': '#ccc',
          'line-width': '0.5'
        }
      }),
      next);
  }, [name]);
  queue.add(function(name, next) {
    var mss = 'project/' + name + '/' + name + '.mss';
    var mml = 'project/' + name + '/' + name + '.mml';
    var data = TileMill.mml.generate({
      stylesheets: [TileMill.backend.url(mss)],
      layers: [{
        id: 'world',
        srs: '&srs900913;',
        // TODO: make configurable
        file: 'http://tilemill-data.s3.amazonaws.com/world_borders_merc.zip',
        type: 'shape'
      }]
    });
    TileMill.backend.post(mml, data, next);
  }, [name]);
  queue.add(function(name) {
    $.bbq.pushState({ 'action': 'project', 'id': name });
  }, [name]);
  queue.execute();
};
*/
<|endoftext|>


<commit_before>var fs = require('fs');

var task = function(fd, fileSize) {
	this.fd = fd;
	this.fileSize = fileSize;

};
var _execute = function(callback) {

	this.callback = callback;
	var self = this;
  //support older versions of node
  if fs.ftruncate {
    fs.ftruncate(this.fd, this.fileSize, self.callback);
  }
  else {
    fs.truncate(this.fd, this.fileSize, self.callback);
  }
	//this.callback();
};

task.prototype.execute = _execute;

module.exports = task;
<commit_msg>parens<commit_after>var fs = require('fs');

var task = function(fd, fileSize) {
	this.fd = fd;
	this.fileSize = fileSize;

};
var _execute = function(callback) {

	this.callback = callback;
	var self = this;
  //support older versions of node
  if (fs.ftruncate) {
    fs.ftruncate(this.fd, this.fileSize, self.callback);
  }
  else {
    fs.truncate(this.fd, this.fileSize, self.callback);
  }
	//this.callback();
};

task.prototype.execute = _execute;

module.exports = task;
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('angular-client-side-auth')
.controller('NavCtrl', ['$rootScope', '$scope', '$location', 'Auth', function($rootScope, $scope, $location, Auth) {
    $scope.user = Auth.user;
    $scope.userRoles = Auth.userRoles;
    $scope.accessLevels = Auth.accessLevels;

    $scope.logout = function() {
        Auth.logout(function() {
            $location.path('/login');
        }, function() {
            $rootScope.error = "Failed to logout";
        });
    };
}]);

angular.module('angular-client-side-auth')
.controller('TransCtrl', ['$rootScope', '$scope', '$location', 'Auth', function($rootScope, $scope, $location, Auth) {
    $scope.user = Auth.user;
    $scope.userRoles = Auth.userRoles;
    $scope.accessLevels = Auth.accessLevels;

    $scope.newTransaction = function() {
        Auth.logout(function() {
            $location.path('/login');
        }, function() {
            $rootScope.error = "Failed to logout";
        });
    };
    /*
        if (Auth.isLoggedIn($scope.user))
            $rootScope.error = "yaya";
        else
            $rootScope.error = "no";
    };
    */
}]);

angular.module('angular-client-side-auth')
.controller('LoginCtrl',
['$rootScope', '$scope', '$location', '$window', 'Auth', function($rootScope, $scope, $location, $window, Auth) {

    $scope.rememberme = true;
    $scope.login = function() {
        Auth.login({
                username: $scope.username,
                password: $scope.password,
                rememberme: $scope.rememberme
            },
            function(res) {
                $location.path('/');
            },
            function(err) {
                $rootScope.error = "Failed to login";
            });
    };

    $scope.loginOauth = function(provider) {
        $window.location.href = '/auth/' + provider;
    };
}]);

angular.module('angular-client-side-auth')
.controller('RegisterCtrl',
['$rootScope', '$scope', '$location', 'Auth', function($rootScope, $scope, $location, Auth) {
    $scope.role = Auth.userRoles.user;
    $scope.userRoles = Auth.userRoles;

    $scope.register = function() {
        Auth.register({
                username: $scope.username,
                password: $scope.password,
                role: $scope.role
            },
            function() {
                $location.path('/');
            },
            function(err) {
                $rootScope.error = err;
            });
    };
}]);

angular.module('angular-client-side-auth')
.controller('AdminCtrl',
['$rootScope', '$scope', 'Users', 'Auth', function($rootScope, $scope, Users, Auth) {
    $scope.loading = true;
    $scope.userRoles = Auth.userRoles;

    Users.getAll(function(res) {
        $scope.users = res;
        $scope.loading = false;
    }, function(err) {
        $rootScope.error = "Failed to fetch users.";
        $scope.loading = false;
    });

}]);

<commit_msg>Trying to create new transaction method<commit_after>'use strict';

/* Controllers */

angular.module('angular-client-side-auth')
.controller('NavCtrl', ['$rootScope', '$scope', '$location', 'Auth', function($rootScope, $scope, $location, Auth) {
    $scope.user = Auth.user;
    $scope.userRoles = Auth.userRoles;
    $scope.accessLevels = Auth.accessLevels;

    $scope.logout = function() {
        Auth.logout(function() {
            $location.path('/login');
        }, function() {
            $rootScope.error = "Failed to logout";
        });
    };
}]);

angular.module('angular-client-side-auth')
.controller('TransCtrl', ['$rootScope', '$scope', '$location', 'Auth', function($rootScope, $scope, $location, Auth) {
    $scope.user = Auth.user;
    $scope.userRoles = Auth.userRoles;
    $scope.accessLevels = Auth.accessLevels;

    $scope.newTransaction = function() {
        Auth.newTransaction(function() {
            $rootScope.error = "Created transaction";
        }, function() {
            $rootScope.error = "Failed to create transaction";
        });
    };
}]);

angular.module('angular-client-side-auth')
.controller('LoginCtrl',
['$rootScope', '$scope', '$location', '$window', 'Auth', function($rootScope, $scope, $location, $window, Auth) {

    $scope.rememberme = true;
    $scope.login = function() {
        Auth.login({
                username: $scope.username,
                password: $scope.password,
                rememberme: $scope.rememberme
            },
            function(res) {
                $location.path('/');
            },
            function(err) {
                $rootScope.error = "Failed to login";
            });
    };

    $scope.loginOauth = function(provider) {
        $window.location.href = '/auth/' + provider;
    };
}]);

angular.module('angular-client-side-auth')
.controller('RegisterCtrl',
['$rootScope', '$scope', '$location', 'Auth', function($rootScope, $scope, $location, Auth) {
    $scope.role = Auth.userRoles.user;
    $scope.userRoles = Auth.userRoles;

    $scope.register = function() {
        Auth.register({
                username: $scope.username,
                password: $scope.password,
                role: $scope.role
            },
            function() {
                $location.path('/');
            },
            function(err) {
                $rootScope.error = err;
            });
    };
}]);

angular.module('angular-client-side-auth')
.controller('AdminCtrl',
['$rootScope', '$scope', 'Users', 'Auth', function($rootScope, $scope, Users, Auth) {
    $scope.loading = true;
    $scope.userRoles = Auth.userRoles;

    Users.getAll(function(res) {
        $scope.users = res;
        $scope.loading = false;
    }, function(err) {
        $rootScope.error = "Failed to fetch users.";
        $scope.loading = false;
    });

}]);

<|endoftext|>


<commit_before>
var ZMSFORMAT = {
  None: 1 << 0,
  Position: 1 << 1,
  Normal: 1 << 2,
  Color: 1 << 3,
  BlendWeight: 1 << 4,
  BlendIndex: 1 << 5,
  Tangent: 1 << 6,
  UV1: 1 << 7,
  UV2: 1 << 8,
  UV3: 1 << 9,
  UV4: 1 << 10
};
var ZMSLoader = {};
ZMSLoader.load = function(path, callback) {
  ROSELoader.load(path, function(rh) {
    var geometry = new THREE.Geometry();

    rh.skip(8);
    var format = rh.readUint32();
    rh.readVector3();
    rh.readVector3();

    var boneCount = rh.readUint16();
    var boneTable = [];
    for (var i = 0; i < boneCount; ++i) {
      boneTable[i] = rh.readUint16();
    }

    var vertexCount = rh.readUint16();
    var vertexUvs = [[], [], [], []];

    for (var i = 0; i < vertexCount; ++i) {
      var v = rh.readVector3();
      geometry.vertices.push(v);
    }

    if (format & ZMSFORMAT.Normal) {
      rh.skip(vertexCount * 3*4)
    }
    if (format & ZMSFORMAT.Color) {
      rh.skip(vertexCount * 4*4)
    }
    if (format & (ZMSFORMAT.BlendIndex|ZMSFORMAT.BlendWeight)) {
      for (var i = 0; i < vertexCount; ++i) {
        var boneWeight1 = rh.readFloat();
        var boneWeight2 = rh.readFloat();
        var boneWeight3 = rh.readFloat();
        var boneWeight4 = rh.readFloat();
        var boneIndex1 = boneTable[rh.readUint16()];
        var boneIndex2 = boneTable[rh.readUint16()];
        var boneIndex3 = boneTable[rh.readUint16()];
        var boneIndex4 = boneTable[rh.readUint16()];

        geometry.skinWeights.push(new THREE.Vector4(boneWeight1, boneWeight2, boneWeight3, boneWeight4));
        geometry.skinIndices.push(new THREE.Vector4(boneIndex1, boneIndex2, boneIndex3, boneIndex4));
      }
    }
    if (format & ZMSFORMAT.Tangent) {
      rh.skip(vertexCount * 3*4)
    }
    if (format & ZMSFORMAT.UV1) {
      for (var i = 0; i < vertexCount; ++i) {
        vertexUvs[0].push(rh.readVector2());
      }
    }
    if (format & ZMSFORMAT.UV2) {
      for (var i = 0; i < vertexCount; ++i) {
        vertexUvs[1].push(rh.readVector2());
      }
    }
    if (format & ZMSFORMAT.UV3) {
      for (var i = 0; i < vertexCount; ++i) {
        vertexUvs[2].push(rh.readVector2());
      }
    }
    if (format & ZMSFORMAT.UV4) {
      for (var i = 0; i < vertexCount; ++i) {
        vertexUvs[3].push(rh.readVector2());
      }
    }

    for (var j = 0; j < 4; ++j) {
      if (vertexUvs[j].length > 0) {
        geometry.faceVertexUvs[j] = [];
      }
    }

    var faceCount = rh.readUint16();
    for (var i = 0; i < faceCount; ++i) {
      var v1 = rh.readUint16();
      var v2 = rh.readUint16();
      var v3 = rh.readUint16();
      geometry.faces.push(new THREE.Face3( v1, v2, v3 ));

      for (var j = 0; j < 4; ++j) {
        if (vertexUvs[j].length > 0) {
          geometry.faceVertexUvs[j].push([vertexUvs[j][v1], vertexUvs[j][v2], vertexUvs[j][v3]]);
        }
      }
    }

    //geometry.mergeVertices();
    geometry.computeBoundingSphere();
    geometry.computeFaceNormals();
    geometry.computeVertexNormals();

    callback(geometry);
  });
};
<commit_msg>Update ZMS to support version 6 and version 8 file formats.<commit_after>/**
 * @constructor
 * @property {RangeVector3} bounds
 * @property {THREE.Vector3[]} vertices
 * @property {THREE.Vector3[]} normals
 * @property {THREE.Vector3[]} tangents
 * @property {Colour3[]} colours
 * @property {THREE.Face3[]} faces
 * @property {{weights: THREE.Vector4[], indices: THREE.Vector4[]}} skin
 * @property {THREE.Vector2[][]} uv
 */
var Mesh = function() {
  this.bounds = {};
  this.vertices = [];
  this.normals = [];
  this.tangents = [];
  this.colours = [];
  this.faces = [];
  this.skin = {
    weights: [],
    indices: []
  };
  this.uv = [
    [], [], [], []
  ];
};

/**
 * Mesh format flags
 *
 * @enum {Number}
 */
Mesh.FORMAT = {
  NONE:         1 << 0,
  POSITION:     1 << 1,
  NORMAL:       1 << 2,
  COLOUR:       1 << 3,
  BLEND_WEIGHT: 1 << 4,
  BLEND_INDEX:  1 << 5,
  TANGENT:      1 << 6,
  UV1:          1 << 7,
  UV2:          1 << 8,
  UV3:          1 << 9,
  UV4:          1 << 10
};

/**
 * @param {BinaryReader} rh
 * @returns {Mesh}
 */
Mesh.loadMesh8 = function(rh) {
  var bones, boneTable, faces, format, i, vertices;
  var data = new Mesh();

  format = rh.readUint32();
  data.bounds.min = rh.readVector3();
  data.bounds.max = rh.readVector3();

  bones = rh.readUint16();
  boneTable = [];
  for (i = 0; i < bones; ++i) {
    boneTable.push(rh.readUint16());
  }

  vertices = rh.readUint16();
  for (i = 0; i < vertices; ++i) {
    data.vertices.push(rh.readVector3());
  }

  if (format & Mesh.FORMAT.NORMAL) {
    for (i = 0; i < vertices; ++i) {
      data.normals.push(rh.readVector3());
    }
  }

  if (format & Mesh.FORMAT.COLOUR) {
    for (i = 0; i < vertices; ++i) {
      data.colours.push(rh.readColour4());
    }
  }

  if (format & (Mesh.FORMAT.BLEND_INDEX | Mesh.FORMAT.BLEND_WEIGHT)) {
    for (i = 0; i < vertices; ++i) {
      var weight1 = rh.readFloat();
      var weight2 = rh.readFloat();
      var weight3 = rh.readFloat();
      var weight4 = rh.readFloat();
      var index1 = boneTable[rh.readUint16()];
      var index2 = boneTable[rh.readUint16()];
      var index3 = boneTable[rh.readUint16()];
      var index4 = boneTable[rh.readUint16()];

      data.skin.weights.push(new THREE.Vector4(weight1, weight2, weight3, weight4));
      data.skin.indices.push(new THREE.Vector4(index1, index2, index3, index4));
    }
  }

  if (format & Mesh.FORMAT.TANGENT) {
    for (i = 0; i < vertices; ++i) {
      data.tangents.push(rh.readVector3());
    }
  }

  if (format & Mesh.FORMAT.UV1) {
    for (i = 0; i < vertices; ++i) {
      data.uv[0].push(rh.readVector2());
    }
  }

  if (format & Mesh.FORMAT.UV2) {
    for (i = 0; i < vertices; ++i) {
      data.uv[1].push(rh.readVector2());
    }
  }
  if (format & Mesh.FORMAT.UV3) {
    for (i = 0; i < vertices; ++i) {
      data.uv[2].push(rh.readVector2());
    }
  }

  if (format & Mesh.FORMAT.UV4) {
    for (i = 0; i < vertices; ++i) {
      data.uv[3].push(rh.readVector2());
    }
  }

  faces = rh.readUint16();
  for (i = 0; i < faces; ++i) {
    var v1 = rh.readUint16();
    var v2 = rh.readUint16();
    var v3 = rh.readUint16();
    data.faces.push(new THREE.Face3(v1, v2, v3));
  }

  return data;
};

/**
 * @param {BinaryReader} rh
 * @returns {Mesh}
 */
Mesh.loadMesh6 = function(rh) {
  var bones, boneTable, faces, format, i, vertices;
  var data = new Mesh();

  format = rh.readUint32();
  data.bounds.min = rh.readVector3();
  data.bounds.max = rh.readVector3();

  bones = rh.readUint32();
  boneTable = [];
  for (i = 0; i < bones; ++i) {
    rh.skip(4);
    boneTable.push(rh.readUint32());
  }

  vertices = rh.readUint32();
  for (i = 0; i < vertices; ++i) {
    rh.skip(4);
    data.vertices.push(rh.readVector3());
  }

  if (format & Mesh.FORMAT.NORMAL) {
    for (i = 0; i < vertices; ++i) {
      rh.skip(4);
      data.normals.push(rh.readVector3());
    }
  }

  if (format & Mesh.FORMAT.COLOUR) {
    for (i = 0; i < vertices; ++i) {
      rh.skip(4);
      data.colours.push(rh.readColour4());
    }
  }

  if (format & (Mesh.FORMAT.BLEND_INDEX | Mesh.FORMAT.BLEND_WEIGHT)) {
    for (i = 0; i < vertices; ++i) {
      var weight1, weight2, weight3, weight4;
      var index1, index2, index3, index4;

      rh.skip(4);
      weight1 = rh.readFloat();
      weight2 = rh.readFloat();
      weight3 = rh.readFloat();
      weight4 = rh.readFloat();
      index1 = boneTable[rh.readUint32()];
      index2 = boneTable[rh.readUint32()];
      index3 = boneTable[rh.readUint32()];
      index4 = boneTable[rh.readUint32()];

      data.skin.weights.push(new THREE.Vector4(weight1, weight2, weight3, weight4));
      data.skin.indices.push(new THREE.Vector4(index1, index2, index3, index4));
    }
  }

  if (format & Mesh.FORMAT.TANGENT) {
    for (i = 0; i < vertices; ++i) {
      rh.skip(4);
      data.tangents.push(rh.readVector3());
    }
  }

  if (format & Mesh.FORMAT.UV1) {
    for (i = 0; i < vertices; ++i) {
      rh.skip(4);
      data.uv[0].push(rh.readVector2());
    }
  }

  if (format & Mesh.FORMAT.UV2) {
    for (i = 0; i < vertices; ++i) {
      rh.skip(4);
      data.uv[1].push(rh.readVector2());
    }
  }
  if (format & Mesh.FORMAT.UV3) {
    for (i = 0; i < vertices; ++i) {
      rh.skip(4);
      data.uv[2].push(rh.readVector2());
    }
  }

  if (format & Mesh.FORMAT.UV4) {
    for (i = 0; i < vertices; ++i) {
      rh.skip(4);
      data.uv[3].push(rh.readVector2());
    }
  }

  faces = rh.readUint32();
  for (i = 0; i < faces; ++i) {
    var v1, v2, v3;
    rh.skip(4);
    v1 = rh.readUint32();
    v2 = rh.readUint32();
    v3 = rh.readUint32();
    data.faces.push(new THREE.Face3(v1, v2, v3));
  }

  return data;
};

/**
 * @returns {THREE.Geometry}
 */
Mesh.prototype.create = function() {
  var geometry, i, j;
  geometry = new THREE.Geometry();
  geometry.vertices = this.vertices;
  geometry.skinWeights = this.skin.weights;
  geometry.skinIndices = this.skin.indices;
  geometry.faces = this.faces;

  for (j = 0; j < 4; ++j) {
    if (this.uv[j].length > 0) {
      geometry.faceVertexUvs[j] = [];
    }
  }

  for (i = 0; i < this.faces.length; ++i) {
    for (j = 0; j < 4; ++j) {
      if (this.uv[j].length > 0) {
        var uv1, uv2, uv3;
        uv1 = this.uv[j][this.faces[i].a];
        uv2 = this.uv[j][this.faces[i].b];
        uv3 = this.uv[j][this.faces[i].c];
        geometry.faceVertexUvs[j].push([uv1, uv2, uv3]);
      }
    }
  }

  geometry.computeBoundingSphere();
  geometry.computeFaceNormals();
  geometry.computeVertexNormals();
  return geometry;
};

/**
 * @callback Mesh~onLoad
 * @param {THREE.Geometry} geometry
 */

/**
 * @param {String} path
 * @param {Mesh~onLoad} callback
 */
Mesh.load = function(path, callback) {
  ROSELoader.load(path, function(rh) {
    var version, magic, mesh;

    magic = rh.readStrLen(7);
    rh.skip(1);

    if (magic === 'ZMS0005') {
      version = 5;
    } else if (magic === 'ZMS0006') {
      version = 6;
    } else if (magic === 'ZMS0007') {
      version = 7;
    } else if (magic === 'ZMS0008') {
      version = 8;
    } else {
      throw 'Unexpected ZMS magic header ' + magic + ' in ' + path;
    }

    if (version >= 7) {
      mesh = Mesh.loadMesh8(rh);
    } else {
      mesh = Mesh.loadMesh6(rh);
    }

    callback(mesh.create());
  });
};
<|endoftext|>