<commit_before>const moment = require('moment');

const queries = require('../db/queries');
const { db, logger } = require('../utils');

const modelAttributes = ['id', 'performanceId', 'spotId', 'firstNameNumber', 'secondNameNumber', 'firstComments', 'secondComments', 'winnerId', 'pending', 'needsApproval'];
const alternateVersusRegular = result =>
  (!result.userOneAlternate && result.userTwoAlternate) ||
  (result.userOneAlternate && !result.userTwoAlternate);
const alternateVersusAlternate = result =>
  result.userOneAlternate && result.userTwoAlternate;
const regularVersusRegular = result =>
  !result.userOneAlternate && !result.userTwoAlternate;

/*
  We need a special sorting for results when we're switching user spots based on results
  - Regular VS Alternate
  - Alternate VS Alternate
  - Regular VS Regular
  This grossness does that
*/
const resultsSort = (a, b) => { // eslint-disable-line consistent-return, array-callback-return
  if (alternateVersusRegular(a) && alternateVersusRegular(b)) return 0;
  if (alternateVersusRegular(a) && alternateVersusAlternate(b)) return -1;
  if (alternateVersusRegular(a) && regularVersusRegular(b)) return -1;
  if (alternateVersusAlternate(a) && alternateVersusRegular(b)) return 1;
  if (alternateVersusAlternate(a) && alternateVersusAlternate(b)) return 0;
  if (alternateVersusAlternate(a) && regularVersusRegular(b)) return -1;
  if (regularVersusRegular(a) && alternateVersusRegular(b)) return 1;
  if (regularVersusRegular(a) && alternateVersusAlternate(b)) return 1;
  if (regularVersusRegular(a) && regularVersusRegular(b)) return 0;
};

class Result {

  constructor(id, fC, fNN, nA, opponentName, pending, perfDate, perfName, perfId, sC, sNN, spotId, uOA, uTA, winnerId) {
    this._id = id;
    this._firstComments = fC;
    this._firstNameNumber = fNN;
    this._needsApproval = nA;
    this._opponentName = opponentName;
    this._pending = pending;
    this._performanceDate = new Date(perfDate);
    this._performanceName = perfName;
    this._performanceId = perfId;
    this._secondComments = sC;
    this._secondNameNumber = sNN;
    this._spotId = spotId;
    this._userOneAlternate = uOA;
    this._userTwoAlternate = uTA;
    this._winnerId = winnerId;
  }

  static get attributes() {
    return modelAttributes;
  }

  static get idName() {
    return 'id';
  }

  static get tableName() {
    return 'results';
  }

  static approve(ids) {
    const client = db.createClient();
    const sql = 'UPDATE results SET needsApproval = FALSE, pending = FALSE WHERE id = ANY($1) RETURNING performanceId';
    let performanceId;

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [ids]);

      query.on('row', ({ performanceid }) => {
        performanceId = performanceid;
      });

      query.on('end', () => {
        client.end();
        resolve(performanceId);
      });
      query.on('error', (err) => {
        reject(err);
        client.end();
      });
    });
  }

  static checkAllDoneForPerformance(id) {
    const client = db.createClient();
    const sql = 'SELECT count(*) FROM results WHERE performanceid = $1 AND needsApproval';
    let count;

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [id]);

      query.on('row', result => {
        count = parseInt(result.count, 10);
      });
      query.on('end', () => {
        client.end();
        resolve(count === 0);
      });
      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static createWithClient(attributes, client) {
    const { sql, values } = db.queryBuilder(Result, attributes);

    return new Promise((resolve, reject) => {
      const query = client.query(sql, values);

      query.on('end', resolve);
      query.on('error', reject);
    });
  }

  static findAllForApproval(user) {
    const client = db.createClient();
    const sql = queries.resultsForApproval;
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [user.instrument, user.part]);

      query.on('row', (resultRow) =>
        results.push(instanceFromDBRow(resultRow))
      );

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static findAllForEval(nameNumber, row) {
    const client = db.createClient();
    const sql = queries.resultsForEval;
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [nameNumber, row]);

      query.on('row', (resultRow) => results.push(instanceFromDBRow(resultRow)));

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static findAllForPerformance(performanceId) {
    const client = db.createClient();
    const sql = queries.resultsForPerformance;
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [performanceId]);

      query.on('row', (resultRow) => results.push(instanceFromDBRow(resultRow)));

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static findAllRawForPerformance(performanceId) {
    const client = db.createClient();
    const sql = 'SELECT * FROM results WHERE performanceId = $1';
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', reject);

      const query = client.query(sql, [performanceId]);

      query.on('row', (resultRow) => results.push(instanceFromDBRow(resultRow)));

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static findAllForUser(nameNumber) {
    const client = db.createClient();
    const sql = queries.resultsForUser;
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [nameNumber]);

      query.on('row', (resultRow) => {
        results.push(instanceFromDBRow(resultRow));
      });

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static switchSpotsForPerformance(id) {
    const client = db.createClient();
    const resultsSql = queries.resultsForPerformance;
    const switchSql = 'SELECT switch_spots_based_on_results($1)';
    const oneUserSql = 'SELECT switch_spots_based_on_results_one_user($1)';
    const results = [];
    const onePersonResultIds = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => {
        logger.errorLog('Results.switchSpotsForPerformance', err);
        reject(err);
      });

      const resultsQuery = client.query(resultsSql, [id]);

      resultsQuery.on('row', resultRow => results.push(instanceFromDBRow(resultRow)));
      resultsQuery.on('end', () => {
        const filteredResults = results.filter(({ secondNameNumber }, i) => {
          if (!secondNameNumber) {
            onePersonResultIds.push(results[i].id);
          }
          return secondNameNumber;
        });
        const filteredResultsIds = filteredResults.sort(resultsSort).map(({ id: resultId }) => resultId);

        const switchQuery = client.query(switchSql, [filteredResultsIds]);

        switchQuery.on('end', () => {
          const oneUserQuery = client.query(oneUserSql, [onePersonResultIds]);

          oneUserQuery.on('end', () => {
            client.end();
            resolve();
          });
          oneUserQuery.on('error', err => {
            client.end();
            logger.errorLog('Results.switchSpotsForPerformance: oneUserQuery', err);
            reject(err);
          });
        });

        switchQuery.on('error', err => {
          client.end();
          logger.errorLog('Results.switchSpotsForPerformance: switchQuery', err);
          reject(err);
        });
      });

      resultsQuery.on('error', err => {
        logger.errorLog('Results.switchSpotsForPerformance', err);
        client.end();
        reject(err);
      });
    });
  }

  static update(attributes) {
    const client = db.createClient();

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const id = attributes.id;

      if (typeof id === 'undefined') {
        reject(new Error('No id provided with attributes'));
      }

      delete attributes.id;
      const { sql, values } = db.queryBuilder(Result, attributes, { statement: 'UPDATE', id });
      const query = client.query(sql, values);

      query.on('end', () => resolve());
      query.on('error', (err) => reject(err));
    });
  }

  static updateForTestsOnly(firstNameNumber, comments1, comments2, winnerId) {
    const client = db.createClient();
    const sql = 'UPDATE results SET firstComments = $1, secondComments = $2, winnerId = $3 WHERE firstNameNumber = $4';

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', reject);

      const query = client.query(sql, [comments1, comments2 || null, winnerId, firstNameNumber]);

      query.on('end', () => {
        client.end();
        resolve();
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  get id() {
    return this._id;
  }

  get firstComments() {
    return this._firstComments;
  }

  get firstNameNumber() {
    return this._firstNameNumber;
  }

  get needsApproval() {
    return this._needsApproval;
  }

  get opponentName() {
    return this._opponentName;
  }

  get pending() {
    return this._pending;
  }

  get performanceId() {
    return this._performanceId;
  }

  get secondComments() {
    return this._secondComments;
  }

  get secondNameNumber() {
    return this._secondNameNumber;
  }

  get spotId() {
    return this._spotId;
  }

  get userOneAlternate() {
    return this._userOneAlternate;
  }

  get userTwoAlternate() {
    return this._userTwoAlternate;
  }

  // This function is only for results returned by findForUser
  toJSONForUser(nameNumber) {
    return {
      comments: this._firstComments,
      opponentName: this._opponentName,
      performanceDate: moment(this._performanceDate).format('MMM D, YYYY'),
      performanceName: this._performanceName,
      spotId: this._spotId,
      winner: this._winnerId === nameNumber
    };
  }
}

// id, fC, fNN, nA, opponentName, pending, perfDate, perfName, perfId, sC, sNN, spotId, winnerId
const instanceFromDBRow = ({
  id,
  firstcomments,
  firstnamenumber,
  needsapproval,
  opponentname,
  pending,
  performdate,
  name,
  performanceid,
  secondcomments,
  secondnamenumber,
  spotid,
  useronealternate,
  usertwoalternate,
  winnerid
}) => new Result(
  id,
  firstcomments,
  firstnamenumber,
  needsapproval,
  opponentname,
  pending,
  performdate,
  name,
  performanceid,
  secondcomments,
  secondnamenumber,
  spotid,
  useronealternate,
  usertwoalternate,
  winnerid
);

module.exports = Result;
<commit_msg>Remove comment<commit_after>const moment = require('moment');

const queries = require('../db/queries');
const { db, logger } = require('../utils');

const modelAttributes = ['id', 'performanceId', 'spotId', 'firstNameNumber', 'secondNameNumber', 'firstComments', 'secondComments', 'winnerId', 'pending', 'needsApproval'];
const alternateVersusRegular = result =>
  (!result.userOneAlternate && result.userTwoAlternate) ||
  (result.userOneAlternate && !result.userTwoAlternate);
const alternateVersusAlternate = result =>
  result.userOneAlternate && result.userTwoAlternate;
const regularVersusRegular = result =>
  !result.userOneAlternate && !result.userTwoAlternate;

/*
  We need a special sorting for results when we're switching user spots based on results
  - Regular VS Alternate
  - Alternate VS Alternate
  - Regular VS Regular
  This grossness does that
*/
const resultsSort = (a, b) => { // eslint-disable-line consistent-return, array-callback-return
  if (alternateVersusRegular(a) && alternateVersusRegular(b)) return 0;
  if (alternateVersusRegular(a) && alternateVersusAlternate(b)) return -1;
  if (alternateVersusRegular(a) && regularVersusRegular(b)) return -1;
  if (alternateVersusAlternate(a) && alternateVersusRegular(b)) return 1;
  if (alternateVersusAlternate(a) && alternateVersusAlternate(b)) return 0;
  if (alternateVersusAlternate(a) && regularVersusRegular(b)) return -1;
  if (regularVersusRegular(a) && alternateVersusRegular(b)) return 1;
  if (regularVersusRegular(a) && alternateVersusAlternate(b)) return 1;
  if (regularVersusRegular(a) && regularVersusRegular(b)) return 0;
};

class Result {

  constructor(id, fC, fNN, nA, opponentName, pending, perfDate, perfName, perfId, sC, sNN, spotId, uOA, uTA, winnerId) {
    this._id = id;
    this._firstComments = fC;
    this._firstNameNumber = fNN;
    this._needsApproval = nA;
    this._opponentName = opponentName;
    this._pending = pending;
    this._performanceDate = new Date(perfDate);
    this._performanceName = perfName;
    this._performanceId = perfId;
    this._secondComments = sC;
    this._secondNameNumber = sNN;
    this._spotId = spotId;
    this._userOneAlternate = uOA;
    this._userTwoAlternate = uTA;
    this._winnerId = winnerId;
  }

  static get attributes() {
    return modelAttributes;
  }

  static get idName() {
    return 'id';
  }

  static get tableName() {
    return 'results';
  }

  static approve(ids) {
    const client = db.createClient();
    const sql = 'UPDATE results SET needsApproval = FALSE, pending = FALSE WHERE id = ANY($1) RETURNING performanceId';
    let performanceId;

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [ids]);

      query.on('row', ({ performanceid }) => {
        performanceId = performanceid;
      });

      query.on('end', () => {
        client.end();
        resolve(performanceId);
      });
      query.on('error', (err) => {
        reject(err);
        client.end();
      });
    });
  }

  static checkAllDoneForPerformance(id) {
    const client = db.createClient();
    const sql = 'SELECT count(*) FROM results WHERE performanceid = $1 AND needsApproval';
    let count;

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [id]);

      query.on('row', result => {
        count = parseInt(result.count, 10);
      });
      query.on('end', () => {
        client.end();
        resolve(count === 0);
      });
      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static createWithClient(attributes, client) {
    const { sql, values } = db.queryBuilder(Result, attributes);

    return new Promise((resolve, reject) => {
      const query = client.query(sql, values);

      query.on('end', resolve);
      query.on('error', reject);
    });
  }

  static findAllForApproval(user) {
    const client = db.createClient();
    const sql = queries.resultsForApproval;
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [user.instrument, user.part]);

      query.on('row', (resultRow) =>
        results.push(instanceFromDBRow(resultRow))
      );

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static findAllForEval(nameNumber, row) {
    const client = db.createClient();
    const sql = queries.resultsForEval;
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [nameNumber, row]);

      query.on('row', (resultRow) => results.push(instanceFromDBRow(resultRow)));

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static findAllForPerformance(performanceId) {
    const client = db.createClient();
    const sql = queries.resultsForPerformance;
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [performanceId]);

      query.on('row', (resultRow) => results.push(instanceFromDBRow(resultRow)));

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static findAllRawForPerformance(performanceId) {
    const client = db.createClient();
    const sql = 'SELECT * FROM results WHERE performanceId = $1';
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', reject);

      const query = client.query(sql, [performanceId]);

      query.on('row', (resultRow) => results.push(instanceFromDBRow(resultRow)));

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static findAllForUser(nameNumber) {
    const client = db.createClient();
    const sql = queries.resultsForUser;
    const results = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [nameNumber]);

      query.on('row', (resultRow) => {
        results.push(instanceFromDBRow(resultRow));
      });

      query.on('end', () => {
        client.end();
        resolve(results);
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  static switchSpotsForPerformance(id) {
    const client = db.createClient();
    const resultsSql = queries.resultsForPerformance;
    const switchSql = 'SELECT switch_spots_based_on_results($1)';
    const oneUserSql = 'SELECT switch_spots_based_on_results_one_user($1)';
    const results = [];
    const onePersonResultIds = [];

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => {
        logger.errorLog('Results.switchSpotsForPerformance', err);
        reject(err);
      });

      const resultsQuery = client.query(resultsSql, [id]);

      resultsQuery.on('row', resultRow => results.push(instanceFromDBRow(resultRow)));
      resultsQuery.on('end', () => {
        const filteredResults = results.filter(({ secondNameNumber }, i) => {
          if (!secondNameNumber) {
            onePersonResultIds.push(results[i].id);
          }
          return secondNameNumber;
        });
        const filteredResultsIds = filteredResults.sort(resultsSort).map(({ id: resultId }) => resultId);

        const switchQuery = client.query(switchSql, [filteredResultsIds]);

        switchQuery.on('end', () => {
          const oneUserQuery = client.query(oneUserSql, [onePersonResultIds]);

          oneUserQuery.on('end', () => {
            client.end();
            resolve();
          });
          oneUserQuery.on('error', err => {
            client.end();
            logger.errorLog('Results.switchSpotsForPerformance: oneUserQuery', err);
            reject(err);
          });
        });

        switchQuery.on('error', err => {
          client.end();
          logger.errorLog('Results.switchSpotsForPerformance: switchQuery', err);
          reject(err);
        });
      });

      resultsQuery.on('error', err => {
        logger.errorLog('Results.switchSpotsForPerformance', err);
        client.end();
        reject(err);
      });
    });
  }

  static update(attributes) {
    const client = db.createClient();

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', (err) => reject(err));

      const id = attributes.id;

      if (typeof id === 'undefined') {
        reject(new Error('No id provided with attributes'));
      }

      delete attributes.id;
      const { sql, values } = db.queryBuilder(Result, attributes, { statement: 'UPDATE', id });
      const query = client.query(sql, values);

      query.on('end', () => resolve());
      query.on('error', (err) => reject(err));
    });
  }

  static updateForTestsOnly(firstNameNumber, comments1, comments2, winnerId) {
    const client = db.createClient();
    const sql = 'UPDATE results SET firstComments = $1, secondComments = $2, winnerId = $3 WHERE firstNameNumber = $4';

    return new Promise((resolve, reject) => {
      client.connect();
      client.on('error', reject);

      const query = client.query(sql, [comments1, comments2 || null, winnerId, firstNameNumber]);

      query.on('end', () => {
        client.end();
        resolve();
      });

      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  get id() {
    return this._id;
  }

  get firstComments() {
    return this._firstComments;
  }

  get firstNameNumber() {
    return this._firstNameNumber;
  }

  get needsApproval() {
    return this._needsApproval;
  }

  get opponentName() {
    return this._opponentName;
  }

  get pending() {
    return this._pending;
  }

  get performanceId() {
    return this._performanceId;
  }

  get secondComments() {
    return this._secondComments;
  }

  get secondNameNumber() {
    return this._secondNameNumber;
  }

  get spotId() {
    return this._spotId;
  }

  get userOneAlternate() {
    return this._userOneAlternate;
  }

  get userTwoAlternate() {
    return this._userTwoAlternate;
  }

  // This function is only for results returned by findForUser
  toJSONForUser(nameNumber) {
    return {
      comments: this._firstComments,
      opponentName: this._opponentName,
      performanceDate: moment(this._performanceDate).format('MMM D, YYYY'),
      performanceName: this._performanceName,
      spotId: this._spotId,
      winner: this._winnerId === nameNumber
    };
  }
}

const instanceFromDBRow = ({
  id,
  firstcomments,
  firstnamenumber,
  needsapproval,
  opponentname,
  pending,
  performdate,
  name,
  performanceid,
  secondcomments,
  secondnamenumber,
  spotid,
  useronealternate,
  usertwoalternate,
  winnerid
}) => new Result(
  id,
  firstcomments,
  firstnamenumber,
  needsapproval,
  opponentname,
  pending,
  performdate,
  name,
  performanceid,
  secondcomments,
  secondnamenumber,
  spotid,
  useronealternate,
  usertwoalternate,
  winnerid
);

module.exports = Result;
<|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);

  },

  getCreepsByJob: function(job, roomName){
    var result = [];
    for(var cName in Game.creeps){
        var c = Game.creeps[cName];
        if(c.memory.role === job && c.memory.room === roomName){
          result.push(c);
        }
    }
    return result;
  },

  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){
    var modifier = Math.max(Math.pow(10,controlLvl-3),10);

    if(room.storage.store.energy < modConstants.roomEnergyBuffer){
      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;
    }else{
      var brokenRamp2 = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+modConstants.structBuffer))&& (object.hitsMax-object.hits>0);

      var brokenWall2 = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+modConstants.structBuffer)) && (object.hitsMax-object.hits>0);
      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 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+modConstants.structBuffer))&& (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_STRUCTURES, {filter: function(object){
      return (object.structureType === STRUCTURE_WALL || object.structureType === STRUCTURE_RAMPART) && (object.hits < 100000);
    }});

    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 = {};
      //opts.ignore = Game.rooms[pos.roomName].find(FIND_MY_CONSTRUCTION_SITES);
      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;
      var reCalc = creep.memory.reCalc;
      if(!creepPath || creep.memory.dest != posStr || posStr === null || reCalc){
          if(reCalc){
            opts.ignoreCreeps = false;
          }else {
            opts.ignoreCreeps = true;
          }
          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;
          creep.memory.reCalc = false;
      }
      creep.memory.lastPos = creep.pos;
      var result = creep.moveByPath(creep.memory.path);
      if(result != OK && result != ERR_TIRED){
        creep.memory.path = null;
        //console.log("Move error: "+result);
      }else if(result === OK){
        if((creep.memory.lastPos === creep.pos) && (creep.fatigue === 0)){
          creep.memory.reCalc = true;
        }
        creep.memory.lastPos = creep.pos;
      }

      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 && type !== RESOURCE_ENERGY){
        return type;
      }
    }
    return RESOURCE_ENERGY;
  },

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

  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>upped allowed ops for multiroom<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);

  },

  getCreepsByJob: function(job, roomName){
    var result = [];
    for(var cName in Game.creeps){
        var c = Game.creeps[cName];
        if(c.memory.role === job && c.memory.room === roomName){
          result.push(c);
        }
    }
    return result;
  },

  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){
    var modifier = Math.max(Math.pow(10,controlLvl-3),10);

    if(room.storage.store.energy < modConstants.roomEnergyBuffer){
      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;
    }else{
      var brokenRamp2 = object.structureType ===STRUCTURE_RAMPART && (object.hits < (500*modifier+modConstants.structBuffer))&& (object.hitsMax-object.hits>0);

      var brokenWall2 = object.structureType ===STRUCTURE_WALL && (object.hits < (500*modifier+modConstants.structBuffer)) && (object.hitsMax-object.hits>0);
      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 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+modConstants.structBuffer))&& (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_STRUCTURES, {filter: function(object){
      return (object.structureType === STRUCTURE_WALL || object.structureType === STRUCTURE_RAMPART) && (object.hits < 100000);
    }});

    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 = {};
      //opts.ignore = Game.rooms[pos.roomName].find(FIND_MY_CONSTRUCTION_SITES);
      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;
      var reCalc = creep.memory.reCalc;
      if(!creepPath || creep.memory.dest != posStr || posStr === null || reCalc){
          if(reCalc){
            opts.ignoreCreeps = false;
          }else {
            opts.ignoreCreeps = true;
          }
          opts.serialize = true;
          if(pos.roomName == creep.room.name){
            opts.maxOps = 1000;
          }else{
            opts.maxOps = 9000;
          }
          creep.memory.path = creep.pos.findPathTo(pos, opts);
          creep.memory.dest = posStr;
          creep.memory.reCalc = false;
      }
      creep.memory.lastPos = creep.pos;
      var result = creep.moveByPath(creep.memory.path);
      if(result != OK && result != ERR_TIRED){
        creep.memory.path = null;
        //console.log("Move error: "+result);
      }else if(result === OK){
        if((creep.memory.lastPos === creep.pos) && (creep.fatigue === 0)){
          creep.memory.reCalc = true;
        }
        creep.memory.lastPos = creep.pos;
      }

      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 && type !== RESOURCE_ENERGY){
        return type;
      }
    }
    return RESOURCE_ENERGY;
  },

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

  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 express = require("express");
var bodyParser = require("body-parser");
var session = require('client-sessions');

var RUN_LOCAL = false;

function start() {
  var API = express();

  API.use(function (req, res, next) {
    if (RUN_LOCAL)
    {
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
    } else {
      res.setHeader('Access-Control-Allow-Origin', 'http://development.mrrorinc-tiles.divshot.io');
    }
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);

    next();
  });

  API.use(session({
    cookieName: 'session',
    secret: 'tiles_prototype',
    duration: 30 * 60 * 1000,
    activeDuration: 5 * 60 * 1000,
  }));
  API.use(bodyParser.json());

  return API;
}

exports.start = start;<commit_msg>commit local version of server<commit_after>var express = require("express");
var bodyParser = require("body-parser");
var session = require('client-sessions');

var RUN_LOCAL = true;

function start() {
  var API = express();

  API.use(function (req, res, next) {
    if (RUN_LOCAL)
    {
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
    } else {
      res.setHeader('Access-Control-Allow-Origin', 'http://development.mrrorinc-tiles.divshot.io');
    }
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);

    next();
  });

  API.use(session({
    cookieName: 'session',
    secret: 'tiles_prototype',
    duration: 30 * 60 * 1000,
    activeDuration: 5 * 60 * 1000,
  }));
  API.use(bodyParser.json());

  return API;
}

exports.start = start;<|endoftext|>


<commit_before>/**
 * CouchDB base class/resource definition.
 * This file should be inherited by all CouchDB models that want to leverage
 * CouchDB's power in rocket.
 */

var crypto = require('crypto')
  , _ = require('underscore')
  , lingo = require('lingo')
  , cradle = require('cradle')
  , async = require('async')
  ;

var oo = require('../utils/oo')
  , namespace = require('../utils/namespace')
  , BaseResource = require('./base_resource')
  ;

/******************************************************************************
 * CONSTANTS
 */

var ROCKET_NAMESPACE = 'rocket';

/******************************************************************************
 * Default connection parameters
 */
CouchDBResource.connection = {
    host: 'localhost'
  , port: 5984
  , options: {
      raw: true
    , cache: false
    , auth: null
    }
  };

/******************************************************************************
 * Default _design documents                                     *** SYNCD ***
 */
CouchDBResource.ddocs = [
    {
      _id: '_design/rocket'
    , lists: {}
    , shows: {}
    , updates: {
        in_place: function(doc, req) {
          var oo  = require('rocket/oo')
            ;
          oo.__extends(doc, req.query, { overwrite: true });

          return [doc, JSON.stringify(doc)];
        }
      }
    , validate_doc_update: function(newDoc, oldDoc, userCtx) {

        if(newDoc._deleted
        || typeof newDoc.doc_type === 'undefined'
        || newDoc.doc_type === null
        || newDoc.doc_type === ''
        ){
          return;
        }

        var schema = require('rocket/schema/' + newDoc.doc_type);

        for(var member in schema) {

          if(typeof schema[member] !== 'undefined'
          && schema[member] !== null) {

            var validator;
            var optional;

            if(typeof schema[member] === 'string') {

              validator = require('rocket/validators/' + schema[member]) || null;

            }else if(typeof schema[member] === 'object') {

              optional = schema[member].optional;
              validator = (schema[member].validate ? require('rocket/validators/' + schema[member].validate) : null);

            }

            if(typeof newDoc[member] !== 'undefined'
            && newDoc[member] !== null) {
              if(validator) {
                validator(member, newDoc[member]);
              }else{
                continue;
              }
            }else if(optional){
              continue;
            }else{
              throw({ invalid: member + ' can\'t be missing or null' });
            }
          }
        }
      }
    , views: {
       all: {
          map: function(doc) { emit(doc._id, doc); }
        }
      }
    }
  ];

/******************************************************************************
 * Default _security document                                    *** SYNCD ***
 */
CouchDBResource._security = {
    admins: {
        names: ["admin"]
      , roles: []
      }
  , readers: {
        names: ["admin"]
      , roles: []
      }
  };

/******************************************************************************
 * Utils functions
 */
function setProperties(dst, src, synced){

  var synced = typeof synced !== 'undefined' ? synced : true;

  if(! dst.synced)  { Object.defineProperty(dst, 'synced', {value: {}}); }
  if(! dst.values)    { Object.defineProperty(dst, 'values', {value: {}}); }

  function createSetter(prop) {
    return function(v) {
      dst.synced[prop] = dst.synced[prop] && dst.values[prop] === v;
      dst.values[prop] = v;
    }
  }

  function createGetter(prop) {
    return function() { return dst.values[prop] };
  }

  for(var prop in src) {
    var val = src[prop];
    delete src[prop];
    Object.defineProperty(dst, prop, { enumerable: true,  configurable: true, get: createGetter(prop), set: createSetter(prop) });
    dst.synced[prop] = synced;
    dst.values[prop] = val;
  }
}

function updateCache(obj, newValues) {
  obj.__db.cache.store[obj._id].document = newValues;
  obj.__db.cache.store[obj._id].attime = Date.now();
}

function timestamp(obj) {

  var current_time = new Date.now();

  if(typeof obj.creation_date === 'undefined'
  || obj.creation_date === null
  ){
    obj.creation_date = current_time;
  }

  obj.modification_date = current_time;
}

function set_doc_type(obj, doc_type){
  if(typeof obj.doc_type === 'undefined'
  || obj.doc_type === null
  || obj.doc_type === ''
  || !obj.propertyIsEnumerable('doc_type')
  || obj.doc_type !== doc_type
  ){
    obj.doc_type = doc_type;
  }
}

/******************************************************************************
 * Resource Prototype Functions (used to create models)
 */
CouchDBResource.prototype = {
    save: function save_CouchDBResourceInstance(callback) {
      var that = this
      ;

      timestamp(this);
      set_doc_type(this, this.doc_type);

      this.__db.save(this._id, this._rev, this, function(err,res) {
        if(err){
          callback(err);
        }else{
          setProperties(that, that);
          callback(null, res);
        }
      });
    }
  , update: function update_CouchDBResourceInstance(callback) {
      var modz = {}
        , that = this
        ;

      timestamp(this);
      set_doc_type(this, this.doc_type);

      for(var k in this) {
        if(this.propertyIsEnumerable(k) === false) {
          continue;
        }

        if(! this.synced[k]) {
          modz[k] = this[k];
        }
      }

      if(modz !== {}) {
        this.__db.update('rocket/in_place', this._id, modz, function(err){
          if(err){
            callback(err);
          }else{
            setProperties(that, that);
            updateCache(that, that.values);
            callback.apply(that, Array.prototype.slice.apply(arguments));
          }
        });
      }else{
        callback(null, '');
      }
    }
  , destroy: function destroy_CouchDBResourceInstance(callback) {
      this.__db.remove(this._id, function(err) { callback(err); });
    }
  , reload: function reload_CouchDBResourceInstance(callback) {
      var that = this;

      this.__db.get(this._id, function(err, doc) {
        if(err) {
          callback(err);
        }else{

          setProperties(that, doc);
          callback(null, that);
        }
      });

    }
  , exists: function exists_CouchDBResourceInstance() {}
  };

/******************************************************************************
 * Resource Factory/Constructor Functions
 */
var factoryFunctions = {
    initialize: function initialize_CouchDBResource(model_name, callback) {
      var that = this
        , doc_type = namespace.extractName(model_name.toLowerCase(), { suffix: '_document' })
        ;

      //Initialize connection object
      that.__connection = new cradle.Connection(
          that.connection.host
        , that.connection.port
        , that.connection.options
        );

      //Infer DB name from file name unless specified
      if(typeof that.db_name !== 'undefined' && that.db_name !== null){
        that.__db_name = that.db_name;
      }else{
        that.__db_name = lingo.en.pluralize(doc_type);
      }

      //setup db object
      that.__db = that.__connection.database(that.__db_name);
      that.prototype.__db  = that.__db;

      that.prototype.doc_type  = doc_type;

      //Create db if it doesn't exists. Harmless otherwise.
      that.__db.create();

      async.parallel(
          [function(callback) {
              async.forEach(that.ddocs, syncDoc, callback);
            }
          , function(callback) {
              that.__db._save('_security', false, that._security, callback);
            }
          ]
        , callback);

      function fctToString(obj) {
       for(var key in obj) {
          if(typeof obj[key] === 'function') {
            obj[key] = obj[key].toString();
          }else if(typeof obj[key] === 'object' && obj[key] !== null) {
            arguments.callee(obj[key]);
          }
        }
      }

      function syncDoc(docObj, callback) {

        //create the `rocket` namespace in the design doc
        docObj[ROCKET_NAMESPACE] = {};

        //add the validators to the design doc
        docObj[ROCKET_NAMESPACE].validators = oo.__extends({}, that.validators);

        //add the schema to the design doc
        docObj[ROCKET_NAMESPACE].schema = {};
        docObj[ROCKET_NAMESPACE].schema[doc_type] = 'module.exports = ' + JSON.stringify(that.schema);

        //convert all functions to strings
        fctToString(docObj);

        //make all validators available through commonJS' `require`
        for(var f in docObj[ROCKET_NAMESPACE].validators) {
          docObj[ROCKET_NAMESPACE].validators[f] = 'module.exports = ' + docObj[ROCKET_NAMESPACE].validators[f];
        }

        //make all the oo functions available through commonJS' `require`
        docObj[ROCKET_NAMESPACE].oo = fs.readFileSync(path.join(__dirname, '../utils/oo.js'), 'utf8');

        that.get(docObj._id, checkAndUpdate);

        function checkAndUpdate(err, doc) {

          doc = doc || {};

          var oldDocJSON = JSON.stringify(doc);

          //extend the DB doc with the current doc
          oo.__deepExtends(doc, docObj, {overwrite: true});

          //docObj to a JSON string
          var docJSON = JSON.stringify(doc);

          if(err) {
            if(err.error === 'not_found'){
              that.__db.save(doc._id, doc, callback);
            }else{
              console.log(('xxx [CouchDBResource] ERROR id: ' + doc._id + ' ' + require('util').inspect(err)).red);
              callback(err);
            }
          }else{

            if(oldDocJSON !== docJSON) {
              that.__db.save(doc._id, doc._rev, doc, callback);
            }else{
              callback(null);
            }
          }
        };
      };
    }
  , create: function create_CouchDBResource(properties, callback) {
      var _id = properties._id;
      delete properties._id;

      timestamp(properties);
      set_doc_type(properties, this.prototype.doc_type);

      this.__db.save(_id, properties, callback);
    }
  , save: function save_CouchDBResource(obj, callback) {
      timestamp(obj);
      set_doc_type(obj, this.prototype.doc_type);
      this.__db.save(obj._id, obj._rev, obj, callback);
    }
  , get: function get_CouchDBResource(_id, callback) {
      this.__db.get(_id, callback);
    }
  , update: function update_CouchDBResource(_id, properties, callback) {
      timestamp(properties);
      set_doc_type(properties, this.prototype.doc_type);
      this.__db.merge(_id, properties, callback);
    }
  , destroy: function destroy_CouchDBResource(_id, callback) {
      this.__db.remove(_id, callback);
    }
  , all: function all_CouchDBResource(callback) {
      this.__db.view('rocket/all', callback);
    }
  , view: function view_CouchDBResource() {
      this.__db.view.apply(this.__db, arguments);
    }
  };

oo.__extends(CouchDBResource, factoryFunctions, {overwrite: true});

/******************************************************************************
 * CouchDBResource's Constructor
 */
function CouchDBResource(obj) {
  arguments.callee.__super__.call(this, obj);
  setProperties(this, this);
};

oo.inherits(CouchDBResource, BaseResource);

//Finally export the CouchDBResource Object
module.exports = CouchDBResource;
<commit_msg>factory functions of CouchDBResource now return full objects. Also allow passing multiple constructors to Model.view<commit_after>/**
 * CouchDB base class/resource definition.
 * This file should be inherited by all CouchDB models that want to leverage
 * CouchDB's power in rocket.
 */

var crypto = require('crypto')
  , _ = require('underscore')
  , lingo = require('lingo')
  , cradle = require('cradle')
  , async = require('async')
  ;

var oo = require('../utils/oo')
  , namespace = require('../utils/namespace')
  , BaseResource = require('./base_resource')
  ;

/******************************************************************************
 * CONSTANTS
 */

var ROCKET_NAMESPACE = 'rocket';

/******************************************************************************
 * Default connection parameters
 */
CouchDBResource.connection = {
    host: 'localhost'
  , port: 5984
  , options: {
      raw: true
    , cache: false
    , auth: null
    }
  };

/******************************************************************************
 * Default _design documents                                     *** SYNCD ***
 */
CouchDBResource.ddocs = [
    {
      _id: '_design/rocket'
    , lists: {}
    , shows: {}
    , updates: {
        in_place: function(doc, req) {
          var oo  = require('rocket/oo')
            ;
          oo.__extends(doc, req.query, { overwrite: true });

          return [doc, JSON.stringify(doc)];
        }
      }
    , validate_doc_update: function(newDoc, oldDoc, userCtx) {

        if(newDoc._deleted
        || typeof newDoc.doc_type === 'undefined'
        || newDoc.doc_type === null
        || newDoc.doc_type === ''
        ){
          return;
        }

        var schema = require('rocket/schema/' + newDoc.doc_type);

        for(var member in schema) {

          if(typeof schema[member] !== 'undefined'
          && schema[member] !== null) {

            var validator;
            var optional;

            if(typeof schema[member] === 'string') {

              validator = require('rocket/validators/' + schema[member]) || null;

            }else if(typeof schema[member] === 'object') {

              optional = schema[member].optional;
              validator = (schema[member].validate ? require('rocket/validators/' + schema[member].validate) : null);

            }

            if(typeof newDoc[member] !== 'undefined'
            && newDoc[member] !== null) {
              if(validator) {
                validator(member, newDoc[member]);
              }else{
                continue;
              }
            }else if(optional){
              continue;
            }else{
              throw({ invalid: member + ' can\'t be missing or null' });
            }
          }
        }
      }
    , views: {
       all: {
          map: function(doc) { emit(doc._id, doc); }
        }
      }
    }
  ];

/******************************************************************************
 * Default _security document                                    *** SYNCD ***
 */
CouchDBResource._security = {
    admins: {
        names: ["admin"]
      , roles: []
      }
  , readers: {
        names: ["admin"]
      , roles: []
      }
  };

/******************************************************************************
 * Utils functions
 */
function setProperties(dst, src, synced) {

  var synced = typeof synced !== 'undefined' ? synced : true;

  if(! dst.synced)  { Object.defineProperty(dst, 'synced', {value: {}}); }
  if(! dst.values)    { Object.defineProperty(dst, 'values', {value: {}}); }

  function createSetter(prop) {
    return function(v) {
      dst.synced[prop] = dst.synced[prop] && dst.values[prop] === v;
      dst.values[prop] = v;
    }
  }

  function createGetter(prop) {
    return function() { return dst.values[prop] };
  }

  for(var prop in src) {
    var val = src[prop];
    delete src[prop];
    Object.defineProperty(dst, prop, { enumerable: true,  configurable: true, get: createGetter(prop), set: createSetter(prop) });
    dst.synced[prop] = synced;
    dst.values[prop] = val;
  }
}

function updateCache(obj, newValues) {
  obj.__db.cache.store[obj._id].document = newValues;
  obj.__db.cache.store[obj._id].attime = Date.now();
}

function timestamp(obj) {

  var current_time = new Date.now();

  if(typeof obj.creation_date === 'undefined'
  || obj.creation_date === null
  ){
    obj.creation_date = current_time;
  }

  obj.modification_date = current_time;
}

function set_doc_type(obj, doc_type) {
  if(typeof obj.doc_type === 'undefined'
  || obj.doc_type === null
  || obj.doc_type === ''
  || !obj.propertyIsEnumerable('doc_type')
  || obj.doc_type !== doc_type
  ){
    obj.doc_type = doc_type;
  }
}

function oo_cb_wrapper(cons, cb){
  return function(err, res) {

    var objects = [];

    if(err){ cb(err); return; }

    if(res) {
      if(Array.isArray(res)){
        cons = (Array.isArray(cons) ? cons : [cons]);

        for(var i = 0, ii = res.length; i < ii; i++) {
          objects.push(new cons[i % cons.length](res[i]));
        }
        cb(err, objects);
      }else{
        //single object...
        cb(err, new cons(res));
      }
    }else{
      cb(err, res); return;
    }

  };
}

/******************************************************************************
 * Resource Prototype Functions (used to create models)
 */
CouchDBResource.prototype = {
    save: function save_CouchDBResourceInstance(callback) {
      var that = this
      ;

      timestamp(this);
      set_doc_type(this, this.doc_type);

      this.__db.save(this._id, this._rev, this, function(err,res) {
        if(err){
          callback(err);
        }else{
          setProperties(that, that);
          callback(null, res);
        }
      });
    }
  , update: function update_CouchDBResourceInstance(callback) {
      var modz = {}
        , that = this
        ;

      timestamp(this);
      set_doc_type(this, this.doc_type);

      for(var k in this) {
        if(this.propertyIsEnumerable(k) === false) {
          continue;
        }

        if(! this.synced[k]) {
          modz[k] = this[k];
        }
      }

      if(modz !== {}) {
        this.__db.update('rocket/in_place', this._id, modz, function(err){
          if(err){
            callback(err);
          }else{
            setProperties(that, that);
            updateCache(that, that.values);
            callback.apply(that, Array.prototype.slice.apply(arguments));
          }
        });
      }else{
        callback(null, '');
      }
    }
  , destroy: function destroy_CouchDBResourceInstance(callback) {
      this.__db.remove(this._id, function(err) { callback(err); });
    }
  , reload: function reload_CouchDBResourceInstance(callback) {
      var that = this;

      this.__db.get(this._id, function(err, doc) {
        if(err) {
          callback(err);
        }else{

          setProperties(that, doc);
          callback(null, that);
        }
      });

    }
  , exists: function exists_CouchDBResourceInstance() {}
  };

/******************************************************************************
 * Resource Factory/Constructor Functions
 */
var factoryFunctions = {
    initialize: function initialize_CouchDBResource(model_name, callback) {
      var that = this
        , doc_type = namespace.extractName(model_name.toLowerCase(), { suffix: '_document' })
        ;

      //Initialize connection object
      that.__connection = new cradle.Connection(
          that.connection.host
        , that.connection.port
        , that.connection.options
        );

      //Infer DB name from file name unless specified
      if(typeof that.db_name !== 'undefined' && that.db_name !== null){
        that.__db_name = that.db_name;
      }else{
        that.__db_name = lingo.en.pluralize(doc_type);
      }

      //setup db object
      that.__db = that.__connection.database(that.__db_name);
      that.prototype.__db  = that.__db;

      that.prototype.doc_type  = doc_type;

      //Create db if it doesn't exists. Harmless otherwise.
      that.__db.create();

      async.parallel(
          [function(callback) {
              async.forEach(that.ddocs, syncDoc, callback);
            }
          , function(callback) {
              that.__db._save('_security', false, that._security, callback);
            }
          ]
        , callback);

      function fctToString(obj) {
       for(var key in obj) {
          if(typeof obj[key] === 'function') {
            obj[key] = obj[key].toString();
          }else if(typeof obj[key] === 'object' && obj[key] !== null) {
            arguments.callee(obj[key]);
          }
        }
      }

      function syncDoc(docObj, callback) {

        //create the `rocket` namespace in the design doc
        docObj[ROCKET_NAMESPACE] = {};

        //add the validators to the design doc
        docObj[ROCKET_NAMESPACE].validators = oo.__extends({}, that.validators);

        //add the schema to the design doc
        docObj[ROCKET_NAMESPACE].schema = {};
        docObj[ROCKET_NAMESPACE].schema[doc_type] = 'module.exports = ' + JSON.stringify(that.schema);

        //convert all functions to strings
        fctToString(docObj);

        //make all validators available through commonJS' `require`
        for(var f in docObj[ROCKET_NAMESPACE].validators) {
          docObj[ROCKET_NAMESPACE].validators[f] = 'module.exports = ' + docObj[ROCKET_NAMESPACE].validators[f];
        }

        //make all the oo functions available through commonJS' `require`
        docObj[ROCKET_NAMESPACE].oo = fs.readFileSync(path.join(__dirname, '../utils/oo.js'), 'utf8');

        that.get(docObj._id, checkAndUpdate);

        function checkAndUpdate(err, doc) {

          doc = doc || {};

          var oldDocJSON = JSON.stringify(doc);

          //extend the DB doc with the current doc
          oo.__deepExtends(doc, docObj, {overwrite: true});

          //docObj to a JSON string
          var docJSON = JSON.stringify(doc);

          if(err) {
            if(err.error === 'not_found'){
              that.__db.save(doc._id, doc, callback);
            }else{
              console.log(('xxx [CouchDBResource] ERROR id: ' + doc._id + ' ' + require('util').inspect(err)).red);
              callback(err);
            }
          }else{

            if(oldDocJSON !== docJSON) {
              that.__db.save(doc._id, doc._rev, doc, callback);
            }else{
              callback(null);
            }
          }
        };
      };
    }
  , create: function create_CouchDBResource(properties, callback) {
      var _id = properties._id;
      delete properties._id;

      timestamp(properties);
      set_doc_type(properties, this.prototype.doc_type);

      this.__db.save(_id, properties, callback);
    }
  , save: function save_CouchDBResource(obj, callback) {
      timestamp(obj);
      set_doc_type(obj, this.prototype.doc_type);
      this.__db.save(obj._id, obj._rev, obj, callback);
    }
  , get: function get_CouchDBResource(_id, callback) {
      this.__db.get(_id, oo_cb_wrapper(this.prototype.constructor, callback));
    }
  , update: function update_CouchDBResource(_id, properties, callback) {
      timestamp(properties);
      set_doc_type(properties, this.prototype.doc_type);
      this.__db.merge(_id, properties, callback);
    }
  , destroy: function destroy_CouchDBResource(_id, callback) {
      this.__db.remove(_id, callback);
    }
  , all: function all_CouchDBResource(args) {
      var args_array = Array.prototype.slice.call(args)
        ;

      args_array.unshift('rocket/all');

      this.view(args_array);
    }
  , view: function view_CouchDBResource() {
      var args_array    = Array.prototype.slice.call(arguments)
        , view          = args_array.shift()
        , params        = (
                             typeof args_array[0] === 'object'
                          && args_array[0]
                          && ! Array.isArray(args_array[0])
                          ? args_array.shift()
                          : {}
                          )
        , constructors  = (
                             typeof args_array[0] === 'object'
                          && args_array[0]
                          && Array.isArray(args_array[0])
                          ? args_array.shift()
                          : this.prototype.constructor
                          )
        , callback      = args_array.shift()
        ;

      //add doc_type argument to filter out other docs
      params.doc_type = this.prototype.doc_type;

      //call with our callback to objectify the result
      this.__db.view.apply(this.__db, params, oo_cb_wrapper(this.prototype.constructor, callback));
    }
  };

oo.__extends(CouchDBResource, factoryFunctions, {overwrite: true});

/******************************************************************************
 * CouchDBResource's Constructor
 */
function CouchDBResource(obj) {
  arguments.callee.__super__.call(this, obj);
  setProperties(this, this);
};

oo.inherits(CouchDBResource, BaseResource);

//Finally export the CouchDBResource Object
module.exports = CouchDBResource;
<|endoftext|>


<commit_before>"use strict";

const KafkaFactory = require("./KafkaFactory.js");
const KStream = require("./KStream.js");
const KTable = require("./KTable.js");
const KStorage = require("./KStorage.js");

/**
 * stream object factory
 */
class KafkaStreams {

    /**
     * can be used as factory to get
     * pre-build KStream and KTable instances
     * injected with a KafkaClient instance
     * and with a KStorage instance
     * @param {object} config
     * @param {KStorage} storageClass
     * @param {object} storageOptions
     * @param {boolean} disableStorageTest
     */
    constructor(config, storageClass = null, storageOptions = {}, disableStorageTest = false){

        this.config = config;

        this.factory = new KafkaFactory(config);
        this.storageClass = storageClass || KStorage;
        this.storageOptions = storageOptions;

        this.kafkaClients = [];
        this.storages = [];

        if(!disableStorageTest){
            KafkaStreams.checkStorageClass(this.storageClass);
        }
    }

    static checkStorageClass(storageClass){

        let test = null;
        try {
            test = new storageClass();
        } catch(e){
            throw new Error("storageClass should be a constructor.");
        }

        if(!(test instanceof KStorage)){
            throw new Error("storageClass should be a constructor that extends KStorage.");
        }
    }

    getKafkaClient(topic){
        const client = this.factory.getKafkaClient(topic);
        this.kafkaClients.push(client);
        return client;
    }

    getStorage(){
        const storage = new this.storageClass(this.storageOptions);
        this.storages.push(storage);
        return storage;
    }

    /**
     * get a new KStream instance
     * representing the topic as change-log
     * @param topic
     * @param storage
     * @returns {KStream}
     */
    getKStream(topic, storage = null){

        const kstream = new KStream(topic,
            storage || this.getStorage(),
            this.getKafkaClient(topic));

        kstream.setKafkaStreamsReference(this);
        return kstream;
    }

    /**
     * get a new KTable instance
     * representing the topic as table like stream
     * @param topic
     * @param keyMapETL
     * @param storage
     * @returns {KTable}
     */
    getKTable(topic, keyMapETL, storage = null){

        const ktable = new KTable(topic,
            keyMapETL,
            storage || this.getStorage(),
            this.getKafkaClient(topic));

        ktable.setKafkaStreamsReference(this);
        return ktable;
    }

    /**
     * returns array of statistics object
     * for each active kafka client in any
     * stream that has been created by this factory
     * stats will give good insights into consumer
     * and producer behaviour
     * warning: depending on the amount of streams you have created
     * this could result in a large object
     * @returns {Array}
     */
    getStats(){
        return this.kafkaClients.map(kafkaClient => kafkaClient.getStats());
    }

    /**
     * close any kafkaClient instance
     * and any storage instance
     * that has every been created by this factory
     */
    closeAll(){

        this.kafkaClients.forEach(consumer => consumer.close());
        this.kafkaClients = [];

        this.storages.forEach(storage => storage.close());
        this.storages = [];
    }
}

module.exports = KafkaStreams;
<commit_msg>fromMost for kakfastreams<commit_after>"use strict";

const KafkaFactory = require("./KafkaFactory.js");
const KStream = require("./KStream.js");
const KTable = require("./KTable.js");
const KStorage = require("./KStorage.js");

/**
 * stream object factory
 */
class KafkaStreams {

    /**
     * can be used as factory to get
     * pre-build KStream and KTable instances
     * injected with a KafkaClient instance
     * and with a KStorage instance
     * @param {object} config
     * @param {KStorage} storageClass
     * @param {object} storageOptions
     * @param {boolean} disableStorageTest
     */
    constructor(config, storageClass = null, storageOptions = {}, disableStorageTest = false){

        this.config = config;

        this.factory = new KafkaFactory(config);
        this.storageClass = storageClass || KStorage;
        this.storageOptions = storageOptions;

        this.kafkaClients = [];
        this.storages = [];

        if(!disableStorageTest){
            KafkaStreams.checkStorageClass(this.storageClass);
        }
    }

    static checkStorageClass(storageClass){

        let test = null;
        try {
            test = new storageClass();
        } catch(e){
            throw new Error("storageClass should be a constructor.");
        }

        if(!(test instanceof KStorage)){
            throw new Error("storageClass should be a constructor that extends KStorage.");
        }
    }

    getKafkaClient(topic){
        const client = this.factory.getKafkaClient(topic);
        this.kafkaClients.push(client);
        return client;
    }

    getStorage(){
        const storage = new this.storageClass(this.storageOptions);
        this.storages.push(storage);
        return storage;
    }

    /**
     * get a new KStream instance
     * representing the topic as change-log
     * @param topic
     * @param storage
     * @returns {KStream}
     */
    getKStream(topic, storage = null){

        const kstream = new KStream(topic,
            storage || this.getStorage(),
            this.getKafkaClient(topic));

        kstream.setKafkaStreamsReference(this);
        return kstream;
    }

    /**
     * get a new KStream instance
     * based on most.js
     * @param stream$
     * @param storage
     * @returns {KStream}
     */
    fromMost(stream$, storage = null){

        const kstream = this.getKStream(null, storage);
        kstream.replaceInternalObservable(stream$);
        return kstream;
    }

    /**
     * get a new KTable instance
     * representing the topic as table like stream
     * @param topic
     * @param keyMapETL
     * @param storage
     * @returns {KTable}
     */
    getKTable(topic, keyMapETL, storage = null){

        const ktable = new KTable(topic,
            keyMapETL,
            storage || this.getStorage(),
            this.getKafkaClient(topic));

        ktable.setKafkaStreamsReference(this);
        return ktable;
    }

    /**
     * returns array of statistics object
     * for each active kafka client in any
     * stream that has been created by this factory
     * stats will give good insights into consumer
     * and producer behaviour
     * warning: depending on the amount of streams you have created
     * this could result in a large object
     * @returns {Array}
     */
    getStats(){
        return this.kafkaClients.map(kafkaClient => kafkaClient.getStats());
    }

    /**
     * close any kafkaClient instance
     * and any storage instance
     * that has every been created by this factory
     */
    closeAll(){

        this.kafkaClients.forEach(consumer => consumer.close());
        this.kafkaClients = [];

        this.storages.forEach(storage => storage.close());
        this.storages = [];
    }
}

module.exports = KafkaStreams;
<|endoftext|>


<commit_before>// jQuery plugins
jQuery.expr[':'].text = function(a, i, m) {
	return jQuery(a).text().replace(/\s/g,'').toLowerCase()
		.indexOf(m[3].replace(/\s/g,'').toLowerCase()) >= 0;
};
jQuery.expr[':'].notext = function(a, i, m) {
	return jQuery(a).text().replace(/\s/g,'').toLowerCase()
		.indexOf(m[3].replace(/\s/g,'').toLowerCase()) < 0;
};

var clicktimer = false;
// разные мелкие функции
function rand(num1, num2) { return Math.round(Math.random() * (num2 - num1) + num1); }
function hastxt(sel, txt) { return $(sel).text().toLowerCase().replace(/\s/g,'').indexOf(txt.toLowerCase().replace(/\s/g,'')) > -1; }
function isUndef(elem) { return typeof elem == "undefined"; }
function empty(txt) { return (isUndef(txt) || txt === '' || txt === null); }
function str2secs(str) {
	str = str.toLowerCase();
	var res = 0;
	var a = str.split(' ');
	if(!a.length) return res;
	for(i=0;i<a.length;i+=2) {
		try {
			var l = a[i+1].substring(0,1);
				 if('ч' == l) res += parseInt(a[i],10) * 3600;
			else if('м' == l) res += parseInt(a[i],10) * 60;
			else if('с' == l) res += parseInt(a[i],10);
		} catch(e) { res += 0; }
	}
	return res;
}
function go(url, timer1, timer2) {
	if(clicktimer) return false;
	if(empty(timer1)) timer1 = 500;
	if(empty(timer2)) timer2 = timer1;
    var time = rand(timer1, timer2);
	setTimeout(function(){ self.location.href = url; }, time);
	return false;
}

// клик
function cl(sel, timer1, timer2) {
	if(clicktimer) return false;
	var clickEvent = document.createEvent ('MouseEvents');
	clickEvent.initEvent ('click', true, true);
	if(timer1 === undefined) timer1 = 500;
	if(timer2 === undefined) timer2 = 750;
	setTimeout(function(){
		try {
			(sel instanceof jQuery ? sel[0] : sel).dispatchEvent (clickEvent);
		} catch(e) {
			self.location.reload();
		}
	}, rand(timer1, timer2));
	clicktimer = true;
	return false;
}

// функция для отключения кликера - прописывается в родное окно
unsafeWindow.endis = function(varname) {
	if(empty(varname)) varname = "scriptenabled";
	var varval = eval(varname);
	GM_setValue(varname, !varval);
	self.location.reload();
}
<commit_msg>Первая попытка сделать универсальный массив<commit_after>// jQuery plugins
jQuery.expr[':'].text = function(a, i, m) {
	return jQuery(a).text().replace(/\s/g,'').toLowerCase()
		.indexOf(m[3].replace(/\s/g,'').toLowerCase()) >= 0;
};
jQuery.expr[':'].notext = function(a, i, m) {
	return jQuery(a).text().replace(/\s/g,'').toLowerCase()
		.indexOf(m[3].replace(/\s/g,'').toLowerCase()) < 0;
};

var clicktimer = false;
// разные мелкие функции
function rand(num1, num2) { return Math.round(Math.random() * (num2 - num1) + num1); }
function hastxt(sel, txt) { return $(sel).text().toLowerCase().replace(/\s/g,'').indexOf(txt.toLowerCase().replace(/\s/g,'')) > -1; }
function isUndef(elem) { return typeof elem == "undefined"; }
function empty(txt) { return (isUndef(txt) || txt === '' || txt === null); }
function str2secs(str) {
	str = str.toLowerCase();
	var res = 0;
	var a = str.split(' ');
	if(!a.length) return res;
	for(i=0;i<a.length;i+=2) {
		try {
			var l = a[i+1].substring(0,1);
				 if('ч' == l) res += parseInt(a[i],10) * 3600;
			else if('м' == l) res += parseInt(a[i],10) * 60;
			else if('с' == l) res += parseInt(a[i],10);
		} catch(e) { res += 0; }
	}
	return res;
}
function go(url, timer1, timer2) {
	if(clicktimer) return false;
	if(empty(timer1)) timer1 = 500;
	if(empty(timer2)) timer2 = timer1;
	var time = rand(timer1, timer2);
	setTimeout(function(){ self.location.href = url; }, time);
	return false;
}

// клик
function cl(sel, timer1, timer2) {
	if(clicktimer) return false;
	var clickEvent = document.createEvent ('MouseEvents');
	clickEvent.initEvent ('click', true, true);
	if(timer1 === undefined) timer1 = 500;
	if(timer2 === undefined) timer2 = 750;
	setTimeout(function(){
		try {
			(sel instanceof jQuery ? sel[0] : sel).dispatchEvent (clickEvent);
		} catch(e) {
			self.location.reload();
		}
	}, rand(timer1, timer2));
	clicktimer = true;
	return false;
}

// основной объект с настройками
var options = {scriptenabled: true};

// функция для отключения кликера - прописывается в родное окно
unsafeWindow.tglbool = function(varname) {
	if(empty(varname)) varname = "scriptenabled";
	var varval = !options[varname];
	GM_setValue("options", options);
	self.location.reload();
}

// инициализация массива с настройками
$(function(){ options = GM_getValue("options", options); });
<|endoftext|>


<commit_before>var alpha_report_service = require('../database/alpha_report.js');
var reporter_service = require('../database/reporter.js');
var nlp_parser = require('../parsers/nlp_parser.js');

module.exports = function(models, io, logger) {
	var me = this;

	me.parseAndSave = function(raw_feed_object, callback) {
		logger.debug("Attempting to parse raw_feed_object with id " + raw_feed_object._id);

		var alpha_report_object = {};

		alpha_report_object.raw_data_id = raw_feed_object._id;
		alpha_report_object.source_name = raw_feed_object.feedSource;

		var object_text = raw_feed_object.text;
		var parsed_text = JSON.parse(object_text);

		alpha_report_object.source_id = parsed_text.id_str;
		alpha_report_object.message_date = new Date(parsed_text.created_at);
		alpha_report_object.message_body = parsed_text.text;
		if(parsed_text.user.utc_offset) {
			alpha_report_object.utc_offset = parsed_text.user.utc_offset;
		}
		if(parsed_text.user.time_zone) {
			alpha_report_object.time_zone = parsed_text.user.time_zone;
		}
		alpha_report_object.lang = parsed_text.lang;

		//create reporter object from parsed data
		var reporter_object = {};
		reporter_object.name = parsed_text.user.name;
		reporter_object.source_name = raw_feed_object.feedSource;
		reporter_object.source_id = parsed_text.user.id_str;
		reporter_object.screen_name = parsed_text.user.screen_name;
		reporter_object.location_name = parsed_text.user.location;
		//reporter_object.email = parsed_text.user.
		//reporter_object.phone = parsed_text.user.
		//reporter_object.ip = parsed_text.user.
		if(parsed_text.user.url) {
			reporter_object.url = parsed_text.user.url;
		}
		reporter_object.description = parsed_text.user.description;
		if(parsed_text.user.time_zone) {
			reporter_object.utc_offset = parsed_text.user.utc_offset;
		}
		if(parsed_text.user.time_zone) {
			reporter_object.time_zone = parsed_text.user.time_zone;
		}
		reporter_object.lang = parsed_text.user.lang;
		//need to figure out geo
		if(parsed_text.coordinates !== undefined && parsed_text.coordinates !== null) {
			alpha_report_object.longitude = parsed_text.coordinates.coordinates[0];
			alpha_report_object.latitude = parsed_text.coordinates.coordinates[1];
		}
		alpha_report_object.radius = 0;

		// TODO  Need to figure out what the callback is for parseAndSave and call it

		reporter_service.saveReporter(reporter_object, function(err, valid, newReporter) {
			if(err) {
				//var msg = "There was an error saving off a parsed Reporter object";
				//me.callback(msg, null);
				logger.error(err);
			} else if (!valid.valid) {
				logger.info("Invalid Reporter " + JSON.stringify(valid.errors));
			} else {
				alpha_report_object.reporter_id = newReporter._id;
				alpha_report_service.saveAlphaReport(alpha_report_object, function(err, valid, res) {
					if (err) {
						//me.callback(err, res);
						logger.debug(res);

					} else if (!valid.valid) {
						logger.info('Invalid alpha_report ' + JSON.stringify(valid.errors));
					} else {
						nlp_parser.parseAndSave(res);
					}
				});
			}
			//callback();
		});
	};
};
<commit_msg>Date parsing for validation<commit_after>var alpha_report_service = require('../database/alpha_report.js');
var reporter_service = require('../database/reporter.js');
var nlp_parser = require('../parsers/nlp_parser.js');

module.exports = function(models, io, logger) {
	var me = this;

	me.parseAndSave = function(raw_feed_object, callback) {
		logger.debug("Attempting to parse raw_feed_object with id " + raw_feed_object._id);

		var alpha_report_object = {};

		alpha_report_object.raw_data_id = raw_feed_object._id;
		alpha_report_object.source_name = raw_feed_object.feedSource;

		var object_text = raw_feed_object.text;
		var parsed_text = JSON.parse(object_text);

		alpha_report_object.source_id = parsed_text.id_str;
		var parsedDate = new Date(parsed_text.created_at);
		console.log(parsedDate);
		alpha_report_object.message_date = parsedDate;
		alpha_report_object.message_body = parsed_text.text;
		if(parsed_text.user.utc_offset) {
			alpha_report_object.utc_offset = parsed_text.user.utc_offset;
		}
		if(parsed_text.user.time_zone) {
			alpha_report_object.time_zone = parsed_text.user.time_zone;
		}
		alpha_report_object.lang = parsed_text.lang;

		//create reporter object from parsed data
		var reporter_object = {};
		reporter_object.name = parsed_text.user.name;
		reporter_object.source_name = raw_feed_object.feedSource;
		reporter_object.source_id = parsed_text.user.id_str;
		reporter_object.screen_name = parsed_text.user.screen_name;
		reporter_object.location_name = parsed_text.user.location;
		//reporter_object.email = parsed_text.user.
		//reporter_object.phone = parsed_text.user.
		//reporter_object.ip = parsed_text.user.
		if(parsed_text.user.url) {
			reporter_object.url = parsed_text.user.url;
		}
		reporter_object.description = parsed_text.user.description;
		if(parsed_text.user.time_zone) {
			reporter_object.utc_offset = parsed_text.user.utc_offset;
		}
		if(parsed_text.user.time_zone) {
			reporter_object.time_zone = parsed_text.user.time_zone;
		}
		reporter_object.lang = parsed_text.user.lang;
		//need to figure out geo
		if(parsed_text.coordinates !== undefined && parsed_text.coordinates !== null) {
			alpha_report_object.longitude = parsed_text.coordinates.coordinates[0];
			alpha_report_object.latitude = parsed_text.coordinates.coordinates[1];
		}
		alpha_report_object.radius = 0;

		// TODO  Need to figure out what the callback is for parseAndSave and call it

		reporter_service.saveReporter(reporter_object, function(err, valid, newReporter) {
			if(err) {
				//var msg = "There was an error saving off a parsed Reporter object";
				//me.callback(msg, null);
				logger.error(err);
			} else if (!valid.valid) {
				logger.info("Invalid Reporter " + JSON.stringify(valid.errors));
			} else {
				alpha_report_object.reporter_id = newReporter._id;
				alpha_report_service.saveAlphaReport(alpha_report_object, function(err, valid, res) {
					if (err) {
						//me.callback(err, res);
						logger.debug(res);

					} else if (!valid.valid) {
						logger.info('Invalid alpha_report ' + JSON.stringify(valid.errors));
					} else {
						nlp_parser.parseAndSave(res);
					}
				});
			}
			//callback();
		});
	};
};
<|endoftext|>


<commit_before>/*
 * React FitText v0.0.3
 * https://github.com/gianu/react-fittext
 *
 * A port of the jQuery plugin: http://github.com/davatron5000/FitText.js
 *
 * Copyright 2014, Sergio Rafael Gianazza http://softwarepsychonaut.com
 *
 * Released under the MIT license
 * http://gianu.mit-license.org
 */
'use strict';

var React = require('react');
var ReactPropTypes = React.PropTypes;

module.exports = React.createClass({
  displayName: 'ReactFitText',

  propTypes: {
    compressor: ReactPropTypes.number,
    minFontSize: ReactPropTypes.number,
    maxFontSize: ReactPropTypes.number
  },

  getDefaultProps: function() {
    return {
      compressor: 1.0,
      minFontSize: Number.NEGATIVE_INFINITY,
      maxFontSize: Number.POSITIVE_INFINITY
    };
  },

  componentDidMount: function() {
    window.addEventListener("resize", this._onBodyResize);
    this._onBodyResize();
  },

  componentWillUnmount: function() {
    window.removeEventListener("resize", this._onBodyResize);
  },

  _onBodyResize: function() {
    var element = this.getDOMNode();
    var width = element.offsetWidth;
    element.style.fontSize = Math.max(
                      Math.min((width / (this.props.compressor*10)),
                                parseFloat(this.props.maxFontSize)),
                      parseFloat(this.props.minFontSize)) + 'px';
  },

  render: function() {
    return this.props.children;
  }
});
<commit_msg>Improved copyright<commit_after>/*
 * React FitText v0.0.3
 * https://github.com/gianu/react-fittext
 *
 * A port of the jQuery plugin: http://github.com/davatron5000/FitText.js
 *
 * Released under the MIT license
 * http://gianu.mit-license.org
 */
'use strict';

var React = require('react');
var ReactPropTypes = React.PropTypes;

module.exports = React.createClass({
  displayName: 'ReactFitText',

  propTypes: {
    compressor: ReactPropTypes.number,
    minFontSize: ReactPropTypes.number,
    maxFontSize: ReactPropTypes.number
  },

  getDefaultProps: function() {
    return {
      compressor: 1.0,
      minFontSize: Number.NEGATIVE_INFINITY,
      maxFontSize: Number.POSITIVE_INFINITY
    };
  },

  componentDidMount: function() {
    window.addEventListener("resize", this._onBodyResize);
    this._onBodyResize();
  },

  componentWillUnmount: function() {
    window.removeEventListener("resize", this._onBodyResize);
  },

  _onBodyResize: function() {
    var element = this.getDOMNode();
    var width = element.offsetWidth;
    element.style.fontSize = Math.max(
                      Math.min((width / (this.props.compressor*10)),
                                parseFloat(this.props.maxFontSize)),
                      parseFloat(this.props.minFontSize)) + 'px';
  },

  render: function() {
    return this.props.children;
  }
});
<|endoftext|>


<commit_before>// @flow

import React, { Component, type ElementProps } from 'react';
import classNames from 'classnames';

type AccordionItemTitleProps = ElementProps<'div'> & {
    hideBodyClassName: string,
    uuid: string | number,
};

type AccordionItemTitleState = {};

class AccordionItemTitle extends Component<
    AccordionItemTitleProps,
    AccordionItemTitleState,
> {
    static accordionElementName = 'AccordionItemTitle';

    handleClick = async () => {
        const { uuid, accordionStore } = this.props;
        const { state } = accordionStore;
        const { accordion, onChange, items } = state;
        const foundItem = items.find(item => item.uuid === uuid);

        await accordionStore.setExpanded(foundItem.uuid, !foundItem.expanded);

        if (accordion) {
            onChange(foundItem.uuid);
        } else {
            onChange(
                accordionStore.state.items
                    .filter(item => item.expanded)
                    .map(item => item.uuid),
            );
        }
    };

    handleKeyPress = (evt: SyntheticKeyboardEvent<HTMLButtonElement>) => {
        if (evt.charCode === 13 || evt.charCode === 32) {
            this.handleClick();
        }
    };

    render() {
        const {
            state: { items, accordion },
        } = this.props.accordionStore;
        const {
            uuid,
            className,
            hideBodyClassName,
            accordionStore,
            ...rest
        } = this.props;
        const foundItem = items.find(item => item.uuid === uuid);

        const { expanded, disabled } = foundItem;

        const id = `accordion__title-${uuid}`;
        const ariaControls = `accordion__body-${uuid}`;
        const role = accordion ? 'tab' : 'button';
        const titleClassName = classNames(className, {
            [hideBodyClassName]: hideBodyClassName && !expanded,
        });

        if (role === 'tab') {
            return (
                <div
                    id={id}
                    aria-selected={expanded}
                    aria-controls={ariaControls}
                    className={titleClassName}
                    onClick={disabled ? undefined : this.handleClick}
                    role={role}
                    tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
                    onKeyPress={this.handleKeyPress}
                    disabled={disabled}
                    {...rest}
                />
            );
        }
        return (
            <div
                id={id}
                aria-expanded={expanded}
                aria-controls={ariaControls}
                className={titleClassName}
                onClick={disabled ? undefined : this.handleClick}
                role={role}
                tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
                onKeyPress={this.handleKeyPress}
                disabled={disabled}
                {...rest}
            />
        );
    }
}

export default AccordionItemTitle;
<commit_msg>Remove async/await from 'accordion-item-title'.<commit_after>// @flow

import React, { Component, type ElementProps } from 'react';
import classNames from 'classnames';

type AccordionItemTitleProps = ElementProps<'div'> & {
    hideBodyClassName: string,
    uuid: string | number,
};

type AccordionItemTitleState = {};

class AccordionItemTitle extends Component<
    AccordionItemTitleProps,
    AccordionItemTitleState,
> {
    static accordionElementName = 'AccordionItemTitle';

    handleClick = () => {
        const { uuid, accordionStore } = this.props;
        const { state } = accordionStore;
        const { accordion, onChange, items } = state;
        const foundItem = items.find(item => item.uuid === uuid);

        accordionStore
            .setExpanded(foundItem.uuid, !foundItem.expanded)
            .then(() => {
                if (accordion) {
                    onChange(foundItem.uuid);
                } else {
                    onChange(
                        accordionStore.state.items
                            .filter(item => item.expanded)
                            .map(item => item.uuid),
                    );
                }
            });
    };

    handleKeyPress = (evt: SyntheticKeyboardEvent<HTMLButtonElement>) => {
        if (evt.charCode === 13 || evt.charCode === 32) {
            this.handleClick();
        }
    };

    render() {
        const {
            state: { items, accordion },
        } = this.props.accordionStore;
        const {
            uuid,
            className,
            hideBodyClassName,
            accordionStore,
            ...rest
        } = this.props;
        const foundItem = items.find(item => item.uuid === uuid);

        const { expanded, disabled } = foundItem;

        const id = `accordion__title-${uuid}`;
        const ariaControls = `accordion__body-${uuid}`;
        const role = accordion ? 'tab' : 'button';
        const titleClassName = classNames(className, {
            [hideBodyClassName]: hideBodyClassName && !expanded,
        });

        if (role === 'tab') {
            return (
                <div
                    id={id}
                    aria-selected={expanded}
                    aria-controls={ariaControls}
                    className={titleClassName}
                    onClick={disabled ? undefined : this.handleClick}
                    role={role}
                    tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
                    onKeyPress={this.handleKeyPress}
                    disabled={disabled}
                    {...rest}
                />
            );
        }
        return (
            <div
                id={id}
                aria-expanded={expanded}
                aria-controls={ariaControls}
                className={titleClassName}
                onClick={disabled ? undefined : this.handleClick}
                role={role}
                tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
                onKeyPress={this.handleKeyPress}
                disabled={disabled}
                {...rest}
            />
        );
    }
}

export default AccordionItemTitle;
<|endoftext|>