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

var RES_NACK     = exports.RES_NACK     = 1;
var REQ_PROPOSE  = exports.REQ_PROPOSE  = 10;
var RES_PROPOSED = exports.RES_PROPOSED = 11;
var REQ_ACCEPT   = exports.REQ_ACCEPT   = 20;
var RES_ACCEPTED = exports.RES_ACCEPTED = 21;

exports.proposer = function(node_name, node_restarts, slot, acceptors, comm, opts) {
  assert(node_name != null);
  assert(node_restarts > 0);
  assert(acceptors.length > 0);

  opts = opts || {};
  var proposer_timeout = opts.proposer_timeout || 3000; // In milliseconds.
  var quorum           = opts.quorum || majority;

  var tot_propose_phase       = 0; // Stats counters.
  var tot_propose_phase_loop  = 0;
  var tot_propose_send        = 0;
  var tot_propose_recv        = 0;
  var tot_propose_recv_err    = 0;
  var tot_propose_vote        = 0;
  var tot_propose_vote_repeat = 0;
  var tot_propose_timeout     = 0;

  function propose(val, cb) {
    var self = {};
    var timer = null;
    var ballot = next_ballot();

    // Run through two similar, sequential phases: propose & accept.
    //
    phase(REQ_PROPOSE, RES_PROPOSED, {},
          function(err, info) {
            if (err) {
              cb(err, info);
            } else {
              phase(REQ_ACCEPT, RES_ACCEPTED, { "val": val }, cb);
            }
          });

    function phase(kind, yea_kind, req, cb_phase) {
      tot_propose_phase = tot_propose_phase + 1;

      req.slot   = slot;
      req.kind   = kind;
      req.ballot = ballot;
      req.sender = node_name;
      comm.broadcast(acceptors, req);
      tot_propose_send = tot_propose_send + acceptors.length;
      restart_timer();

      var yea_needed = quorum(acceptors.length);
      var nay_needed = acceptors.length - yea_needed + 1;

      var tally = {};
      tally[yea_kind] = [ [], yea_needed, null ];
      tally[RES_NACK] = [ [], nay_needed, "rejected" ];

      self.on_msg = function(src, res) {
        tot_propose_recv = tot_propose_recv + 1;

        if (!timer) {
          log("paxos.propose - late message: " + res + " from src: " + src);
          return; // Drop/ignore late messages.
        }

        if (timer) {
          clearTimeout(timer);
        }
        timer = null;

        if (opts.msg_preprocess) {
          res = opts.msg_preprocess(src, res);
        }

        // Stop when recv()'ed votes reach tally quorum, either yea or nay.
        //
        if (is_member(acceptors, src) &&
            res != null &&
            res.req != null &&
            ballot_eq(res.req.ballot, ballot) &&
            tally[res.kind] != null) {
          var vkind = tally[res.kind];
          var votes = vkind[0];
          if (!is_member(votes, src)) {
            tot_propose_vote = tot_propose_vote + 1;
            votes[votes.length] = src;
            if (votes.length >= vkind[1]) {
              if (opts.on_phase_complete) {
                opts.on_phase_complete(yea_kind, vkind[2]);
              }

              cb_phase(vkind[2],
                       { "highest_proposed_ballot": res.highest_proposed_ballot,
                         "accepted_ballot":         res.accepted_ballot,
                         "accepted_val":            res.accepted_val });
              return;
            }
          } else {
            tot_propose_vote_repeat = tot_propose_vote_repeat + 1;
            log("paxos.propose - repeat vote: " + res + " from src: " + src);
          }
        } else {
          tot_propose_recv_err = tot_propose_recv_err + 1;
          log("paxos.propose - bad msg: " + res + " from src: " + src);
        }

        tot_propose_phase_loop = tot_propose_phase_loop + 1;
        timer_restart();
      }

      function restart_timer() {
        assert(!timer);
        timer = setTimeout(function() {
                             tot_propose_timeout = tot_propose_timeout + 1;
                             if (timer != null) {
                               timer = null;
                               cb_phase('timeout');
                             }
                           }, proposer_timeout);
      }
    }

    return self; // Provids a self.on_msg(src, msg) function.
  }

  var cur_ballot = ballot_mk(-1, node_name, node_restarts);
  function next_ballot() {
    cur_ballot = ballot_inc(cur_ballot);
    return cur_ballot;
  }

  function stats() {
    return { "tot_propose_phase"       : tot_propose_phase,
             "tot_propose_phase_loop"  : tot_propose_phase_loop,
             "tot_propose_send"        : tot_propose_send,
             "tot_propose_recv"        : tot_propose_recv,
             "tot_propose_recv_err"    : tot_propose_recv_err,
             "tot_propose_vote"        : tot_propose_vote,
             "tot_propose_vote_repeat" : tot_propose_vote_repeat,
             "tot_propose_timeout"     : tot_propose_timeout };
  }

  return { "propose": propose,
           "stats": stats };
};

// ----------------------------------------------------------------

exports.acceptor = function(storage, comm, opts) {
  opts = opts || {};
  var quorum = opts.quorum || majority;

  var tot_accept_bad_req      = 0; // Stats counters.
  var tot_accept_bad_req_kind = 0;
  var tot_accept_recv         = 0;
  var tot_accept_send         = 0;
  var tot_accept_propose      = 0;
  var tot_accept_proposed     = 0;
  var tot_accept_accept       = 0;
  var tot_accept_accepted     = 0;
  var tot_accept_nack_storage = 0;
  var tot_accept_nack_behind  = 0;

  function on_msg(src, req) {
    tot_accept_recv = tot_accept_recv + 1;
    if (req != null &&
        req.slot != null &&
        req.ballot != null) {
      // The acceptor's main responsibility is to process incoming
      // propose or accept requests with higher ballots.
      //
      storage.slot_read(req.slot, on_slot_read);

      function on_slot_read(err, slot_state) {
        if (!err) {
          slot_state = slot_state || {};
          var highest_proposed_ballot = slot_state.highest_proposed_ballot;
          var accepted_ballot         = slot_state.accepted_ballot;
          var accepted_val            = slot_state.accepted_val;

          if (ballot_gte(req.ballot, highest_proposed_ballot)) {
            if (req.kind == REQ_PROPOSE) {
              tot_accept_propose = tot_accept_propose + 1;
              storage.slot_save_highest_proposed_ballot(
                req.slot,
                req.ballot,
                function(err) {
                  if (!err) {
                    tot_accept_proposed = tot_accept_proposed + 1;
                    highest_proposed_ballot = req.ballot;
                    respond(req, RES_PROPOSED);
                  } else {
                    tot_accept_nack_storage = tot_accept_nack_storage + 1;
                    respond(req, RES_NACK);
                  }
                });
            } else if (req.kind == REQ_ACCEPT) {
              tot_accept_accept = tot_accept_accept + 1;
              storage.slot_save_accepted(
                req.slot,
                req.ballot,
                req.val,
                function(err) {
                  if (!err) {
                    tot_accept_accepted = tot_accept_accepted + 1;
                    highest_proposed_ballot = req.ballot;
                    accepted_ballot = req.ballot;
                    accepted_val = req.val;
                    respond(req, RES_ACCEPTED);
                  } else {
                    tot_accept_nack_storage = tot_accept_nack_storage + 1;
                    respond(req, RES_NACK);
                  }
                });
            } else {
              tot_accept_bad_req_kind = tot_accept_bad_req_kind + 1;
              log("paxos.accept - unknown req.kind: " + req.kind);
              respond(req, RES_NACK);
            }
          } else {
            tot_accept_nack_behind = tot_accept_nack_behind + 1;
            respond(req, RES_NACK,
                    { // Allow requestor to catch up to our accepted value.
                      "accepted_ballot": accepted_ballot,
                      "accepted_val":    accepted_val } );
          }

          function respond(req, kind, msg) {
            msg = msg || {};
            msg.highest_proposed_ballot = highest_proposed_ballot;
            respond_full(req, kind, msg);
          }
        } else {
          tot_accept_nack_storage = tot_accept_nack_storage + 1;
          respond_full(req, RES_NACK);
        }
      }
    } else {
      tot_accept_bad_req = tot_accept_bad_req + 1;
      log("paxos.accept - bad req");
    }
  }

  function respond_full(req, kind, msg) {
    msg = msg || {};
    msg.kind = kind;
    msg.req = req;
    if (opts.respond_preprocess) {
      msg = opts.respond_preproces(msg);
    }
    comm.send(req.sender, msg);
    tot_accept_send = tot_accept_send + 1;
  }

  function stats() {
    return { "tot_accept_bad_req"      : tot_accept_bad_req,
             "tot_accept_bad_req_kind" : tot_accept_bad_req_kind,
             "tot_accept_recv"         : tot_accept_recv,
             "tot_accept_send"         : tot_accept_send,
             "tot_accept_propose"      : tot_accept_propose,
             "tot_accept_proposed"     : tot_accept_proposed,
             "tot_accept_accept"       : tot_accept_accept,
             "tot_accept_accepted"     : tot_accept_accepted,
             "tot_accept_nack_storage" : tot_accept_nack_storage,
             "tot_accept_nack_behind"  : tot_accept_nack_behind };
  }

  return { "on_msg": on_msg,
           "stats":  stats };
};

// ----------------------------------------------------------------

function majority(n) {
  return Math.floor(n / 2) + 1;
}
exports.majority = majority;

function is_member(collection, item) {
  for (var i in collection) {
    if (collection[i] == item) {
      return true;
    }
  }
  return false;
}
exports.is_member = is_member;

// ----------------------------------------------------------------

var BALLOT_SEQ_NUM           = exports.BALLOT_SEQ_NUM           = 0;
var BALLOT_PROPOSER_NAME     = exports.BALLOT_PROPOSER_NAME     = 1;
var BALLOT_PROPOSER_RESTARTS = exports.BALLOT_PROPOSER_RESTARTS = 2;

function ballot_mk(seq_num, proposer_name, proposer_restarts) {
  return [seq_num, proposer_name, proposer_restarts];
}

var BOTTOM_BALLOT = ballot_mk(-1, -1, -1);

function ballot_inc(ballot) {
  return ballot_mk(ballot[BALLOT_SEQ_NUM] + 1,
                   ballot[BALLOT_PROPOSER_NAME],
                   ballot[BALLOT_PROPOSER_RESTARTS]);
}

function ballot_gte(a, b) { // Greater than or equal.
  a = a || BOTTOM_BALLOT;
  b = b || BOTTOM_BALLOT;
  for (var i = 0; i < Math.min(a.length, b.length); i++) {
    if (a[i] > b[i]) {
      return true;
    }
    if (a[i] < b[i]) {
      return false;
    }
  }
  return true;
}

function ballot_eq(a, b) {
  for (var i = 0; i < Math.min(a.length, b.length); i++) {
    if (a[i] != b[i]) {
      return false;
    }
  }
  return true;
}

exports.ballot_mk  = ballot_mk;
exports.ballot_inc = ballot_inc;
exports.ballot_gte = ballot_gte;
exports.ballot_eq  = ballot_eq;

<commit_msg>paxos acceptor responds with same slot as requested.<commit_after>var assert = require('assert');

var RES_NACK     = exports.RES_NACK     = 1;
var REQ_PROPOSE  = exports.REQ_PROPOSE  = 10;
var RES_PROPOSED = exports.RES_PROPOSED = 11;
var REQ_ACCEPT   = exports.REQ_ACCEPT   = 20;
var RES_ACCEPTED = exports.RES_ACCEPTED = 21;

exports.proposer = function(node_name, node_restarts, slot, acceptors, comm, opts) {
  assert(node_name != null);
  assert(node_restarts > 0);
  assert(acceptors.length > 0);

  opts = opts || {};
  var proposer_timeout = opts.proposer_timeout || 3000; // In milliseconds.
  var quorum           = opts.quorum || majority;

  var tot_propose_phase       = 0; // Stats counters.
  var tot_propose_phase_loop  = 0;
  var tot_propose_send        = 0;
  var tot_propose_recv        = 0;
  var tot_propose_recv_err    = 0;
  var tot_propose_vote        = 0;
  var tot_propose_vote_repeat = 0;
  var tot_propose_timeout     = 0;

  function propose(val, cb) {
    var self = {};
    var timer = null;
    var ballot = next_ballot();

    // Run through two similar, sequential phases: propose & accept.
    //
    phase(REQ_PROPOSE, RES_PROPOSED, {},
          function(err, info) {
            if (err) {
              cb(err, info);
            } else {
              phase(REQ_ACCEPT, RES_ACCEPTED, { "val": val }, cb);
            }
          });

    function phase(kind, yea_kind, req, cb_phase) {
      tot_propose_phase = tot_propose_phase + 1;

      req.slot   = slot;
      req.kind   = kind;
      req.ballot = ballot;
      req.sender = node_name;
      comm.broadcast(acceptors, req);
      tot_propose_send = tot_propose_send + acceptors.length;
      restart_timer();

      var yea_needed = quorum(acceptors.length);
      var nay_needed = acceptors.length - yea_needed + 1;

      var tally = {};
      tally[yea_kind] = [ [], yea_needed, null ];
      tally[RES_NACK] = [ [], nay_needed, "rejected" ];

      self.on_msg = function(src, res) {
        tot_propose_recv = tot_propose_recv + 1;

        if (!timer) {
          log("paxos.propose - late message: " + res + " from src: " + src);
          return; // Drop/ignore late messages.
        }

        if (timer) {
          clearTimeout(timer);
        }
        timer = null;

        if (opts.msg_preprocess) {
          res = opts.msg_preprocess(src, res);
        }

        // Stop when recv()'ed votes reach tally quorum, either yea or nay.
        //
        if (is_member(acceptors, src) &&
            res != null &&
            res.req != null &&
            ballot_eq(res.req.ballot, ballot) &&
            tally[res.kind] != null) {
          var vkind = tally[res.kind];
          var votes = vkind[0];
          if (!is_member(votes, src)) {
            tot_propose_vote = tot_propose_vote + 1;
            votes[votes.length] = src;
            if (votes.length >= vkind[1]) {
              if (opts.on_phase_complete) {
                opts.on_phase_complete(yea_kind, vkind[2]);
              }

              cb_phase(vkind[2],
                       { "highest_proposed_ballot": res.highest_proposed_ballot,
                         "accepted_ballot":         res.accepted_ballot,
                         "accepted_val":            res.accepted_val });
              return;
            }
          } else {
            tot_propose_vote_repeat = tot_propose_vote_repeat + 1;
            log("paxos.propose - repeat vote: " + res + " from src: " + src);
          }
        } else {
          tot_propose_recv_err = tot_propose_recv_err + 1;
          log("paxos.propose - bad msg: " + res + " from src: " + src);
        }

        tot_propose_phase_loop = tot_propose_phase_loop + 1;
        timer_restart();
      }

      function restart_timer() {
        assert(!timer);
        timer = setTimeout(function() {
                             tot_propose_timeout = tot_propose_timeout + 1;
                             if (timer != null) {
                               timer = null;
                               cb_phase('timeout');
                             }
                           }, proposer_timeout);
      }
    }

    return self; // Provids a self.on_msg(src, msg) function.
  }

  var cur_ballot = ballot_mk(-1, node_name, node_restarts);
  function next_ballot() {
    cur_ballot = ballot_inc(cur_ballot);
    return cur_ballot;
  }

  function stats() {
    return { "tot_propose_phase"       : tot_propose_phase,
             "tot_propose_phase_loop"  : tot_propose_phase_loop,
             "tot_propose_send"        : tot_propose_send,
             "tot_propose_recv"        : tot_propose_recv,
             "tot_propose_recv_err"    : tot_propose_recv_err,
             "tot_propose_vote"        : tot_propose_vote,
             "tot_propose_vote_repeat" : tot_propose_vote_repeat,
             "tot_propose_timeout"     : tot_propose_timeout };
  }

  return { "propose": propose,
           "stats": stats };
};

// ----------------------------------------------------------------

exports.acceptor = function(storage, comm, opts) {
  opts = opts || {};
  var quorum = opts.quorum || majority;

  var tot_accept_bad_req      = 0; // Stats counters.
  var tot_accept_bad_req_kind = 0;
  var tot_accept_recv         = 0;
  var tot_accept_send         = 0;
  var tot_accept_propose      = 0;
  var tot_accept_proposed     = 0;
  var tot_accept_accept       = 0;
  var tot_accept_accepted     = 0;
  var tot_accept_nack_storage = 0;
  var tot_accept_nack_behind  = 0;

  function on_msg(src, req) {
    tot_accept_recv = tot_accept_recv + 1;
    if (req != null &&
        req.slot != null &&
        req.ballot != null) {
      // The acceptor's main responsibility is to process incoming
      // propose or accept requests with higher ballots.
      //
      storage.slot_read(req.slot, on_slot_read);

      function on_slot_read(err, slot_state) {
        if (!err) {
          slot_state = slot_state || {};
          var highest_proposed_ballot = slot_state.highest_proposed_ballot;
          var accepted_ballot         = slot_state.accepted_ballot;
          var accepted_val            = slot_state.accepted_val;

          if (ballot_gte(req.ballot, highest_proposed_ballot)) {
            if (req.kind == REQ_PROPOSE) {
              tot_accept_propose = tot_accept_propose + 1;
              storage.slot_save_highest_proposed_ballot(
                req.slot,
                req.ballot,
                function(err) {
                  if (!err) {
                    tot_accept_proposed = tot_accept_proposed + 1;
                    highest_proposed_ballot = req.ballot;
                    respond(req, RES_PROPOSED);
                  } else {
                    tot_accept_nack_storage = tot_accept_nack_storage + 1;
                    respond(req, RES_NACK);
                  }
                });
            } else if (req.kind == REQ_ACCEPT) {
              tot_accept_accept = tot_accept_accept + 1;
              storage.slot_save_accepted(
                req.slot,
                req.ballot,
                req.val,
                function(err) {
                  if (!err) {
                    tot_accept_accepted = tot_accept_accepted + 1;
                    highest_proposed_ballot = req.ballot;
                    accepted_ballot = req.ballot;
                    accepted_val = req.val;
                    respond(req, RES_ACCEPTED);
                  } else {
                    tot_accept_nack_storage = tot_accept_nack_storage + 1;
                    respond(req, RES_NACK);
                  }
                });
            } else {
              tot_accept_bad_req_kind = tot_accept_bad_req_kind + 1;
              log("paxos.accept - unknown req.kind: " + req.kind);
              respond(req, RES_NACK);
            }
          } else {
            tot_accept_nack_behind = tot_accept_nack_behind + 1;
            respond(req, RES_NACK,
                    { // Allow requestor to catch up to our accepted value.
                      "accepted_ballot": accepted_ballot,
                      "accepted_val":    accepted_val } );
          }

          function respond(req, kind, msg) {
            msg = msg || {};
            msg.highest_proposed_ballot = highest_proposed_ballot;
            respond_full(req, kind, msg);
          }
        } else {
          tot_accept_nack_storage = tot_accept_nack_storage + 1;
          respond_full(req, RES_NACK);
        }
      }
    } else {
      tot_accept_bad_req = tot_accept_bad_req + 1;
      log("paxos.accept - bad req");
    }
  }

  function respond_full(req, kind, msg) {
    msg = msg || {};
    msg.slot = req.slot;
    msg.kind = kind;
    msg.req = req;
    if (opts.respond_preprocess) {
      msg = opts.respond_preproces(msg);
    }
    comm.send(req.sender, msg);
    tot_accept_send = tot_accept_send + 1;
  }

  function stats() {
    return { "tot_accept_bad_req"      : tot_accept_bad_req,
             "tot_accept_bad_req_kind" : tot_accept_bad_req_kind,
             "tot_accept_recv"         : tot_accept_recv,
             "tot_accept_send"         : tot_accept_send,
             "tot_accept_propose"      : tot_accept_propose,
             "tot_accept_proposed"     : tot_accept_proposed,
             "tot_accept_accept"       : tot_accept_accept,
             "tot_accept_accepted"     : tot_accept_accepted,
             "tot_accept_nack_storage" : tot_accept_nack_storage,
             "tot_accept_nack_behind"  : tot_accept_nack_behind };
  }

  return { "on_msg": on_msg,
           "stats":  stats };
};

// ----------------------------------------------------------------

function majority(n) {
  return Math.floor(n / 2) + 1;
}
exports.majority = majority;

function is_member(collection, item) {
  for (var i in collection) {
    if (collection[i] == item) {
      return true;
    }
  }
  return false;
}
exports.is_member = is_member;

// ----------------------------------------------------------------

var BALLOT_SEQ_NUM           = exports.BALLOT_SEQ_NUM           = 0;
var BALLOT_PROPOSER_NAME     = exports.BALLOT_PROPOSER_NAME     = 1;
var BALLOT_PROPOSER_RESTARTS = exports.BALLOT_PROPOSER_RESTARTS = 2;

function ballot_mk(seq_num, proposer_name, proposer_restarts) {
  return [seq_num, proposer_name, proposer_restarts];
}

var BOTTOM_BALLOT = ballot_mk(-1, -1, -1);

function ballot_inc(ballot) {
  return ballot_mk(ballot[BALLOT_SEQ_NUM] + 1,
                   ballot[BALLOT_PROPOSER_NAME],
                   ballot[BALLOT_PROPOSER_RESTARTS]);
}

function ballot_gte(a, b) { // Greater than or equal.
  a = a || BOTTOM_BALLOT;
  b = b || BOTTOM_BALLOT;
  for (var i = 0; i < Math.min(a.length, b.length); i++) {
    if (a[i] > b[i]) {
      return true;
    }
    if (a[i] < b[i]) {
      return false;
    }
  }
  return true;
}

function ballot_eq(a, b) {
  for (var i = 0; i < Math.min(a.length, b.length); i++) {
    if (a[i] != b[i]) {
      return false;
    }
  }
  return true;
}

exports.ballot_mk  = ballot_mk;
exports.ballot_inc = ballot_inc;
exports.ballot_gte = ballot_gte;
exports.ballot_eq  = ballot_eq;

<|endoftext|>


<commit_before>#!/usr/bin/env node
var geneToOsReaction = {};
var geneToProjReaction = {};
require('readline').createInterface({
  input: require('fs').createReadStream(process.argv[2]),
  terminal: false
})
.on('line', function(line) {
/*
0  Os Reaction Name
1  Os Reaction DB ID
2  Proj Reaction DB ID
3  Proj Reaction Species
4  Os Gene Product Locus ID
5  Os Gene Product DB ID
6  Proj Gene Product Locus ID
7  Proj Gene Product DB ID
*/
  var fields = line.split("\t");
  if (fields.length === 8) {
    var Os_gene_id = fields[4].toUpperCase();
    var Proj_gene_id = fields[6].toUpperCase();
    var Os_reaction_id = fields[1];
    var Proj_reaction_id = fields[2];
    // rice gene to rice reaction
    if (!geneToOsReaction.hasOwnProperty(Os_gene_id)) {
      geneToOsReaction[Os_gene_id] = {};
    }
    geneToOsReaction[Os_gene_id][Os_reaction_id] = 1;
    // projected gene to rice reaction
    if (!geneToOsReaction.hasOwnProperty(Proj_gene_id)) {
      geneToOsReaction[Proj_gene_id] = {};
    }
    geneToOsReaction[Proj_gene_id][Os_reaction_id] = 1;
    // projected gene to projected reaction
    if (!geneToProjReaction.hasOwnProperty(Proj_gene_id)) {
      geneToProjReaction[Proj_gene_id] = {};
    }
    geneToProjReaction[Proj_gene_id][Proj_reaction_id] = 1;
    // rice gene to rice reaction, but in the geneToProjReaction hash
    if (!geneToProjReaction.hasOwnProperty(Os_gene_id)) {
      geneToProjReaction[Os_gene_id] = {};
    }
    geneToProjReaction[Os_gene_id][Os_reaction_id] = 1;
  }
})
.on('close', function() {
  // read genes documents
  require('readline').createInterface(
    {
      input: process.stdin,
      terminal: false
    }
  )
  .on('line', function(line) { // one JSON object per line
     var gene = JSON.parse(line);
     if (geneToOsReaction.hasOwnProperty(gene._id.toUpperCase())) {
       gene.xrefs.pathways = Object.keys(geneToOsReaction[gene._id.toUpperCase()]); // these become pathways__ancestors in add_xref_ancestors.js
       gene.xrefs.reactions = Object.keys(geneToProjReaction[gene._id.toUpperCase()]); // these are for linking to plant reactome
     }
     console.log(JSON.stringify(gene));
  });
});
<commit_msg>make xrefs.reactions integers<commit_after>#!/usr/bin/env node
var geneToOsReaction = {};
var geneToProjReaction = {};
require('readline').createInterface({
  input: require('fs').createReadStream(process.argv[2]),
  terminal: false
})
.on('line', function(line) {
/*
0  Os Reaction Name
1  Os Reaction DB ID
2  Proj Reaction DB ID
3  Proj Reaction Species
4  Os Gene Product Locus ID
5  Os Gene Product DB ID
6  Proj Gene Product Locus ID
7  Proj Gene Product DB ID
*/
  var fields = line.split("\t");
  if (fields.length === 8) {
    var Os_gene_id = fields[4].toUpperCase();
    var Proj_gene_id = fields[6].toUpperCase();
    var Os_reaction_id = fields[1];
    var Proj_reaction_id = fields[2];
    // rice gene to rice reaction
    if (!geneToOsReaction.hasOwnProperty(Os_gene_id)) {
      geneToOsReaction[Os_gene_id] = {};
    }
    geneToOsReaction[Os_gene_id][Os_reaction_id] = 1;
    // projected gene to rice reaction
    if (!geneToOsReaction.hasOwnProperty(Proj_gene_id)) {
      geneToOsReaction[Proj_gene_id] = {};
    }
    geneToOsReaction[Proj_gene_id][Os_reaction_id] = 1;
    // projected gene to projected reaction
    if (!geneToProjReaction.hasOwnProperty(Proj_gene_id)) {
      geneToProjReaction[Proj_gene_id] = {};
    }
    geneToProjReaction[Proj_gene_id][Proj_reaction_id] = 1;
    // rice gene to rice reaction, but in the geneToProjReaction hash
    if (!geneToProjReaction.hasOwnProperty(Os_gene_id)) {
      geneToProjReaction[Os_gene_id] = {};
    }
    geneToProjReaction[Os_gene_id][Os_reaction_id] = 1;
  }
})
.on('close', function() {
  // read genes documents
  require('readline').createInterface(
    {
      input: process.stdin,
      terminal: false
    }
  )
  .on('line', function(line) { // one JSON object per line
     var gene = JSON.parse(line);
     if (geneToOsReaction.hasOwnProperty(gene._id.toUpperCase())) {
       gene.xrefs.pathways = Object.keys(geneToOsReaction[gene._id.toUpperCase()]); // these become pathways__ancestors in add_xref_ancestors.js
       gene.xrefs.reactions = Object.keys(geneToProjReaction[gene._id.toUpperCase()]).map(function(r){return +r}); // these are for linking to plant reactome
     }
     console.log(JSON.stringify(gene));
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var _ = require('lodash');
var router = express.Router();

router.get('/inbox', function(req, res) {
	req.getCredentials(function(error, credentials){
		if(error) res.status(500).json({ error: "Not Authenticated" });

		res.json(req.body);
	});
});

module.exports = router;<commit_msg>Fixed a reference issue<commit_after>var express = require('express');
var _ = require('lodash');
var router = express.Router();

router.get('/', function(req, res) {
	req.getCredentials(function(error, credentials){
		if(error) res.status(500).json({ error: "Not Authenticated" });

		res.json(req.body);
	});
});

module.exports = router;<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2016 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Object that controls settings for the workspace.
 * @author fenichel@google.com (Rachel Fenichel)
 */
'use strict';

goog.provide('Blockly.Options');
goog.require('Blockly.Colours');

/**
 * Parse the user-specified options, using reasonable defaults where behaviour
 * is unspecified.
 * @param {!Object} options Dictionary of options.  Specification:
 *   https://developers.google.com/blockly/guides/get-started/web#configuration
 * @constructor
 */
Blockly.Options = function(options) {
  var readOnly = !!options['readOnly'];
  if (readOnly) {
    var languageTree = null;
    var hasCategories = false;
    var hasTrashcan = false;
    var hasCollapse = false;
    var hasComments = false;
    var hasDisable = false;
    var hasSounds = false;
  } else {
    if (!options['toolbox']) {
      var oParser = new DOMParser();
      var dom = oParser.parseFromString(Blockly.Blocks.defaultToolbox, 'text/xml');
      options['toolbox'] = dom.children[0];
    }
    var languageTree = Blockly.Options.parseToolboxTree(options['toolbox']);
    var hasCategories = Boolean(languageTree &&
        languageTree.getElementsByTagName('category').length);
    var hasTrashcan = options['trashcan'];
    if (hasTrashcan === undefined) {
      hasTrashcan = hasCategories;
    }
    var hasCollapse = options['collapse'];
    if (hasCollapse === undefined) {
      hasCollapse = hasCategories;
    }
    var hasComments = options['comments'];
    if (hasComments === undefined) {
      hasComments = hasCategories;
    }
    var hasDisable = options['disable'];
    if (hasDisable === undefined) {
      hasDisable = hasCategories;
    }
    var hasSounds = options['sounds'];
    if (hasSounds === undefined) {
      hasSounds = true;
    }
  }
  var rtl = !!options['rtl'];
  var horizontalLayout = options['horizontalLayout'];
  if (horizontalLayout === undefined) {
    horizontalLayout = false;
  }
  var toolboxAtStart = options['toolboxPosition'];
  if (toolboxAtStart === 'end') {
    toolboxAtStart = false;
  } else {
    toolboxAtStart = true;
  }

  if (horizontalLayout) {
    var toolboxPosition = toolboxAtStart ?
        Blockly.TOOLBOX_AT_TOP : Blockly.TOOLBOX_AT_BOTTOM;
  } else {
    var toolboxPosition = (toolboxAtStart == rtl) ?
        Blockly.TOOLBOX_AT_RIGHT : Blockly.TOOLBOX_AT_LEFT;
  }

  var hasScrollbars = options['scrollbars'];
  if (hasScrollbars === undefined) {
    hasScrollbars = hasCategories;
  }
  var hasCss = options['css'];
  if (hasCss === undefined) {
    hasCss = true;
  }
  var pathToMedia = 'https://blockly-demo.appspot.com/static/media/';
  if (options['media']) {
    pathToMedia = options['media'];
  } else if (options['path']) {
    // 'path' is a deprecated option which has been replaced by 'media'.
    pathToMedia = options['path'] + 'media/';
  }
  if (options['oneBasedIndex'] === undefined) {
    var oneBasedIndex = true;
  } else {
    var oneBasedIndex = !!options['oneBasedIndex'];
  }

  var enableRealtime = !!options['realtime'];
  var realtimeOptions = enableRealtime ? options['realtimeOptions'] : undefined;

  // Colour overrides provided by the injection
  var colours = options['colours'];
  if (colours) {
    for (var colourProperty in colours) {
      if (colours.hasOwnProperty(colourProperty) &&
          Blockly.Colours.hasOwnProperty(colourProperty)) {
        // If a property is in both colours option and Blockly.Colours,
        // set the Blockly.Colours value to the override.
        Blockly.Colours[colourProperty] = colours[colourProperty];
      }
    }
  }

  this.RTL = rtl;
  this.oneBasedIndex = oneBasedIndex;
  this.collapse = hasCollapse;
  this.comments = hasComments;
  this.disable = hasDisable;
  this.readOnly = readOnly;
  this.pathToMedia = pathToMedia;
  this.hasCategories = hasCategories;
  this.hasScrollbars = hasScrollbars;
  this.hasTrashcan = hasTrashcan;
  this.hasSounds = hasSounds;
  this.hasCss = hasCss;
  this.horizontalLayout = horizontalLayout;
  this.languageTree = languageTree;
  this.gridOptions = Blockly.Options.parseGridOptions_(options);
  this.zoomOptions = Blockly.Options.parseZoomOptions_(options);
  this.enableRealtime = enableRealtime;
  this.realtimeOptions = realtimeOptions;
  this.toolboxPosition = toolboxPosition;
};

/**
 * The parent of the current workspace, or null if there is no parent workspace.
 * @type {Blockly.Workspace}
 **/
Blockly.Options.prototype.parentWorkspace = null;

/**
 * If set, sets the translation of the workspace to match the scrollbars.
 */
Blockly.Options.prototype.setMetrics = null;

/**
 * Return an object with the metrics required to size the workspace.
 * @return {Object} Contains size and position metrics, or null.
 */
Blockly.Options.prototype.getMetrics = null;

/**
 * Parse the user-specified zoom options, using reasonable defaults where
 * behaviour is unspecified.  See zoom documentation:
 *   https://developers.google.com/blockly/guides/configure/web/zoom
 * @param {!Object} options Dictionary of options.
 * @return {!Object} A dictionary of normalized options.
 * @private
 */
Blockly.Options.parseZoomOptions_ = function(options) {
  var zoom = options['zoom'] || {};
  var zoomOptions = {};
  if (zoom['controls'] === undefined) {
    zoomOptions.controls = false;
  } else {
    zoomOptions.controls = !!zoom['controls'];
  }
  if (zoom['wheel'] === undefined) {
    zoomOptions.wheel = false;
  } else {
    zoomOptions.wheel = !!zoom['wheel'];
  }
  if (zoom['startScale'] === undefined) {
    zoomOptions.startScale = 1;
  } else {
    zoomOptions.startScale = parseFloat(zoom['startScale']);
  }
  if (zoom['maxScale'] === undefined) {
    zoomOptions.maxScale = 3;
  } else {
    zoomOptions.maxScale = parseFloat(zoom['maxScale']);
  }
  if (zoom['minScale'] === undefined) {
    zoomOptions.minScale = 0.3;
  } else {
    zoomOptions.minScale = parseFloat(zoom['minScale']);
  }
  if (zoom['scaleSpeed'] === undefined) {
    zoomOptions.scaleSpeed = 1.2;
  } else {
    zoomOptions.scaleSpeed = parseFloat(zoom['scaleSpeed']);
  }
  return zoomOptions;
};

/**
 * Parse the user-specified grid options, using reasonable defaults where
 * behaviour is unspecified. See grid documentation:
 *   https://developers.google.com/blockly/guides/configure/web/grid
 * @param {!Object} options Dictionary of options.
 * @return {!Object} A dictionary of normalized options.
 * @private
 */
Blockly.Options.parseGridOptions_ = function(options) {
  var grid = options['grid'] || {};
  var gridOptions = {};
  gridOptions.spacing = parseFloat(grid['spacing']) || 0;
  gridOptions.colour = grid['colour'] || '#888';
  gridOptions.length = parseFloat(grid['length']) || 1;
  gridOptions.snap = gridOptions.spacing > 0 && !!grid['snap'];
  return gridOptions;
};

/**
 * Parse the provided toolbox tree into a consistent DOM format.
 * @param {Node|string} tree DOM tree of blocks, or text representation of same.
 * @return {Node} DOM tree of blocks, or null.
 */
Blockly.Options.parseToolboxTree = function(tree) {
  if (tree) {
    if (typeof tree != 'string') {
      if (typeof XSLTProcessor == 'undefined' && tree.outerHTML) {
        // In this case the tree will not have been properly built by the
        // browser. The HTML will be contained in the element, but it will
        // not have the proper DOM structure since the browser doesn't support
        // XSLTProcessor (XML -> HTML). This is the case in IE 9+.
        tree = tree.outerHTML;
      } else if (!(tree instanceof Element)) {
        tree = null;
      }
    }
    if (typeof tree == 'string') {
      tree = Blockly.Xml.textToDom(tree);
    }
  } else {
    tree = null;
  }
  return tree;
};
<commit_msg>Fix IE and Edge Default Toolbox<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2016 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Object that controls settings for the workspace.
 * @author fenichel@google.com (Rachel Fenichel)
 */
'use strict';

goog.provide('Blockly.Options');
goog.require('Blockly.Colours');

/**
 * Parse the user-specified options, using reasonable defaults where behaviour
 * is unspecified.
 * @param {!Object} options Dictionary of options.  Specification:
 *   https://developers.google.com/blockly/guides/get-started/web#configuration
 * @constructor
 */
Blockly.Options = function(options) {
  var readOnly = !!options['readOnly'];
  if (readOnly) {
    var languageTree = null;
    var hasCategories = false;
    var hasTrashcan = false;
    var hasCollapse = false;
    var hasComments = false;
    var hasDisable = false;
    var hasSounds = false;
  } else {
    if (!options['toolbox']) {
      var oParser = new DOMParser();
      var dom = oParser.parseFromString(Blockly.Blocks.defaultToolbox, 'text/xml');
      options['toolbox'] = dom.documentElement;
    }
    var languageTree = Blockly.Options.parseToolboxTree(options['toolbox']);
    var hasCategories = Boolean(languageTree &&
        languageTree.getElementsByTagName('category').length);
    var hasTrashcan = options['trashcan'];
    if (hasTrashcan === undefined) {
      hasTrashcan = hasCategories;
    }
    var hasCollapse = options['collapse'];
    if (hasCollapse === undefined) {
      hasCollapse = hasCategories;
    }
    var hasComments = options['comments'];
    if (hasComments === undefined) {
      hasComments = hasCategories;
    }
    var hasDisable = options['disable'];
    if (hasDisable === undefined) {
      hasDisable = hasCategories;
    }
    var hasSounds = options['sounds'];
    if (hasSounds === undefined) {
      hasSounds = true;
    }
  }
  var rtl = !!options['rtl'];
  var horizontalLayout = options['horizontalLayout'];
  if (horizontalLayout === undefined) {
    horizontalLayout = false;
  }
  var toolboxAtStart = options['toolboxPosition'];
  if (toolboxAtStart === 'end') {
    toolboxAtStart = false;
  } else {
    toolboxAtStart = true;
  }

  if (horizontalLayout) {
    var toolboxPosition = toolboxAtStart ?
        Blockly.TOOLBOX_AT_TOP : Blockly.TOOLBOX_AT_BOTTOM;
  } else {
    var toolboxPosition = (toolboxAtStart == rtl) ?
        Blockly.TOOLBOX_AT_RIGHT : Blockly.TOOLBOX_AT_LEFT;
  }

  var hasScrollbars = options['scrollbars'];
  if (hasScrollbars === undefined) {
    hasScrollbars = hasCategories;
  }
  var hasCss = options['css'];
  if (hasCss === undefined) {
    hasCss = true;
  }
  var pathToMedia = 'https://blockly-demo.appspot.com/static/media/';
  if (options['media']) {
    pathToMedia = options['media'];
  } else if (options['path']) {
    // 'path' is a deprecated option which has been replaced by 'media'.
    pathToMedia = options['path'] + 'media/';
  }
  if (options['oneBasedIndex'] === undefined) {
    var oneBasedIndex = true;
  } else {
    var oneBasedIndex = !!options['oneBasedIndex'];
  }

  var enableRealtime = !!options['realtime'];
  var realtimeOptions = enableRealtime ? options['realtimeOptions'] : undefined;

  // Colour overrides provided by the injection
  var colours = options['colours'];
  if (colours) {
    for (var colourProperty in colours) {
      if (colours.hasOwnProperty(colourProperty) &&
          Blockly.Colours.hasOwnProperty(colourProperty)) {
        // If a property is in both colours option and Blockly.Colours,
        // set the Blockly.Colours value to the override.
        Blockly.Colours[colourProperty] = colours[colourProperty];
      }
    }
  }

  this.RTL = rtl;
  this.oneBasedIndex = oneBasedIndex;
  this.collapse = hasCollapse;
  this.comments = hasComments;
  this.disable = hasDisable;
  this.readOnly = readOnly;
  this.pathToMedia = pathToMedia;
  this.hasCategories = hasCategories;
  this.hasScrollbars = hasScrollbars;
  this.hasTrashcan = hasTrashcan;
  this.hasSounds = hasSounds;
  this.hasCss = hasCss;
  this.horizontalLayout = horizontalLayout;
  this.languageTree = languageTree;
  this.gridOptions = Blockly.Options.parseGridOptions_(options);
  this.zoomOptions = Blockly.Options.parseZoomOptions_(options);
  this.enableRealtime = enableRealtime;
  this.realtimeOptions = realtimeOptions;
  this.toolboxPosition = toolboxPosition;
};

/**
 * The parent of the current workspace, or null if there is no parent workspace.
 * @type {Blockly.Workspace}
 **/
Blockly.Options.prototype.parentWorkspace = null;

/**
 * If set, sets the translation of the workspace to match the scrollbars.
 */
Blockly.Options.prototype.setMetrics = null;

/**
 * Return an object with the metrics required to size the workspace.
 * @return {Object} Contains size and position metrics, or null.
 */
Blockly.Options.prototype.getMetrics = null;

/**
 * Parse the user-specified zoom options, using reasonable defaults where
 * behaviour is unspecified.  See zoom documentation:
 *   https://developers.google.com/blockly/guides/configure/web/zoom
 * @param {!Object} options Dictionary of options.
 * @return {!Object} A dictionary of normalized options.
 * @private
 */
Blockly.Options.parseZoomOptions_ = function(options) {
  var zoom = options['zoom'] || {};
  var zoomOptions = {};
  if (zoom['controls'] === undefined) {
    zoomOptions.controls = false;
  } else {
    zoomOptions.controls = !!zoom['controls'];
  }
  if (zoom['wheel'] === undefined) {
    zoomOptions.wheel = false;
  } else {
    zoomOptions.wheel = !!zoom['wheel'];
  }
  if (zoom['startScale'] === undefined) {
    zoomOptions.startScale = 1;
  } else {
    zoomOptions.startScale = parseFloat(zoom['startScale']);
  }
  if (zoom['maxScale'] === undefined) {
    zoomOptions.maxScale = 3;
  } else {
    zoomOptions.maxScale = parseFloat(zoom['maxScale']);
  }
  if (zoom['minScale'] === undefined) {
    zoomOptions.minScale = 0.3;
  } else {
    zoomOptions.minScale = parseFloat(zoom['minScale']);
  }
  if (zoom['scaleSpeed'] === undefined) {
    zoomOptions.scaleSpeed = 1.2;
  } else {
    zoomOptions.scaleSpeed = parseFloat(zoom['scaleSpeed']);
  }
  return zoomOptions;
};

/**
 * Parse the user-specified grid options, using reasonable defaults where
 * behaviour is unspecified. See grid documentation:
 *   https://developers.google.com/blockly/guides/configure/web/grid
 * @param {!Object} options Dictionary of options.
 * @return {!Object} A dictionary of normalized options.
 * @private
 */
Blockly.Options.parseGridOptions_ = function(options) {
  var grid = options['grid'] || {};
  var gridOptions = {};
  gridOptions.spacing = parseFloat(grid['spacing']) || 0;
  gridOptions.colour = grid['colour'] || '#888';
  gridOptions.length = parseFloat(grid['length']) || 1;
  gridOptions.snap = gridOptions.spacing > 0 && !!grid['snap'];
  return gridOptions;
};

/**
 * Parse the provided toolbox tree into a consistent DOM format.
 * @param {Node|string} tree DOM tree of blocks, or text representation of same.
 * @return {Node} DOM tree of blocks, or null.
 */
Blockly.Options.parseToolboxTree = function(tree) {
  if (tree) {
    if (typeof tree != 'string') {
      if (typeof XSLTProcessor == 'undefined' && tree.outerHTML) {
        // In this case the tree will not have been properly built by the
        // browser. The HTML will be contained in the element, but it will
        // not have the proper DOM structure since the browser doesn't support
        // XSLTProcessor (XML -> HTML). This is the case in IE 9+.
        tree = tree.outerHTML;
      } else if (!(tree instanceof Element)) {
        tree = null;
      }
    }
    if (typeof tree == 'string') {
      tree = Blockly.Xml.textToDom(tree);
    }
  } else {
    tree = null;
  }
  return tree;
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Vanderbilt University, All rights reserved.
 *
 * Author: Tamas Kecskes
 */

define([ "util/assert"], function (ASSERT) {
    "use strict";

    var SETS_ID = '_sets';
    var REL_ID = 'member';

    function SetCore(innerCore){

        //help functions
        var setModified = function(node){
            //innerCore.setRegistry(node,'_sets_',(innerCore.getRegistry(node,'_sets_') || 0)+1);
        };
        var getMemberPath = function(node,setElementNode){
            var ownPath = innerCore.getPath(node),
                memberPath = innerCore.getPointerPath(setElementNode,REL_ID);
            ownPath = ownPath.substring(0,ownPath.indexOf('/_')); //TODO this is a hack and should be solved some other way if possible
            if(ownPath !== memberPath){
                return memberPath;
            }

            //now we should check who really set this member as its own
            while(innerCore.getBase(node) !== null && innerCore.getBase(setElementNode) !== null && innerCore.getRegistry(innerCore.getBase(setElementNode),'_') === '_'){
                node = innerCore.getBase(node);
                setElementNode = innerCore.getBase(setElementNode);
                ownPath = innerCore.getPath(node);
                ownPath = ownPath.substring(0,ownPath.indexOf('/_')); //TODO this is a hack and should be solved some other way if possible
            }

            return ownPath;

        };
        var getMemberRelId = function(node,setName,memberPath){
            ASSERT(typeof setName === 'string');
            var setNode = innerCore.getChild(innerCore.getChild(node,SETS_ID),setName);
            var elements = innerCore.getChildrenRelids(setNode);

            for(var i=0;i<elements.length;i++){
                if(getMemberPath(node,innerCore.getChild(setNode,elements[i])) === memberPath){
                    return elements[i];
                }
            }
            return null;
        };
        var createNewMemberRelid = function(setNode){
            var MAX_RELID = Math.pow(2, 31);
            var existingRelIds = innerCore.getChildrenRelids(setNode);
            var relid;
            do{
                relid = Math.floor(Math.random() * MAX_RELID);
            } while (existingRelIds.indexOf(relid) !== -1);
            return "" + relid;
        };

        //copy lower layer
        var setcore = {};
        for(var i in innerCore){
            setcore[i] = innerCore[i];
        }

        //adding new functions
        setcore.getSetNumbers = function(node){
            return this.getSetNames(node).length;
        };
        setcore.getSetNames = function(node){
            return  innerCore.getPointerNames(innerCore.getChild(node,SETS_ID))|| [];
        };
        setcore.getPointerNames = function(node){
            var sorted = [],
                raw = innerCore.getPointerNames(node);
            for(var i=0;i<raw.length;i++){
                if(raw[i].indexOf(REL_ID) === -1){
                    sorted.push(raw[i]);
                }
            }
            return sorted;
        };
        setcore.getCollectionNames = function(node){
            var sorted = [],
                raw = innerCore.getCollectionNames(node);
            for(var i=0;i<raw.length;i++){
                if(raw[i].indexOf(REL_ID) === -1){
                    sorted.push(raw[i]);
                }
            }
            return sorted;
        };
        setcore.getMemberPaths = function(node,setName){
            ASSERT(typeof setName === 'string');
            var setNode = innerCore.getChild(innerCore.getChild(node,SETS_ID),setName);
            var members = [];
            var elements = innerCore.getChildrenRelids(setNode);
            for(var i=0;i<elements.length;i++){
                var path = getMemberPath(node,innerCore.getChild(setNode,elements[i]));
                if(path){
                    members.push(path);
                }
            }
            return members;
        };
        setcore.delMember = function(node,setName,memberPath){
            ASSERT(typeof setName === 'string');
            //we only need the path of the member so we allow to enter only it
            if(typeof memberPath !== 'string'){
                memberPath = innerCore.getPath(memberPath);
            }

            var setMemberRelId = getMemberRelId(node,setName,memberPath);
            if(setMemberRelId){
                var setMemberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),setMemberRelId);
                innerCore.deleteNode(setMemberNode);
                setModified(node);
            }
        };
        setcore.addMember = function(node,setName,member){
            ASSERT(typeof setName === 'string');
            var setsNode = innerCore.getChild(node,SETS_ID);
            //TODO decide if the member addition should really create the set or it should fail...
            if(innerCore.getPointerPath(setsNode,setName) === undefined){
                setcore.createSet(node,setName);
            }
            var setNode = innerCore.getChild(setsNode,setName);
            var setMemberRelId = getMemberRelId(node,setName,setcore.getPath(member));
            if(setMemberRelId === null){
                var setMember =  innerCore.getChild(setNode,createNewMemberRelid(setNode));
                innerCore.setPointer(setMember,'member',member);
                innerCore.setRegistry(setMember,"_","_");//TODO hack, somehow the empty children have been removed during persist
                setModified(node);
            }
        };

        setcore.getMemberAttributeNames = function(node,setName,memberPath){
            ASSERT(typeof setName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                return innerCore.getAttributeNames(memberNode);
            }
            return [];
        };
        setcore.getMemberAttribute = function(node,setName,memberPath,attrName){
            ASSERT(typeof setName === 'string' && typeof attrName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                return innerCore.getAttribute(memberNode,attrName);
            }
        };
        setcore.setMemberAttribute = function(node,setName,memberPath,attrName,attrValue){
            ASSERT(typeof setName === 'string' && typeof attrName === 'string' && attrValue !== undefined);
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                innerCore.setAttribute(memberNode,attrName,attrValue);
                setModified(node);
            }
        };
        setcore.delMemberAttribute = function(node,setName,memberPath,attrName){
            ASSERT(typeof setName === 'string' && typeof attrName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                innerCore.delAttribute(memberNode,attrName);
                setModified(node);
            }
        };

        setcore.getMemberRegistryNames = function(node,setName,memberPath){
            ASSERT(typeof setName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                return innerCore.getRegistryNames(memberNode);
            }
            return [];
        };
        setcore.getMemberRegistry = function(node,setName,memberPath,regName){
            ASSERT(typeof setName === 'string' && typeof regName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                return innerCore.getRegistry(memberNode,regName);
            }
        };
        setcore.setMemberRegistry = function(node,setName,memberPath,regName,regValue){
            ASSERT(typeof setName === 'string' && typeof regName === 'string' && regValue !== undefined);
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                innerCore.setRegistry(memberNode,regName,regValue);
                setModified(node);
            }
        };
        setcore.delMemberRegistry = function(node,setName,memberPath,regName){
            ASSERT(typeof setName === 'string' && typeof regName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                innerCore.delRegistry(memberNode,regName);
                setModified(node);
            }
        };
        setcore.createSet = function(node,setName) {
            ASSERT(typeof setName === 'string');
            var setsNode = innerCore.getChild(node,SETS_ID),
                setNode = innerCore.getChild(setsNode,setName);
            innerCore.setRegistry(setNode,"_","_");//TODO hack, somehow the empty children have been removed during persist
            innerCore.setPointer(innerCore.getChild(node,SETS_ID), setName, null);
            setModified(node);
        };
        setcore.deleteSet = function(node,setName) {
            ASSERT(typeof setName === 'string');
            var setsNode = innerCore.getChild(node,SETS_ID),
                setNode = innerCore.getChild(setsNode,setName);
            innerCore.deletePointer(setsNode,setName);
            innerCore.deleteNode(setNode);
            setModified(node);
        };

        setcore.isMemberOf = function(node){
            //TODO we should find a proper way to do this - or at least some support from lower layers would be fine
            var coll = setcore.getCollectionPaths(node,REL_ID);
            var sets = {};
            for(var i=0;i<coll.length;i++){
                var pathArray = coll[i].split('/');
                if(pathArray.indexOf('_meta') === -1){
                    //now we simply skip META sets...
                    var index = pathArray.indexOf(SETS_ID);
                    if(index>0 && pathArray.length>index+1){
                        //otherwise it is not a real set
                        var ownerPath = pathArray.slice(0,index).join('/');
                        if(sets[ownerPath] === undefined){
                            sets[ownerPath] = [];
                        }
                        sets[ownerPath].push(pathArray[index+1]);
                    }
                }
            }
            return sets;
        };

        setcore.getSingleNodeHash = function(node){
            //TODO this function only needed while the inheritance is not in its final form!!!
            //bb377d14fd57cbe2b0a2ad297a7a303b7a5fccf3
            ASSERT(setcore.isValidNode(node));
            function xorHashes (a, b) {
                var outHash = "";
                if(a.length === b.length){
                    for(var i=0;i< a.length;i++){
                        outHash += (parseInt(a.charAt(i),16) ^ parseInt(b.charAt(i),16)).toString(16);
                    }
                }
                return outHash;
            }
            //var hash = "0000000000000000000000000000000000000000";
            var hash = innerCore.getSingleNodeHash(node);

            //now we should stir all the sets hashes into the node's hash to get changes deep inside
            var names = setcore.getSetNames(node);
            for(var i=0;i<names.length;i++){
                var setNode = setcore.getChild(setcore.getChild(node,SETS_ID),names[i]);
                var memberRelids = setcore.getChildrenRelids(setNode);
                for(var j=0;j<memberRelids.length;j++){
                    hash = xorHashes(hash,innerCore.getSingleNodeHash(setcore.getChild(setNode,memberRelids[j])));
                }
            }

            return hash;
        };

        return setcore;

    }

    return SetCore;
});

<commit_msg>instance member containment issue has been resolved<commit_after>/*
 * Copyright (C) 2012 Vanderbilt University, All rights reserved.
 *
 * Author: Tamas Kecskes
 */

define([ "util/assert"], function (ASSERT) {
    "use strict";

    var SETS_ID = '_sets';
    var REL_ID = 'member';

    function SetCore(innerCore){

        //help functions
        var setModified = function(node){
            //innerCore.setRegistry(node,'_sets_',(innerCore.getRegistry(node,'_sets_') || 0)+1);
        };
        var getMemberPath = function(node,setElementNode){
            var ownPath = innerCore.getPath(node),
                memberPath = innerCore.getPointerPath(setElementNode,REL_ID);
            ownPath = ownPath.substring(0,ownPath.indexOf('/_')); //TODO this is a hack and should be solved some other way if possible
            if(ownPath !== memberPath){
                return memberPath;
            }

            //now we should check who really set this member as its own
            while(innerCore.getBase(node) !== null && innerCore.getBase(setElementNode) !== null && innerCore.getRegistry(innerCore.getBase(setElementNode),'_') === '_'){
                node = innerCore.getBase(node);
                setElementNode = innerCore.getBase(setElementNode);
                ownPath = innerCore.getPath(node);
                ownPath = ownPath.substring(0,ownPath.indexOf('/_')); //TODO this is a hack and should be solved some other way if possible
            }
            memberPath = innerCore.getPointerPath(setElementNode,REL_ID);

            return memberPath;

        };
        var getMemberRelId = function(node,setName,memberPath){
            ASSERT(typeof setName === 'string');
            var setNode = innerCore.getChild(innerCore.getChild(node,SETS_ID),setName);
            var elements = innerCore.getChildrenRelids(setNode);

            for(var i=0;i<elements.length;i++){
                if(getMemberPath(node,innerCore.getChild(setNode,elements[i])) === memberPath){
                    return elements[i];
                }
            }
            return null;
        };
        var createNewMemberRelid = function(setNode){
            var MAX_RELID = Math.pow(2, 31);
            var existingRelIds = innerCore.getChildrenRelids(setNode);
            var relid;
            do{
                relid = Math.floor(Math.random() * MAX_RELID);
            } while (existingRelIds.indexOf(relid) !== -1);
            return "" + relid;
        };

        //copy lower layer
        var setcore = {};
        for(var i in innerCore){
            setcore[i] = innerCore[i];
        }

        //adding new functions
        setcore.getSetNumbers = function(node){
            return this.getSetNames(node).length;
        };
        setcore.getSetNames = function(node){
            return  innerCore.getPointerNames(innerCore.getChild(node,SETS_ID))|| [];
        };
        setcore.getPointerNames = function(node){
            var sorted = [],
                raw = innerCore.getPointerNames(node);
            for(var i=0;i<raw.length;i++){
                if(raw[i].indexOf(REL_ID) === -1){
                    sorted.push(raw[i]);
                }
            }
            return sorted;
        };
        setcore.getCollectionNames = function(node){
            var sorted = [],
                raw = innerCore.getCollectionNames(node);
            for(var i=0;i<raw.length;i++){
                if(raw[i].indexOf(REL_ID) === -1){
                    sorted.push(raw[i]);
                }
            }
            return sorted;
        };
        setcore.getMemberPaths = function(node,setName){
            ASSERT(typeof setName === 'string');
            var setNode = innerCore.getChild(innerCore.getChild(node,SETS_ID),setName);
            var members = [];
            var elements = innerCore.getChildrenRelids(setNode);
            for(var i=0;i<elements.length;i++){
                var path = getMemberPath(node,innerCore.getChild(setNode,elements[i]));
                if(path){
                    members.push(path);
                }
            }
            return members;
        };
        setcore.delMember = function(node,setName,memberPath){
            ASSERT(typeof setName === 'string');
            //we only need the path of the member so we allow to enter only it
            if(typeof memberPath !== 'string'){
                memberPath = innerCore.getPath(memberPath);
            }

            var setMemberRelId = getMemberRelId(node,setName,memberPath);
            if(setMemberRelId){
                var setMemberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),setMemberRelId);
                innerCore.deleteNode(setMemberNode);
                setModified(node);
            }
        };
        setcore.addMember = function(node,setName,member){
            ASSERT(typeof setName === 'string');
            var setsNode = innerCore.getChild(node,SETS_ID);
            //TODO decide if the member addition should really create the set or it should fail...
            if(innerCore.getPointerPath(setsNode,setName) === undefined){
                setcore.createSet(node,setName);
            }
            var setNode = innerCore.getChild(setsNode,setName);
            var setMemberRelId = getMemberRelId(node,setName,setcore.getPath(member));
            if(setMemberRelId === null){
                var setMember =  innerCore.getChild(setNode,createNewMemberRelid(setNode));
                innerCore.setPointer(setMember,'member',member);
                innerCore.setRegistry(setMember,"_","_");//TODO hack, somehow the empty children have been removed during persist
                setModified(node);
            }
        };

        setcore.getMemberAttributeNames = function(node,setName,memberPath){
            ASSERT(typeof setName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                return innerCore.getAttributeNames(memberNode);
            }
            return [];
        };
        setcore.getMemberAttribute = function(node,setName,memberPath,attrName){
            ASSERT(typeof setName === 'string' && typeof attrName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                return innerCore.getAttribute(memberNode,attrName);
            }
        };
        setcore.setMemberAttribute = function(node,setName,memberPath,attrName,attrValue){
            ASSERT(typeof setName === 'string' && typeof attrName === 'string' && attrValue !== undefined);
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                innerCore.setAttribute(memberNode,attrName,attrValue);
                setModified(node);
            }
        };
        setcore.delMemberAttribute = function(node,setName,memberPath,attrName){
            ASSERT(typeof setName === 'string' && typeof attrName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                innerCore.delAttribute(memberNode,attrName);
                setModified(node);
            }
        };

        setcore.getMemberRegistryNames = function(node,setName,memberPath){
            ASSERT(typeof setName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                return innerCore.getRegistryNames(memberNode);
            }
            return [];
        };
        setcore.getMemberRegistry = function(node,setName,memberPath,regName){
            ASSERT(typeof setName === 'string' && typeof regName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                return innerCore.getRegistry(memberNode,regName);
            }
        };
        setcore.setMemberRegistry = function(node,setName,memberPath,regName,regValue){
            ASSERT(typeof setName === 'string' && typeof regName === 'string' && regValue !== undefined);
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                innerCore.setRegistry(memberNode,regName,regValue);
                setModified(node);
            }
        };
        setcore.delMemberRegistry = function(node,setName,memberPath,regName){
            ASSERT(typeof setName === 'string' && typeof regName === 'string');
            var memberRelId = getMemberRelId(node,setName,memberPath);
            if(memberRelId){
                var memberNode = innerCore.getChild(innerCore.getChild(innerCore.getChild(node,SETS_ID),setName),memberRelId);
                innerCore.delRegistry(memberNode,regName);
                setModified(node);
            }
        };
        setcore.createSet = function(node,setName) {
            ASSERT(typeof setName === 'string');
            var setsNode = innerCore.getChild(node,SETS_ID),
                setNode = innerCore.getChild(setsNode,setName);
            innerCore.setRegistry(setNode,"_","_");//TODO hack, somehow the empty children have been removed during persist
            innerCore.setPointer(innerCore.getChild(node,SETS_ID), setName, null);
            setModified(node);
        };
        setcore.deleteSet = function(node,setName) {
            ASSERT(typeof setName === 'string');
            var setsNode = innerCore.getChild(node,SETS_ID),
                setNode = innerCore.getChild(setsNode,setName);
            innerCore.deletePointer(setsNode,setName);
            innerCore.deleteNode(setNode);
            setModified(node);
        };

        setcore.isMemberOf = function(node){
            //TODO we should find a proper way to do this - or at least some support from lower layers would be fine
            var coll = setcore.getCollectionPaths(node,REL_ID);
            var sets = {};
            for(var i=0;i<coll.length;i++){
                var pathArray = coll[i].split('/');
                if(pathArray.indexOf('_meta') === -1){
                    //now we simply skip META sets...
                    var index = pathArray.indexOf(SETS_ID);
                    if(index>0 && pathArray.length>index+1){
                        //otherwise it is not a real set
                        var ownerPath = pathArray.slice(0,index).join('/');
                        if(sets[ownerPath] === undefined){
                            sets[ownerPath] = [];
                        }
                        sets[ownerPath].push(pathArray[index+1]);
                    }
                }
            }
            return sets;
        };

        setcore.getSingleNodeHash = function(node){
            //TODO this function only needed while the inheritance is not in its final form!!!
            //bb377d14fd57cbe2b0a2ad297a7a303b7a5fccf3
            ASSERT(setcore.isValidNode(node));
            function xorHashes (a, b) {
                var outHash = "";
                if(a.length === b.length){
                    for(var i=0;i< a.length;i++){
                        outHash += (parseInt(a.charAt(i),16) ^ parseInt(b.charAt(i),16)).toString(16);
                    }
                }
                return outHash;
            }
            //var hash = "0000000000000000000000000000000000000000";
            var hash = innerCore.getSingleNodeHash(node);

            //now we should stir all the sets hashes into the node's hash to get changes deep inside
            var names = setcore.getSetNames(node);
            for(var i=0;i<names.length;i++){
                var setNode = setcore.getChild(setcore.getChild(node,SETS_ID),names[i]);
                var memberRelids = setcore.getChildrenRelids(setNode);
                for(var j=0;j<memberRelids.length;j++){
                    hash = xorHashes(hash,innerCore.getSingleNodeHash(setcore.getChild(setNode,memberRelids[j])));
                }
            }

            return hash;
        };

        return setcore;

    }

    return SetCore;
});

<|endoftext|>


<commit_before>M.wrap('github/jillix/crud-links/dev/links.js', function (require, module, exports) {

var Events = require('github/jillix/events');

// function to clone a JSON object (it wil not clone function, dates, etc.)
function cloneJSON(obj) {
    // basic type deep copy
    if (obj === null || obj === undefined || typeof obj !== 'object')  {
        return obj
    }
    // array deep copy
    if (obj instanceof Array) {
        var cloneA = [];
        for (var i = 0; i < obj.length; ++i) {
            cloneA[i] = cloneJSON(obj[i]);
        }
        return cloneA;
    }
    // object deep copy
    var cloneO = {};
    for (var i in obj) {
        cloneO[i] = cloneJSON(obj[i]);
    }
    return cloneO;
}

function setData (data) {
    //console.log(data);
}

function setTemplate (template) {

    var self = this;

    if (!template || (self.template && self.template._id === template._id)) {
        return;
    }

    self.template = template;

    // uninit the clones
    for (var cloneMiid in self.clones) {
        self.uninit(cloneMiid);
    }

    // empty the clone cache
    self.clones = {};

    // nothing to do when there are no links
    if (!template.links) {
        return;
    }

    for (var i = 0, l = template.links.length; i < l; ++i) {
        // we clone the default configurations because they will be modified by the modules
        var filterConfig = cloneJSON(self.config.clones.filter.config) || {};
        var tableConfig = cloneJSON(self.config.clones.table.config) || {};

        // links with table only option have only a filter with no UI
        if (!template.links[i].tableOnly && filterConfig.ui) {
            delete filterConfig.ui;
        }

        // clone the filters for this link
        var filterCloneMiid = self.config.clones.filter.miid + '_' + template._id;
        M.clone('#linksContainer', self.config.clones.filter.miid, '_' + template._id, filterConfig, function(module) {
            self.clones[filterCloneMiid] = module;
        });
        // clone the table for this link
        var tableCloneMiid = self.config.clones.table.miid + '_' + template._id;
        M.clone('#linksContainer', self.config.clones.table.miid, '_' + template._id, tableConfig, function(module) {
            self.clones[tableCloneMiid] = module;
        });
    }
}

function init (config) {
    var self = this;
    self.config = config;

    self.on('setData', setData);
    self.on('setTemplate', setTemplate);

    // listen to external events
    Events.call(self, self.config);

    self.emit('ready');
}

module.exports = init;

return module; });
<commit_msg>Added event configuration between filter and table link pairs<commit_after>M.wrap('github/jillix/crud-links/dev/links.js', function (require, module, exports) {

var Events = require('github/jillix/events');

// function to clone a JSON object (it wil not clone function, dates, etc.)
function cloneJSON(obj) {
    // basic type deep copy
    if (obj === null || obj === undefined || typeof obj !== 'object')  {
        return obj
    }
    // array deep copy
    if (obj instanceof Array) {
        var cloneA = [];
        for (var i = 0; i < obj.length; ++i) {
            cloneA[i] = cloneJSON(obj[i]);
        }
        return cloneA;
    }
    // object deep copy
    var cloneO = {};
    for (var i in obj) {
        cloneO[i] = cloneJSON(obj[i]);
    }
    return cloneO;
}

function setData (data) {
    //console.log(data);
}

function setTemplate (template) {

    var self = this;

    if (!template || (self.template && self.template._id === template._id)) {
        return;
    }

    self.template = template;

    // uninit the clones
    for (var cloneMiid in self.clones) {
        self.uninit(cloneMiid);
    }

    // empty the clone cache
    self.clones = {};

    // nothing to do when there are no links
    if (!template.links) {
        return;
    }

    for (var i = 0, l = template.links.length; i < l; ++i) {
        var targetTemplateId = template.links[i]._tp;
        // we clone the default configurations because they will be modified by the modules
        var filterConfig = cloneJSON(self.config.clones.filter.config) || {};
        var tableConfig = cloneJSON(self.config.clones.table.config) || {};
        // the clone miids
        var filterCloneMiid = self.config.clones.filter.miid + '_' + template._id + '_' + targetTemplateId;
        var tableCloneMiid = self.config.clones.table.miid + '_' + template._id + '_' + targetTemplateId;

        // let CRUD know that he should listen to this new filter module
        self.emit('listenTo', [filterCloneMiid]);

        // the filter must wait for the table to load because it will notify the table about the template
        filterConfig.waitFor = filterConfig.waitFor || [];
        filterConfig.waitFor.push(tableCloneMiid);
        // configure the table to listen to the filter module
        filterConfig.listen = filterConfig.listen || {};
        filterConfig.listen[self.miid] = {};
        filterConfig.listen[self.miid][filterCloneMiid + '_setTemplate'] = [ { emit: 'setTemplate' } ];

        // configure the table to listen to the filter module
        tableConfig.listen = tableConfig.listen || {};
        tableConfig.listen[filterCloneMiid] = {
            result: [ { handler: 'renderItemsFromResult' } ],
            template: [ { handler: 'setTemplate' } ],
            filtersChanged: [ { handler: 'clearSkip' } ]
        };

        // links with table only option have only a filter with no UI
        if (!template.links[i].tableOnly && filterConfig.ui) {
            delete filterConfig.ui;
        }

        // emit a special event to set the template for this filter module
        (function(targetTemplateId){
            self.on('ready', filterCloneMiid, function() {
                self.emit(filterCloneMiid + '_setTemplate', targetTemplateId);
            });
        })(targetTemplateId);

        // clone the filters for this link
        M.clone('#linksContainer', self.config.clones.filter.miid, '_' + template._id + '_' + targetTemplateId, filterConfig, (function(filterCloneMiid) {
            return function(module) {
                self.clones[filterCloneMiid] = module;
            };
        })(filterCloneMiid));

        // clone the table for this link
        M.clone('#linksContainer', self.config.clones.table.miid, '_' + template._id + '_' + targetTemplateId, tableConfig, (function(tableCloneMiid) {
            return function(module) {
                self.clones[tableCloneMiid] = module;
            };
        })(tableCloneMiid));
    }
}

function init (config) {
    var self = this;
    self.config = config;

    self.on('setData', setData);
    self.on('setTemplate', setTemplate);

    // listen to external events
    Events.call(self, self.config);

    self.emit('ready');
}

module.exports = init;

return module; });
<|endoftext|>


<commit_before>Meteor.publish('allResidents', function () {
  return Residents.find();
});

Meteor.publish('selectResidents', function (residentIdsArray) {
  return Residents.find({_id: {$in: residentIdsArray}});
});
<commit_msg>Add homeResidents publication; comments<commit_after>Meteor.publish('allResidents', function () {
  // Publish all residents
  return Residents.find();
});

Meteor.publish('selectResidents', function (residentIdsArray) {
  // Publish residents indicated by array of IDs
  return Residents.find({_id: {$in: residentIdsArray}});
});

Meteor.publish('homeResidents', function (homeId) {
  // Publish all residents of a given home
  return Residents.find({homeId: homeId});
});
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
var expect = chai.expect;
chai.use(sinonChai);

var Copyright = require('../../helpers/modules/Copyright');
var CopyrightValidator = require('../doubles/CopyrightValidator');

describe('copyright', function() {

    var copyright,
        validator;

    beforeEach(function() {
        validator = new CopyrightValidator();
        copyright = new Copyright(validator);
    });

    afterEach(function() {
        copyright = null;
        validator = null;
    });

    describe('Return values', function() {

        describe('format not provided', function() {

            it('should call validateCurrentYear() of CopyrightValidator with correct arguments', function() {
                var currentYear = 2018;
                var spy = sinon.spy(CopyrightValidator.prototype, 'validateCurrentYear');

                copyright.get(2013, currentYear);

                expect(spy.withArgs(currentYear)).calledOnce;

                CopyrightValidator.prototype.validateCurrentYear.restore();
            });

            it('should return correct text', function() {
                var startYear = 2013,
                    currentYear = 2018,
                    expected = `${currentYear}`;

                var actual = copyright.get(startYear, currentYear);

                expect(actual).to.equal(expected);
            });

        });

        describe('format "current"', function() {

            var format;

            beforeEach(function() {
                format = 'current';
            });

            it('should call validateCurrentYear() of CopyrightValidator with correct arguments', function() {
                var currentYear = 2018;
                var spy = sinon.spy(CopyrightValidator.prototype, 'validateCurrentYear');

                copyright.get(2013, currentYear, format);

                expect(spy.withArgs(currentYear)).calledOnce;

                CopyrightValidator.prototype.validateCurrentYear.restore();
            });

            it('should return correct text', function() {
                var startYear = 2013,
                    currentYear = 2018,
                    expected = `${currentYear}`;

                var actual = copyright.get(startYear, currentYear, format);

                expect(actual).to.equal(expected);
            });

        });

        describe('format "range"', function() {

            var format;

            beforeEach(function() {
                format = 'range';
            });

            it('should call validateRange() of CopyrightValidator with correct arguments', function() {
                var startYear = 2013,
                    currentYear = 2018;

                var spy = sinon.spy(CopyrightValidator.prototype, 'validateRange');

                copyright.get(startYear, currentYear, format);

                expect(spy.withArgs(startYear, currentYear)).calledOnce;

                CopyrightValidator.prototype.validateRange.restore();
            });

            it('should return correct text if startYear is equal to currentYear', function() {
                var startYear = 2018,
                    currentYear = 2018,
                    expectedText = `${currentYear}`;

                var actualText = copyright.get(startYear, currentYear, format);

                expect(actualText).to.equal(expectedText);
            });

            it('should return correct text if currentYear is greater than startYear', function() {
                var startYear = 2014,
                    currentYear = 2020,
                    expectedText = `${startYear} - ${currentYear}`;

                var actualText = copyright.get(startYear, currentYear, format);

                expect(actualText).to.equal(expectedText);
            });

        });

    });

});<commit_msg>Refactor copyright test<commit_after>'use strict';

var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
var expect = chai.expect;
chai.use(sinonChai);

var Copyright = require('../../helpers/modules/Copyright');
var CopyrightValidator = require('../doubles/CopyrightValidator');

describe('copyright', function() {

    var copyright,
        validator;

    beforeEach(function() {
        validator = new CopyrightValidator();
        copyright = new Copyright(validator);
    });

    afterEach(function() {
        copyright = null;
        validator = null;
    });

    describe('get', function() {

        describe('format not provided', function() {

            it('should call validateCurrentYear() of CopyrightValidator with correct arguments', function() {
                var currentYear = 2018;
                var spy = sinon.spy(CopyrightValidator.prototype, 'validateCurrentYear');

                copyright.get(2013, currentYear);

                expect(spy.withArgs(currentYear)).calledOnce;

                CopyrightValidator.prototype.validateCurrentYear.restore();
            });

            it('should return correct text', function() {
                var startYear = 2013,
                    currentYear = 2018,
                    expected = `${currentYear}`;

                var actual = copyright.get(startYear, currentYear);

                expect(actual).to.equal(expected);
            });

        });

        describe('format "current"', function() {

            var format;

            beforeEach(function() {
                format = 'current';
            });

            it('should call validateCurrentYear() of CopyrightValidator with correct arguments', function() {
                var currentYear = 2018;
                var spy = sinon.spy(CopyrightValidator.prototype, 'validateCurrentYear');

                copyright.get(2013, currentYear, format);

                expect(spy.withArgs(currentYear)).calledOnce;

                CopyrightValidator.prototype.validateCurrentYear.restore();
            });

            it('should return correct text', function() {
                var startYear = 2013,
                    currentYear = 2018,
                    expected = `${currentYear}`;

                var actual = copyright.get(startYear, currentYear, format);

                expect(actual).to.equal(expected);
            });

        });

        describe('format "range"', function() {

            var format;

            beforeEach(function() {
                format = 'range';
            });

            it('should call validateRange() of CopyrightValidator with correct arguments', function() {
                var startYear = 2013,
                    currentYear = 2018;

                var spy = sinon.spy(CopyrightValidator.prototype, 'validateRange');

                copyright.get(startYear, currentYear, format);

                expect(spy.withArgs(startYear, currentYear)).calledOnce;

                CopyrightValidator.prototype.validateRange.restore();
            });

            it('should return correct text if startYear is equal to currentYear', function() {
                var startYear = 2018,
                    currentYear = 2018,
                    expectedText = `${currentYear}`;

                var actualText = copyright.get(startYear, currentYear, format);

                expect(actualText).to.equal(expectedText);
            });

            it('should return correct text if currentYear is greater than startYear', function() {
                var startYear = 2014,
                    currentYear = 2020,
                    expectedText = `${startYear} - ${currentYear}`;

                var actualText = copyright.get(startYear, currentYear, format);

                expect(actualText).to.equal(expectedText);
            });

        });

    });

});<|endoftext|>


<commit_before>/* eslint-disable */
import CodeMirror from 'codemirror'

const tags = {
  'mj-accordion': {},
  'mj-body': {},
  'mj-button': {},
  'mj-carousel': {},
  'mj-cli': {},
  'mj-column': {},
  'mj-container': {},
  'mj-core': {},
  'mj-divider': {},
  'mj-group': {},
  'mj-head-attributes': {},
  'mj-head-font': {},
  'mj-head-style': {},
  'mj-head-title': {},
  'mj-hero': {},
  'mj-html': {},
  'mj-image': {},
  'mj-invoice': {},
  'mj-list': {},
  'mj-location': {},
  'mj-navbar': {},
  'mj-raw': {},
  'mj-section': {},
  'mj-social': {},
  'mj-spacer': {},
  'mj-table': {},
  'mj-text': {},
  'mj-wrapper': {},
}

export function completeAfter(cm, pred) {
  var cur = cm.getCursor();
  if (!pred || pred()) setTimeout(function() {
    if (!cm.state.completionActive)
      cm.showHint({completeSingle: false});
  }, 100);
  return CodeMirror.Pass;
}
export function completeIfAfterLt(cm) {
  return completeAfter(cm, function() {
    var cur = cm.getCursor();
    return cm.getRange(CodeMirror.Pos(cur.line, cur.ch - 1), cur) == '<';
  });
}
export function completeIfInTag(cm) {
  return completeAfter(cm, function() {
    var tok = cm.getTokenAt(cm.getCursor());
    if (tok.type == 'string' && (!/['"]/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1)) return false;
    var inner = CodeMirror.innerMode(cm.getMode(), tok.state).state;
    return inner.tagName;
  });
}

exports.autocompleteTags = tags
<commit_msg>update tags list<commit_after>/* eslint-disable */
import CodeMirror from 'codemirror'

const tags = {
  'mj-accordion': {},
  'mj-attributes': {},
  'mj-body': {},
  'mj-button': {},
  'mj-carousel': {},
  'mj-column': {},
  'mj-container': {},
  'mj-core': {},
  'mj-divider': {},
  'mj-font': {},
  'mj-group': {},
  'mj-head': {},
  'mj-hero': {},
  'mj-html': {},
  'mj-image': {},
  'mj-invoice': {},
  'mj-list': {},
  'mj-location': {},
  'mj-navbar': {},
  'mj-raw': {},
  'mj-section': {},
  'mj-social': {},
  'mj-spacer': {},
  'mj-style': {},
  'mj-table': {},
  'mj-text': {},
  'mj-title': {},
  'mj-wrapper': {},
}

export function completeAfter(cm, pred) {
  var cur = cm.getCursor();
  if (!pred || pred()) setTimeout(function() {
    if (!cm.state.completionActive)
      cm.showHint({completeSingle: false});
  }, 100);
  return CodeMirror.Pass;
}
export function completeIfAfterLt(cm) {
  return completeAfter(cm, function() {
    var cur = cm.getCursor();
    return cm.getRange(CodeMirror.Pos(cur.line, cur.ch - 1), cur) == '<';
  });
}
export function completeIfInTag(cm) {
  return completeAfter(cm, function() {
    var tok = cm.getTokenAt(cm.getCursor());
    if (tok.type == 'string' && (!/['"]/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1)) return false;
    var inner = CodeMirror.innerMode(cm.getMode(), tok.state).state;
    return inner.tagName;
  });
}

exports.autocompleteTags = tags
<|endoftext|>


<commit_before>// @flow

import * as React from 'react';
import { Platform } from 'react-native';
import { WebView } from '@kiwicom/react-native-app-shared';
import moment from 'moment';
import querystring from 'querystring';

import { sanitizeDate } from '../GraphQLSanitizers';

export type PaymentParameters = {|
  hotelId: number,
  checkin: Date,
  checkout: Date,
  rooms: Array<{|
    id: string,
    count: number, // how many rooms with this ID?
  |}>,
  affiliateId: string,
  language: string,
  currency: string,
|};

export default function PaymentScreen(props: PaymentParameters) {
  return <WebView source={{ uri: createURI(props) }} />;
}

export function createURI(pp: PaymentParameters): string {
  const checkinQuery = sanitizeDate(pp.checkin);
  const intervalQuery = moment(pp.checkout.getTime()).diff(
    moment(pp.checkin.getTime()),
    'days',
  );

  const roomsQuery = pp.rooms.reduce((acc, curVal) => {
    acc[`nr_rooms_${curVal.id}`] = curVal.count;
    return acc;
  }, {});

  return (
    'https://secure.booking.com/book.html?' +
    querystring.stringify({
      from_source: 'hotel',
      hostname: 'hotels.kiwi.com',
      hotel_id: pp.hotelId,
      stage: 1, // 0 - room selection, 1 - address editing, 2 - final overview
      checkin: checkinQuery,
      interval: intervalQuery,
      children_extrabeds: '', // ???
      ...roomsQuery,
      rt_pos_selected: '', // ???
      aid: pp.affiliateId,
      label: `kiwi-${Platform.OS}-react`,
      lang: pp.language,
      selected_currency: pp.currency,
    })
  );
}
<commit_msg>PaymentScreen: add log message for displayed payment<commit_after>// @flow

import * as React from 'react';
import { Platform } from 'react-native';
import { WebView, Logger } from '@kiwicom/react-native-app-shared';
import moment from 'moment';
import querystring from 'querystring';

import { sanitizeDate } from '../GraphQLSanitizers';

export type PaymentParameters = {|
  hotelId: number,
  checkin: Date,
  checkout: Date,
  rooms: Array<{|
    id: string,
    count: number, // how many rooms with this ID?
  |}>,
  affiliateId: string,
  language: string,
  currency: string,
|};

export default class PaymentScreen extends React.Component<PaymentParameters> {
  componentDidMount = () => {
    Logger.ancillaryDisplayed(Logger.Type.ANCILLARY_STEP_PAYMENT);
  };

  render = () => (
    <WebView
      source={{
        uri: createURI(this.props),
      }}
    />
  );
}

export function createURI(pp: PaymentParameters): string {
  const checkinQuery = sanitizeDate(pp.checkin);
  const intervalQuery = moment(pp.checkout.getTime()).diff(
    moment(pp.checkin.getTime()),
    'days',
  );

  const roomsQuery = pp.rooms.reduce((acc, curVal) => {
    acc[`nr_rooms_${curVal.id}`] = curVal.count;
    return acc;
  }, {});

  return (
    'https://secure.booking.com/book.html?' +
    querystring.stringify({
      from_source: 'hotel',
      hostname: 'hotels.kiwi.com',
      hotel_id: pp.hotelId,
      stage: 1, // 0 - room selection, 1 - address editing, 2 - final overview
      checkin: checkinQuery,
      interval: intervalQuery,
      children_extrabeds: '', // ???
      ...roomsQuery,
      rt_pos_selected: '', // ???
      aid: pp.affiliateId,
      label: `kiwi-${Platform.OS}-react`,
      lang: pp.language,
      selected_currency: pp.currency,
    })
  );
}
<|endoftext|>