<commit_before>// A report is a single post/comment/article or other chunk of data from a source.
// This class is responsible for executing ReportQuerys.

var database = require('../lib/database');
var mongoose = database.mongoose;
var textSearch = require('mongoose-text-search');
var listenTo = require('mongoose-listento');
var Source = require('./source');
var Query = require('./query');
var _ = require('underscore');
var async = require('async');

var Schema = mongoose.Schema;
var ITEMS_PER_BATCH = 10; // 10 items per batch
var BATCH_TIMEOUT = 5 * 60 * 1000 // 5 minutes

var schema = new Schema({
  authoredAt: Date,
  fetchedAt: Date,
  storedAt: Date,
  content: String,
  author: String,
  url: String,
  read: {type: Boolean, default: false, required: true},
  flagged: {type: Boolean, default: false, required: true},
  _source: {type: String, ref: 'Source'},
  _media: String,
  _sourceNickname: String,
  _incident: {type: String, ref: 'Incident'},
  checkedOutBy : { type: Schema.ObjectId, ref: 'User' },
  checkedOutAt: Date
});

// Give the report schema text search capabilities
schema.plugin(textSearch);
schema.plugin(listenTo);
// Add a text index to the `content` field
schema.index({content: 'text'});

schema.path('_incident').set(function(_incident) {
  this._prevIncident = this._incident;
  return _incident;
});

schema.pre('save', function(next) {
  if (this.isNew) {
    this._wasNew = true;

    // Set default storedAt.
    if (!this.storedAt) this.storedAt = new Date();

  } else {
    // Capture updates before saving report
    if (this.isModified('_incident')) {
      this._incidentWasModified = true;
    }

  }
  next();
});

// Emit information about updates after saving report
schema.post('save', function() {
  if (this._wasNew) schema.emit('report:new', {_id: this._id.toString()});
  if (!this._wasNew) schema.emit('report:updated', {_id: this._id.toString()});

  if (this._incidentWasModified) {
    schema.emit('report:incident', {_id: this._id.toString(), _incident: this._incident ? this._incident.toString() : null});
    schema.emit('change:incident', this._prevIncident, this._incident);
  }
});

schema.methods.flag = function() {
  this.flagged = true;
  this.markAsRead();
};

schema.methods.markAsRead = function() {
  this.read = true;
  this.checkedOutBy = null;
  this.checkedOutAt = null;
};

var Report = mongoose.model('Report', schema);

// Query reports based on passed query data
Report.queryReports = function(query, page, callback) {
  if (typeof query === 'function') return Report.findPage(query);
  if (typeof page === 'function') {
    callback = page;
    page = 0;
  }
  if (page < 0) page = 0;

  query.limit = 100;
  query.filter = {};

  // Determine inclusive date filters
  if (query.after || query.before) {
    query.filter.storedAt = {};
    if (query.after) query.filter.storedAt.$gte = query.after;
    if (query.before) query.filter.storedAt.$lte = query.before;
  }

  // Convert reference fields for Report compatibility
  if (query.sourceId) query.filter._source = query.sourceId;
  if (query.sourceType) query.filter._media = query.sourceType;
  if (query.incidentId) query.filter._incident = query.incidentId;

  // Determine author filter
  if (query.author) {
    query.filter.author = {};
    query.filter.author.$in = query.author.trim().split(/\s*,\s*/).sort().map(function(author){
      // Use case-insensitive matching with anchors so mongo index is still used.
      return new RegExp('^' + author + '$', 'i');
    });
  }

  // Return only newer results
  if (query.since) {
    query.filter.storedAt = query.filter.storedAt || {};
    query.filter.storedAt.$gte = query.since;
  }

  // Re-set search timestamp
  query.since = new Date();

  if (!query.keywords) {
    // Just use filters when no keywords are provided
    Report.findSortedPage(query.filter, page, callback);
  } else {
    Report.textSearch(query.keywords, _.pick(query, ['filter', 'limit']), function(err, reports) {
      if (err) return callback(err);
      var result = {
        total: reports.stats.n ? reports.stats.nscannedObjects : 0,
        results: _.chain(reports.results).pluck('obj').sortBy('storedAt').value().reverse()
      };
      callback(null, result);
    });
  }
};

Report.findSortedPage = function(filter, page, callback) {
  Report.findPage(filter, page, {sort: '-storedAt'}, function(err, reports) {
    if (err) return callback(err);
    callback(null, reports);
  });
};

Report.checkoutBatch = function(userId, callback) {
  async.series([
    this.releaseBatch,
    this.lockBatch.bind(this, userId, ITEMS_PER_BATCH),
    this.loadBatch.bind(this, userId, ITEMS_PER_BATCH)
  ], function(err, results) {
    if (err) return callback(err);
    callback(null, results[2]);
  });
}

// release items in older batches
Report.releaseBatch = function(callback) {
  var conditions = { checkedOutAt: { $lt: timeAgo(BATCH_TIMEOUT) } };
  var update = { checkedOutBy: null, checkedOutAt: null };

  Report.update(conditions, update, { multi: true }, callback);
}

// cancel give batch
Report.cancelBatch = function(userId, callback) {
  var conditions = { checkedOutBy: userId };
  var update = { checkedOutBy: null, checkedOutAt: null };

  Report.update(conditions, update, { multi: true }, callback);
}

// lock a new batch for given user
Report.lockBatch = function(userId, limit, callback) {
  var conditions = {
    checkedOutAt: null,
    checkedOutBy: null,
    read: false
  };

  Report.find(conditions).sort({storedAt: -1}).limit(limit).exec(function(err, reports) {
    if (err) return callback(err);
    var ids = reports.map(function(report) { return report._id; });
    var update = { checkedOutBy: userId, checkedOutAt: new Date() };
    Report.update({ _id: { $in: ids } }, update, { multi: true }, callback);
  });
}

// load a batch for user
Report.loadBatch = function(userId, limit, callback) {
  var conditions = {
    checkedOutAt: { $ne: null },
    checkedOutBy: userId
  };

  Report.find(conditions).limit(limit).exec(callback);
}

// helpers

function timeAgo(miliseconds) {
  var now = new Date();
  return new Date(now.getTime() - miliseconds);
}

module.exports = Report;
<commit_msg>cleanup report model<commit_after>// A report is a single post/comment/article or other chunk of data from a source.
// This class is responsible for executing ReportQuerys.

var database = require('../lib/database');
var mongoose = database.mongoose;
var textSearch = require('mongoose-text-search');
var listenTo = require('mongoose-listento');
var Source = require('./source');
var Query = require('./query');
var _ = require('underscore');
var async = require('async');

var Schema = mongoose.Schema;
var ITEMS_PER_BATCH = 10; // 10 items per batch
var BATCH_TIMEOUT = 5 * 60 * 1000 // 5 minutes

var schema = new Schema({
  authoredAt: Date,
  fetchedAt: Date,
  storedAt: Date,
  content: String,
  author: String,
  url: String,
  read: {type: Boolean, default: false, required: true},
  flagged: {type: Boolean, default: false, required: true},
  _source: {type: String, ref: 'Source'},
  _media: String,
  _sourceNickname: String,
  _incident: {type: String, ref: 'Incident'},
  checkedOutBy : { type: Schema.ObjectId, ref: 'User' },
  checkedOutAt: Date
});

// Give the report schema text search capabilities
schema.plugin(textSearch);
schema.plugin(listenTo);
// Add a text index to the `content` field
schema.index({content: 'text'});

schema.path('_incident').set(function(_incident) {
  this._prevIncident = this._incident;
  return _incident;
});

schema.pre('save', function(next) {
  if (this.isNew) {
    this._wasNew = true;

    // Set default storedAt.
    if (!this.storedAt) this.storedAt = new Date();

  } else {
    // Capture updates before saving report
    if (this.isModified('_incident')) {
      this._incidentWasModified = true;
    }

  }
  next();
});

// Emit information about updates after saving report
schema.post('save', function() {
  if (this._wasNew) schema.emit('report:new', {_id: this._id.toString()});
  if (!this._wasNew) schema.emit('report:updated', {_id: this._id.toString()});

  if (this._incidentWasModified) {
    schema.emit('report:incident', {_id: this._id.toString(), _incident: this._incident ? this._incident.toString() : null});
    schema.emit('change:incident', this._prevIncident, this._incident);
  }
});

schema.methods.flag = function() {
  this.flagged = true;
  this.markAsRead();
};

schema.methods.markAsRead = function() {
  this.read = true;
  this.checkedOutBy = null;
  this.checkedOutAt = null;
};

var Report = mongoose.model('Report', schema);

// Query reports based on passed query data
Report.queryReports = function(query, page, callback) {
  if (typeof query === 'function') return Report.findPage(query);
  if (typeof page === 'function') {
    callback = page;
    page = 0;
  }
  if (page < 0) page = 0;

  query.limit = 100;
  query.filter = {};

  // Determine inclusive date filters
  if (query.after || query.before) {
    query.filter.storedAt = {};
    if (query.after) query.filter.storedAt.$gte = query.after;
    if (query.before) query.filter.storedAt.$lte = query.before;
  }

  // Convert reference fields for Report compatibility
  if (query.sourceId) query.filter._source = query.sourceId;
  if (query.sourceType) query.filter._media = query.sourceType;
  if (query.incidentId) query.filter._incident = query.incidentId;

  // Determine author filter
  if (query.author) {
    query.filter.author = {};
    query.filter.author.$in = query.author.trim().split(/\s*,\s*/).sort().map(function(author){
      // Use case-insensitive matching with anchors so mongo index is still used.
      return new RegExp('^' + author + '$', 'i');
    });
  }

  // Return only newer results
  if (query.since) {
    query.filter.storedAt = query.filter.storedAt || {};
    query.filter.storedAt.$gte = query.since;
  }

  // Re-set search timestamp
  query.since = new Date();

  if (!query.keywords) {
    // Just use filters when no keywords are provided
    Report.findSortedPage(query.filter, page, callback);
  } else {
    Report.textSearch(query.keywords, _.pick(query, ['filter', 'limit']), function(err, reports) {
      if (err) return callback(err);
      var result = {
        total: reports.stats.n ? reports.stats.nscannedObjects : 0,
        results: _.chain(reports.results).pluck('obj').sortBy('storedAt').value().reverse()
      };
      callback(null, result);
    });
  }
};

Report.findSortedPage = function(filter, page, callback) {
  Report.findPage(filter, page, {sort: '-storedAt'}, function(err, reports) {
    if (err) return callback(err);
    callback(null, reports);
  });
};

Report.checkoutBatch = function(userId, callback) {
  async.series([
    this.releaseBatch,
    this.lockBatch.bind(this, userId, ITEMS_PER_BATCH),
    this.loadBatch.bind(this, userId, ITEMS_PER_BATCH)
  ], function(err, results) {
    if (err) return callback(err);
    callback(null, results[2]);
  });
}

// release items in older batches
Report.releaseBatch = function(callback) {
  var conditions = { checkedOutAt: { $lt: timeAgo(BATCH_TIMEOUT) } };
  var update = { checkedOutBy: null, checkedOutAt: null };

  Report.update(conditions, update, { multi: true }, callback);
}

// cancel batch for given user
Report.cancelBatch = function(userId, callback) {
  var conditions = { checkedOutBy: userId };
  var update = { checkedOutBy: null, checkedOutAt: null };

  Report.update(conditions, update, { multi: true }, callback);
}

// lock a new batch for given user
Report.lockBatch = function(userId, limit, callback) {
  var conditions = {
    checkedOutAt: null,
    checkedOutBy: null,
    read: false
  };

  Report.find(conditions).sort({storedAt: -1}).limit(limit).exec(function(err, reports) {
    if (err) return callback(err);
    var ids = reports.map(function(report) { return report._id; });
    var update = { checkedOutBy: userId, checkedOutAt: new Date() };
    Report.update({ _id: { $in: ids } }, update, { multi: true }, callback);
  });
}

// load a batch for user
Report.loadBatch = function(userId, limit, callback) {
  var conditions = {
    checkedOutAt: { $ne: null },
    checkedOutBy: userId
  };

  Report.find(conditions).limit(limit).exec(callback);
}

// helpers

function timeAgo(miliseconds) {
  var now = new Date();
  return new Date(now.getTime() - miliseconds);
}

module.exports = Report;
<|endoftext|>


<commit_before>var Base = require('./base.js').Base;
var util = require("util");
var utils = require('../libs/utils.js');
var errors = require('./errors.js');
var validator = require('../libs/schemas/validator');
var settings = require('../settings.js');
var redis = require('../libs/redis-client');
var log = require('czagenda-log').from(__filename);
var async = require('async');

function Schema() {
	this._attributs = {
		schema : null,
		'final' : false,
		sample : null,
		template : null,
		status : this.constructor.PROPOSAL,
		name : null,
		"description" : null,
		author : null
	};
	Base.call(this, 'schema');
}

Schema.REFUSED = 'REFUSED';
Schema.PROPOSAL = 'PROPOSAL';
Schema.APPROVED = 'APPROVED';

util.inherits(Schema, Base);

Schema.publicAttributes = Base.publicAttributes.concat(['schema', 'final', 'sample', 'template', 'status', 'name', 'author']);
Schema.staffAttributes = Schema.publicAttributes.concat(Base.staffAttributes);
Schema.metaAttributes = ['schema'];

Schema.publicWriteAttributes = ['schema', 'name', 'sample', 'template'];
Schema.staffWriteAttributes = Schema.publicWriteAttributes.concat(['final', 'status', 'name']);

Schema.prototype._findMissingDependencies = function(schema, env) {

	var deps = [];

	for(k in schema) {

		var testValue = schema[k];

		if(k === '$ref' || (k === 'href' && typeof (testValue) === 'string')) {

			if( typeof (env.findSchema(schema[k])) === 'undefined') {
				deps.push(schema[k]);
			}

		} else if(( testValue instanceof Array) === true) {

			for(var i = 0, l = testValue.length; i < l; i++) {
				if((testValue[i] instanceof Object) === true) {
					deps = deps.concat(this._findMissingDependencies(testValue[i], env));
				}
			}

		} else if(( testValue instanceof Object) === true) {
			deps = deps.concat(this._findMissingDependencies(testValue, env));
		}

	}

	return deps;
}

Schema.prototype._validate = function(callback) {

	this.validateString('name', false, null, 64);
	this.validateBoolean('final', false);
	this.validateString('sample', true, null, null);
	this.validateString('template', true, null, null);
	this.validateChoice('status', [Schema.REFUSED, Schema.PROPOSAL, Schema.APPROVED]);

	this.validateNotEmptyObject('schema');

	// validate schema with user environment (include user's schema with status proposal')
	if(this.status === Schema.PROPOSAL) {
		var userEnv = new validator.ValidatorEnvironment();
		userEnv.load( function(err, res) {
			if(err !== null) {
				log.warning('Unable to load ValidatorEnvironment for user ' + this.author, err);
				callback(err);
			} else {
				var veSchema = userEnv.getEnv().findSchema(userEnv.getEnv().getOption("latestJSONSchemaSchemaURI"));
				var report = veSchema.validate(this.schema);
				if(report.errors.length > 0) {
					this.parseJSVErrors(report.errors);
				} else {

					var missing = this._findMissingDependencies(this.schema, userEnv.getEnv());
					if(missing.length > 0) {
						this.addGlobalValidationError("Missing schema dependencies: " + missing.join(' ,'));
						callback(null);
						return;
					}

				}

				callback(null);
			}

		}.bind(this), this.author);

	} else {
		var veSchema = validator.approvedEnvironment.getEnv().findSchema(validator.approvedEnvironment.getEnv().getOption("latestJSONSchemaSchemaURI"));
		var report = veSchema.validate(this.schema);
		if(report.errors.length > 0) {
			this.parseJSVErrors(report.errors);
		} else {

			var missing = this._findMissingDependencies(this.schema, validator.approvedEnvironment.getEnv());
			if(missing.length > 0) {
				this.addGlobalValidationError("Missing schema dependencies: " + missing.join(' ,'));
				callback(null);
				return;
			}

		}
		callback(null);
	}

}

Schema.prototype._generateHash = function() {

	c = require('crypto')
	h = c.createHash('md5')
	h.update(this._type);
	h.update(this['final'] === true ? 'true':'false');
	h.update(JSON.stringify(this.schema));
	this._data['hash'] = h.digest('hex')

}

Schema.prototype._generateId = function() {
	return '/schema/' + utils.slugify(this.name + " " + (this['final'] === true ? "" : "abstract"));
}
/*
Schema.prototype.save = function(callback) {

	if( typeof (this.name) !== 'string') {
		this.addValidationError('name', 'a string is required')
		callback(new errors.ValidationError(), this);
		return;
	}

	Base.prototype.save.call(this, callback);

}
*/
Schema.prototype.__deleteKey = function(key, broadcast, callback) {

	redis.redisClient.srem(key, this.id, function(err, res) {

		if(err !== null) {
			log.critical('REDIS SCHEMAS: error on sdel ', key, this.id, err)
		} else if(res === 1 && broadcast === true) {
			// braodcast
		}

		callback(err);

	}.bind(this))
}

Schema.prototype.__addKey = function(key, broadcast, callback) {
	log.debug('REDIS SCHEMAS: add key ' + key + ' ' + this.id)
	redis.redisClient.sadd(key, this.id, function(err, res) {

		if(err !== null) {
			log.critical('REDIS SCHEMAS: error on sadd ', key, this.id, err)
		} else if(res === 1 && broadcast === true) {
			// braodcast
		}

		callback(err);

	}.bind(this))
}

Schema.prototype.__getRedisSchemasTasks = function () {
	var methods = [];

	if(this.status === Schema.APPROVED) {
		// approved => supprimer userId proposal + ajouter dans approved
		methods.push(this.__addKey.bind(this, redis.SCHEMA_APPROVED, true));
		methods.push(this.__deleteKey.bind(this, redis.PREFIX_SCHEMA_PROPOSAL + this.author, false));

	} else if(this.status === Schema.PROPOSAL) {
		// proposal => ajouter dans userId proposal + supprimer dans approved
		methods.push(this.__deleteKey.bind(this, redis.SCHEMA_APPROVED, true));
		methods.push(this.__addKey.bind(this, redis.PREFIX_SCHEMA_PROPOSAL + this.author, false));

	} else if(this.status === Schema.REFUSED) {
		// refused => this._postDel
		methods.push(this.__deleteKey.bind(this, redis.SCHEMA_APPROVED, true));
		methods.push(this.__deleteKey.bind(this, redis.PREFIX_SCHEMA_PROPOSAL + this.author, false));
	}

	return methods;
}

Schema.prototype._postSave = function(err, next) {

	if (err === null) {

		async.parallel(this.__getRedisSchemasTasks(), function () {
			next();
		})

	} else {
		next();
	}
}

Schema.prototype._preDel = function(callback) {

	var methods = [];

	methods.push(this.__deleteKey.bind(this,redis.SCHEMA_APPROVED, true));
	methods.push(this.__deleteKey.bind(this,redis.PREFIX_SCHEMA_PROPOSAL + this.author, false));

	async.parallel(methods, function (err) {
		if (typeof(err) !== 'undefined' && err !== null) {
			callback(new errors.InternalError('Error when trying to remove or add key in redis'));
		} else {
			callback(null);
		}

	});

}

Schema.prototype._postDel = function(err, next) {
	if (err === null || err instanceof errors.ObjectDoesNotExist) {
		next();
	} else {
		// restore redis
		async.parallel(this.__getRedisSchemasTasks(), function () {
			next();
		})
	}

}

Schema.get = function(options, callback) {
	Base.get(options, Schema, callback)
}

Schema.search = function(query, attrs, callback) {
	Base.search(query, settings.elasticsearch.index, 'schema', attrs, Schema, callback)
}

Schema.count = function(query, callback) {
	Base.count(query, settings.elasticsearch.index, 'schema', callback)
}

exports.Schema = Schema;
<commit_msg>add schema perms<commit_after>var Base = require('./base.js').Base;
var util = require("util");
var utils = require('../libs/utils.js');
var errors = require('./errors.js');
var validator = require('../libs/schemas/validator');
var settings = require('../settings.js');
var redis = require('../libs/redis-client');
var log = require('czagenda-log').from(__filename);
var async = require('async');

function Schema() {
	this._attributs = {
		schema : null,
		'final' : false,
		sample : null,
		template : null,
		status : this.constructor.PROPOSAL,
		name : null,
		"description" : null,
		author : null
	};
	Base.call(this, 'schema');
}

Schema.REFUSED = 'REFUSED';
Schema.PROPOSAL = 'PROPOSAL';
Schema.APPROVED = 'APPROVED';

util.inherits(Schema, Base);

Schema.publicAttributes = Base.publicAttributes.concat(['schema', 'final', 'sample', 'template', 'status', 'name', 'author']);
Schema.staffAttributes = Schema.publicAttributes.concat(Base.staffAttributes);
Schema.metaAttributes = ['schema'];

Schema.publicWriteAttributes = ['schema', 'name', 'sample', 'template'];
Schema.staffWriteAttributes = Schema.publicWriteAttributes.concat(['final', 'status', 'name']);

Schema.prototype.hasPerm = function (perm, user, callback) {

	switch (perm) {
		case 'create':
		case 'read':
			callback(null, true);
			break;

		case 'write':
		case 'del':
			callback(null, this.status !== Schema.APPROVED && (user.isStaff === true || user.isSuperuser === true || user.id === this.author));
			break;

		default:
			return false;

	}
}

Schema.prototype._findMissingDependencies = function(schema, env) {

	var deps = [];

	for(k in schema) {

		var testValue = schema[k];

		if(k === '$ref' || (k === 'href' && typeof (testValue) === 'string')) {

			if( typeof (env.findSchema(schema[k])) === 'undefined') {
				deps.push(schema[k]);
			}

		} else if(( testValue instanceof Array) === true) {

			for(var i = 0, l = testValue.length; i < l; i++) {
				if((testValue[i] instanceof Object) === true) {
					deps = deps.concat(this._findMissingDependencies(testValue[i], env));
				}
			}

		} else if(( testValue instanceof Object) === true) {
			deps = deps.concat(this._findMissingDependencies(testValue, env));
		}

	}

	return deps;
}

Schema.prototype._validate = function(callback) {

	this.validateString('name', false, null, 64);
	this.validateBoolean('final', false);
	this.validateString('sample', true, null, null);
	this.validateString('template', true, null, null);
	this.validateChoice('status', [Schema.REFUSED, Schema.PROPOSAL, Schema.APPROVED]);

	this.validateNotEmptyObject('schema');

	// validate schema with user environment (include user's schema with status proposal')
	if(this.status === Schema.PROPOSAL) {
		var userEnv = new validator.ValidatorEnvironment();
		userEnv.load( function(err, res) {
			if(err !== null) {
				log.warning('Unable to load ValidatorEnvironment for user ' + this.author, err);
				callback(err);
			} else {
				var veSchema = userEnv.getEnv().findSchema(userEnv.getEnv().getOption("latestJSONSchemaSchemaURI"));
				var report = veSchema.validate(this.schema);
				if(report.errors.length > 0) {
					this.parseJSVErrors(report.errors);
				} else {

					var missing = this._findMissingDependencies(this.schema, userEnv.getEnv());
					if(missing.length > 0) {
						this.addGlobalValidationError("Missing schema dependencies: " + missing.join(' ,'));
						callback(null);
						return;
					}

				}

				callback(null);
			}

		}.bind(this), this.author);

	} else {
		var veSchema = validator.approvedEnvironment.getEnv().findSchema(validator.approvedEnvironment.getEnv().getOption("latestJSONSchemaSchemaURI"));
		var report = veSchema.validate(this.schema);
		if(report.errors.length > 0) {
			this.parseJSVErrors(report.errors);
		} else {

			var missing = this._findMissingDependencies(this.schema, validator.approvedEnvironment.getEnv());
			if(missing.length > 0) {
				this.addGlobalValidationError("Missing schema dependencies: " + missing.join(' ,'));
				callback(null);
				return;
			}

		}
		callback(null);
	}

}

Schema.prototype._generateHash = function() {

	c = require('crypto')
	h = c.createHash('md5')
	h.update(this._type);
	h.update(this['final'] === true ? 'true':'false');
	h.update(JSON.stringify(this.schema));
	this._data['hash'] = h.digest('hex')

}

Schema.prototype._generateId = function() {
	return '/schema/' + utils.slugify(this.name + " " + (this['final'] === true ? "" : "abstract"));
}
/*
Schema.prototype.save = function(callback) {

	if( typeof (this.name) !== 'string') {
		this.addValidationError('name', 'a string is required')
		callback(new errors.ValidationError(), this);
		return;
	}

	Base.prototype.save.call(this, callback);

}
*/
Schema.prototype.__deleteKey = function(key, broadcast, callback) {

	redis.redisClient.srem(key, this.id, function(err, res) {

		if(err !== null) {
			log.critical('REDIS SCHEMAS: error on sdel ', key, this.id, err)
		} else if(res === 1 && broadcast === true) {
			// braodcast
		}

		callback(err);

	}.bind(this))
}

Schema.prototype.__addKey = function(key, broadcast, callback) {
	log.debug('REDIS SCHEMAS: add key ' + key + ' ' + this.id)
	redis.redisClient.sadd(key, this.id, function(err, res) {

		if(err !== null) {
			log.critical('REDIS SCHEMAS: error on sadd ', key, this.id, err)
		} else if(res === 1 && broadcast === true) {
			// braodcast
		}

		callback(err);

	}.bind(this))
}

Schema.prototype.__getRedisSchemasTasks = function () {
	var methods = [];

	if(this.status === Schema.APPROVED) {
		// approved => supprimer userId proposal + ajouter dans approved
		methods.push(this.__addKey.bind(this, redis.SCHEMA_APPROVED, true));
		methods.push(this.__deleteKey.bind(this, redis.PREFIX_SCHEMA_PROPOSAL + this.author, false));

	} else if(this.status === Schema.PROPOSAL) {
		// proposal => ajouter dans userId proposal + supprimer dans approved
		methods.push(this.__deleteKey.bind(this, redis.SCHEMA_APPROVED, true));
		methods.push(this.__addKey.bind(this, redis.PREFIX_SCHEMA_PROPOSAL + this.author, false));

	} else if(this.status === Schema.REFUSED) {
		// refused => this._postDel
		methods.push(this.__deleteKey.bind(this, redis.SCHEMA_APPROVED, true));
		methods.push(this.__deleteKey.bind(this, redis.PREFIX_SCHEMA_PROPOSAL + this.author, false));
	}

	return methods;
}

Schema.prototype._postSave = function(err, next) {

	if (err === null) {

		async.parallel(this.__getRedisSchemasTasks(), function () {
			next();
		})

	} else {
		next();
	}
}

Schema.prototype._preDel = function(callback) {

	var methods = [];

	methods.push(this.__deleteKey.bind(this,redis.SCHEMA_APPROVED, true));
	methods.push(this.__deleteKey.bind(this,redis.PREFIX_SCHEMA_PROPOSAL + this.author, false));

	async.parallel(methods, function (err) {
		if (typeof(err) !== 'undefined' && err !== null) {
			callback(new errors.InternalError('Error when trying to remove or add key in redis'));
		} else {
			callback(null);
		}

	});

}

Schema.prototype._postDel = function(err, next) {
	if (err === null || err instanceof errors.ObjectDoesNotExist) {
		next();
	} else {
		// restore redis
		async.parallel(this.__getRedisSchemasTasks(), function () {
			next();
		})
	}

}

Schema.get = function(options, callback) {
	Base.get(options, Schema, callback)
}

Schema.search = function(query, attrs, callback) {
	Base.search(query, settings.elasticsearch.index, 'schema', attrs, Schema, callback)
}

Schema.count = function(query, callback) {
	Base.count(query, settings.elasticsearch.index, 'schema', callback)
}

exports.Schema = Schema;
<|endoftext|>


<commit_before>var modCommon = {

  getFatigue: function(creep){
    var body = creep.body;
    var nonMoveCount = 0;
    var moveCount = 0;
    var total = 0;
    for(var limb in body){
      if(limb.type === MOVE){
        moveCount++;
        total++;
      }else{
        nonMoveCount++;
        total++;
      }
    }
    return 2*(nonMoveCount * 0.5 - moveCount);

  },

  distTo: function(creep, pos){
    var x = creep.pos.x - pos.x;
    var y = creep.pos.y - pos.y;
    var xSquared = x * x;
    var ySquared = y * y;
    var root = xSquared + ySquared;
    var dist = Math.sqrt(root);
    return dist;
  },

  //Gets energy from availible locations, including sources
  //if it can self harvest but at a lower priority
  getEn: function(creep){
    var maxTicks = 50;
    //Priority 1 is dropped energy, since it detiorates
    var dropped = creep.pos.findClosestByPath(FIND_DROPPED_ENERGY);
    if(dropped && dropped.resourceType === RESOURCE_ENERGY){
      var dist;
      var fat;
      var worth = 2;
      dist = this.distTo(creep, dropped.pos);
      fat = this.getFatigue(creep);
      worth = (dist * fat) / maxTicks;
      if(dropped && worth<=1){
        if(creep.pickup(dropped)== ERR_NOT_IN_RANGE){
          modCommon.move(creep,dropped.pos);
        }else{
          creep.memory.path = null;
        }
      }
    }else{
      //Next priority is the closest container or storage
      var storage = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        filter: (object)=>((object.structureType === STRUCTURE_CONTAINER) || (object.structureType === STRUCTURE_STORAGE)) && (object.store[RESOURCE_ENERGY] > creep.carryCapacity)
      });
      if(storage!==null){
        var getEnergy = creep.withdraw(storage, RESOURCE_ENERGY, creep.carryCapacity-creep.carry);
        if(getEnergy===ERR_NOT_IN_RANGE) {
            modCommon.move(creep, storage);
        }else{
          creep.memory.path = null;
        }
      //Finally, the creep will harvest if it can
      }else if(creep.memory.selfHarvest){
        var sources = creep.room.find(FIND_SOURCES);
        if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
          modCommon.move(creep, sources[0]);
        }else{
          creep.memory.path = null;
        }
      }
    }
  },

  //Function to remove 'dead' creeps from the memory to conserve space
  clearDead: function(){
    for(var i in Memory.creeps) {
      if(!Game.creeps[i]) {
          var job = Memory.creeps[i].role;
          this.decrementNum(job);
          delete Memory.creeps[i];
      }
    }
  },

  decrementNum:function(creepType){
    if(creepType==="harvester"){
      --Memory.roles.numHarvesters;
    }else if(creepType === "upgrader"){
      --Memory.roles.numUpgraders;
    }else if(creepType === "builder"){
      --Memory.roles.numBuilders;
    }else if(creepType === "repair"){
      --Memory.roles.numRepair;
    }else if (creepType === "architect"){
      --Memory.roles.numArchitects;
    }else if(creepType === "miner"){
      --Memory.roles.numMiners;
    }else if(creepType === "hauler"){
      --Memory.roles.numHaulers;
    }else if(creepType === "feeder"){
      --Memory.roles.numFeeders;
    }else if(creepType === "geo"){
      --Memory.roles.numGeo;
    }else if(creepType === "geoH"){
      --Memory.roles.numGeoH;
    }else if(creepType === "merchant"){
      --Memory.roles.numMerchant;
    }
    --Memory.roles.numCreeps;
  },

  //Method to find the next structure to repair, shared by repair creeps and towers
  findToFixArr: function(room){
    var controlLvl = room.controller.level;
    var modifier = Math.max(Math.pow(10,controlLvl-3),10);
    var buffer = 1000;
    var roomBuffer = 300000;

    var fixeArrPriority = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < 3000);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < 5000)&& (object.hitsMax-object.hits>0);
      var brokenCont = object.structureType ===STRUCTURE_CONTAINER && (object.hits < 100000);
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp || brokenCont || brokenWall;
    }});

    var fixeArr = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < object.hitsMax/2);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+buffer))&& (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp;
    }});

    var fixeArr2 = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+buffer)) && (object.hitsMax-object.hits>0);
      return brokenWall;
    }});

    if(room.storage.energy < roomBuffer || fixeArrPriority.length>0){
      return fixeArrPriority;
    }else if(fixeArr.length>0){
      return fixeArr;
    }else {
      return fixeArr2;
    }
    return NULL;
  },

  findToFortify: function(room){
    // use  '|| object.structureType ===STRUCTURE_RAMPART' ?
    var fortArr = room.find(FIND_STRUCTURES, {filter: function(object){
      return (object.structureType ===STRUCTURE_WALL || object.structureType === STRUCTURE_RAMPART) && (object.hits < 100000) && (object.hitsMax-object.hits>0);
    }});

    return fortArr;
  },

  //Function to run away and hide
  retreat: function(creep){
    this.move(creep, creep.room.controller.pos);
    creep.say("HELP ME!");
  },

  //Function to move useing a stored path
  move:function(creep,pos){
    var emptyPath = false;
    var creepPath = creep.memory.path;
    var destX = -1;
    var destY = -1;
    var lastObj = null;
    if(creepPath && creepPath.length>0){
      var index = creepPath.length-1;
      lastObj = creepPath[index];
      destX = lastObj.x + lastObj.dx;
      destY = lastObj.y + lastObj.dy;
    }else{
      emptyPath = true;
    }

    if(emptyPath || (lastObj && (pos.x !== destX || pos.y !== destY))){
      creep.memory.path = creep.pos.findPathTo(pos);
    }
    creep.moveByPath(creep.memory.path);
  },

  playerAttack:function(allCreepList){
    //priority Targets
    var pTargets = _.filter(allCreepList, (creep) => (creep.owner && !( creep.owner.username == "PCarton" || creep.owner.username == 'Invader')));
    return pTargets.length;
  },

  findInjured:function(allCreepList){
    var hTargets = _.filter(allCreepList, (creep) => creep.hits<creep.hitsMax && creep.owner.username === "PCarton");
    //TODO sort by a priority
    return hTargets;
  },

  whatCarry:function(creep){
    var resourceType;

    var creepCarry = creep.carry;
    if(creepCarry.energy>0){
      resourceType = RESOURCE_ENERGY;
    }else if(creepCarry.power>0){
      resourceType = RESOURCE_POWER;
    }else if(creepCarry.H>0){
      resourceType = RESOURCE_HYDROGEN;
    }else if(creepCarry.O>0){
      resourceType = RESOURCE_OXYGEN;
    }else if(creepCarry.U>0){
      resourceType = RESOURCE_UTRIUM;
    }else if(creepCarry.L>0){
      resourceType = RESOURCE_LEMERGIUM;
    }else if(creepCarry.K>0){
      resourceType = RESOURCE_KEANIUM;
    }else if(creepCarry.Z>0){
      resourceType = RESOURCE_ZYNTHIUM;
    }else if(creepCarry.X>0){
      resourceType = RESOURCE_CATALYST;
    }else if(creepCarry.G>0){
      resourceType = RESOURCE_GHODIUM;
    }else{
      resourceType = RESOURCE_ENERGY;
    }

    return resourceType;
  },

  whatStore:function(struct){
    var resourceType;

    var structStore = struct.store;
    if(structStore.power>0){
      resourceType = RESOURCE_POWER;
    }else if(structStore.H>0){
      resourceType = RESOURCE_HYDROGEN;
    }else if(structStore.O>0){
      resourceType = RESOURCE_OXYGEN;
    }else if(structStore.U>0){
      resourceType = RESOURCE_UTRIUM;
    }else if(structStore.L>0){
      resourceType = RESOURCE_LEMERGIUM;
    }else if(structStore.K>0){
      resourceType = RESOURCE_KEANIUM;
    }else if(structStore.Z>0){
      resourceType = RESOURCE_ZYNTHIUM;
    }else if(structStore.X>0){
      resourceType = RESOURCE_CATALYST;
    }else if(structStore.G>0){
      resourceType = RESOURCE_GHODIUM;
    }else{
      resourceType = RESOURCE_ENERGY;
    }

    return resourceType;
  },

  getResourceCount:function(storeObj, resourceType){
    var count;
    switch(resourceType){
      case RESOURCE_ENERGY:
        count = storeObj.energy;
        break;
      case RESOURCE_POWER:
        count = storeObj.power;
        break;
      case RESOURCE_HYDROGEN:
        count = storeObj.H;
        break;
      case RESOURCE_OXYGEN:
        count = storeObj.O;
        break;
      case RESOURCE_UTRIUM:
        count = storeObj.U;
        break;
      case RESOURCE_LEMERGIUM:
        count = storeObj.L;
        break;
      case RESOURCE_KEANIUM:
        count = storeObj.K;
        break;
      case RESOURCE_ZYNTHIUM:
        count = storeObj.Z;
        break;
      case RESOURCE_CATALYST:
        count = storeObj.X;
        break;
      case RESOURCE_GHODIUM:
        count = storeObj.G;
        break;
      default:
        count = 0;
    }
    return count;
  },
  //TODO Emergency upgrade logic

  //TODO link to history page for the room at given tick
  //Formated as https://screeps.com/a/#!/history/E33N43?t=15527000
  linkRoomAtTick:function(room,tick,msg){
    return ""+msg+"";
  }

};

module.exports = modCommon;
<commit_msg>fixed getting amount of energy in storage<commit_after>var modCommon = {

  getFatigue: function(creep){
    var body = creep.body;
    var nonMoveCount = 0;
    var moveCount = 0;
    var total = 0;
    for(var limb in body){
      if(limb.type === MOVE){
        moveCount++;
        total++;
      }else{
        nonMoveCount++;
        total++;
      }
    }
    return 2*(nonMoveCount * 0.5 - moveCount);

  },

  distTo: function(creep, pos){
    var x = creep.pos.x - pos.x;
    var y = creep.pos.y - pos.y;
    var xSquared = x * x;
    var ySquared = y * y;
    var root = xSquared + ySquared;
    var dist = Math.sqrt(root);
    return dist;
  },

  //Gets energy from availible locations, including sources
  //if it can self harvest but at a lower priority
  getEn: function(creep){
    var maxTicks = 50;
    //Priority 1 is dropped energy, since it detiorates
    var dropped = creep.pos.findClosestByPath(FIND_DROPPED_ENERGY);
    if(dropped && dropped.resourceType === RESOURCE_ENERGY){
      var dist;
      var fat;
      var worth = 2;
      dist = this.distTo(creep, dropped.pos);
      fat = this.getFatigue(creep);
      worth = (dist * fat) / maxTicks;
      if(dropped && worth<=1){
        if(creep.pickup(dropped)== ERR_NOT_IN_RANGE){
          modCommon.move(creep,dropped.pos);
        }else{
          creep.memory.path = null;
        }
      }
    }else{
      //Next priority is the closest container or storage
      var storage = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        filter: (object)=>((object.structureType === STRUCTURE_CONTAINER) || (object.structureType === STRUCTURE_STORAGE)) && (object.store[RESOURCE_ENERGY] > creep.carryCapacity)
      });
      if(storage!==null){
        var getEnergy = creep.withdraw(storage, RESOURCE_ENERGY, creep.carryCapacity-creep.carry);
        if(getEnergy===ERR_NOT_IN_RANGE) {
            modCommon.move(creep, storage);
        }else{
          creep.memory.path = null;
        }
      //Finally, the creep will harvest if it can
      }else if(creep.memory.selfHarvest){
        var sources = creep.room.find(FIND_SOURCES);
        if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
          modCommon.move(creep, sources[0]);
        }else{
          creep.memory.path = null;
        }
      }
    }
  },

  //Function to remove 'dead' creeps from the memory to conserve space
  clearDead: function(){
    for(var i in Memory.creeps) {
      if(!Game.creeps[i]) {
          var job = Memory.creeps[i].role;
          this.decrementNum(job);
          delete Memory.creeps[i];
      }
    }
  },

  decrementNum:function(creepType){
    if(creepType==="harvester"){
      --Memory.roles.numHarvesters;
    }else if(creepType === "upgrader"){
      --Memory.roles.numUpgraders;
    }else if(creepType === "builder"){
      --Memory.roles.numBuilders;
    }else if(creepType === "repair"){
      --Memory.roles.numRepair;
    }else if (creepType === "architect"){
      --Memory.roles.numArchitects;
    }else if(creepType === "miner"){
      --Memory.roles.numMiners;
    }else if(creepType === "hauler"){
      --Memory.roles.numHaulers;
    }else if(creepType === "feeder"){
      --Memory.roles.numFeeders;
    }else if(creepType === "geo"){
      --Memory.roles.numGeo;
    }else if(creepType === "geoH"){
      --Memory.roles.numGeoH;
    }else if(creepType === "merchant"){
      --Memory.roles.numMerchant;
    }
    --Memory.roles.numCreeps;
  },

  //Method to find the next structure to repair, shared by repair creeps and towers
  findToFixArr: function(room){
    var controlLvl = room.controller.level;
    var modifier = Math.max(Math.pow(10,controlLvl-3),10);
    var buffer = 1000;
    var roomBuffer = 300000;

    var fixeArrPriority = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < 3000);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < 5000)&& (object.hitsMax-object.hits>0);
      var brokenCont = object.structureType ===STRUCTURE_CONTAINER && (object.hits < 100000);
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp || brokenCont || brokenWall;
    }});

    var fixeArr = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < object.hitsMax/2);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+buffer))&& (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp;
    }});

    var fixeArr2 = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+buffer)) && (object.hitsMax-object.hits>0);
      return brokenWall;
    }});

    if(room.storage.store.energy < roomBuffer || fixeArrPriority.length>0){
      return fixeArrPriority;
    }else if(fixeArr.length>0){
      return fixeArr;
    }else {
      return fixeArr2;
    }
    return NULL;
  },

  findToFortify: function(room){
    // use  '|| object.structureType ===STRUCTURE_RAMPART' ?
    var fortArr = room.find(FIND_STRUCTURES, {filter: function(object){
      return (object.structureType ===STRUCTURE_WALL || object.structureType === STRUCTURE_RAMPART) && (object.hits < 100000) && (object.hitsMax-object.hits>0);
    }});

    return fortArr;
  },

  //Function to run away and hide
  retreat: function(creep){
    this.move(creep, creep.room.controller.pos);
    creep.say("HELP ME!");
  },

  //Function to move useing a stored path
  move:function(creep,pos){
    var emptyPath = false;
    var creepPath = creep.memory.path;
    var destX = -1;
    var destY = -1;
    var lastObj = null;
    if(creepPath && creepPath.length>0){
      var index = creepPath.length-1;
      lastObj = creepPath[index];
      destX = lastObj.x + lastObj.dx;
      destY = lastObj.y + lastObj.dy;
    }else{
      emptyPath = true;
    }

    if(emptyPath || (lastObj && (pos.x !== destX || pos.y !== destY))){
      creep.memory.path = creep.pos.findPathTo(pos);
    }
    creep.moveByPath(creep.memory.path);
  },

  playerAttack:function(allCreepList){
    //priority Targets
    var pTargets = _.filter(allCreepList, (creep) => (creep.owner && !( creep.owner.username == "PCarton" || creep.owner.username == 'Invader')));
    return pTargets.length;
  },

  findInjured:function(allCreepList){
    var hTargets = _.filter(allCreepList, (creep) => creep.hits<creep.hitsMax && creep.owner.username === "PCarton");
    //TODO sort by a priority
    return hTargets;
  },

  whatCarry:function(creep){
    var resourceType;

    var creepCarry = creep.carry;
    if(creepCarry.energy>0){
      resourceType = RESOURCE_ENERGY;
    }else if(creepCarry.power>0){
      resourceType = RESOURCE_POWER;
    }else if(creepCarry.H>0){
      resourceType = RESOURCE_HYDROGEN;
    }else if(creepCarry.O>0){
      resourceType = RESOURCE_OXYGEN;
    }else if(creepCarry.U>0){
      resourceType = RESOURCE_UTRIUM;
    }else if(creepCarry.L>0){
      resourceType = RESOURCE_LEMERGIUM;
    }else if(creepCarry.K>0){
      resourceType = RESOURCE_KEANIUM;
    }else if(creepCarry.Z>0){
      resourceType = RESOURCE_ZYNTHIUM;
    }else if(creepCarry.X>0){
      resourceType = RESOURCE_CATALYST;
    }else if(creepCarry.G>0){
      resourceType = RESOURCE_GHODIUM;
    }else{
      resourceType = RESOURCE_ENERGY;
    }

    return resourceType;
  },

  whatStore:function(struct){
    var resourceType;

    var structStore = struct.store;
    if(structStore.power>0){
      resourceType = RESOURCE_POWER;
    }else if(structStore.H>0){
      resourceType = RESOURCE_HYDROGEN;
    }else if(structStore.O>0){
      resourceType = RESOURCE_OXYGEN;
    }else if(structStore.U>0){
      resourceType = RESOURCE_UTRIUM;
    }else if(structStore.L>0){
      resourceType = RESOURCE_LEMERGIUM;
    }else if(structStore.K>0){
      resourceType = RESOURCE_KEANIUM;
    }else if(structStore.Z>0){
      resourceType = RESOURCE_ZYNTHIUM;
    }else if(structStore.X>0){
      resourceType = RESOURCE_CATALYST;
    }else if(structStore.G>0){
      resourceType = RESOURCE_GHODIUM;
    }else{
      resourceType = RESOURCE_ENERGY;
    }

    return resourceType;
  },

  getResourceCount:function(storeObj, resourceType){
    var count;
    switch(resourceType){
      case RESOURCE_ENERGY:
        count = storeObj.energy;
        break;
      case RESOURCE_POWER:
        count = storeObj.power;
        break;
      case RESOURCE_HYDROGEN:
        count = storeObj.H;
        break;
      case RESOURCE_OXYGEN:
        count = storeObj.O;
        break;
      case RESOURCE_UTRIUM:
        count = storeObj.U;
        break;
      case RESOURCE_LEMERGIUM:
        count = storeObj.L;
        break;
      case RESOURCE_KEANIUM:
        count = storeObj.K;
        break;
      case RESOURCE_ZYNTHIUM:
        count = storeObj.Z;
        break;
      case RESOURCE_CATALYST:
        count = storeObj.X;
        break;
      case RESOURCE_GHODIUM:
        count = storeObj.G;
        break;
      default:
        count = 0;
    }
    return count;
  },
  //TODO Emergency upgrade logic

  //TODO link to history page for the room at given tick
  //Formated as https://screeps.com/a/#!/history/E33N43?t=15527000
  linkRoomAtTick:function(room,tick,msg){
    return ""+msg+"";
  }

};

module.exports = modCommon;
<|endoftext|>


<commit_before>var modConstants = require('module.constants');

var modCommon = {

  getFatigue: function(creep){
    var body = creep.body;
    var nonMoveCount = 0;
    var moveCount = 0;
    var total = 0;
    for(var limb in body){
      if(limb.type === MOVE){
        moveCount++;
        total++;
      }else{
        nonMoveCount++;
        total++;
      }
    }
    return 2*(nonMoveCount * 0.5 - moveCount);

  },

  distTo: function(creep, pos){
    var x = creep.pos.x - pos.x;
    var y = creep.pos.y - pos.y;
    var xSquared = x * x;
    var ySquared = y * y;
    var root = xSquared + ySquared;
    var dist = Math.sqrt(root);
    return dist;
  },

  //Gets energy from availible locations, including sources
  //if it can self harvest but at a lower priority
  getEn: function(creep){
    var maxTicks = 50;
    //Priority 1 is dropped energy, since it detiorates
    //TODO find why creeps will pick up compounds
    var dropped = creep.pos.findClosestByPath(FIND_DROPPED_RESOURCES);
    if(dropped && dropped.resourceType === RESOURCE_ENERGY){
      var dist;
      var fat;
      var worth = 2;
      dist = this.distTo(creep, dropped.pos);
      fat = this.getFatigue(creep);
      worth = (dist * fat) / maxTicks;
      if(dropped && worth<=1){
        if(creep.pickup(dropped)== ERR_NOT_IN_RANGE){
          modCommon.move(creep,dropped.pos);
        }else{
          creep.memory.path = null;
        }
      }
      return;
    }
    //Next priority is the closest container or storage
    var storage = creep.pos.findClosestByPath(FIND_STRUCTURES, {
      filter: (object)=>((object.structureType === STRUCTURE_CONTAINER) || (object.structureType === STRUCTURE_STORAGE)) && (object.store[RESOURCE_ENERGY] > creep.carryCapacity)
    });
    if(storage!==null){
      var getEnergy = creep.withdraw(storage, RESOURCE_ENERGY, creep.carryCapacity-creep.carry);
      if(getEnergy===ERR_NOT_IN_RANGE) {
          modCommon.move(creep, storage);
      }else{
        creep.memory.path = null;
      }
    //Finally, the creep will harvest if it can
    }else if(creep.memory.selfHarvest){
      var source = creep.pos.findClosestByPath(FIND_SOURCES);
      if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
        modCommon.move(creep, source);
      }else{
        creep.memory.path = null;
      }
    }
  },

  stillToFix:function(object){
    //Priority
    var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < 3000);
    var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < 5000)&& (object.hitsMax-object.hits>0);
    var brokenCont = object.structureType ===STRUCTURE_CONTAINER && (object.hits < 100000);
    var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
    //Priority 2
    var brokenRamp2 = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+buffer))&& (object.hitsMax-object.hits>0);
    //Lowest Priority
    var brokenWall2 = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+modConstants.structBuffer)) && (object.hitsMax-object.hits>0);

    if(room.storage.store.energy < modConstants.roomEnergyBuffer){
      return brokenRoad || brokenRamp || brokenCont || brokenWall;
    }else if(brokenRamp2){
      return brokenRamp2;
    }else {
      return brokenWall2;
    }
    return false;
  },

  //Method to find the next structure to repair, shared by repair creeps and towers
  findToFixArr: function(room){
    var controlLvl = room.controller.level;
    var modifier = Math.max(Math.pow(10,controlLvl-3),10);
    var buffer = modConstants.structBuffer;

    var fixeArrPriority = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType == STRUCTURE_ROAD && (object.hits < 3000);
      var brokenRamp = object.structureType == STRUCTURE_RAMPART && (object.hits < 5000)&& (object.hitsMax-object.hits>0);
      var brokenCont = object.structureType == STRUCTURE_CONTAINER && (object.hits < 100000);
      var brokenWall = object.structureType == STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp || brokenCont || brokenWall;
    }});

    var fixeArr = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+buffer))&& (object.hitsMax-object.hits>0);
      return brokenRamp;
    }});

    var fixeArr2 = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+modConstants.structBuffer)) && (object.hitsMax-object.hits>0);
      return brokenWall;
    }});

    if((room.storage && room.storage.store.energy < modConstants.roomEnergyBuffer) || fixeArrPriority.length>0){
      return fixeArrPriority;
    }else if(fixeArr.length>0){
      return fixeArr;
    }else {
      return fixeArr2;
    }
    return NULL;
  },

  findToFortify: function(room){
    // use  '|| object.structureType ===STRUCTURE_RAMPART' ?
    var fortArr = room.find(FIND_MY_STRUCTURES, {filter: function(object){
      return (object.structureType ===STRUCTURE_WALL || object.structureType === STRUCTURE_RAMPART) && (object.hits < 100000) && (object.hitsMax-object.hits>0);
    }});

    return fortArr;
  },

  //Function to run away and hide
  retreat: function(creep){
    this.move(creep, creep.room.controller.pos);
    creep.say("HELP ME!");
  },

  //Function to move useing a stored path
  move:function(creep,pos){
    if(creep.pos.x === 0){
      creep.move(RIGHT);
    }else if(creep.pos.x === 49){
      creep.move(LEFT);
    }else if(creep.pos.y === 49){
      creep.move(TOP);
    }else if(creep.pos.y === 0){
      creep.move(BOTTOM);
    }else{
      var roomName;
      var opts = {};
      var posStr = null;
      if(pos.roomName === undefined || pos.x === undefined || pos.y === undefined){
        posStr = null;
      }else{
        posStr = pos.roomName+":"+pos.x+","+pos.y;
        roomName = pos.roomName;
      }
      opts.ignoreCreeps = false;
      opts.serialize = true;
      if(pos.roomName == creep.room.name){
        opts.maxOps = 500;
      }else{
        opts.maxOps = 2000;
      }
      var emptyPath = false;
      var creepPath = creep.memory.path;
      if(!creepPath || creep.memory.dest != posStr || posStr === null){
          creep.memory.path = creep.pos.findPathTo(pos, opts);
          creep.memory.dest = posStr;
      }
      var result = creep.moveByPath(creep.memory.path);
      if(result != OK && result != ERR_TIRED){
        creep.memory.path = null;
        //console.log("Move error: "+result);
      }
      return result;
    }
  },

  playerAttack:function(allCreepList){
    //priority Targets
    var pTargets = _.filter(allCreepList, (creep) => !creep.my);
    var attackers = [];
    for(var creepName in pTargets){
      var owner = pTargets[creepName].owner.username;
      if(owner != "Invader"){
        var bodies = pTargets[creepName].body;
        var justAttack = _.filter(bodies, (part)=>(part.type==ATTACK || part.type==RANGED_ATTACK));
        if(justAttack.length > 0 && !attackers.includes(owner))
          attackers.push(owner);
      }
    }
    if(attackers.length > 0){
      return attackers[0]; //TODO turn this into a string of all attackers;
    }else{
      return null;
    }
  },

  findInjured:function(allCreepList){
    var hTargets = _.filter(allCreepList, (creep) => creep.hits<creep.hitsMax && creep.owner.username === "PCarton");
    //TODO sort by a priority
    return hTargets;
  },

  whatCarry:function(creep){
    var creepCarry = creep.carry;
    for(var type in creepCarry){
      if(creepCarry[type]>0){
        return type;
      }
    }
    return null;
  },

  whatStore:function(struct){
    var structStore = struct.store;
    for(var type in structStore){
      if(structStore[type]>0){
        return type;
      }
    }
    return null;
  },

  getResourceCount:function(storeObj, resourceType){
    var count;
    if(storeObj){
      count = storeObj[resourceType];
    }
    return count;
  },
  //TODO Emergency upgrade logic

  linkRoomAtTick:function(room,tick,msg){
    //Disables the autolinking
    //See http://support.screeps.com/hc/en-us/community/posts/206652879-Email-links-broken
    let roomName = room.name.replace(/^\w/,"&#"+room.name.charCodeAt(0)+";");

    var link = "http://screeps.com/a/#!/history/"+roomName+"?t="+tick;
    msg = "Room>"+roomName+":"+msg+"@"+tick;
    return ""+msg+"";
  }

};

module.exports = modCommon;
<commit_msg>moved opt setting to when needed a new path<commit_after>var modConstants = require('module.constants');

var modCommon = {

  getFatigue: function(creep){
    var body = creep.body;
    var nonMoveCount = 0;
    var moveCount = 0;
    var total = 0;
    for(var limb in body){
      if(limb.type === MOVE){
        moveCount++;
        total++;
      }else{
        nonMoveCount++;
        total++;
      }
    }
    return 2*(nonMoveCount * 0.5 - moveCount);

  },

  distTo: function(creep, pos){
    var x = creep.pos.x - pos.x;
    var y = creep.pos.y - pos.y;
    var xSquared = x * x;
    var ySquared = y * y;
    var root = xSquared + ySquared;
    var dist = Math.sqrt(root);
    return dist;
  },

  //Gets energy from availible locations, including sources
  //if it can self harvest but at a lower priority
  getEn: function(creep){
    var maxTicks = 50;
    //Priority 1 is dropped energy, since it detiorates
    //TODO find why creeps will pick up compounds
    var dropped = creep.pos.findClosestByPath(FIND_DROPPED_RESOURCES);
    if(dropped && dropped.resourceType === RESOURCE_ENERGY){
      var dist;
      var fat;
      var worth = 2;
      dist = this.distTo(creep, dropped.pos);
      fat = this.getFatigue(creep);
      worth = (dist * fat) / maxTicks;
      if(dropped && worth<=1){
        if(creep.pickup(dropped)== ERR_NOT_IN_RANGE){
          modCommon.move(creep,dropped.pos);
        }else{
          creep.memory.path = null;
        }
      }
      return;
    }
    //Next priority is the closest container or storage
    var storage = creep.pos.findClosestByPath(FIND_STRUCTURES, {
      filter: (object)=>((object.structureType === STRUCTURE_CONTAINER) || (object.structureType === STRUCTURE_STORAGE)) && (object.store[RESOURCE_ENERGY] > creep.carryCapacity)
    });
    if(storage!==null){
      var getEnergy = creep.withdraw(storage, RESOURCE_ENERGY, creep.carryCapacity-creep.carry);
      if(getEnergy===ERR_NOT_IN_RANGE) {
          modCommon.move(creep, storage);
      }else{
        creep.memory.path = null;
      }
    //Finally, the creep will harvest if it can
    }else if(creep.memory.selfHarvest){
      var source = creep.pos.findClosestByPath(FIND_SOURCES);
      if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
        modCommon.move(creep, source);
      }else{
        creep.memory.path = null;
      }
    }
  },

  stillToFix:function(object){
    //Priority
    var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < 3000);
    var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < 5000)&& (object.hitsMax-object.hits>0);
    var brokenCont = object.structureType ===STRUCTURE_CONTAINER && (object.hits < 100000);
    var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
    //Priority 2
    var brokenRamp2 = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+buffer))&& (object.hitsMax-object.hits>0);
    //Lowest Priority
    var brokenWall2 = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+modConstants.structBuffer)) && (object.hitsMax-object.hits>0);

    if(room.storage.store.energy < modConstants.roomEnergyBuffer){
      return brokenRoad || brokenRamp || brokenCont || brokenWall;
    }else if(brokenRamp2){
      return brokenRamp2;
    }else {
      return brokenWall2;
    }
    return false;
  },

  //Method to find the next structure to repair, shared by repair creeps and towers
  findToFixArr: function(room){
    var controlLvl = room.controller.level;
    var modifier = Math.max(Math.pow(10,controlLvl-3),10);
    var buffer = modConstants.structBuffer;

    var fixeArrPriority = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType == STRUCTURE_ROAD && (object.hits < 3000);
      var brokenRamp = object.structureType == STRUCTURE_RAMPART && (object.hits < 5000)&& (object.hitsMax-object.hits>0);
      var brokenCont = object.structureType == STRUCTURE_CONTAINER && (object.hits < 100000);
      var brokenWall = object.structureType == STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
      return brokenRoad || brokenRamp || brokenCont || brokenWall;
    }});

    var fixeArr = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+buffer))&& (object.hitsMax-object.hits>0);
      return brokenRamp;
    }});

    var fixeArr2 = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+modConstants.structBuffer)) && (object.hitsMax-object.hits>0);
      return brokenWall;
    }});

    if((room.storage && room.storage.store.energy < modConstants.roomEnergyBuffer) || fixeArrPriority.length>0){
      return fixeArrPriority;
    }else if(fixeArr.length>0){
      return fixeArr;
    }else {
      return fixeArr2;
    }
    return NULL;
  },

  findToFortify: function(room){
    // use  '|| object.structureType ===STRUCTURE_RAMPART' ?
    var fortArr = room.find(FIND_MY_STRUCTURES, {filter: function(object){
      return (object.structureType ===STRUCTURE_WALL || object.structureType === STRUCTURE_RAMPART) && (object.hits < 100000) && (object.hitsMax-object.hits>0);
    }});

    return fortArr;
  },

  //Function to run away and hide
  retreat: function(creep){
    this.move(creep, creep.room.controller.pos);
    creep.say("HELP ME!");
  },

  //Function to move useing a stored path
  move:function(creep,pos){
    if(creep.pos.x === 0){
      creep.move(RIGHT);
    }else if(creep.pos.x === 49){
      creep.move(LEFT);
    }else if(creep.pos.y === 49){
      creep.move(TOP);
    }else if(creep.pos.y === 0){
      creep.move(BOTTOM);
    }else{
      var opts = {};
      var posStr = null;
      if(pos.roomName === undefined || pos.x === undefined || pos.y === undefined){
        posStr = null;
      }else{
        posStr = pos.roomName+":"+pos.x+","+pos.y;
      }
      var creepPath = creep.memory.path;
      if(!creepPath || creep.memory.dest != posStr || posStr === null){
          opts.ignoreCreeps = false;
          opts.serialize = true;
          if(pos.roomName == creep.room.name){
            opts.maxOps = 1000;
          }else{
            opts.maxOps = 2000;
          }
          creep.memory.path = creep.pos.findPathTo(pos, opts);
          creep.memory.dest = posStr;
      }
      var result = creep.moveByPath(creep.memory.path);
      if(result != OK && result != ERR_TIRED){
        creep.memory.path = null;
        //console.log("Move error: "+result);
      }
      return result;
    }
  },

  playerAttack:function(allCreepList){
    //priority Targets
    var pTargets = _.filter(allCreepList, (creep) => !creep.my);
    var attackers = [];
    for(var creepName in pTargets){
      var owner = pTargets[creepName].owner.username;
      if(owner != "Invader"){
        var bodies = pTargets[creepName].body;
        var justAttack = _.filter(bodies, (part)=>(part.type==ATTACK || part.type==RANGED_ATTACK));
        if(justAttack.length > 0 && !attackers.includes(owner))
          attackers.push(owner);
      }
    }
    if(attackers.length > 0){
      return attackers[0]; //TODO turn this into a string of all attackers;
    }else{
      return null;
    }
  },

  findInjured:function(allCreepList){
    var hTargets = _.filter(allCreepList, (creep) => creep.hits<creep.hitsMax && creep.owner.username === "PCarton");
    //TODO sort by a priority
    return hTargets;
  },

  whatCarry:function(creep){
    var creepCarry = creep.carry;
    for(var type in creepCarry){
      if(creepCarry[type]>0){
        return type;
      }
    }
    return null;
  },

  whatStore:function(struct){
    var structStore = struct.store;
    for(var type in structStore){
      if(structStore[type]>0){
        return type;
      }
    }
    return null;
  },

  getResourceCount:function(storeObj, resourceType){
    var count;
    if(storeObj){
      count = storeObj[resourceType];
    }
    return count;
  },
  //TODO Emergency upgrade logic

  linkRoomAtTick:function(room,tick,msg){
    //Disables the autolinking
    //See http://support.screeps.com/hc/en-us/community/posts/206652879-Email-links-broken
    let roomName = room.name.replace(/^\w/,"&#"+room.name.charCodeAt(0)+";");

    var link = "http://screeps.com/a/#!/history/"+roomName+"?t="+tick;
    msg = "Room>"+roomName+":"+msg+"@"+tick;
    return ""+msg+"";
  }

};

module.exports = modCommon;
<|endoftext|>


<commit_before>var modCommon = {
  //Gets energy from availible locations, including sources
  //if it can self harvest but at a lower priority
  getEn: function(creep){

    var emptyPath = false;
    var creepPath = creep.memory.path;
    var destX = -1;
    var destY = -1;
    var lastObj = null;
    if(creepPath && creepPath.length>0){
     var index = creepPath.length-1;
     lastObj = creepPath[index];
      destX = lastObj.x + lastObj.dx;
      destY = lastObj.y + lastObj.dy;
    }else{
      emptyPath = true;
    }

    var dropped = creep.pos.findClosestByPath(FIND_DROPPED_ENERGY);
    if(dropped){
      if(creep.pickup(dropped)== ERR_NOT_IN_RANGE){
        modCommon.move(creep,dropped.pos);
      }else{
        creep.memory.path = null;
      }
    }else{
      var storage = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        filter: (object)=>((object.structureType === STRUCTURE_CONTAINER) || (object.structureType === STRUCTURE_STORAGE)) && (object.store[RESOURCE_ENERGY] > creep.carryCapacity)
      });
      if(storage!==null){
        var getEnergy = creep.withdraw(storage, RESOURCE_ENERGY, creep.carryCapacity-creep.carry);
        if(getEnergy===ERR_NOT_IN_RANGE) {
          if(emptyPath || (lastObj && (storage.pos.x !== destX || storage.pos.y !== destY))){
            creep.memory.path = creep.pos.findPathTo(storage);
          }
          creep.moveByPath(creep.memory.path);
        }else{
          creep.memory.path = null;
        }
      }else if(creep.memory.selfHarvest){
        var sources = creep.room.find(FIND_SOURCES);
        if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
          if(emptyPath || (lastObj && (sources[0].pos.x !== destX || sources[0].pos.y !== destY))){
            creep.memory.path = creep.pos.findPathTo(sources[0]);
          }
          creep.moveByPath(creep.memory.path);
        }else{
          creep.memory.path = null;
        }
      }
    }
  },

  //Function to remove 'dead' creeps from the memory to conserve space
  clearDead: function(){
    for(var i in Memory.creeps) {
      if(!Game.creeps[i]) {
          delete Memory.creeps[i];
      }
    }
  },

  findToFixArr: function(room){
    var fixeArr = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < object.hitsMax/2);
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < 5000);
      var brokenCont = object.structureType ===STRUCTURE_CONTAINER && (object.hits < 100000);
      return brokenRoad || brokenWall || brokenRamp || brokenCont;
    }});

    return fixeArr;
  },

  retreat: function(creep){
    this.move(creep, creep.room.controller.pos);
    creep.say("HELP ME!");
  },

  move:function(creep,pos){
    var emptyPath = false;
    var creepPath = creep.memory.path;
    var destX = -1;
    var destY = -1;
    var lastObj = null;
    if(creepPath && creepPath.length>0){
      var index = creepPath.length-1;
      lastObj = creepPath[index];
      destX = lastObj.x + lastObj.dx;
      destY = lastObj.y + lastObj.dy;
    }else{
      emptyPath = true;
    }

    if(emptyPath || (lastObj && (pos.x !== destX || pos.y !== destY))){
      creep.memory.path = creep.pos.findPathTo(pos);
    }
    creep.moveByPath(creep.memory.path);
  }
  //TODO Emergency upgrade logic
};

module.exports = modCommon;
<commit_msg>documentation and removal of old movement code<commit_after>var modCommon = {

  //Gets energy from availible locations, including sources
  //if it can self harvest but at a lower priority
  getEn: function(creep){
    //Priority 1 is dropped energy, since it detiorates
    var dropped = creep.pos.findClosestByPath(FIND_DROPPED_ENERGY);
    if(dropped){
      if(creep.pickup(dropped)== ERR_NOT_IN_RANGE){
        modCommon.move(creep,dropped.pos);
      }else{
        creep.memory.path = null;
      }
    }else{
      //Next priority is the closest container or storage
      var storage = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        filter: (object)=>((object.structureType === STRUCTURE_CONTAINER) || (object.structureType === STRUCTURE_STORAGE)) && (object.store[RESOURCE_ENERGY] > creep.carryCapacity)
      });
      if(storage!==null){
        var getEnergy = creep.withdraw(storage, RESOURCE_ENERGY, creep.carryCapacity-creep.carry);
        if(getEnergy===ERR_NOT_IN_RANGE) {
            modCommon.move(creep, storage);
        }else{
          creep.memory.path = null;
        }
      //Finally, the creep will harvest if it can
      }else if(creep.memory.selfHarvest){
        var sources = creep.room.find(FIND_SOURCES);
        if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
          modCommon.move(creep, sources[0]);
        }else{
          creep.memory.path = null;
        }
      }
    }
  },

  //Function to remove 'dead' creeps from the memory to conserve space
  clearDead: function(){
    for(var i in Memory.creeps) {
      if(!Game.creeps[i]) {
          delete Memory.creeps[i];
      }
    }
  },

  //Method to find the next structure to repair, shared by repair creeps and towers
  findToFixArr: function(room){
    var fixeArr = room.find(FIND_STRUCTURES, {filter: function(object){
      var brokenRoad = object.structureType ===STRUCTURE_ROAD && (object.hits < object.hitsMax/2);
      var brokenWall = object.structureType ===STRUCTURE_WALL && (object.hits < 5000) && (object.hitsMax-object.hits>0);
      var brokenRamp = object.structureType ===STRUCTURE_RAMPART && (object.hits < 5000);
      var brokenCont = object.structureType ===STRUCTURE_CONTAINER && (object.hits < 100000);
      return brokenRoad || brokenWall || brokenRamp || brokenCont;
    }});

    return fixeArr;
  },

  //Function to run away and hide
  retreat: function(creep){
    this.move(creep, creep.room.controller.pos);
    creep.say("HELP ME!");
  },

  //Function to move useing a stored path
  move:function(creep,pos){
    var emptyPath = false;
    var creepPath = creep.memory.path;
    var destX = -1;
    var destY = -1;
    var lastObj = null;
    if(creepPath && creepPath.length>0){
      var index = creepPath.length-1;
      lastObj = creepPath[index];
      destX = lastObj.x + lastObj.dx;
      destY = lastObj.y + lastObj.dy;
    }else{
      emptyPath = true;
    }

    if(emptyPath || (lastObj && (pos.x !== destX || pos.y !== destY))){
      creep.memory.path = creep.pos.findPathTo(pos);
    }
    creep.moveByPath(creep.memory.path);
  }
  //TODO Emergency upgrade logic
};

module.exports = modCommon;
<|endoftext|>


<commit_before>var modMemory = {

  init:function(){
    Memory.rooms = {};
    for(var roomName in Game.rooms){
      this.initRoom(roomName);
    }
    Memory.initialized = true;
  },
  initRoom:function(roomName){
    Memory.rooms[roomName] = {
      roles: {
          numCreeps:0,
          numHarvesters:0,
          maxHarvesters:1,
          numUpgraders:0,
          maxUpgraders:1,
          numBuilders:0,
          maxBuilders:1,
          numRepair:0,
          maxRepair:1,
          numArchitects:0,
          betterHarvesters1:0,
          betterHarvesters2:0,
          numMiners:0,
          maxMiners:1,
          numHaulers:0,
          maxHaulers:1,
          numFeeders:0,
          maxFeeders:1,
          numGeo:0,
          maxGeo:1,
          numGeoH:0,
          maxGeoH:0,
          numMerchant:0,
          maxMerchant:0,
        },
      spawnQ:[],
      conservation: false,
      fortify: false,
      towers:{},
      sourceIDs:[],
      signMsg:"",
      //TODO extend the creep prototype and add signing based on this memory value
      //http://support.screeps.com/hc/en-us/articles/203013212-Creep#signController
      initialized:false, //Set to true when init is run

    };
    //TODO any other things go here (like Tower init)
    Memory.rooms[roomName].roomBorders = this.getBorders(roomName);
    Memory.rooms[roomName].initialized = true;
  },
  initTower:function(tower){
    var roomName = tower.room.name;
    var towerID = tower.id;
    Memory.rooms[roomName].towers[tower.id]={
      target:null,
      mode:"attack"
    };
  },
  getSpawnQ:function(roomName){
    return Memory.rooms[roomName].spawnQ;
  },
  changeCreepNum:function(roomName,creepType,num,set){}, //creepType - creepJob to change, num, num to add or set to, set - bool, true to set, false to add
  getInitalCreepMem:function(creepType){
    var memoryObj ={
      role:"none",
      path:null,
      dest:null,
      assist:"", //set to roomName of assisted room
      room:"",
    };
    if(creepType === "harvester"){
      memoryObj.role = 'harvester';
      memoryObj.selfHarvest = true;
      memoryObj.source = "";
      memoryObj.military = true;
    }
    else if(creepType === "upgrader"){
      memoryObj.role = 'upgrader';
      memoryObj.selfHarvest = true;
    }
    else if(creepType === "builder"){
      memoryObj.role = 'builder';
      memoryObj.selfHarvest = 'false';
    }
    else if(creepType === "repair"){
      memoryObj.role = 'repair';
      memoryObj.selfHarvest = true;
      memoryObj.toFix = '';
      memoryObj.military = true;
    }
    else if(creepType === "architect"){
      memoryObj.role = 'architect';
      memoryObj.selfHarvest = false;
    }
    else if(creepType === "miner"){
      memoryObj.role = 'miner';
      memoryObj.dropOff = "";
      memoryObj.source = "";
      memoryObj.military = true;
    }
    else if(creepType === "hauler"){
      memoryObj.role = 'hauler';
      memoryObj.dropOff = "";
      memoryObj.military = true;
    }
    else if(creepType === "feeder"){
      memoryObj.role = 'feeder';
      memoryObj.military = true;
    }
    else if(creepType === "geo"){
      memoryObj.role = 'geo';
      memoryObj.mineral = "";
      memoryObj.dropOff = "";
    }
    else if(creepType === "merchant"){
      memoryObj.role = 'merchant';
      memoryObj.terminal = "";
      memoryObj.storage = "";
      var toLoad = {};
      toLoad.amount = 0;
      toLoad.resource = RESOURCE_ENERGY;
      memoryObj.toLoad = toLoad;
    }
    else if(creepTpe === "settler"){
      memoryObj.role = 'settler';
    }

    return memoryObj;
  },
  getBorders:function(roomName){
    roomBorders = [];
    for(i = 0; i<50; i++){
      for(j = 0; j<50; j++){
        if(i===0 || i===49 || j===0 || j===49){
          roomBorders.push(new RoomPosition(i,j,roomName));
        }
      }
    }
    return roomBorders;
  }
};

module.exports = modMemory;
<commit_msg>upped default num of feeders so that when one dies the other can replinish the extensions<commit_after>var modMemory = {

  init:function(){
    Memory.rooms = {};
    for(var roomName in Game.rooms){
      this.initRoom(roomName);
    }
    Memory.initialized = true;
  },
  initRoom:function(roomName){
    Memory.rooms[roomName] = {
      roles: {
          numCreeps:0,
          numHarvesters:0,
          maxHarvesters:1,
          numUpgraders:0,
          maxUpgraders:1,
          numBuilders:0,
          maxBuilders:1,
          numRepair:0,
          maxRepair:1,
          numArchitects:0,
          betterHarvesters1:0,
          betterHarvesters2:0,
          numMiners:0,
          maxMiners:1,
          numHaulers:0,
          maxHaulers:1,
          numFeeders:0,
          maxFeeders:2,
          numGeo:0,
          maxGeo:1,
          numGeoH:0,
          maxGeoH:0,
          numMerchant:0,
          maxMerchant:0,
        },
      spawnQ:[],
      conservation: false,
      fortify: false,
      towers:{},
      sourceIDs:[],
      signMsg:"",
      //TODO extend the creep prototype and add signing based on this memory value
      //http://support.screeps.com/hc/en-us/articles/203013212-Creep#signController
      initialized:false, //Set to true when init is run

    };
    //TODO any other things go here (like Tower init)
    Memory.rooms[roomName].roomBorders = this.getBorders(roomName);
    Memory.rooms[roomName].initialized = true;
  },
  initTower:function(tower){
    var roomName = tower.room.name;
    var towerID = tower.id;
    Memory.rooms[roomName].towers[tower.id]={
      target:null,
      mode:"attack"
    };
  },
  getSpawnQ:function(roomName){
    return Memory.rooms[roomName].spawnQ;
  },
  changeCreepNum:function(roomName,creepType,num,set){}, //creepType - creepJob to change, num, num to add or set to, set - bool, true to set, false to add
  getInitalCreepMem:function(creepType){
    var memoryObj ={
      role:"none",
      path:null,
      dest:null,
      assist:"", //set to roomName of assisted room
      room:"",
    };
    if(creepType === "harvester"){
      memoryObj.role = 'harvester';
      memoryObj.selfHarvest = true;
      memoryObj.source = "";
      memoryObj.military = true;
    }
    else if(creepType === "upgrader"){
      memoryObj.role = 'upgrader';
      memoryObj.selfHarvest = true;
    }
    else if(creepType === "builder"){
      memoryObj.role = 'builder';
      memoryObj.selfHarvest = 'false';
    }
    else if(creepType === "repair"){
      memoryObj.role = 'repair';
      memoryObj.selfHarvest = true;
      memoryObj.toFix = '';
      memoryObj.military = true;
    }
    else if(creepType === "architect"){
      memoryObj.role = 'architect';
      memoryObj.selfHarvest = false;
    }
    else if(creepType === "miner"){
      memoryObj.role = 'miner';
      memoryObj.dropOff = "";
      memoryObj.source = "";
      memoryObj.military = true;
    }
    else if(creepType === "hauler"){
      memoryObj.role = 'hauler';
      memoryObj.dropOff = "";
      memoryObj.military = true;
    }
    else if(creepType === "feeder"){
      memoryObj.role = 'feeder';
      memoryObj.military = true;
    }
    else if(creepType === "geo"){
      memoryObj.role = 'geo';
      memoryObj.mineral = "";
      memoryObj.dropOff = "";
    }
    else if(creepType === "merchant"){
      memoryObj.role = 'merchant';
      memoryObj.terminal = "";
      memoryObj.storage = "";
      var toLoad = {};
      toLoad.amount = 0;
      toLoad.resource = RESOURCE_ENERGY;
      memoryObj.toLoad = toLoad;
    }
    else if(creepTpe === "settler"){
      memoryObj.role = 'settler';
    }

    return memoryObj;
  },
  getBorders:function(roomName){
    roomBorders = [];
    for(i = 0; i<50; i++){
      for(j = 0; j<50; j++){
        if(i===0 || i===49 || j===0 || j===49){
          roomBorders.push(new RoomPosition(i,j,roomName));
        }
      }
    }
    return roomBorders;
  }
};

module.exports = modMemory;
<|endoftext|>


<commit_before>const RichTextXform = require('../strings/rich-text-xform');
const utils = require('../../../utils/utils');
const BaseXform = require('../base-xform');

/**
  <comment ref="B1" authorId="0">
    <text>
      <r>
        <rPr>
          <b/>
          <sz val="9"/>
          <rFont val="宋体"/>
          <charset val="134"/>
        </rPr>
        <t>51422:</t>
      </r>
      <r>
        <rPr>
          <sz val="9"/>
          <rFont val="宋体"/>
          <charset val="134"/>
        </rPr>
        <t xml:space="preserve">
test</t>
      </r>
    </text>
  </comment>
 */

const CommentXform = (module.exports = function(model) {
  this.model = model;
});

utils.inherits(CommentXform, BaseXform, {
  get tag() {
    return 'r';
  },

  get richTextXform() {
    if (!this._richTextXform) {
      this._richTextXform = new RichTextXform();
    }
    return this._richTextXform;
  },

  render(xmlStream, model) {
    model = model || this.model;

    xmlStream.openNode('comment', {
      ref: model.ref,
      authorId: 0,
    });
    xmlStream.openNode('text');
    if (model.note.texts) {
      model.note.texts.forEach(text => {
        this.richTextXform.render(xmlStream, text);
      });
    }
    xmlStream.closeNode();
    xmlStream.closeNode();
  },

  parseOpen(node) {
    if (this.parser) {
      this.parser.parseOpen(node);
      return true;
    }
    switch (node.name) {
      case 'comment':
        this.model = {
          texts: [],
          ...node.attributes,
        };
        return true;
      case 'r':
        this.parser = this.richTextXform;
        this.parser.parseOpen(node);
        return true;
      default:
        return false;
    }
  },
  parseText(text) {
    if (this.parser) {
      this.parser.parseText(text);
    }
  },
  parseClose(name) {
    switch (name) {
      case 'comment':
        return false;
      case 'r':
        this.model.texts.push(this.parser.model);
        this.parser = undefined;
        return true;
      default:
        if (this.parser) {
          this.parser.parseClose(name);
        }
        return true;
    }
  },
});
<commit_msg>fix(comment): malformed comment crashes on write (#880)<commit_after>const RichTextXform = require('../strings/rich-text-xform');
const utils = require('../../../utils/utils');
const BaseXform = require('../base-xform');

/**
  <comment ref="B1" authorId="0">
    <text>
      <r>
        <rPr>
          <b/>
          <sz val="9"/>
          <rFont val="宋体"/>
          <charset val="134"/>
        </rPr>
        <t>51422:</t>
      </r>
      <r>
        <rPr>
          <sz val="9"/>
          <rFont val="宋体"/>
          <charset val="134"/>
        </rPr>
        <t xml:space="preserve">
test</t>
      </r>
    </text>
  </comment>
 */

const CommentXform = (module.exports = function(model) {
  this.model = model;
});

utils.inherits(CommentXform, BaseXform, {
  get tag() {
    return 'r';
  },

  get richTextXform() {
    if (!this._richTextXform) {
      this._richTextXform = new RichTextXform();
    }
    return this._richTextXform;
  },

  render(xmlStream, model) {
    model = model || this.model;

    xmlStream.openNode('comment', {
      ref: model.ref,
      authorId: 0,
    });
    xmlStream.openNode('text');
    if (model && model.note && model.note.texts) {
      model.note.texts.forEach(text => {
        this.richTextXform.render(xmlStream, text);
      });
    }
    xmlStream.closeNode();
    xmlStream.closeNode();
  },

  parseOpen(node) {
    if (this.parser) {
      this.parser.parseOpen(node);
      return true;
    }
    switch (node.name) {
      case 'comment':
        this.model = {
          texts: [],
          ...node.attributes,
        };
        return true;
      case 'r':
        this.parser = this.richTextXform;
        this.parser.parseOpen(node);
        return true;
      default:
        return false;
    }
  },
  parseText(text) {
    if (this.parser) {
      this.parser.parseText(text);
    }
  },
  parseClose(name) {
    switch (name) {
      case 'comment':
        return false;
      case 'r':
        this.model.texts.push(this.parser.model);
        this.parser = undefined;
        return true;
      default:
        if (this.parser) {
          this.parser.parseClose(name);
        }
        return true;
    }
  },
});
<|endoftext|>


<commit_before>export default (properties) => {
  return {
    '0': {
      patch: require('object-assign')({}, properties)
    }
  };
};
<commit_msg>Fix vPatch<commit_after>export default (attributes) => {
  return {
    '0': {
      patch: {attributes}
    }
  };
};
<|endoftext|>


<commit_before>var fs = require('fs');
var commands = [];
var modules = [];

function InitModules() {
    console.log('Loading modules...');
    fs.readdir('modules', function(err, files) {
        if (err) throw err;
        for(var i = 0; i < files.length; i++) {
            Loader(files[i]);
            }
    });
}

function Loader(filename) {
    var mod = require('./modules/' + filename);
    modules[mod.info['name']] = mod;
    if(mod.info['commanda']) {
        commands.push(mod.info['command']);
    }
    console.log('Loaded module %s(%s) !', mod.info['name'], filename);
}

function Unload() {
    modules = [];
    commands = [];
    console.log('All Unloaded!');
}

exports.InitModules = InitModules;
exports.Unload = Unload;
exports.commands = commands;
exports.modules = modules;
<commit_msg>fix help<commit_after>var fs = require('fs');
var commands = [];
var modules = [];

function InitModules() {
    console.log('Loading modules...');
    fs.readdir('modules', function(err, files) {
        if (err) throw err;
        for(var i = 0; i < files.length; i++) {
            Loader(files[i]);
            }
    });
}

function Loader(filename) {
    var mod = require('./modules/' + filename);
    modules[mod.info['name']] = mod;
    if(mod.info['command']) {
        commands.push(mod.info['command']);
    }
    console.log('Loaded module %s(%s) !', mod.info['name'], filename);
}

function Unload() {
    modules = [];
    commands = [];
    console.log('All Unloaded!');
}

exports.InitModules = InitModules;
exports.Unload = Unload;
exports.commands = commands;
exports.modules = modules;
<|endoftext|>