<commit_before>"use strict"

var f = require('util').format;

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful reconnect when driver looses touch with entire replicaset'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];
    var die = false;

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(primary[0]);
            } else if(doc.insert) {
              request.reply({ "ok" : 1, "n" : 1 });
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(firstSecondary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(arbiter[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 2000,
        socketTimeout: 5000,
        haInterval: 500,
        size: 500
    });

    server.on('connect', function(e) {
      server.__connected = true;

      for(var i = 0; i < 100000; i++) {
        // Execute the write
        server.insert(f("%s.inserts", configuration.db), [{a:1}], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
        });
      }

      setTimeout(function() {
        die = true;

        setTimeout(function() {
          die = false;

          setTimeout(function() {
            server.command('admin.$cmd', {ismaster:true}, function(err, r) {
              test.equal(null, err);
              test.ok(server.s.replState.primary != null);
              test.equal(1, server.s.replState.secondaries.length);
              test.equal(1, server.s.replState.arbiters.length);

              primaryServer.destroy();
              firstSecondaryServer.destroy();
              arbiterServer.destroy();
              server.destroy();
              running = false;

              test.done();
            });
          }, 5000);
        }, 2500);
      }, 2500);
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

// exports['Successfully come back from a dead replicaset that has been unavailable for a long time'] = {
//   metadata: {
//     requires: {
//       generators: true,
//       topology: "single"
//     }
//   },
//
//   test: function(configuration, test) {
//     var ReplSet = configuration.require.ReplSet,
//       ObjectId = configuration.require.BSON.ObjectId,
//       ReadPreference = configuration.require.ReadPreference,
//       Long = configuration.require.BSON.Long,
//       co = require('co'),
//       mockupdb = require('../../../mock');
//
//     // Contain mock server
//     var primaryServer = null;
//     var firstSecondaryServer = null;
//     var arbiterServer = null;
//     var running = true;
//     var electionIds = [new ObjectId(), new ObjectId()];
//     var die = false;
//
//     // Default message fields
//     var defaultFields = {
//       "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
//       "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
//       "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
//       "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
//     }
//
//     // Primary server states
//     var primary = [extend(defaultFields, {
//       "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
//     })];
//
//     // Primary server states
//     var firstSecondary = [extend(defaultFields, {
//       "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
//     })];
//
//     // Primary server states
//     var arbiter = [extend(defaultFields, {
//       "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
//     })];
//
//     // Boot the mock
//     co(function*() {
//       primaryServer = yield mockupdb.createServer(32000, 'localhost');
//       firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
//       arbiterServer = yield mockupdb.createServer(32002, 'localhost');
//
//       // Primary state machine
//       co(function*() {
//         while(running) {
//           var request = yield primaryServer.receive();
//           if(die) {
//             console.log("------------------ die 1")
//             // request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(primary[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//
//       // First secondary state machine
//       co(function*() {
//         while(running) {
//           var request = yield firstSecondaryServer.receive();
//           if(die) {
//             console.log("------------------ die 2")
//             // request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(firstSecondary[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//
//       // Second secondary state machine
//       co(function*() {
//         while(running) {
//           var request = yield arbiterServer.receive();
//           if(die) {
//             console.log("------------------ die 3")
//             // request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(arbiter[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//     });
//
//     // Attempt to connect
//     var server = new ReplSet([
//       { host: 'localhost', port: 32000 },
//       { host: 'localhost', port: 32001 },
//       { host: 'localhost', port: 32002 }], {
//         setName: 'rs',
//         connectionTimeout: 5000,
//         socketTimeout: 5000,
//         haInterval: 1000,
//         size: 1
//     });
//
//     server.on('connect', function(e) {
//       server.__connected = true;
//
//       setTimeout(function() {
//         die = true;
//
//         server.command('admin.$cmd', {ismaster:true}, function(err, r) {
//           test.ok(err != null);
//         });
//
//         setTimeout(function() {
//           die = false;
//           // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ALIVE")
//
//           setTimeout(function() {
//             server.command('admin.$cmd', {ismaster:true}, function(err, r) {
//               // console.log("---------------------------------------------------------------")
//               // console.dir(err)
//               // console.log("server.s.replState.secondaries = " + server.s.replState.secondaries.length)
//               // console.log("server.s.replState.arbiters = " + server.s.replState.arbiters.length)
//               // console.log("server.s.replState.primary = " + (server.s.replState.primary != null))
//               // console.dir(err)
//               // console.dir(r.result)
//
//               test.equal(null, err);
//               test.ok(server.s.replState.primary != null);
//               test.equal(1, server.s.replState.secondaries.length);
//               test.equal(1, server.s.replState.arbiters.length);
//
//               primaryServer.destroy();
//               firstSecondaryServer.destroy();
//               arbiterServer.destroy();
//               server.destroy();
//               running = false;
//
//               test.done();
//             });
//           }, 5000);
//         }, 60000 * 3);
//       }, 2500);
//     });
//
//     // Add event listeners
//     server.on('fullsetup', function(_server) {});
//     // Gives proxies a chance to boot up
//     setTimeout(function() {
//       server.connect();
//     }, 100)
//   }
// }
<commit_msg>attempt to track down travis issue<commit_after>"use strict"

var f = require('util').format;

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful reconnect when driver looses touch with entire replicaset'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];
    var die = false;

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(primary[0]);
            } else if(doc.insert) {
              request.reply({ "ok" : 1, "n" : 1 });
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(firstSecondary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(arbiter[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 2000,
        socketTimeout: 5000,
        haInterval: 500,
        size: 500
    });

    server.on('connect', function(e) {
      server.__connected = true;
      console.log("------------------------------- step 0 ")

      for(var i = 0; i < 100000; i++) {
        // Execute the write
        server.insert(f("%s.inserts", configuration.db), [{a:1}], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
        });
      }

      setTimeout(function() {
        console.log("------------------------------- step 1 ")
        die = true;

        setTimeout(function() {
          console.log("------------------------------- step 2 ")
          die = false;

          setTimeout(function() {
            console.log("------------------------------- step 3 ")
            server.command('admin.$cmd', {ismaster:true}, function(err, r) {
              console.log("------------------------------- step 4 ")
              console.dir(err)
              test.equal(null, err);
              test.ok(server.s.replState.primary != null);
              test.equal(1, server.s.replState.secondaries.length);
              test.equal(1, server.s.replState.arbiters.length);

              primaryServer.destroy();
              firstSecondaryServer.destroy();
              arbiterServer.destroy();
              server.destroy();
              running = false;

              test.done();
            });
          }, 5000);
        }, 2500);
      }, 2500);
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

// exports['Successfully come back from a dead replicaset that has been unavailable for a long time'] = {
//   metadata: {
//     requires: {
//       generators: true,
//       topology: "single"
//     }
//   },
//
//   test: function(configuration, test) {
//     var ReplSet = configuration.require.ReplSet,
//       ObjectId = configuration.require.BSON.ObjectId,
//       ReadPreference = configuration.require.ReadPreference,
//       Long = configuration.require.BSON.Long,
//       co = require('co'),
//       mockupdb = require('../../../mock');
//
//     // Contain mock server
//     var primaryServer = null;
//     var firstSecondaryServer = null;
//     var arbiterServer = null;
//     var running = true;
//     var electionIds = [new ObjectId(), new ObjectId()];
//     var die = false;
//
//     // Default message fields
//     var defaultFields = {
//       "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
//       "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
//       "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
//       "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
//     }
//
//     // Primary server states
//     var primary = [extend(defaultFields, {
//       "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
//     })];
//
//     // Primary server states
//     var firstSecondary = [extend(defaultFields, {
//       "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
//     })];
//
//     // Primary server states
//     var arbiter = [extend(defaultFields, {
//       "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
//     })];
//
//     // Boot the mock
//     co(function*() {
//       primaryServer = yield mockupdb.createServer(32000, 'localhost');
//       firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
//       arbiterServer = yield mockupdb.createServer(32002, 'localhost');
//
//       // Primary state machine
//       co(function*() {
//         while(running) {
//           var request = yield primaryServer.receive();
//           if(die) {
//             console.log("------------------ die 1")
//             // request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(primary[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//
//       // First secondary state machine
//       co(function*() {
//         while(running) {
//           var request = yield firstSecondaryServer.receive();
//           if(die) {
//             console.log("------------------ die 2")
//             // request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(firstSecondary[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//
//       // Second secondary state machine
//       co(function*() {
//         while(running) {
//           var request = yield arbiterServer.receive();
//           if(die) {
//             console.log("------------------ die 3")
//             // request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(arbiter[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//     });
//
//     // Attempt to connect
//     var server = new ReplSet([
//       { host: 'localhost', port: 32000 },
//       { host: 'localhost', port: 32001 },
//       { host: 'localhost', port: 32002 }], {
//         setName: 'rs',
//         connectionTimeout: 5000,
//         socketTimeout: 5000,
//         haInterval: 1000,
//         size: 1
//     });
//
//     server.on('connect', function(e) {
//       server.__connected = true;
//
//       setTimeout(function() {
//         die = true;
//
//         server.command('admin.$cmd', {ismaster:true}, function(err, r) {
//           test.ok(err != null);
//         });
//
//         setTimeout(function() {
//           die = false;
//           // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ALIVE")
//
//           setTimeout(function() {
//             server.command('admin.$cmd', {ismaster:true}, function(err, r) {
//               // console.log("---------------------------------------------------------------")
//               // console.dir(err)
//               // console.log("server.s.replState.secondaries = " + server.s.replState.secondaries.length)
//               // console.log("server.s.replState.arbiters = " + server.s.replState.arbiters.length)
//               // console.log("server.s.replState.primary = " + (server.s.replState.primary != null))
//               // console.dir(err)
//               // console.dir(r.result)
//
//               test.equal(null, err);
//               test.ok(server.s.replState.primary != null);
//               test.equal(1, server.s.replState.secondaries.length);
//               test.equal(1, server.s.replState.arbiters.length);
//
//               primaryServer.destroy();
//               firstSecondaryServer.destroy();
//               arbiterServer.destroy();
//               server.destroy();
//               running = false;
//
//               test.done();
//             });
//           }, 5000);
//         }, 60000 * 3);
//       }, 2500);
//     });
//
//     // Add event listeners
//     server.on('fullsetup', function(_server) {});
//     // Gives proxies a chance to boot up
//     setTimeout(function() {
//       server.connect();
//     }, 100)
//   }
// }
<|endoftext|>


<commit_before>var countbutton = document.getElementById('wordcount_button');
var topwordsbutton = document.getElementById('topwords_button');
var toplettersbutton = document.getElementById('topletters_button');

var input_area = document.getElementById('words_textarea');

input_area.onkeyup = function() {
  topWords()
}

countbutton.onclick = function() {
  wordCount();
  input_area.onkeyup = function() {
    wordCount()
  }
};

topwordsbutton.onclick = function() {
  topWords();
  input_area.onkeyup = function() {
    topWords()
  }
};

toplettersbutton.onclick = function() {
  topletters();
  input_area.onkeyup = function() {
    topletters()
  }
};

function wordCount() {

  document.getElementById('all_text').innerHTML = '';

  var words = document.getElementById("words_textarea").value.trim().match(/\w+/g);

  var para = document.createElement("p");

  if (words.length > 1) {
    var count = document.createTextNode('Your document is ' + words.length + ' words long.');
  } else if (words.length = 1) {
    var count = document.createTextNode('Your document is ' + words.length + ' word long.');
  } else if (words[0] === "") {
    var count = document.createTextNode('Your document is 0 words long.');
  }

  para.appendChild(count);

  var element = document.getElementById("all_text");
  element.appendChild(para);
}

function topWords() {

  document.getElementById('all_text').innerHTML = '';

  var words = document.getElementById("words_textarea").value.trim().match(/\w+/g);

  var counts = [];

  for (i = 0; i <= words.length - 1; i++) {
    var found = false;
    var current_word = words[i].toLowerCase();
    var irrelevant = ['aboard', 'about', 'above', 'across', 'after', 'against', 'along', 'around', 'before', 'behind', 'below', 'beneath', 'beside', 'between', 'beyond', 'during', 'except', 'following', 'inside', 'minus', 'onto', 'opposite', 'outside', 'round', 'since', 'through', 'toward', 'under', 'underneath', 'unlike', 'until', 'upon', 'without', 'as', 'at', 'but', 'by', 'down', 'for', 'from', 'in', 'into', 'like', 'near', 'next', 'of', 'off', 'on', 'onto', 'out', 'over', 'past', 'plus', 'minus', 'since', 'than', 'to', 'up', 'with'];

    if ($.inArray(current_word, irrelevant) == -1) {
      for (n = 0; n <= counts.length - 1; n++) {
        if (counts[n][0] == current_word) {
          counts[n][1] += 1;
          found = true;
          break;
        }
      }

      if (found == false) {
        counts.push([current_word, 1]);
      }
    }
  }

  var sorted = counts.sort(function(a, b) {
    return b[1] - a[1]
  });

  function createTable() {
    var element = document.getElementById("all_text");

    var tbl = document.createElement('table');

    tbl.style.width = '100%';

    tbl.setAttribute('border', '1');

    var tbdy = document.createElement('tbody');

    var tr = document.createElement('tr');
    var word = document.createElement('td');
    word.innerHTML = "Word"
    var countword = document.createElement('td');
    countword.innerHTML = "Count"
    var suggestions = document.createElement('td');
    suggestions.innerHTML = "Suggestions"

    tr.appendChild(word)
    tr.appendChild(countword)
    tr.appendChild(suggestions)
    tbdy.appendChild(tr);
    tbl.appendChild(tbdy);
    element.appendChild(tbl)

    for (i = 0; i <= counts.length - 1; i++) {

      if (counts[i][1] < 3) {

        var tr = document.createElement('tr');
        var word = document.createElement('td');
        word.innerHTML = counts[i][0]
        var countword = document.createElement('td');
        countword.innerHTML = counts[i][1]
        var suggestion = document.createElement('td');

        tr.appendChild(word)
        tr.appendChild(countword)
        tr.appendChild(suggestion)
        tbdy.appendChild(tr)

      }

      if (counts[i][1] >= 3) {
        var rowIndex = 1;

        $.ajax({
          type: 'GET',
          url: 'http://words.bighugelabs.com/api/2/f5915b0e669a698049a43e63af4704af/' + counts[i][0] + '/json?callback=?',
          dataType: 'json',
          success: function(data) {

            var parsedWord = this.url.split('/')[6];

            var tr = document.createElement('tr');
            var word = document.createElement('td');
            word.innerHTML = parsedWord

            var countword = document.createElement('td');

            for (i = 0; i <= counts.length - 1; i++) {
              if (parsedWord === counts[i][0]) {
                countword.innerHTML = counts[i][1]
                break
              }
            }

            var suggestion = document.createElement('td');

            thesaurusHandling(data,suggestion)

            if (rowIndex > 1) {
              tr.insertBefore(word, tr.childNodes[rowIndex])
              tr.insertBefore(countword, tr.childNodes[rowIndex])
              tr.insertBefore(suggestion, tr.childNodes[rowIndex])
              tbdy.insertBefore(tr, tbdy.childNodes[rowIndex])
              rowIndex += 1
            } else {
              tr.insertBefore(word, tr.childNodes[rowIndex])
              tr.insertBefore(suggestion, tr.childNodes[rowIndex])
              tr.insertBefore(countword, tr.childNodes[rowIndex])
              tbdy.insertBefore(tr, tbdy.childNodes[rowIndex])
              rowIndex += 1
            }
          }
        });
      }
    }
    tbl.appendChild(tbdy)
    element.appendChild(tbl)
  }
  createTable()
};

function thesaurusHandling(data,suggestion) {

  var options = ['noun', 'verb', 'adverb', 'adjective']

  for (i = 0; i <= options.length - 1; i++) {

    var thisWordType = options[i]

    if (typeof data[thisWordType] != "undefined") {

      if (typeof data[thisWordType].syn != "undefined" && typeof data[thisWordType].sim != "undefined") {
        suggestion.innerHTML = suggestion.innerHTML + "" + thisWordType + ": synonyms " + data[thisWordType].syn.slice(0, 3) + " similar " + data[thisWordType].sim.slice(0, 3) + "\n"
      } else if (typeof data[thisWordType].syn != "undefined" && typeof data[thisWordType].sim === "undefined") {
        suggestion.innerHTML = suggestion.innerHTML + "" + thisWordType + ": synonyms " + data[thisWordType].syn.slice(0, 3) + "\n"
      } else if (typeof data[thisWordType].syn === "undefined" && typeof data[thisWordType].sim != "undefined") {
        suggestion.innerHTML = suggestion.innerHTML + "" + thisWordType + ": similar " + data[thisWordType].sim.slice(0, 3) + "\n"
      }
    }
  }
}

function topletters() {

  document.getElementById('all_text').innerHTML = '';

  var letters = document.getElementById("words_textarea").value.trim().match(/[A-z]/g);

  var counts = [];

  for (i = 0; i <= letters.length - 1; i++) {
    var found = false;
    var current_letter = letters[i].toLowerCase();

    for (n = 0; n <= counts.length - 1; n++) {
      if (counts[n][0] == current_letter) {
        counts[n][1] += 1;
        found = true;
        break;
      }
    }

    if (found == false) {
      counts.push([current_letter, 1]);
    }
  }

  var sorted = counts.sort(function(a, b) {
    return b[1] - a[1]
  });

  function createTable() {
    var element = document.getElementById("all_text");

    var tbl = document.createElement('table');

    tbl.style.width = '100%';

    tbl.setAttribute('border', '1');

    var tbdy = document.createElement('tbody');

    var tr = document.createElement('tr');
    var word = document.createElement('td');
    word.innerHTML = "Character"
    var countword = document.createElement('td');
    countword.innerHTML = "Count"
    tr.appendChild(word)
    tr.appendChild(countword)
    tbdy.appendChild(tr);
    tbl.appendChild(tbdy);
    element.appendChild(tbl)

    for (i = 0; i <= counts.length - 1; i++) {
      var tr = document.createElement('tr');
      var word = document.createElement('td');
      word.innerHTML = counts[i][0]
      var countword = document.createElement('td');
      countword.innerHTML = counts[i][1]
      tr.appendChild(word)
      tr.appendChild(countword)
      tbdy.appendChild(tr);
    }
    tbl.appendChild(tbdy);
    element.appendChild(tbl)
  }
  createTable()
}
<commit_msg>blank string changed to null<commit_after>var countbutton = document.getElementById('wordcount_button');
var topwordsbutton = document.getElementById('topwords_button');
var toplettersbutton = document.getElementById('topletters_button');

var input_area = document.getElementById('words_textarea');

input_area.onkeyup = function() {
  topWords()
}

countbutton.onclick = function() {
  wordCount();
  input_area.onkeyup = function() {
    wordCount()
  }
};

topwordsbutton.onclick = function() {
  topWords();
  input_area.onkeyup = function() {
    topWords()
  }
};

toplettersbutton.onclick = function() {
  topletters();
  input_area.onkeyup = function() {
    topletters()
  }
};

function wordCount() {

  document.getElementById('all_text').innerHTML = '';

  var words = document.getElementById("words_textarea").value.trim().match(/\w+/g);

  var para = document.createElement("p");

  if (words.length > 1) {
    var count = document.createTextNode('Your document is ' + words.length + ' words long.');
  } else if (words.length = 1) {
    var count = document.createTextNode('Your document is ' + words.length + ' word long.');
  } else if (words[0] === "") {
    var count = document.createTextNode('Your document is 0 words long.');
  }

  para.appendChild(count);

  var element = document.getElementById("all_text");
  element.appendChild(para);
}

function topWords() {

  document.getElementById('all_text').innerHTML = null;

  var words = document.getElementById("words_textarea").value.trim().match(/\w+/g);

  var counts = [];

  for (i = 0; i <= words.length - 1; i++) {
    var found = false;
    var current_word = words[i].toLowerCase();
    var irrelevant = ['aboard', 'about', 'above', 'across', 'after', 'against', 'along', 'around', 'before', 'behind', 'below', 'beneath', 'beside', 'between', 'beyond', 'during', 'except', 'following', 'inside', 'minus', 'onto', 'opposite', 'outside', 'round', 'since', 'through', 'toward', 'under', 'underneath', 'unlike', 'until', 'upon', 'without', 'as', 'at', 'but', 'by', 'down', 'for', 'from', 'in', 'into', 'like', 'near', 'next', 'of', 'off', 'on', 'onto', 'out', 'over', 'past', 'plus', 'minus', 'since', 'than', 'to', 'up', 'with'];

    if ($.inArray(current_word, irrelevant) == -1) {
      for (n = 0; n <= counts.length - 1; n++) {
        if (counts[n][0] == current_word) {
          counts[n][1] += 1;
          found = true;
          break;
        }
      }

      if (found == false) {
        counts.push([current_word, 1]);
      }
    }
  }

  var sorted = counts.sort(function(a, b) {
    return b[1] - a[1]
  });

  function createTable() {
    var element = document.getElementById("all_text");

    var tbl = document.createElement('table');

    tbl.style.width = '100%';

    tbl.setAttribute('border', '1');

    var tbdy = document.createElement('tbody');

    var tr = document.createElement('tr');
    var word = document.createElement('td');
    word.innerHTML = "Word"
    var countword = document.createElement('td');
    countword.innerHTML = "Count"
    var suggestions = document.createElement('td');
    suggestions.innerHTML = "Suggestions"

    tr.appendChild(word)
    tr.appendChild(countword)
    tr.appendChild(suggestions)
    tbdy.appendChild(tr);
    tbl.appendChild(tbdy);
    element.appendChild(tbl)

    for (i = 0; i <= counts.length - 1; i++) {

      if (counts[i][1] < 3) {

        var tr = document.createElement('tr');
        var word = document.createElement('td');
        word.innerHTML = counts[i][0]
        var countword = document.createElement('td');
        countword.innerHTML = counts[i][1]
        var suggestion = document.createElement('td');

        tr.appendChild(word)
        tr.appendChild(countword)
        tr.appendChild(suggestion)
        tbdy.appendChild(tr)

      }

      if (counts[i][1] >= 3) {
        var rowIndex = 1;

        $.ajax({
          type: 'GET',
          url: 'http://words.bighugelabs.com/api/2/f5915b0e669a698049a43e63af4704af/' + counts[i][0] + '/json?callback=?',
          dataType: 'json',
          success: function(data) {

            var parsedWord = this.url.split('/')[6];

            var tr = document.createElement('tr');
            var word = document.createElement('td');
            word.innerHTML = parsedWord

            var countword = document.createElement('td');

            for (i = 0; i <= counts.length - 1; i++) {
              if (parsedWord === counts[i][0]) {
                countword.innerHTML = counts[i][1]
                break
              }
            }

            var suggestion = document.createElement('td');

            thesaurusHandling(data,suggestion)

            if (rowIndex > 1) {
              tr.insertBefore(word, tr.childNodes[rowIndex])
              tr.insertBefore(countword, tr.childNodes[rowIndex])
              tr.insertBefore(suggestion, tr.childNodes[rowIndex])
              tbdy.insertBefore(tr, tbdy.childNodes[rowIndex])
              rowIndex += 1
            } else {
              tr.insertBefore(word, tr.childNodes[rowIndex])
              tr.insertBefore(suggestion, tr.childNodes[rowIndex])
              tr.insertBefore(countword, tr.childNodes[rowIndex])
              tbdy.insertBefore(tr, tbdy.childNodes[rowIndex])
              rowIndex += 1
            }
          }
        });
      }
    }
    tbl.appendChild(tbdy)
    element.appendChild(tbl)
  }
  createTable()
};

function thesaurusHandling(data,suggestion) {

  var options = ['noun', 'verb', 'adverb', 'adjective']

  for (i = 0; i <= options.length - 1; i++) {

    var thisWordType = options[i]

    if (typeof data[thisWordType] != "undefined") {

      if (typeof data[thisWordType].syn != "undefined" && typeof data[thisWordType].sim != "undefined") {
        suggestion.innerHTML = suggestion.innerHTML + "" + thisWordType + ": synonyms " + data[thisWordType].syn.slice(0, 3) + " similar " + data[thisWordType].sim.slice(0, 3) + "\n"
      } else if (typeof data[thisWordType].syn != "undefined" && typeof data[thisWordType].sim === "undefined") {
        suggestion.innerHTML = suggestion.innerHTML + "" + thisWordType + ": synonyms " + data[thisWordType].syn.slice(0, 3) + "\n"
      } else if (typeof data[thisWordType].syn === "undefined" && typeof data[thisWordType].sim != "undefined") {
        suggestion.innerHTML = suggestion.innerHTML + "" + thisWordType + ": similar " + data[thisWordType].sim.slice(0, 3) + "\n"
      }
    }
  }
}

function topletters() {

  document.getElementById('all_text').innerHTML = '';

  var letters = document.getElementById("words_textarea").value.trim().match(/[A-z]/g);

  var counts = [];

  for (i = 0; i <= letters.length - 1; i++) {
    var found = false;
    var current_letter = letters[i].toLowerCase();

    for (n = 0; n <= counts.length - 1; n++) {
      if (counts[n][0] == current_letter) {
        counts[n][1] += 1;
        found = true;
        break;
      }
    }

    if (found == false) {
      counts.push([current_letter, 1]);
    }
  }

  var sorted = counts.sort(function(a, b) {
    return b[1] - a[1]
  });

  function createTable() {
    var element = document.getElementById("all_text");

    var tbl = document.createElement('table');

    tbl.style.width = '100%';

    tbl.setAttribute('border', '1');

    var tbdy = document.createElement('tbody');

    var tr = document.createElement('tr');
    var word = document.createElement('td');
    word.innerHTML = "Character"
    var countword = document.createElement('td');
    countword.innerHTML = "Count"
    tr.appendChild(word)
    tr.appendChild(countword)
    tbdy.appendChild(tr);
    tbl.appendChild(tbdy);
    element.appendChild(tbl)

    for (i = 0; i <= counts.length - 1; i++) {
      var tr = document.createElement('tr');
      var word = document.createElement('td');
      word.innerHTML = counts[i][0]
      var countword = document.createElement('td');
      countword.innerHTML = counts[i][1]
      tr.appendChild(word)
      tr.appendChild(countword)
      tbdy.appendChild(tr);
    }
    tbl.appendChild(tbdy);
    element.appendChild(tbl)
  }
  createTable()
}
<|endoftext|>


<commit_before>import path from 'path';
import {cloneDeep, template} from 'lodash';
import engine from 'structor-commons';
import metadata from './metadata.js';
import dependencies from './dependencies.js';

const templateNames = [
	'components', 'defaultModels', 'docs', 'test'
];

const mergeScripts = [
	'componentsFile'
];

export function preProcess(currentDir, dataObject) {

	let newMetaData = cloneDeep(metadata);
	return newMetaData;

}

export function process(currentDir, dataObject) {

	const templateDatas = {};
	let templateReaders = [];

	templateNames.forEach(name => {
		templateReaders.push(
			engine.readFile(path.join(currentDir, 'templates', name + '.tpl'))
				.then(fileData => {
					templateDatas[name] = fileData;
				})
		);
	});
	return Promise.all(templateReaders)
		.then(() => {
			let newDependencies = cloneDeep(dependencies);
			let files = [];
			let file;
			templateNames.forEach(name => {
				const generatorModule = require(path.join(currentDir, 'scripts', name + '.js'));
				file = generatorModule.getFile(dataObject, templateDatas[name]);
				if (file.outputFilePath) {
					file.outputFileName = path.basename(file.outputFilePath);
					files.push(file);
				}
			});
			mergeScripts.forEach(script => {
				const mergeModule = require(path.join(currentDir, 'merge', script + '.js'));
				file = mergeModule.getFile(dataObject, dependencies);
				if (file.outputFilePath) {
					file.outputFileName = path.basename(file.outputFilePath);
					files.push(file);
				}
			});
			return {files, dependencies: newDependencies};
		});
}
<commit_msg>Fix generator template name<commit_after>import path from 'path';
import {cloneDeep, template} from 'lodash';
import engine from 'structor-commons';
import metadata from './metadata.js';
import dependencies from './dependencies.js';

const templateNames = [
	'component', 'defaultModels', 'docs', 'test'
];

const mergeScripts = [
	'componentsFile'
];

export function preProcess(currentDir, dataObject) {

	let newMetaData = cloneDeep(metadata);
	return newMetaData;

}

export function process(currentDir, dataObject) {

	const templateDatas = {};
	let templateReaders = [];

	templateNames.forEach(name => {
		templateReaders.push(
			engine.readFile(path.join(currentDir, 'templates', name + '.tpl'))
				.then(fileData => {
					templateDatas[name] = fileData;
				})
		);
	});
	return Promise.all(templateReaders)
		.then(() => {
			let newDependencies = cloneDeep(dependencies);
			let files = [];
			let file;
			templateNames.forEach(name => {
				const generatorModule = require(path.join(currentDir, 'scripts', name + '.js'));
				file = generatorModule.getFile(dataObject, templateDatas[name]);
				if (file.outputFilePath) {
					file.outputFileName = path.basename(file.outputFilePath);
					files.push(file);
				}
			});
			mergeScripts.forEach(script => {
				const mergeModule = require(path.join(currentDir, 'merge', script + '.js'));
				file = mergeModule.getFile(dataObject, dependencies);
				if (file.outputFilePath) {
					file.outputFileName = path.basename(file.outputFilePath);
					files.push(file);
				}
			});
			return {files, dependencies: newDependencies};
		});
}
<|endoftext|>


<commit_before>import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';

export default Model.extend({
  routeNumber: attr('number'),
  routeName: attr('string'),
  serviceType: attr('string'),
  isHighRidership: attr('boolean'),
  dailyRiderships: hasMany('daily-ridership')
});
<commit_msg>Add 'isTopRoute' computed property to route model.<commit_after>import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';

export default Model.extend({
  routeNumber: attr('number'),
  routeName: attr('string'),
  serviceType: attr('string'),
  isHighRidership: attr('boolean'),
  dailyRiderships: hasMany('daily-ridership'),

  isTopRoute: Ember.computed('isHighRidership', function() {
    if (this.get('isHighRidership')){
      return 'Yes'
    } else {
      return 'No'
    }
  })
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';

let roleUrlRegex = new RegExp('/roles/([a-zA-Z0-9\-]+)$');

function getRoleIdFromPermission(permission){
  var roleUrl = permission.get('data.links.role');
  return roleUrlRegex.exec(roleUrl)[1];
}

export default DS.Model.extend({
  // properties
  name: DS.attr('string'),
  handle: DS.attr('string'),
  number: DS.attr('string'),
  type: DS.attr('string'),
  syslogHost: DS.attr('string'),
  syslogPort: DS.attr('string'),
  organizationUrl: DS.attr('string'),
  activated: DS.attr('boolean'),
  containerCount: DS.attr('number'),
  appContainerCount: DS.attr('number'),
  databaseContainerCount: DS.attr('number'),
  domainCount: DS.attr('number'),
  totalAppCount: DS.attr('number'),
  totalDatabaseCount: DS.attr('number'),
  totalDiskSize: DS.attr('number'),

  // relationships
  apps: DS.hasMany('app', {async: true}),
  certificates: DS.hasMany('certificate', {async: true}),
  databases: DS.hasMany('database', {async: true}),
  permissions: DS.hasMany('permission', {async:true}),
  organization: DS.belongsTo('organization', {async:true}),
  logDrains: DS.hasMany('log-drain', {async:true}),
  vhosts: DS.hasMany('vhost', {async:true}),

  // computed properties
  pending: Ember.computed.not('activated'),
  allowPHI: Ember.computed.match('type', /production/),
  appContainerCentsPerHour: 8,

  getUsageByResourceType(type) {
    let usageAttr = { container: 'containerCount', disk: 'totalDiskSize',
                      domain: 'domainCount' }[type];
    return this.get(usageAttr);
  },

  permitsRole(role, scope){
    let permissions;

    if (role.get('privileged') &&
        role.get('data.links.organization') === this.get('data.links.organization')) {
      return new Ember.RSVP.Promise((resolve) => {
        resolve(true);
      });
    }

    return this.get('permissions').then(function(_permissions){
      permissions = _permissions;

      return permissions.map(function(perm){
        return {
          roleId: getRoleIdFromPermission(perm),
          scope:  perm.get('scope')
        };
      });
    }).then(function(stackRoleScopes){
      return Ember.A(Ember.A(stackRoleScopes).filter((stackRoleScope) => {
        return role.get('id') === stackRoleScope.roleId;
      })).any((stackRoleScope) => {
        return stackRoleScope.scope === 'manage' ||
          stackRoleScope.scope === scope;
      });
    });
  }
});
<commit_msg>Adds persistedVhosts and vhostNames properties to Stack<commit_after>import Ember from 'ember';
import DS from 'ember-data';

let roleUrlRegex = new RegExp('/roles/([a-zA-Z0-9\-]+)$');

function getRoleIdFromPermission(permission){
  var roleUrl = permission.get('data.links.role');
  return roleUrlRegex.exec(roleUrl)[1];
}

export default DS.Model.extend({
  // properties
  name: DS.attr('string'),
  handle: DS.attr('string'),
  number: DS.attr('string'),
  type: DS.attr('string'),
  syslogHost: DS.attr('string'),
  syslogPort: DS.attr('string'),
  organizationUrl: DS.attr('string'),
  activated: DS.attr('boolean'),
  containerCount: DS.attr('number'),
  appContainerCount: DS.attr('number'),
  databaseContainerCount: DS.attr('number'),
  domainCount: DS.attr('number'),
  totalAppCount: DS.attr('number'),
  totalDatabaseCount: DS.attr('number'),
  totalDiskSize: DS.attr('number'),

  // relationships
  apps: DS.hasMany('app', {async: true}),
  certificates: DS.hasMany('certificate', {async: true}),
  databases: DS.hasMany('database', {async: true}),
  permissions: DS.hasMany('permission', {async:true}),
  organization: DS.belongsTo('organization', {async:true}),
  logDrains: DS.hasMany('log-drain', {async:true}),
  vhosts: DS.hasMany('vhost', {async:true}),

  // computed properties
  allowPHI: Ember.computed.match('type', /production/),
  appContainerCentsPerHour: 8,
  pending: Ember.computed.not('activated'),
  persistedVhosts: Ember.computed.filterBy('vhosts', 'isNew', false),
  vhostNames: Ember.computed.mapBy('persistedVhosts', 'virtualDomain'),

  getUsageByResourceType(type) {
    let usageAttr = { container: 'containerCount', disk: 'totalDiskSize',
                      domain: 'domainCount' }[type];
    return this.get(usageAttr);
  },

  permitsRole(role, scope){
    let permissions;

    if (role.get('privileged') &&
        role.get('data.links.organization') === this.get('data.links.organization')) {
      return new Ember.RSVP.Promise((resolve) => {
        resolve(true);
      });
    }

    return this.get('permissions').then(function(_permissions){
      permissions = _permissions;

      return permissions.map(function(perm){
        return {
          roleId: getRoleIdFromPermission(perm),
          scope:  perm.get('scope')
        };
      });
    }).then(function(stackRoleScopes){
      return Ember.A(Ember.A(stackRoleScopes).filter((stackRoleScope) => {
        return role.get('id') === stackRoleScope.roleId;
      })).any((stackRoleScope) => {
        return stackRoleScope.scope === 'manage' ||
          stackRoleScope.scope === scope;
      });
    });
  }
});
<|endoftext|>


<commit_before>const $ = require('jquery')
const crypto = require('crypto')
const formatDate = require('../helpers/date.js')
const { ipcRenderer } = require('electron')

async function mail () {
  if (!testLoaded('mail')) return

  logger.debug(`We're loading up the mail page now.`)
  page('mail', ['basic', 'mail'])

  $('#compose-button').click(() => {
    ipcRenderer.send('open', { file: 'compose' })
  })

  if (typeof state.account === 'undefined') {
    // I have no idea when this happens, but just in case
    // Perhaps this could happen if someone deleted their state.json file?
    // Or it was unreadable.
    let doc = await new Promise((resolve, reject) => {
      accounts.find({}).sort({ date: 0 }).limit(1).exec((err, docs) => {
        if (err) return reject(err)
        resolve(docs[0])
      })
    })
    stateSet('account', Object.assign(state.account, { hash: doc.hash, user: doc.user }))
  }

  let account = (await accounts.findAsync({ user: state.account.user }, {}))[0]
  let folders = htmlFolders(account.folders)

  if (typeof mailStore[state.account.hash] === 'undefined') {
    setupMailDB(state.account.user)
  }

  if (typeof state.account.folder === 'undefined') {
    // Here, we somewhat fake the folder tree for the inbox folder.
    // We don't really need the seperator, in this instance it should never be used,
    // but we keep it just in case.
    stateSet('account', Object.assign(state.account, {
      folder: [{
        name: 'INBOX',
        delimiter: findSeperator(account.folders)
      }]
    }))
  }

  if (typeof account.folders[state.account.folder[0].name] === 'undefined') {
    stateSet('account', Object.assign(state.account, {
      folder: [{
        name: 'Inbox',
        delimiter: findSeperator(account.folders)
      }]
    }))
  }

  $('#folders').html(folders)

  linkFolders($('#folders').children().children())
  updateMailDiv()

  logger.log(`Loading mail window complete.`)
}

async function updateMailDiv () {
  let mail = await new Promise((resolve) => {
    mailStore[state.account.hash].find({ folder: mailer.compilePath(state.account.folder) }).sort({ date: -1 }).exec((err, docs) => {
      resolve(docs)
    })
  })

  $('#mail').html('')

  $('#title').html(`
    Femto
    ${state.account.user}
  `)

  for (let i = 0; i < state.account.folder.length; i++) {
    $('#title').append(`<a href="#!" class="breadcrumb">${state.account.folder[i].name}</a>`)
  }

  for (let i = 0; i < mail.length; i++) {
    $('#mail').append($(`<e-mail class="email-item" data-uid="${escape(mail[i].uid)}"></e-mail>`))
  }

  if (mail.length === 0) {
    // This folder is empty...
    $('#mail').html('This folder is empty ;(')
  }

  $('.email-item').off('click')

  $('.email-item').click((e) => {
    loadEmail(unescape(e.currentTarget.attributes['data-uid'].nodeValue))
  })
}

/**
 * Currently not functioning.
 *
 * @param  {object} tree
 * @return {object}
 */
function organiseFolders (tree) {
  let keys = Object.getOwnPropertyNames(tree)
  let results = {}
  for (let i = 0; i < keys.length; i++) {
    if (tree[keys[i]].children) {
      results[keys[i]] = organiseFolders(tree[keys[i]].children)
    } else {
      results[keys[i]] = {}
    }
  }
  return results
}

function htmlFolders (tree, journey) {
  journey = journey || []
  let html = ''
  for (let prop in tree) {
    temp = journey.concat({ name: prop, delimiter: tree[prop].delimiter })
    // Folders with depth
    html += `

${prop} ${htmlFolders(tree[prop].children, temp)}

    `
    // Folders without depth
    // html += `
    //

    //
${prop}

    //

    // `
    // html += htmlFolders(tree[prop].children, temp)
  }
  return html
}

function linkFolders (children) {
  children.each((index, item) => {
    $(`#${item.id.replace(/=/g, '\\=')}`).click((element) => {
      logger.log(`Switching page to ${atob(element.target.id)}`)
      stateSet('account', Object.assign(state.account, {
        folder: JSON.parse(atob(element.target.id))
      }))
      updateMailDiv()
    })

    let items = $(`#${item.id.replace(/=/g, '\\=')}`).children().children()
    if (items.length) {
      linkFolders(items)
    }
  })
}

function loadEmail (uid) {
  console.log(uid)
}

global.findFolders = (folders, path) => {
  let keys = folders ? Object.getOwnPropertyNames(folders) : []
  let results = []
  path = path || []
  for (let i = 0; i < keys.length; i++) {
    let tempPath = JSON.parse(JSON.stringify(path))
    tempPath.push({ delimiter: folders[keys[i]].delimiter, name: keys[i]})
    results = results.concat(findFolders(folders[keys[i]].children, tempPath))
  }
  results.push(path)
  return results
}

global.findSeperator = (folders) => {
  // We assume they use one delimiter for the entire inbox, otherwise...
  // Well, I worry for their health..
  // Try not to use this function too much, at some point I intend to deprecate it.
  return typeof folders.INBOX === 'undefined' ? folders.Inbox.delimiter : folders.INBOX.delimiter
}

// Possibly also document.registerElement()?
customElements.define('e-mail', class extends HTMLElement {
  constructor () {
    super()

    // Shadow root is it's *own* entire DOM.  This makes it impact less when
    // we change and search through other parts of the DOM, *hopefully* making it
    // slightly quicker.  It also allows us to use the cool <e-mail> tags.
    // const shadowRoot = this.attachShadow({ mode: 'open' })

    this.innerHTML = `

Loading...

    `

    // We're able to assume some values from the current state.
    // However, we don't rely on it, preferring instead to find it in the email itself.
    let email = this.getAttribute('data-email') ||
                state.account.user
    let hash = this.getAttribute('data-hash') ||
                crypto.createHash('md5').update(email).digest('hex') ||
                state.account.hash
    let uid = unescape(this.getAttribute('data-uid'))

    loadMail(email, hash, uid).then((mail) => {
      // Attach a shadow root to <e-mail>.
      // NOTE: All of these *have* to be HTML escaped.  Consider using `escapeHTML(string)` which
      // is globally accessible.
      this.innerHTML = `

<input type="checkbox" id="${mail.uid}" />

          <div class="text ${mail.flags.includes('\\Seen') ? `read` : `unread`}">

${escapeHTML(mail.subject)}

${escapeHTML(typeof mail.from !== 'undefined' ? mail.from.value[0].name || mail.from.value[0].address : 'No Sender...')}

${formatDate(mail.date)}

      `
    })
  }
})

/*

  UID: ${escapeHTML(mail.uid)}

  Subject: ${escapeHTML(mail.subject)}

  From: ${escapeHTML(mail.from ? mail.from.text : 'No Sender?')}

  Flags: ${escapeHTML(JSON.stringify(mail.flags))}

  Folder: ${escapeHTML(mail.folder)}

  ModSeq: ${mail.modseq}

  Date: ${formatDate(mail.date)}

  ${mail.threadMsg ? `Children: ${JSON.stringify(mail.threadMsg)}<br />` : ``}
  ChildMsg: ${mail.isThreadChild ? `Yes` : `No`}

*/

module.exports = { mail }
<commit_msg>Improve performance of adding emails<commit_after>const $ = require('jquery')
const crypto = require('crypto')
const formatDate = require('../helpers/date.js')
const { ipcRenderer } = require('electron')

async function mail () {
  if (!testLoaded('mail')) return

  logger.debug(`We're loading up the mail page now.`)
  page('mail', ['basic', 'mail'])

  $('#compose-button').click(() => {
    ipcRenderer.send('open', { file: 'compose' })
  })

  if (typeof state.account === 'undefined') {
    // I have no idea when this happens, but just in case
    // Perhaps this could happen if someone deleted their state.json file?
    // Or it was unreadable.
    let doc = await new Promise((resolve, reject) => {
      accounts.find({}).sort({ date: 0 }).limit(1).exec((err, docs) => {
        if (err) return reject(err)
        resolve(docs[0])
      })
    })
    stateSet('account', Object.assign(state.account, { hash: doc.hash, user: doc.user }))
  }

  let account = (await accounts.findAsync({ user: state.account.user }, {}))[0]
  let folders = htmlFolders(account.folders)

  if (typeof mailStore[state.account.hash] === 'undefined') {
    setupMailDB(state.account.user)
  }

  if (typeof state.account.folder === 'undefined') {
    // Here, we somewhat fake the folder tree for the inbox folder.
    // We don't really need the seperator, in this instance it should never be used,
    // but we keep it just in case.
    stateSet('account', Object.assign(state.account, {
      folder: [{
        name: 'INBOX',
        delimiter: findSeperator(account.folders)
      }]
    }))
  }

  if (typeof account.folders[state.account.folder[0].name] === 'undefined') {
    stateSet('account', Object.assign(state.account, {
      folder: [{
        name: 'Inbox',
        delimiter: findSeperator(account.folders)
      }]
    }))
  }

  $('#folders').html(folders)

  linkFolders($('#folders').children().children())
  updateMailDiv()

  logger.log(`Loading mail window complete.`)
}

async function updateMailDiv () {
  let mail = await new Promise((resolve) => {
    mailStore[state.account.hash].find({ folder: mailer.compilePath(state.account.folder) }).sort({ date: -1 }).exec((err, docs) => {
      resolve(docs)
    })
  })

  $('#mail').html('')

  $('#title').html(`
    Femto
    ${state.account.user}
  `)

  for (let i = 0; i < state.account.folder.length; i++) {
    $('#title').append(`<a href="#!" class="breadcrumb">${state.account.folder[i].name}</a>`)
  }

  let html = ""
  for (let i = 0; i < mail.length; i++) {
    html += `<e-mail class="email-item" data-uid="${escape(mail[i].uid)}"></e-mail>`
  }
  $('#mail').html($(html))

  if (mail.length === 0) {
    // This folder is empty...
    $('#mail').html('This folder is empty ;(')
  }

  $('.email-item').off('click')

  $('.email-item').click((e) => {
    loadEmail(unescape(e.currentTarget.attributes['data-uid'].nodeValue))
  })
}

/**
 * Currently not functioning.
 *
 * @param  {object} tree
 * @return {object}
 */
function organiseFolders (tree) {
  let keys = Object.getOwnPropertyNames(tree)
  let results = {}
  for (let i = 0; i < keys.length; i++) {
    if (tree[keys[i]].children) {
      results[keys[i]] = organiseFolders(tree[keys[i]].children)
    } else {
      results[keys[i]] = {}
    }
  }
  return results
}

function htmlFolders (tree, journey) {
  journey = journey || []
  let html = ''
  for (let prop in tree) {
    temp = journey.concat({ name: prop, delimiter: tree[prop].delimiter })
    // Folders with depth
    html += `

${prop} ${htmlFolders(tree[prop].children, temp)}

    `
    // Folders without depth
    // html += `
    //

    //
${prop}

    //

    // `
    // html += htmlFolders(tree[prop].children, temp)
  }
  return html
}

function linkFolders (children) {
  children.each((index, item) => {
    $(`#${item.id.replace(/=/g, '\\=')}`).click((element) => {
      logger.log(`Switching page to ${atob(element.target.id)}`)
      stateSet('account', Object.assign(state.account, {
        folder: JSON.parse(atob(element.target.id))
      }))
      $(`.folder-tree`).removeClass('teal')
      $(`#${element.target.id.replace(/=/g, '\\=')}`).addClass('teal')
      updateMailDiv()
    })

    let items = $(`#${item.id.replace(/=/g, '\\=')}`).children().children()
    if (items.length) {
      linkFolders(items)
    }
  })
}

function loadEmail (uid) {
  console.log(uid)
}

global.findFolders = (folders, path) => {
  let keys = folders ? Object.getOwnPropertyNames(folders) : []
  let results = []
  path = path || []
  for (let i = 0; i < keys.length; i++) {
    let tempPath = JSON.parse(JSON.stringify(path))
    tempPath.push({ delimiter: folders[keys[i]].delimiter, name: keys[i]})
    results = results.concat(findFolders(folders[keys[i]].children, tempPath))
  }
  results.push(path)
  return results
}

global.findSeperator = (folders) => {
  // We assume they use one delimiter for the entire inbox, otherwise...
  // Well, I worry for their health..
  // Try not to use this function too much, at some point I intend to deprecate it.
  return typeof folders.INBOX === 'undefined' ? folders.Inbox.delimiter : folders.INBOX.delimiter
}

// Possibly also document.registerElement()?
customElements.define('e-mail', class extends HTMLElement {
  constructor () {
    super()

    // Shadow root is it's *own* entire DOM.  This makes it impact less when
    // we change and search through other parts of the DOM, *hopefully* making it
    // slightly quicker.  It also allows us to use the cool <e-mail> tags.
    // const shadowRoot = this.attachShadow({ mode: 'open' })

    this.innerHTML = `

Loading...

    `

    // We're able to assume some values from the current state.
    // However, we don't rely on it, preferring instead to find it in the email itself.
    let email = this.getAttribute('data-email') ||
                state.account.user
    let hash = this.getAttribute('data-hash') ||
                crypto.createHash('md5').update(email).digest('hex') ||
                state.account.hash
    let uid = unescape(this.getAttribute('data-uid'))

    loadMail(email, hash, uid).then((mail) => {
      // Attach a shadow root to <e-mail>.
      // NOTE: All of these *have* to be HTML escaped.  Consider using `escapeHTML(string)` which
      // is globally accessible.
      this.innerHTML = `

<input type="checkbox" id="${mail.uid}" />

          <div class="text ${mail.flags.includes('\\Seen') ? `read` : `unread`}">

${escapeHTML(mail.subject)}

${escapeHTML(typeof mail.from !== 'undefined' ? mail.from.value[0].name || mail.from.value[0].address : 'No Sender...')}

${formatDate(mail.date)}

      `
    })
  }
})

/*

  UID: ${escapeHTML(mail.uid)}

  Subject: ${escapeHTML(mail.subject)}

  From: ${escapeHTML(mail.from ? mail.from.text : 'No Sender?')}

  Flags: ${escapeHTML(JSON.stringify(mail.flags))}

  Folder: ${escapeHTML(mail.folder)}

  ModSeq: ${mail.modseq}

  Date: ${formatDate(mail.date)}

  ${mail.threadMsg ? `Children: ${JSON.stringify(mail.threadMsg)}<br />` : ``}
  ChildMsg: ${mail.isThreadChild ? `Yes` : `No`}

*/

module.exports = { mail }
<|endoftext|>


<commit_before>define([
  "require",
  "namespace",

  // Libs
  "use!backbone",

  // Modules
  "modules/leaguevine",
  "modules/navigation",
  "modules/title",
  "modules/teamplayer",
  "modules/game"
],

function(require, namespace, Backbone, Leaguevine, Navigation, Title) {
	var app = namespace.app;
	var Team = namespace.module();

	//
	// MODEL
	//
	Team.Model = Backbone.Model.extend({
		defaults: {// Include defaults for any attribute that will be rendered.
			id: "",//id is used as href in template so we need default.
			name: "",
			info: "",
			season: {},
			teamplayers: {},
			games: {}
		},
		urlRoot: Leaguevine.API.root + "teams",
		parse: function(resp, xhr) {
			resp = Backbone.Model.prototype.parse(resp);
			return resp;
		},
		toJSON: function() {
			//TODO: Remove attributes that are not stored (teamplayers, games)
			return _.clone(this.attributes);
		}
	});

	//
	// COLLECTION
	//
	Team.Collection = Backbone.Collection.extend({
		model: Team.Model,
		urlRoot: Leaguevine.API.root + "teams",
		url: function(models) {
			var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
			url += '/?'
			if ( models && models.length ) {
				url += 'team_ids=' + JSON.stringify(models.pluck('id')) + '&';
			}
            if (this.name) {
                url += 'name=' + this.name + '&';
            }
			if (this.season_id) {
				url += 'season_id=' + this.season_id + '&';
			}
			url += 'limit=30&';
            url += 'order_by=[name, -season_id]';
			return url;
		},
		comparator: function(team) {// Define how items in the collection will be sorted.
            return team.get("name").toLowerCase();
		},
		parse: function(resp, xhr) {
			resp = Backbone.Collection.prototype.parse(resp);
			return resp;
		},
		initialize: function(models, options) {
			if (options) {
        		this.season_id = options.season_id;
        		this.name = options.name;
    		}
		}
	});

	//
	// ROUTER
	//
	Team.Router = Backbone.Router.extend({
		// Create a router to map faux-URLs to actions.
		// Faux-URLs come from Backbone.history.navigate or hashes in a URL from a followed link.
		routes : {
			"teams": "listTeams", //List all teams.
			"teams/:teamId": "showTeam", //Show detail for one team.
			"newteam": "editTeam",
			"editteam/:teamId": "editTeam"
		},
		listTeams: function () {//Route for all teams.
			// Prepare the data.
			var teams = new Team.Collection([],{season_id: Leaguevine.API.season_id});
			//var teams = new Team.Collection();//No defaults?
			teams.fetch();

			// Prepare the layout/view(s)
			var myLayout = app.router.useLayout("nav_content");// Get the layout from a layout cache.
			// Layout from cache might have different views set. Let's (re-)set them now.
			myLayout.view(".navbar", new Navigation.Views.Navbar({}));
			myLayout.view(".titlebar", new Title.Views.Titlebar({title: "Teams", right_btn_href: "#newteam", right_btn_class: "add"}));
			myLayout.view(".content", new Team.Views.SearchableList({collection: teams}));//pass the List view a collection of (fetched) teams.
			myLayout.render(function(el) {$("#main").html(el);});// Render the layout, calling each subview's .render first.
		},
		showTeam: function (teamId) {
			//Prepare the data.
			var team = new Team.Model({id: teamId});

            titlebarOptions = {title: team.get("name"), left_btn_href:"#teams", left_btn_class: "back", left_btn_txt: "Teams", right_btn_href: "#editteam/"+teamId, right_btn_txt: "Edit"};

            team.fetch({success: function (model, response) {
                // After the team has been fetched, render the nav-bar with the team's fetched name
                var myLayout = app.router.useLayout("div");
                titlebarOptions.title = team.get("name");
                myLayout.view("div", new Title.Views.Titlebar(titlebarOptions));
                myLayout.render(function(el) {$(".titlebar").html(el)});
                }
            });

			var TeamPlayer = require("modules/teamplayer");
			var teamplayers = new TeamPlayer.Collection([],{team_id: team.get('id')});
			teamplayers.fetch();
			//team.set('teamplayers', teamplayers);

			var Game = require("modules/game");
			var games = new Game.Collection([],{team_1_id: team.get('id')});
			games.fetch();
			//team.set('games', games);

			var myLayout = app.router.useLayout("nav_detail_list");// Get the layout. Has .navbar, .detail, .list_children
			myLayout.setViews({
				".navbar": new Navigation.Views.Navbar({}),
				".detail": new Team.Views.Detail( {model: team}),
				".list_children": new Team.Views.Multilist({ teamplayers: teamplayers, games: games}),
                ".titlebar": new Title.Views.Titlebar(titlebarOptions)
			});
			myLayout.render(function(el) {$("#main").html(el);});// Render the layout, calling each subview's .render first.
		},
		editTeam: function (teamId) {
			var myLayout = app.router.useLayout("nav_content");
			//If we have teamId, then we are editing. If not, then we are creating a new team.
			if (teamId) { //make the edit team page
				var team = new Team.Model({id: teamId});
                myLayout.view(".titlebar", new Title.Views.Titlebar({title: "Edit", left_btn_href: "#teams/"+teamId, left_btn_class: "back", left_btn_txt: "Cancel"}));
			}
			else { //make the add team page
				var team = new Team.Model({season_id: app.api.season_id});//Do we need the season_id here?
                myLayout.view(".titlebar", new Title.Views.Titlebar({title: "Add a Team", left_btn_href: "#teams", left_btn_class: "back", left_btn_txt: "Cancel"}));
			}
			team.fetch();
			myLayout.view(".navbar", new Navigation.Views.Navbar({}));
			myLayout.view(".content", new Team.Views.Edit({model: team}));
			myLayout.render(function(el) {$("#main").html(el);});
		}
	});
	Team.router = new Team.Router();// INITIALIZE ROUTER

	//
	// VIEWS
	//
    Team.Views.SearchableList = Backbone.View.extend({
    	//Our team collection is this.collection
        template: "teams/searchable_list",
        events: {
            "keyup #team_search": "filterTeams"
        },
        filterTeams: function(ev){//If a user types something into the search box, filter on the string
            var search_string = ev.currentTarget.value;
            var my_collection=this.collection;
            my_collection.name=search_string;
            //Create a new collection for fetching
            var search_results = new Team.Collection([],{name: search_string});
			search_results.fetch({//Fetch the new collection
				success: function (collection, response){//When it returns, add it to our current collection.
					//returned models with identical properties will have different cids, thus _.union does not discriminate.
					var models = _.reject(collection.models, function(model){
						return my_collection.pluck("id").indexOf(model.get("id")) != -1
					});
					my_collection.reset(_.union(my_collection.models, models));
				}
			});
			my_collection.reset(my_collection.models);//I hope the name attribute passes through.
        },
		render: function(layout) {
            var view = layout(this); //Get this view from the layout.
            var temp_collection = {};
			this.setViews({
				".team_list_area": new Team.Views.List( {collection: this.collection})
			});
			return view.render().then(function(el) {
				$('.team_list_area').html(el);
			});
       },
       initialize: function() {
       		this.search_string = "";
		}
    });
	Team.Views.List = Backbone.View.extend({
		template: "teams/list",
		className: "teams-wrapper",
		render: function(layout) {
			var view = layout(this); //Get this view from the layout.
			var filter_by = this.collection.name ? this.collection.name : "";
			this.collection.each(function(team) {//for each team in the collection.
				//Do collection filtering here
				if (!filter_by || team.get("name").toLowerCase().indexOf(filter_by.toLowerCase()) != -1) {
					view.insert("ul", new Team.Views.Item({//Inserts the team into the ul in the list template.
						model: team//pass each team to a Item view instance.
					}));
				}
			});
			return view.render({ count: this.collection.length });
		},
		initialize: function() {
			this.collection.bind("reset", function() {
                if (Backbone.history.fragment == "teams") {
                    this.render();
                }
            }, this);
		}
	});
	Team.Views.Item = Backbone.View.extend({
		template: "teams/item",
		tagName: "li",//Creates a li for each instance of this view. Note below that this li is inserted into a ul by the list's render function.
		serialize: function() {
            // Add a couple attributes to the team for displaying
            var team = this.model.toJSON();
            team.season_name = '';
            team.league_name = '';
            if (team.season != null) {
                team.season_name = team.season.name;
                team.league_name = team.season.league.name;
            }
            return team
        } //render looks for this to manipulate model before passing to the template.
	});
	Team.Views.Detail = Backbone.View.extend({
		//We were passed a model on creation by Team.Router.showTeam(), so we have this.model
		template: "teams/detail",
		serialize: function() {return this.model.toJSON();},
		initialize: function() {this.model.bind("change", function() {this.render();}, this);}
	});
	Team.Views.Multilist = Backbone.View.extend({
		template: "teams/multilist",
		events: {
			"click .bplayers": "showPlayers",
			"click .bgames": "showGames"
		},
		showPlayers: function(ev){
			$('.lgames').hide();
			$('.lplayers').show();
            $('.list_children button').removeClass('is_active');
            $('button.bplayers').addClass('is_active');
		},
		showGames: function(ev){
			$('.lplayers').hide();
			$('.lgames').show();
            $('.list_children button').removeClass('is_active');
            $('button.bgames').addClass('is_active');
		},
		render: function(layout) {
			var view = layout(this); //Get this view from the layout.
			var Game = require("modules/game");
			var TeamPlayer = require("modules/teamplayer");
			this.setViews({
				".lgames": new Game.Views.List( {collection: this.options.games} ),
				".lplayers": new TeamPlayer.Views.PlayerList( {collection: this.options.teamplayers} )
			});
			return view.render().then(function(el) {
				//I'd rather the render function only do this once, instead of everytime the data are reset
				//But it might turn out to be a non-issue.
				$('.lplayers').hide();
			});
		},
		initialize: function() {
			this.options.teamplayers.bind("reset", function() {this.render();}, this);
			this.options.games.bind("reset", function() {this.render();}, this);
		}
	});
	Team.Views.Edit = Backbone.View.extend({
		template: "teams/edit",
		render: function(layout) {return layout(this).render(this.model.toJSON());},
		initialize: function() {this.model.bind("change", function() {this.render();}, this);},
  		events: {
			"click .save": "saveModel",
			"click .delete": "deleteModel"
		},
		saveModel: function(ev){
			this.model.save(
				{
					name:$("#name").val(),
					info:$("#info").val()
				},
				{
					headers: { "Authorization": "bearer " + app.api.d_token() }
					//error: function(){...} }//TODO: Add an error callback if not authorized.
				}
			);
			Backbone.history.navigate('teams', true);

		},
		deleteModel: function(ev) {
			this.model.destroy(
				{
					headers: { "Authorization": "bearer " + app.api.d_token() },
					//error: function(model,respose){...}//TODO: Add an error callback to handle unauthorized delete requests.
				}
			);
			Backbone.history.navigate('teams', true);
		}
	});
	return Team;// Required, return the module for AMD compliance
	//exports.Team = Team;
});
<commit_msg>Use collection.trigger("reset") instead of collection.reset(collection.models). Might perform better.<commit_after>define([
  "require",
  "namespace",

  // Libs
  "use!backbone",

  // Modules
  "modules/leaguevine",
  "modules/navigation",
  "modules/title",
  "modules/teamplayer",
  "modules/game"
],

function(require, namespace, Backbone, Leaguevine, Navigation, Title) {
	var app = namespace.app;
	var Team = namespace.module();

	//
	// MODEL
	//
	Team.Model = Backbone.Model.extend({
		defaults: {// Include defaults for any attribute that will be rendered.
			id: "",//id is used as href in template so we need default.
			name: "",
			info: "",
			season: {},
			teamplayers: {},
			games: {}
		},
		urlRoot: Leaguevine.API.root + "teams",
		parse: function(resp, xhr) {
			resp = Backbone.Model.prototype.parse(resp);
			return resp;
		},
		toJSON: function() {
			//TODO: Remove attributes that are not stored (teamplayers, games)
			return _.clone(this.attributes);
		}
	});

	//
	// COLLECTION
	//
	Team.Collection = Backbone.Collection.extend({
		model: Team.Model,
		urlRoot: Leaguevine.API.root + "teams",
		url: function(models) {
			var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
			url += '/?'
			if ( models && models.length ) {
				url += 'team_ids=' + JSON.stringify(models.pluck('id')) + '&';
			}
            if (this.name) {
                url += 'name=' + this.name + '&';
            }
			if (this.season_id) {
				url += 'season_id=' + this.season_id + '&';
			}
			url += 'limit=30&';
            url += 'order_by=[name, -season_id]';
			return url;
		},
		comparator: function(team) {// Define how items in the collection will be sorted.
            return team.get("name").toLowerCase();
		},
		parse: function(resp, xhr) {
			resp = Backbone.Collection.prototype.parse(resp);
			return resp;
		},
		initialize: function(models, options) {
			if (options) {
        		this.season_id = options.season_id;
        		this.name = options.name;
    		}
		}
	});

	//
	// ROUTER
	//
	Team.Router = Backbone.Router.extend({
		// Create a router to map faux-URLs to actions.
		// Faux-URLs come from Backbone.history.navigate or hashes in a URL from a followed link.
		routes : {
			"teams": "listTeams", //List all teams.
			"teams/:teamId": "showTeam", //Show detail for one team.
			"newteam": "editTeam",
			"editteam/:teamId": "editTeam"
		},
		listTeams: function () {//Route for all teams.
			// Prepare the data.
			var teams = new Team.Collection([],{season_id: Leaguevine.API.season_id});
			//var teams = new Team.Collection();//No defaults?
			teams.fetch();

			// Prepare the layout/view(s)
			var myLayout = app.router.useLayout("nav_content");// Get the layout from a layout cache.
			// Layout from cache might have different views set. Let's (re-)set them now.
			myLayout.view(".navbar", new Navigation.Views.Navbar({}));
			myLayout.view(".titlebar", new Title.Views.Titlebar({title: "Teams", right_btn_href: "#newteam", right_btn_class: "add"}));
			myLayout.view(".content", new Team.Views.SearchableList({collection: teams}));//pass the List view a collection of (fetched) teams.
			myLayout.render(function(el) {$("#main").html(el);});// Render the layout, calling each subview's .render first.
		},
		showTeam: function (teamId) {
			//Prepare the data.
			var team = new Team.Model({id: teamId});

            titlebarOptions = {title: team.get("name"), left_btn_href:"#teams", left_btn_class: "back", left_btn_txt: "Teams", right_btn_href: "#editteam/"+teamId, right_btn_txt: "Edit"};

            team.fetch({success: function (model, response) {
                // After the team has been fetched, render the nav-bar with the team's fetched name
                var myLayout = app.router.useLayout("div");
                titlebarOptions.title = team.get("name");
                myLayout.view("div", new Title.Views.Titlebar(titlebarOptions));
                myLayout.render(function(el) {$(".titlebar").html(el)});
                }
            });

			var TeamPlayer = require("modules/teamplayer");
			var teamplayers = new TeamPlayer.Collection([],{team_id: team.get('id')});
			teamplayers.fetch();
			//team.set('teamplayers', teamplayers);

			var Game = require("modules/game");
			var games = new Game.Collection([],{team_1_id: team.get('id')});
			games.fetch();
			//team.set('games', games);

			var myLayout = app.router.useLayout("nav_detail_list");// Get the layout. Has .navbar, .detail, .list_children
			myLayout.setViews({
				".navbar": new Navigation.Views.Navbar({}),
				".detail": new Team.Views.Detail( {model: team}),
				".list_children": new Team.Views.Multilist({ teamplayers: teamplayers, games: games}),
                ".titlebar": new Title.Views.Titlebar(titlebarOptions)
			});
			myLayout.render(function(el) {$("#main").html(el);});// Render the layout, calling each subview's .render first.
		},
		editTeam: function (teamId) {
			var myLayout = app.router.useLayout("nav_content");
			//If we have teamId, then we are editing. If not, then we are creating a new team.
			if (teamId) { //make the edit team page
				var team = new Team.Model({id: teamId});
                myLayout.view(".titlebar", new Title.Views.Titlebar({title: "Edit", left_btn_href: "#teams/"+teamId, left_btn_class: "back", left_btn_txt: "Cancel"}));
			}
			else { //make the add team page
				var team = new Team.Model({season_id: app.api.season_id});//Do we need the season_id here?
                myLayout.view(".titlebar", new Title.Views.Titlebar({title: "Add a Team", left_btn_href: "#teams", left_btn_class: "back", left_btn_txt: "Cancel"}));
			}
			team.fetch();
			myLayout.view(".navbar", new Navigation.Views.Navbar({}));
			myLayout.view(".content", new Team.Views.Edit({model: team}));
			myLayout.render(function(el) {$("#main").html(el);});
		}
	});
	Team.router = new Team.Router();// INITIALIZE ROUTER

	//
	// VIEWS
	//
    Team.Views.SearchableList = Backbone.View.extend({
    	//Our team collection is this.collection
        template: "teams/searchable_list",
        events: {
            "keyup #team_search": "filterTeams"
        },
        filterTeams: function(ev){//If a user types something into the search box, filter on the string
            var search_string = ev.currentTarget.value;
            var my_collection=this.collection;
            my_collection.name=search_string;
            //Create a new collection for fetching
            var search_results = new Team.Collection([],{name: search_string});
			search_results.fetch({//Fetch the new collection
				success: function (collection, response){//When it returns, add it to our current collection.
					//returned models with identical properties will have different cids, thus _.union does not discriminate.
					var models = _.reject(collection.models, function(model){
						return my_collection.pluck("id").indexOf(model.get("id")) != -1
					});
					my_collection.reset(_.union(my_collection.models, models));
				}
			});
			//my_collection.reset(my_collection.models);//I hope the name attribute passes through.
			my_collection.trigger('reset');
        },
		render: function(layout) {
            var view = layout(this); //Get this view from the layout.
            var temp_collection = {};
			this.setViews({
				".team_list_area": new Team.Views.List( {collection: this.collection})
			});
			return view.render().then(function(el) {
				$('.team_list_area').html(el);
			});
       },
       initialize: function() {
       		this.search_string = "";
		}
    });
	Team.Views.List = Backbone.View.extend({
		template: "teams/list",
		className: "teams-wrapper",
		render: function(layout) {
			var view = layout(this); //Get this view from the layout.
			var filter_by = this.collection.name ? this.collection.name : "";
			this.collection.each(function(team) {//for each team in the collection.
				//Do collection filtering here
				if (!filter_by || team.get("name").toLowerCase().indexOf(filter_by.toLowerCase()) != -1) {
					view.insert("ul", new Team.Views.Item({//Inserts the team into the ul in the list template.
						model: team//pass each team to a Item view instance.
					}));
				}
			});
			return view.render({ count: this.collection.length });
		},
		initialize: function() {
			this.collection.bind("reset", function() {
                if (Backbone.history.fragment == "teams") {
                    this.render();
                }
            }, this);
		}
	});
	Team.Views.Item = Backbone.View.extend({
		template: "teams/item",
		tagName: "li",//Creates a li for each instance of this view. Note below that this li is inserted into a ul by the list's render function.
		serialize: function() {
            // Add a couple attributes to the team for displaying
            var team = this.model.toJSON();
            team.season_name = '';
            team.league_name = '';
            if (team.season != null) {
                team.season_name = team.season.name;
                team.league_name = team.season.league.name;
            }
            return team
        } //render looks for this to manipulate model before passing to the template.
	});
	Team.Views.Detail = Backbone.View.extend({
		//We were passed a model on creation by Team.Router.showTeam(), so we have this.model
		template: "teams/detail",
		serialize: function() {return this.model.toJSON();},
		initialize: function() {this.model.bind("change", function() {this.render();}, this);}
	});
	Team.Views.Multilist = Backbone.View.extend({
		template: "teams/multilist",
		events: {
			"click .bplayers": "showPlayers",
			"click .bgames": "showGames"
		},
		showPlayers: function(ev){
			$('.lgames').hide();
			$('.lplayers').show();
            $('.list_children button').removeClass('is_active');
            $('button.bplayers').addClass('is_active');
		},
		showGames: function(ev){
			$('.lplayers').hide();
			$('.lgames').show();
            $('.list_children button').removeClass('is_active');
            $('button.bgames').addClass('is_active');
		},
		render: function(layout) {
			var view = layout(this); //Get this view from the layout.
			var Game = require("modules/game");
			var TeamPlayer = require("modules/teamplayer");
			this.setViews({
				".lgames": new Game.Views.List( {collection: this.options.games} ),
				".lplayers": new TeamPlayer.Views.PlayerList( {collection: this.options.teamplayers} )
			});
			return view.render().then(function(el) {
				//I'd rather the render function only do this once, instead of everytime the data are reset
				//But it might turn out to be a non-issue.
				$('.lplayers').hide();
			});
		},
		initialize: function() {
			this.options.teamplayers.bind("reset", function() {this.render();}, this);
			this.options.games.bind("reset", function() {this.render();}, this);
		}
	});
	Team.Views.Edit = Backbone.View.extend({
		template: "teams/edit",
		render: function(layout) {return layout(this).render(this.model.toJSON());},
		initialize: function() {this.model.bind("change", function() {this.render();}, this);},
  		events: {
			"click .save": "saveModel",
			"click .delete": "deleteModel"
		},
		saveModel: function(ev){
			this.model.save(
				{
					name:$("#name").val(),
					info:$("#info").val()
				},
				{
					headers: { "Authorization": "bearer " + app.api.d_token() }
					//error: function(){...} }//TODO: Add an error callback if not authorized.
				}
			);
			Backbone.history.navigate('teams', true);

		},
		deleteModel: function(ev) {
			this.model.destroy(
				{
					headers: { "Authorization": "bearer " + app.api.d_token() },
					//error: function(model,respose){...}//TODO: Add an error callback to handle unauthorized delete requests.
				}
			);
			Backbone.history.navigate('teams', true);
		}
	});
	return Team;// Required, return the module for AMD compliance
	//exports.Team = Team;
});
<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var User = require('../models/users'),
	Pic = require('../models/pics'),
	mongoose = require('mongoose');

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

var urlencodedParser = bodyParser.urlencoded({ extended: false });

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			next();
		} else {
			res.redirect('/auth/twitter/callback');
		}
	}

	app.route('/')
		.get(function (req, res) {
			if (req.isAuthenticated()) {
				res.render(path + '/app/views/all.handlebars', {loggedin: true});
			} else {
				res.render(path + '/app/views/all.handlebars', {loggedin: false});
			}
		});

	app.route('/user/:id')
		.get(function(req, res) {
			if (req.isAuthenticated()) {
				res.render(path + '/app/views/userpics.handlebars', {loggedin: true, id: req.params.id});
			} else {
				res.render(path + '/app/views/userpics.handlebars', {loggedin: false, id: req.params.id});
			}
		});
	app.route('/userpics/:id')
		.get(function(req, res) {
			Pic.find({_creator: req.params.id}, function(err, pics) {
				res.json(pics);
			})
		})

	app.route('/remove/:id')
		.get(function(req, res) {
			Pic.findOneAndRemove(req.params.id)
			.then(function() {
				console.log('pic removed!')
				console.log(req.params.id)
				res.redirect('/my_pics');
			})
		})

	app.route('/all_pics')
		.get(function(req, res, next){
			Pic.find({}).then(function(pics) {
				res.json(pics);
			})
		})

	app.route('/get_my_pics')
		.get(isLoggedIn, function(req, res, next) {

				Pic.find({}, function(err, pics) {
					if (err) throw err;
					res.json(pics);
				});

		})

	app.route('/my_pics')
		.get(isLoggedIn, function(req, res, next) {
			res.render(path + '/app/views/mypics.handlebars', {loggedin: true});
		});

	app.route('/submit_pic')
		.post(isLoggedIn, urlencodedParser, function(req, res, next) {
			User.findOne({_id: req.user._id}, function(err, user) {
				if (err) throw err;

				var newPic = new Pic({
										  url: req.body.url,
										  description: req.body.description,
										  _creator: user._id,
										  creator_username: user.twitter.username,
									  });
				newPic.save();
			});
			res.redirect('/')
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/');
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/api/:id')
		.get(isLoggedIn, function (req, res) {
			res.json(req.user.github);
		});

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/',
		}));

};<commit_msg>something<commit_after>'use strict';

var path = process.cwd();
var User = require('../models/users'),
	Pic = require('../models/pics'),
	mongoose = require('mongoose');

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

var urlencodedParser = bodyParser.urlencoded({ extended: false });

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			next();
		} else {
			res.redirect('/auth/twitter/callback');
		}
	}

	app.route('/')
		.get(function (req, res) {
			if (req.isAuthenticated()) {
				res.render(path + '/app/views/all.handlebars', {loggedin: true});
			} else {
				res.render(path + '/app/views/all.handlebars', {loggedin: false});
			}
		});

	app.route('/user/:id')
		.get(function(req, res) {
			if (req.isAuthenticated()) {
				res.render(path + '/app/views/userpics.handlebars', {loggedin: true, id: req.params.id});
			} else {
				res.render(path + '/app/views/userpics.handlebars', {loggedin: false, id: req.params.id});
			}
		});
	app.route('/userpics/:id')
		.get(function(req, res) {
			Pic.find({_creator: req.params.id}, function(err, pics) {
				res.json(pics);
			})
		})

	app.route('/remove/:id')
		.get(function(req, res) {
			Pic.findOneAndRemove(req.params.id)
			.then(function() {
				console.log('pic removed!')
				console.log(req.params.id)
				res.redirect('/my_pics');
			})
		})

	app.route('/all_pics')
		.get(function(req, res, next){
			Pic.find({}).then(function(pics) {
				res.json(pics);
			})
		})

	app.route('/get_my_pics')
		.get(isLoggedIn, function(req, res, next) {

				Pic.find({_creator: req.user._id}, function(err, pics) {
					if (err) throw err;
					res.json(pics);
				});

		})

	app.route('/my_pics')
		.get(isLoggedIn, function(req, res, next) {
			res.render(path + '/app/views/mypics.handlebars', {loggedin: true});
		});

	app.route('/submit_pic')
		.post(isLoggedIn, urlencodedParser, function(req, res, next) {
			User.findOne({_id: req.user._id}, function(err, user) {
				if (err) throw err;

				var newPic = new Pic({
										  url: req.body.url,
										  description: req.body.description,
										  _creator: user._id,
										  creator_username: user.twitter.username,
									  });
				newPic.save();
			});
			res.redirect('/')
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/');
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/api/:id')
		.get(isLoggedIn, function (req, res) {
			res.json(req.user.github);
		});

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/',
		}));

};<|endoftext|>


<commit_before>const userRoutes = require('./user_routes');
/* eslint-disable func-names */
module.exports = function(app, db) {
    userRoutes(app, db);
};
/* eslint-enable func-names */
<commit_msg>redirect from root<commit_after>const userRoutes = require('./user_routes');
/* eslint-disable func-names */
module.exports = function(app, db) {
    app.get('/', (req, res) => {
        res.redirect(301, '/docs');
    });
    userRoutes(app, db);
};
/* eslint-enable func-names */
<|endoftext|>