<commit_before>/**
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var neo4jv1 = require("../../lib/v1");

var _console = console;

/**
* The tests below are examples that get pulled into the Driver Manual using the tags inside the tests.
*
* DO NOT add tests to this file that are not for that exact purpose.
* DO NOT modify these tests without ensuring they remain consistent with the equivalent examples in other drivers
*/
describe('examples', function() {

  var driverGlobal, sessionGlobal, out, console;

  beforeEach(function(done) {
    var neo4j = neo4jv1;
    //tag::construct-driver[]
    driverGlobal = neo4j.driver("bolt://myserver:7687", neo4j.auth.basic("neo4j", "neo4j"));
    //end::construct-driver[]
    sessionGlobal = driverGlobal.session();

    // Override console.log, to assert on stdout output
    out = [];
    console = { log: function(msg) { out.push(msg); }  };

    sessionGlobal.run("MATCH (n) DETACH DELETE n").then(done);
  });

  afterEach(function() {
    sessionGlobal.close();
    driverGlobal.close();
  });

  it('should document a minimal import and usage example', function (done) {
    //OH my is this a hack
    var require = function (arg) {
      return {v1: neo4jv1}
    };
    // tag::minimal-example-import[]
    var neo4j = require('neo4j-driver').v1;
    // end::minimal-example-import[]
    // tag::minimal-example[]
    var driver = neo4j.driver("bolt://myserver:7687", neo4j.auth.basic("neo4j", "neo4j"));
    var session = driver.session();
    session
      .run( "CREATE (a:Person {name:'Arthur', title:'King'})" )
      .then( function()
      {
        return session.run( "MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title" )
      })
      .then( function( result ) {
        console.log( result.records[0].get("title") + " " + result.records[0].get("name") );
        session.close();
        driver.close();
      })
    // end::minimal-example[]
      .then(function() {
        expect(out[0]).toBe("King Arthur");
        done();
      });
  });

  it('should be able to configure session pool size', function (done) {
   var neo4j = neo4jv1;
    // tag::configuration[]
    var driver = neo4j.driver("bolt://myserver:7687", neo4j.auth.basic("neo4j", "neo4j"), {connectionPoolSize: 50});
    //end::configuration[]

    var s = driver.session();
    s.run( "CREATE (p:Person { name: {name} })", {name: "The One"} )
      .then( function(result) {
        var theOnesCreated = result.summary.counters.nodesCreated();
        console.log(theOnesCreated);
        s.close();
        driver.close();
      })
      .then(function() {
        expect(out[0]).toBe(1);
        done();
    });
  });

  it('should document a statement', function(done) {
    var session = sessionGlobal;
    // tag::statement[]
    session
      .run( "CREATE (person:Person {name: {name}})", {name: "Arthur"} )
    // end::statement[]
      .then( function(result) {
        var theOnesCreated = result.summary.counters.nodesCreated();
        console.log("There were " + theOnesCreated + " the ones created.")
      })
      .then(function() {
        expect(out[0]).toBe("There were 1 the ones created.");
        done();
      });
  });

  it('should document a statement without parameters', function(done) {
    var session = sessionGlobal;
    // tag::statement-without-parameters[]
    session
      .run( "CREATE (p:Person { name: 'Arthur' })" )
    // end::statement-without-parameters[]
      .then( function(result) {
        var theOnesCreated = result.summary.counters.nodesCreated();
        console.log("There were " + theOnesCreated + " the ones created.");
      });

    // Then
    setTimeout(function() {
      expect(out[0]).toBe("There were 1 the ones created.");
      done();
    }, 1000)
  });

  it('should be able to iterate results', function(done) {
    var session = sessionGlobal;
    session
      .run( "CREATE (weapon:Weapon { name: 'Sword in the stone' })" )
      .then(function() {
    // tag::result-traversal[]
      var searchTerm = "Sword";
      session
        .run( "MATCH (weapon:Weapon) WHERE weapon.name CONTAINS {term} RETURN weapon.name", {term : searchTerm} )
        .subscribe({
          onNext: function(record) {
            console.log("" + record.get("weapon.name"));
          },
          onCompleted: function() {
            session.close();
          },
          onError: function(error) {
            console.log(error);
          }
        });
    // end::result-traversal[]
    });
    // Then
    setTimeout(function() {
      expect(out[0]).toBe("Sword in the stone");
      done();
    }, 1000);
  });

  it('should be able to access records', function(done) {
    var session = sessionGlobal;
    session
      .run( "CREATE (weapon:Weapon { name: 'Sword in the stone', owner: 'Arthur', material: 'Stone', size: 'Huge' })" )
      .then(function() {
      // tag::access-record[]
        var searchTerm = "Arthur";
        session
          .run( "MATCH (weapon:Weapon) WHERE weapon.owner CONTAINS {term} RETURN weapon.name, weapon.material, weapon.size", {term : searchTerm} )
          .subscribe({
            onNext: function(record) {
              var sword = [];
              record.forEach(function(value, key)
              {
                sword.push(key + ": " + value);
              });
              console.log(sword);
            },
            onCompleted: function() {
              session.close();
            },
            onError: function(error) {
              console.log(error);
            }
          });
      // end::access-record[]
      });

    // Then
    setTimeout(function() {
      expect(out[0].length).toBe(3);
      done();
    }, 1000)
  });

  it('should be able to retain for later processing', function(done) {
    var session = sessionGlobal;

    session
    .run("CREATE (knight:Person:Knight { name: 'Lancelot', castle: 'Camelot' })")
    .then(function() {
      // tag::retain-result[]
      session
        .run("MATCH (knight:Person:Knight) WHERE knight.castle = {castle} RETURN knight.name AS name", {castle: "Camelot"})
        .then(function (result) {
          var records = [];
          for (i = 0; i < result.records.length; i++) {
            records.push(result.records[i]);
          }
          return records;
        })
        .then(function (records) {
          for(i = 0; i < records.length; i ++)
          {
            console.log(records[i].get("name") + " is a knight of Camelot");
          }
        });
      // end::retain-result[]
    });

    //await the result
    setTimeout(function() {
      expect(out[0]).toBe("Lancelot is a knight of Camelot");
      done();
    }, 1000);
  });

  it('should be able to do nested queries', function(done) {
    var session = sessionGlobal;
    session
      .run( "CREATE (knight:Person:Knight { name: 'Lancelot', castle: 'Camelot' })" +
            "CREATE (king:Person { name: 'Arthur', title: 'King' })" )
      .then(function() {
        // tag::nested-statements[]
          session
            .run("MATCH (knight:Person:Knight) WHERE knight.castle = {castle} RETURN id(knight) AS knight_id", {"castle": "Camelot"})
            .subscribe({
              onNext: function(record) {
                session
                  .run("MATCH (knight) WHERE id(knight) = {id} MATCH (king:Person) WHERE king.name = {king} CREATE (knight)-[:DEFENDS]->(king)",
                  {"id": record.get("knight_id"), "king": "Arthur"});
              },
              onCompleted: function() {
                session
                  .run("MATCH (:Knight)-[:DEFENDS]->() RETURN count(*)")
                  .then(function (result) {
                    console.log("Count is " + result.records[0].get(0).toInt());
                  });
              },
              onError: function(error) {
                console.log(error);
              }
            });
        // end::nested-statements[]
        });

    //await the result
    setTimeout(function() {
      expect(out[0]).toBe("Count is 1");
      done();
    }, 1000);
  });

  it('should be able to handle cypher error', function(done) {
    var session = sessionGlobal;

    // tag::handle-cypher-error[]
    session
      .run("Then will cause a syntax error")
      .catch( function(err) {
        expect(err.fields[0].code).toBe( "Neo.ClientError.Statement.SyntaxError" );
        done();
      });
    // end::handle-cypher-error[]
  });

  it('should be able to profile', function(done) {
    var session = sessionGlobal;

    session.run("CREATE (:Person {name:'Arthur'})").then(function() {
      // tag::result-summary-query-profile[]
      session
        .run("PROFILE MATCH (p:Person {name: {name}}) RETURN id(p)", {name: "Arthur"})
        .then(function (result) {
          console.log(result.summary.profile);
        });
      // end::result-summary-query-profile[]
    });

    //await the result
    setTimeout(function() {
      expect(out.length).toBe(1);
      done();
    }, 1000);
  });

  it('should be able to see notifications', function(done) {
    var session = sessionGlobal;

    // tag::result-summary-notifications[]
    session
      .run("EXPLAIN MATCH (king), (queen) RETURN king, queen")
      .then(function (result) {
        var notifications = result.summary.notifications, i;
        for (i = 0; i < notifications.length; i++) {
          console.log(notifications[i].code);
        }
      });
    // end::result-summary-notifications[]

    setTimeout(function () {
      expect(out[0]).toBe("Neo.ClientNotification.Statement.CartesianProductWarning");
      done();
    }, 1000);
  });

  it('should document committing a transaction', function() {
    var session = sessionGlobal;

    // tag::transaction-commit[]
    var tx = session.beginTransaction();
    tx.run( "CREATE (:Person {name: 'Guinevere'})" );
    tx.commit();
    // end::transaction-commit[]
  });

  it('should document rolling back a transaction', function() {
    var session = sessionGlobal;

    // tag::transaction-rollback[]
    var tx = session.beginTransaction();
    tx.run( "CREATE (:Person {name: 'Merlin'})" );
    tx.rollback();
    // end::transaction-rollback[]
  });

  it('should document how to require encryption', function() {
    var session = sessionGlobal;

    var neo4j = neo4jv1;
    // tag::tls-require-encryption[]
    var driver = neo4j.driver("bolt://myserver:7687", neo4j.auth.basic("neo4j", "neo4j"), {
      // In NodeJS, encryption is on by default. In the web bundle, it is off.
      encrypted:true
    });
    // end::tls-require-encryption[]
    driver.close();
  });

  it('should document how to configure trust-on-first-use', function() {
    var neo4j = neo4jv1;
    // tag::tls-trust-on-first-use[]
    var driver = neo4j.driver("bolt://myserver:7687", neo4j.auth.basic("neo4j", "neo4j"), {
      // Note that trust-on-first-use is not available in the browser bundle,
      // in NodeJS, trust-on-first-use is the default trust mode. In the browser
      // it is TRUST_CUSTOM_CA_SIGNED_CERTIFICATES.
      trust: "TRUST_ON_FIRST_USE",
      encrypted:true
    });
    // end::tls-trust-on-first-use[]
    driver.close();
  });

  it('should document how to configure a trusted signing certificate', function() {
    var neo4j = neo4jv1;
    // tag::tls-signed[]
    var driver = neo4j.driver("bolt://myserver:7687", neo4j.auth.basic("neo4j", "neo4j"), {
      trust: "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES",
      // Configuring which certificates to trust here is only available
      // in NodeJS. In the browser bundle the browsers list of trusted
      // certificates is used, due to technical limitations in some browsers.
      trustedCertificates : ["path/to/ca.crt"],
      encrypted:true
    });
    // end::tls-signed[]
    driver.close();
  });

  it('should document how to disable auth', function() {
    var neo4j = neo4jv1;
    // tag::connect-with-auth-disabled[]
    var driver = neo4j.driver("bolt://myserver:7687", {
      // In NodeJS, encryption is on by default. In the web bundle, it is off.
      encrypted:true
    });
    // end::connect-with-auth-disabled[]
    driver.close();
  });

});
<commit_msg>`myserver` -> `localhost` in examples<commit_after>/**
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var neo4jv1 = require("../../lib/v1");

var _console = console;

/**
* The tests below are examples that get pulled into the Driver Manual using the tags inside the tests.
*
* DO NOT add tests to this file that are not for that exact purpose.
* DO NOT modify these tests without ensuring they remain consistent with the equivalent examples in other drivers
*/
describe('examples', function() {

  var driverGlobal, sessionGlobal, out, console;

  beforeEach(function(done) {
    var neo4j = neo4jv1;
    //tag::construct-driver[]
    driverGlobal = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"));
    //end::construct-driver[]
    sessionGlobal = driverGlobal.session();

    // Override console.log, to assert on stdout output
    out = [];
    console = { log: function(msg) { out.push(msg); }  };

    sessionGlobal.run("MATCH (n) DETACH DELETE n").then(done);
  });

  afterEach(function() {
    sessionGlobal.close();
    driverGlobal.close();
  });

  it('should document a minimal import and usage example', function (done) {
    //OH my is this a hack
    var require = function (arg) {
      return {v1: neo4jv1}
    };
    // tag::minimal-example-import[]
    var neo4j = require('neo4j-driver').v1;
    // end::minimal-example-import[]
    // tag::minimal-example[]
    var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"));
    var session = driver.session();
    session
      .run( "CREATE (a:Person {name:'Arthur', title:'King'})" )
      .then( function()
      {
        return session.run( "MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title" )
      })
      .then( function( result ) {
        console.log( result.records[0].get("title") + " " + result.records[0].get("name") );
        session.close();
        driver.close();
      })
    // end::minimal-example[]
      .then(function() {
        expect(out[0]).toBe("King Arthur");
        done();
      });
  });

  it('should be able to configure session pool size', function (done) {
   var neo4j = neo4jv1;
    // tag::configuration[]
    var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"), {connectionPoolSize: 50});
    //end::configuration[]

    var s = driver.session();
    s.run( "CREATE (p:Person { name: {name} })", {name: "The One"} )
      .then( function(result) {
        var theOnesCreated = result.summary.counters.nodesCreated();
        console.log(theOnesCreated);
        s.close();
        driver.close();
      })
      .then(function() {
        expect(out[0]).toBe(1);
        done();
    });
  });

  it('should document a statement', function(done) {
    var session = sessionGlobal;
    // tag::statement[]
    session
      .run( "CREATE (person:Person {name: {name}})", {name: "Arthur"} )
    // end::statement[]
      .then( function(result) {
        var theOnesCreated = result.summary.counters.nodesCreated();
        console.log("There were " + theOnesCreated + " the ones created.")
      })
      .then(function() {
        expect(out[0]).toBe("There were 1 the ones created.");
        done();
      });
  });

  it('should document a statement without parameters', function(done) {
    var session = sessionGlobal;
    // tag::statement-without-parameters[]
    session
      .run( "CREATE (p:Person { name: 'Arthur' })" )
    // end::statement-without-parameters[]
      .then( function(result) {
        var theOnesCreated = result.summary.counters.nodesCreated();
        console.log("There were " + theOnesCreated + " the ones created.");
      });

    // Then
    setTimeout(function() {
      expect(out[0]).toBe("There were 1 the ones created.");
      done();
    }, 1000)
  });

  it('should be able to iterate results', function(done) {
    var session = sessionGlobal;
    session
      .run( "CREATE (weapon:Weapon { name: 'Sword in the stone' })" )
      .then(function() {
    // tag::result-traversal[]
      var searchTerm = "Sword";
      session
        .run( "MATCH (weapon:Weapon) WHERE weapon.name CONTAINS {term} RETURN weapon.name", {term : searchTerm} )
        .subscribe({
          onNext: function(record) {
            console.log("" + record.get("weapon.name"));
          },
          onCompleted: function() {
            session.close();
          },
          onError: function(error) {
            console.log(error);
          }
        });
    // end::result-traversal[]
    });
    // Then
    setTimeout(function() {
      expect(out[0]).toBe("Sword in the stone");
      done();
    }, 1000);
  });

  it('should be able to access records', function(done) {
    var session = sessionGlobal;
    session
      .run( "CREATE (weapon:Weapon { name: 'Sword in the stone', owner: 'Arthur', material: 'Stone', size: 'Huge' })" )
      .then(function() {
      // tag::access-record[]
        var searchTerm = "Arthur";
        session
          .run( "MATCH (weapon:Weapon) WHERE weapon.owner CONTAINS {term} RETURN weapon.name, weapon.material, weapon.size", {term : searchTerm} )
          .subscribe({
            onNext: function(record) {
              var sword = [];
              record.forEach(function(value, key)
              {
                sword.push(key + ": " + value);
              });
              console.log(sword);
            },
            onCompleted: function() {
              session.close();
            },
            onError: function(error) {
              console.log(error);
            }
          });
      // end::access-record[]
      });

    // Then
    setTimeout(function() {
      expect(out[0].length).toBe(3);
      done();
    }, 1000)
  });

  it('should be able to retain for later processing', function(done) {
    var session = sessionGlobal;

    session
    .run("CREATE (knight:Person:Knight { name: 'Lancelot', castle: 'Camelot' })")
    .then(function() {
      // tag::retain-result[]
      session
        .run("MATCH (knight:Person:Knight) WHERE knight.castle = {castle} RETURN knight.name AS name", {castle: "Camelot"})
        .then(function (result) {
          var records = [];
          for (i = 0; i < result.records.length; i++) {
            records.push(result.records[i]);
          }
          return records;
        })
        .then(function (records) {
          for(i = 0; i < records.length; i ++)
          {
            console.log(records[i].get("name") + " is a knight of Camelot");
          }
        });
      // end::retain-result[]
    });

    //await the result
    setTimeout(function() {
      expect(out[0]).toBe("Lancelot is a knight of Camelot");
      done();
    }, 1000);
  });

  it('should be able to do nested queries', function(done) {
    var session = sessionGlobal;
    session
      .run( "CREATE (knight:Person:Knight { name: 'Lancelot', castle: 'Camelot' })" +
            "CREATE (king:Person { name: 'Arthur', title: 'King' })" )
      .then(function() {
        // tag::nested-statements[]
          session
            .run("MATCH (knight:Person:Knight) WHERE knight.castle = {castle} RETURN id(knight) AS knight_id", {"castle": "Camelot"})
            .subscribe({
              onNext: function(record) {
                session
                  .run("MATCH (knight) WHERE id(knight) = {id} MATCH (king:Person) WHERE king.name = {king} CREATE (knight)-[:DEFENDS]->(king)",
                  {"id": record.get("knight_id"), "king": "Arthur"});
              },
              onCompleted: function() {
                session
                  .run("MATCH (:Knight)-[:DEFENDS]->() RETURN count(*)")
                  .then(function (result) {
                    console.log("Count is " + result.records[0].get(0).toInt());
                  });
              },
              onError: function(error) {
                console.log(error);
              }
            });
        // end::nested-statements[]
        });

    //await the result
    setTimeout(function() {
      expect(out[0]).toBe("Count is 1");
      done();
    }, 1000);
  });

  it('should be able to handle cypher error', function(done) {
    var session = sessionGlobal;

    // tag::handle-cypher-error[]
    session
      .run("Then will cause a syntax error")
      .catch( function(err) {
        expect(err.fields[0].code).toBe( "Neo.ClientError.Statement.SyntaxError" );
        done();
      });
    // end::handle-cypher-error[]
  });

  it('should be able to profile', function(done) {
    var session = sessionGlobal;

    session.run("CREATE (:Person {name:'Arthur'})").then(function() {
      // tag::result-summary-query-profile[]
      session
        .run("PROFILE MATCH (p:Person {name: {name}}) RETURN id(p)", {name: "Arthur"})
        .then(function (result) {
          console.log(result.summary.profile);
        });
      // end::result-summary-query-profile[]
    });

    //await the result
    setTimeout(function() {
      expect(out.length).toBe(1);
      done();
    }, 1000);
  });

  it('should be able to see notifications', function(done) {
    var session = sessionGlobal;

    // tag::result-summary-notifications[]
    session
      .run("EXPLAIN MATCH (king), (queen) RETURN king, queen")
      .then(function (result) {
        var notifications = result.summary.notifications, i;
        for (i = 0; i < notifications.length; i++) {
          console.log(notifications[i].code);
        }
      });
    // end::result-summary-notifications[]

    setTimeout(function () {
      expect(out[0]).toBe("Neo.ClientNotification.Statement.CartesianProductWarning");
      done();
    }, 1000);
  });

  it('should document committing a transaction', function() {
    var session = sessionGlobal;

    // tag::transaction-commit[]
    var tx = session.beginTransaction();
    tx.run( "CREATE (:Person {name: 'Guinevere'})" );
    tx.commit();
    // end::transaction-commit[]
  });

  it('should document rolling back a transaction', function() {
    var session = sessionGlobal;

    // tag::transaction-rollback[]
    var tx = session.beginTransaction();
    tx.run( "CREATE (:Person {name: 'Merlin'})" );
    tx.rollback();
    // end::transaction-rollback[]
  });

  it('should document how to require encryption', function() {
    var session = sessionGlobal;

    var neo4j = neo4jv1;
    // tag::tls-require-encryption[]
    var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"), {
      // In NodeJS, encryption is on by default. In the web bundle, it is off.
      encrypted:true
    });
    // end::tls-require-encryption[]
    driver.close();
  });

  it('should document how to configure trust-on-first-use', function() {
    var neo4j = neo4jv1;
    // tag::tls-trust-on-first-use[]
    var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"), {
      // Note that trust-on-first-use is not available in the browser bundle,
      // in NodeJS, trust-on-first-use is the default trust mode. In the browser
      // it is TRUST_CUSTOM_CA_SIGNED_CERTIFICATES.
      trust: "TRUST_ON_FIRST_USE",
      encrypted:true
    });
    // end::tls-trust-on-first-use[]
    driver.close();
  });

  it('should document how to configure a trusted signing certificate', function() {
    var neo4j = neo4jv1;
    // tag::tls-signed[]
    var driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo4j"), {
      trust: "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES",
      // Configuring which certificates to trust here is only available
      // in NodeJS. In the browser bundle the browsers list of trusted
      // certificates is used, due to technical limitations in some browsers.
      trustedCertificates : ["path/to/ca.crt"],
      encrypted:true
    });
    // end::tls-signed[]
    driver.close();
  });

  it('should document how to disable auth', function() {
    var neo4j = neo4jv1;
    // tag::connect-with-auth-disabled[]
    var driver = neo4j.driver("bolt://localhost:7687", {
      // In NodeJS, encryption is on by default. In the web bundle, it is off.
      encrypted:true
    });
    // end::connect-with-auth-disabled[]
    driver.close();
  });

});
<|endoftext|>


<commit_before>var dbConfig = require('./../../config/db-config');

var knex = require('knex')(dbConfig.db[process.env.NODE_ENV]);

var bookshelf = require('bookshelf')(knex);

knex.schema.hasTable('users')
  .then( function (exists) {
    // body...
    if (!exists) {
      bookshelf.knex.schema.createTable('users', function(table) {
        table.increments('user_id').primary();
        table.string('first_name', 30).notNullable();
        table.string('last_name', 30).notNullable();
        table.string('email', 30).notNullable().unique();
        table.string('username', 30).notNullable().unique();
        table.string('password', 30).notNullable();
        table.boolean('admin').defaultTo(false);
        table.timestamp('joined_on');
        table.timestamp('last_update');
      })
      .then(function() {
        console.log('Table has been created');
      });
    }
  });

var user = bookshelf.Model.extend({
  tableName: 'users',
  idAttribute: 'user_id',
  defaults: {
    admin: false
  },
  hasTimestamps: ['joined_on', 'last_update']
});

var users = bookshelf.Collection.extend({
  model: user
})

module.exports = [user, users];<commit_msg>change column name<commit_after>var dbConfig = require('./../../config/db-config');

var knex = require('knex')(dbConfig.db[process.env.NODE_ENV]);

var bookshelf = require('bookshelf')(knex);

knex.schema.hasTable('users')
  .then( function (exists) {
    // body...
    if (!exists) {
      bookshelf.knex.schema.createTable('users', function(table) {
        table.increments('user_id').primary();
        table.string('first_name', 30).notNullable();
        table.string('last_name', 30).notNullable();
        table.string('email', 30).notNullable().unique();
        table.string('username', 30).notNullable().unique();
        table.string('password', 30).notNullable();
        table.boolean('admin').defaultTo(false);
        table.timestamp('joined_on');
        table.timestamp('last_updated');
      })
      .then(function() {
        console.log('Table has been created');
      });
    }
  });

var user = bookshelf.Model.extend({
  tableName: 'users',
  idAttribute: 'user_id',
  defaults: {
    admin: false
  },
  hasTimestamps: ['joined_on', 'last_updated']
});

var users = bookshelf.Collection.extend({
  model: user
})

module.exports = [user, users];<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var request = require('request');
// imports the hooks module _injected_ by dredd.
var hooks = require('hooks');
var url = require('url');

var BASE_URL;

// DELETE /todos
// after: check that there is no more completed todos.
hooks.after('Todos > Todos Collection > Archive completed Todos', function (t, done) {
	request.get(uri(t, '/todos'), function (err, res, body) {
		JSON.parse(body).forEach(function (todo) {
			console.assert(!todo.complete);
		});
		return done();
	});
});

// GET /todos/:id
// before: create a new todo.
hooks.before('Todos > Todo > Get a Todo', function (t, done) {
	request.post({
		uri: uri(t, '/todos'),
		json: {
			title: 'dredd'
		}
	}, function (err, res, todo) {
		t.fullPath = '/todos/' + todo.id;
		return done();
	});
});

// DELETE /todos/:id
// before: create a new todo.
// after: check that the todo is gone.
hooks.before('Todos > Todo > Delete a Todo', function (t, done) {
	request.post({
		uri: uri(t, '/todos'),
		json: {
			title: 'dredd'
		}
	}, function (err, res, todo) {
		t.fullPath = '/todos/' + todo.id;
		return done();
	});
});

hooks.after('Todos > Todo > Delete a Todo', function (t, done) {
	request.get(uri(t, t.fullPath), function (err, res) {
		console.assert(res.statusCode === 404);
		return done();
	});
});

// Remove all todos that were created by the tests.
hooks.afterAll(function (done) {
	request.get(uri('/todos'), function (err, res, todos) {
		if (!Array.isArray(todos)) {
			try {
				todos = JSON.parse(todos);
			} catch (e) {
				done(e);
			}
		}

		var todosToDelete = todos.filter(function (todo) {
			return todo.title === 'dredd';
		});

		async.parallel(todosToDelete.map(function (todo) {
			return function (next) {
				request.del(uri('/todos/' + todo.id), next);
			};
		}), done);
	});
});

function uri(t, path) {
	path = path || t;
	if (!BASE_URL) {
		BASE_URL = t;
	}
	return url.format({
		protocol: BASE_URL.protocol,
		hostname: BASE_URL.host,
		port: BASE_URL.port,
		pathname: path
	});
}
<commit_msg>Fixed the PUT test by extending hooks.js.<commit_after>'use strict';

var async = require('async');
var request = require('request');
// imports the hooks module _injected_ by dredd.
var hooks = require('hooks');
var url = require('url');

var BASE_URL;

// DELETE /todos
// after: check that there is no more completed todos.
hooks.after('Todos > Todos Collection > Archive completed Todos', function (t, done) {
	request.get(uri(t, '/todos'), function (err, res, body) {
		JSON.parse(body).forEach(function (todo) {
			console.assert(!todo.complete);
		});
		return done();
	});
});

// GET /todos/:id
// before: create a new todo.
hooks.before('Todos > Todo > Get a Todo', function (t, done) {
	request.post({
		uri: uri(t, '/todos'),
		json: {
			title: 'dredd'
		}
	}, function (err, res, todo) {
		t.fullPath = '/todos/' + todo.id;
		return done();
	});
});

// PUT /todos/:id
// before: create a new todo.
// after: check that the todo is marked complete.
hooks.before('Todos > Todo > Update a Todo', function (t, done) {
	request.post({
		uri: uri(t, '/todos'),
		json: {
			title: 'dredd',
            "completed": false
		}
	}, function (err, res, todo) {
		t.fullPath = '/todos/' + todo.id;
		return done();
	});
});

// DELETE /todos/:id
// before: create a new todo.
// after: check that the todo is gone.
hooks.before('Todos > Todo > Delete a Todo', function (t, done) {
	request.post({
		uri: uri(t, '/todos'),
		json: {
			title: 'dredd'
		}
	}, function (err, res, todo) {
		t.fullPath = '/todos/' + todo.id;
		return done();
	});
});

hooks.after('Todos > Todo > Delete a Todo', function (t, done) {
	request.get(uri(t, t.fullPath), function (err, res) {
		console.assert(res.statusCode === 404);
		return done();
	});
});

// Remove all todos that were created by the tests.
hooks.afterAll(function (done) {
	request.get(uri('/todos'), function (err, res, todos) {
		if (!Array.isArray(todos)) {
			try {
				todos = JSON.parse(todos);
			} catch (e) {
				done(e);
			}
		}

		var todosToDelete = todos.filter(function (todo) {
			return todo.title === 'dredd';
		});

		async.parallel(todosToDelete.map(function (todo) {
			return function (next) {
				request.del(uri('/todos/' + todo.id), next);
			};
		}), done);
	});
});

function uri(t, path) {
	path = path || t;
	if (!BASE_URL) {
		BASE_URL = t;
	}
	return url.format({
		protocol: BASE_URL.protocol,
		hostname: BASE_URL.host,
		port: BASE_URL.port,
		pathname: path
	});
}
<|endoftext|>


<commit_before>import fetchMock from 'fetch-mock'
import { expect } from 'chai'
import wfetch from '../src/wobbuffetch'

const data = { hello: 'world' }

    // fetchMock.get('*', data)
    // fetchMock.head('*', data)
    // fetchMock.delete('*', data)
    // fetchMock.post('*', data)
    // fetchMock.put('*', data)
    // fetchMock.patch('*', data)

describe('#wobbuffetch', () => {
  afterEach(() => {
    fetchMock.restore()
  })
  it('should be defined', () => {
    expect(wfetch).to.not.be.undefined
  })
  it('should be a function', () => {
    expect(wfetch).to.be.a('function')
  })
  it('should has "defaults" object', () => {
    expect(wfetch.defaults).to.be.an('object')
  })
  it('should has a GET method', () => {
    expect(wfetch.get).to.be.a('function')
  })
  it('should has a HEAD method', () => {
    expect(wfetch.head).to.be.a('function')
  })
  it('should has a DELETE method', () => {
    expect(wfetch.delete).to.be.a('function')
  })
  it('should has a POST method', () => {
    expect(wfetch.post).to.be.a('function')
  })
  it('should has a PUT method', () => {
    expect(wfetch.put).to.be.a('function')
  })
  it('should has a PATCH method', () => {
    expect(wfetch.patch).to.be.a('function')
  })
  describe('INSTANCE', () => {
    beforeEach(() => {
      fetchMock.get('*', data)
      fetchMock.post('*', data)
    })
    it('should call with the instance wobbuffetch', () => {
      expect(wfetch({ url: 'http://something' }).subscribe).to.be.an('function')
    })
    it('should call with the instance wobbuffetch other method', () => {
      expect(wfetch({ url: 'http://something', method: 'post' }).subscribe).to.be.an('function')
    })
  })
  describe('GET', () => {
    beforeEach(() => {
      fetchMock.get('*', data)
    })
    it('should call with config param', () => {
      wfetch.get('http://something', { params: data })
      expect(fetchMock.lastUrl()).to.be.equal('http://something?hello=world')
    })
    it('should GET return Observable', () => {
      expect(wfetch.get('http://something').subscribe).to.be.an('function')
    })
    it('should test GET response', (done) => {
      wfetch.get('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(res.data).to.deep.equal(data)
        done()
      })
    })
  })
  describe('HEAD', () => {
    beforeEach(() => {
      fetchMock.head('*', data)
    })
    it('should HEAD return Observable', () => {
      expect(wfetch.head('http://something').subscribe).to.be.an('function')
    })
    it('should HEAD return response without data', (done) => {
      wfetch.head('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(res.data).to.be.undefined
        done()
      })
    })
  })
  describe('DELETE', () => {
    beforeEach(() => {
      fetchMock.delete('*', data)
    })
    it('should DELETE return Observable', () => {
      expect(wfetch.delete('http://something').subscribe).to.be.an('function')
    })
    it('should DELETE return response', (done) => {
      wfetch.delete('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        done()
      })
    })
  })
  describe('POST', () => {
    beforeEach(() => {
      fetchMock.post('*', data)
    })
    it('should POST return Observable', () => {
      expect(wfetch.post('http://something').subscribe).to.be.an('function')
    })
    it('should POST return response', (done) => {
      wfetch.post('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        done()
      })
    })
    it('should POST data', (done) => {
      const body = { 'body': 'builder' }
      wfetch.post('http://something', { data: body }).subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(fetchMock.lastOptions().method).to.be.equals('post')
        expect(JSON.parse(fetchMock.lastOptions().body)).to.deep.equal(body)
        done()
      })
    })
  })
  describe('PUT', () => {
    beforeEach(() => {
      fetchMock.put('*', data)
    })
    it('should PUT return Observable', () => {
      expect(wfetch.put('http://something').subscribe).to.be.an('function')
    })
    it('should PUT return response', (done) => {
      wfetch.put('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        done()
      })
    })
    it('should PUT data', (done) => {
      const body = { 'body': 'builder' }
      wfetch.put('http://something', { data: body }).subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(fetchMock.lastOptions().method).to.be.equals('put')
        expect(JSON.parse(fetchMock.lastOptions().body)).to.deep.equal(body)
        done()
      })
    })
  })
  describe('PATCH', () => {
    beforeEach(() => {
      fetchMock.patch('*', data)
    })
    it('should PATCH return Observable', () => {
      expect(wfetch.patch('http://something').subscribe).to.be.an('function')
    })
    it('should PATCH return response', (done) => {
      wfetch.patch('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        done()
      })
    })
    it('should PATCH data', (done) => {
      const body = { 'body': 'builder' }
      wfetch.patch('http://something', { data: body }).subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(fetchMock.lastOptions().method).to.be.equals('patch')
        expect(JSON.parse(fetchMock.lastOptions().body)).to.deep.equal(body)
        done()
      })
    })
  })
  describe('Error treatment', () => {
    beforeEach(() => {
      fetchMock.get('http://something', 200).catch(503)
    })
    it('should throw Object error', () => {
      expect(() => { wfetch() }).to.throw('wobbuffetch config is not present or is not an object')
    })
    it('should throw URL error', () => {
      expect(() => { wfetch({}) }).to.throw('wobbuffetch: URL is required')
    })
    it('should throw method error', () => {
      expect(() => { wfetch({ url: 'http://something', method: 'options' }) }).to.throw('wobbuffetch: : this \'options\' method does not supported')
    })
    it('should catch status', (done) => {
      wfetch({ url: 'http://nothing' }).subscribe(res => {}, err => {
        expect(err).to.be.instanceOf(Error)
        expect(err.response).to.be.instanceOf(Response)
        expect(err.response.status).to.be.equals(503)
        done()
      })
    })
  })
})
<commit_msg>remove comments<commit_after>import fetchMock from 'fetch-mock'
import { expect } from 'chai'
import wfetch from '../src/wobbuffetch'

const data = { hello: 'world' }

describe('#wobbuffetch', () => {
  afterEach(() => {
    fetchMock.restore()
  })
  it('should be defined', () => {
    expect(wfetch).to.not.be.undefined
  })
  it('should be a function', () => {
    expect(wfetch).to.be.a('function')
  })
  it('should has "defaults" object', () => {
    expect(wfetch.defaults).to.be.an('object')
  })
  it('should has a GET method', () => {
    expect(wfetch.get).to.be.a('function')
  })
  it('should has a HEAD method', () => {
    expect(wfetch.head).to.be.a('function')
  })
  it('should has a DELETE method', () => {
    expect(wfetch.delete).to.be.a('function')
  })
  it('should has a POST method', () => {
    expect(wfetch.post).to.be.a('function')
  })
  it('should has a PUT method', () => {
    expect(wfetch.put).to.be.a('function')
  })
  it('should has a PATCH method', () => {
    expect(wfetch.patch).to.be.a('function')
  })
  describe('INSTANCE', () => {
    beforeEach(() => {
      fetchMock.get('*', data)
      fetchMock.post('*', data)
    })
    it('should call with the instance wobbuffetch', () => {
      expect(wfetch({ url: 'http://something' }).subscribe).to.be.an('function')
    })
    it('should call with the instance wobbuffetch other method', () => {
      expect(wfetch({ url: 'http://something', method: 'post' }).subscribe).to.be.an('function')
    })
  })
  describe('GET', () => {
    beforeEach(() => {
      fetchMock.get('*', data)
    })
    it('should call with config param', () => {
      wfetch.get('http://something', { params: data })
      expect(fetchMock.lastUrl()).to.be.equal('http://something?hello=world')
    })
    it('should GET return Observable', () => {
      expect(wfetch.get('http://something').subscribe).to.be.an('function')
    })
    it('should test GET response', (done) => {
      wfetch.get('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(res.data).to.deep.equal(data)
        done()
      })
    })
  })
  describe('HEAD', () => {
    beforeEach(() => {
      fetchMock.head('*', data)
    })
    it('should HEAD return Observable', () => {
      expect(wfetch.head('http://something').subscribe).to.be.an('function')
    })
    it('should HEAD return response without data', (done) => {
      wfetch.head('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(res.data).to.be.undefined
        done()
      })
    })
  })
  describe('DELETE', () => {
    beforeEach(() => {
      fetchMock.delete('*', data)
    })
    it('should DELETE return Observable', () => {
      expect(wfetch.delete('http://something').subscribe).to.be.an('function')
    })
    it('should DELETE return response', (done) => {
      wfetch.delete('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        done()
      })
    })
  })
  describe('POST', () => {
    beforeEach(() => {
      fetchMock.post('*', data)
    })
    it('should POST return Observable', () => {
      expect(wfetch.post('http://something').subscribe).to.be.an('function')
    })
    it('should POST return response', (done) => {
      wfetch.post('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        done()
      })
    })
    it('should POST data', (done) => {
      const body = { 'body': 'builder' }
      wfetch.post('http://something', { data: body }).subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(fetchMock.lastOptions().method).to.be.equals('post')
        expect(JSON.parse(fetchMock.lastOptions().body)).to.deep.equal(body)
        done()
      })
    })
  })
  describe('PUT', () => {
    beforeEach(() => {
      fetchMock.put('*', data)
    })
    it('should PUT return Observable', () => {
      expect(wfetch.put('http://something').subscribe).to.be.an('function')
    })
    it('should PUT return response', (done) => {
      wfetch.put('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        done()
      })
    })
    it('should PUT data', (done) => {
      const body = { 'body': 'builder' }
      wfetch.put('http://something', { data: body }).subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(fetchMock.lastOptions().method).to.be.equals('put')
        expect(JSON.parse(fetchMock.lastOptions().body)).to.deep.equal(body)
        done()
      })
    })
  })
  describe('PATCH', () => {
    beforeEach(() => {
      fetchMock.patch('*', data)
    })
    it('should PATCH return Observable', () => {
      expect(wfetch.patch('http://something').subscribe).to.be.an('function')
    })
    it('should PATCH return response', (done) => {
      wfetch.patch('http://something').subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        done()
      })
    })
    it('should PATCH data', (done) => {
      const body = { 'body': 'builder' }
      wfetch.patch('http://something', { data: body }).subscribe(res => {
        expect(res.status).to.be.equal(200)
        expect(res.statusText).to.be.equal('OK')
        expect(res.headers).to.be.instanceof(Headers)
        expect(fetchMock.lastOptions().method).to.be.equals('patch')
        expect(JSON.parse(fetchMock.lastOptions().body)).to.deep.equal(body)
        done()
      })
    })
  })
  describe('Error treatment', () => {
    beforeEach(() => {
      fetchMock.get('http://something', 200).catch(503)
    })
    it('should throw Object error', () => {
      expect(() => { wfetch() }).to.throw('wobbuffetch config is not present or is not an object')
    })
    it('should throw URL error', () => {
      expect(() => { wfetch({}) }).to.throw('wobbuffetch: URL is required')
    })
    it('should throw method error', () => {
      expect(() => { wfetch({ url: 'http://something', method: 'options' }) }).to.throw('wobbuffetch: : this \'options\' method does not supported')
    })
    it('should catch status', (done) => {
      wfetch({ url: 'http://nothing' }).subscribe(res => {}, err => {
        expect(err).to.be.instanceOf(Error)
        expect(err.response).to.be.instanceOf(Response)
        expect(err.response.status).to.be.equals(503)
        done()
      })
    })
  })
})
<|endoftext|>


<commit_before>
// Reference to the root of the Firebase database
var database = new Firebase("https://conquiz.firebaseio.com/");
var gamebase = new Firebase("https://towercoord.firebaseio.com/");
var coordbase = gamebase.child("-K2aUIZRYFI5l6Tov1JA");
var towerbase = coordbase.child("towers");
var playerbase = coordbase.child("players");
var troopbase = coordbase.child("troops");
// Reference to the google sheets of questions
var questionsLink = 'https://spreadsheets.google.com/feeds/list/1C1POJrIlpm1R3muE0ImmI_ifxpH_aEfPP-QSyl3o2Kg/1/public/basic?alt=json';

var question;
var questionJSON;
var rows;

/*--------------------------------------------*/
/*---> Get Game -> Whole game dir <-----------*/
/*--------------------------------------------*/
function getGame() {
	//var gameHolder = []; // for futre updates with multi-lobby
	var newGame;
	coordbase.on('child_added', function(update){
		var gameJSON = update.val();
		newGame = new Game({
			id: gameJSON['id'],
			moode: gameJSON['mode'],
			name: gameJSON['name'],
			players: loadPlayers(),
			questions: loadQuestions(),
			questionLength: gameJSON['questionLength'],
			rounds: gameJSON['spawnRate'],
			spawnRate: gameJSON['spawnRate'],
			//taskManager: JSON.parse(gameJSON['taskManager']),
			towers: loadTowers(),
			troops: loadTroops()
		});
	});
	return newGame;
}

/*--------------------------------------------*/
/*---> Download Task from Firebase <----------*/
/*--------------------------------------------*/
function loadTasks() {

}

/*--------------------------------------------*/
/*---> Download troops from Firebase <--------*/
/*--------------------------------------------*/
function loadTroops() {
	var troopHolder = [];
	var newTroop;
	troopbase.on('child_added', function(update){
		if (update['Empty'] != "DoNotDelete") { //Stops the empty from being pulled
			var troopJSON = update.val();
			newTroop = new Troop({
				id: update['id'],
				name: update['name'],
				playerID: update['playerID'],
				towerID: update['towerID'],
				question: update['question'],
				alive: update['alive']
			});
			troopHolder.push(newTroop);
		}

	});
	return troopHolder;
}

/*--------------------------------------------*/
/*---> Upload troops to Firebase <------------*/
/*--------------------------------------------*/
function uploadTroops(data) {
	$.each(data, function(index, value){
		troopbase.push({
			id: value['id'],
			name: value['name'],
			playerID: value['playerID'],
			towerID: value['towerID'],
			question: value['question'],
			alive: value['alive']
		});
	});
	setDefaultTroops();
}
function setDefaultTroops(){
		towerbase.once('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			var child = childSnapshot.val();
			var path = new Firebase(towerbase.child(childSnapshot.key()).toString());
			path.set({
				id: childSnapshot.key(),
				name: child['name'],
				playerID: child['playerID'],
				towerID: child['towerID'],
				question: child['question'],
				alive: child['child']
			});
		});
	});
}
function updateTroops(data) {
	$.each(data, function(index, value){
		var path = new Firebase(troopbase.child(value['id']).toString());
		path.set({
			id: value['id'],
			name: value['name'],
			playerID: value['playerID'],
			towerID: value['towerID'],
			question: value['question'],
			alive: value['alive']
		});
	});
}
// This will remove all the troops in the troops folder
function removeTroops(data) {
	$.each(data, function(index, value){

	});
	troopbase.once('value', function(snapshot) {
		snapshot.forEach(function(childSnapshot){
			// You can also get the key and the value of the child in the troopbase folder
			//var key = childSnapshot.key();
			//var childData = childSnapshot.val();
			if (childSnapshot.val()!="DoNotDelete") {
				var path = new Firebase(troopbase.child(childSnapshot.key()).toString());
				path.remove();
			}
		});
	});
}

/*--------------------------------------------*/
/*---> Download player from Firebase <--------*/
/*--------------------------------------------*/
function loadPlayers() {
	var playerHolder = [];
	var newPlayer;
	playerbase.on('child_added', function(update) {
		var playerJSON = update.val();
		newPlayer = new Player({
			id: playerJSON['id'],
			icon: playerJSON['team']['icon'],
			color: playerJSON['team']['color'],
			coordinate: { latitude: playerJSON['latitude'], longitude: playerJSON['longitude']},
			troops: JSON.stringify(playerJSON['troops'])
		});
		playerHolder.push(newPlayer);
	});
	return playerHolder;
}

/*--------------------------------------------*/
/*---> Upload player to Firebase <------------*/
/*--------------------------------------------*/
function uploadPlayerbase(data) {
	$.each(data, function(index, value){
		playerbase.push({
			id: value['id'],
			name: value['name'],
			team: {icon: value['icon'], color: value['color']},
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			troops: JSON.Stringify(value['troops'])
		});
	});
}

/*--------------------------------------------*/
/*---> Download towers from Firebase <--------*/
/*--------------------------------------------*/
function loadTowers() {
	var towerHolder = [];
	var newTower;
	towerbase.on('child_added', function(update) {
		var towerJSON = update.val();
		//console.log(towerJSON);
		newTower = new Tower({
			id: towerJSON['id'],
			name: towerJSON['name'],
			coordinate: {latitude: towerJSON['latitude'], longitude: towerJSON['longitude']},
			size: towerJSON['size'],
			player: JSON.stringify(towerJSON['player']),
			troops: "[]"
		});
		towerHolder.push(newTower);
	});
	return towerHolder;
}

/*--------------------------------------------*/
/*---> Upload towers to Firebase <------------*/
/*--------------------------------------------*/
function uploadTowerbase(data) {
	$.each(data, function(index, value){
		towerbase.push({id: value['id'],
			name: value['name'],
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			size: value['size'],
			player: value['player'] });
	});
	setDefaultTower();
}
function setDefaultTower(){
	towerbase.once('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			var path = new Firebase(towerbase.child(childSnapshot.key()).toString());
			path.set({
				id: childSnapshot.key(),
				name: "",
				latitude: 0,
				longitude: 0,
				size: 10,
				player: ""
			});
		});
	});
}

function updateTowerbase(data) {
	$.each(data, function(index, value){
		var path = new Firebase(towerbase.child(value['id']).toString());
		path.set({
			id: value['id'],
			name: value['name'],
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			size: value['size'],
			player: value['player']
		});
	});
}
// Don't have time - going for hard code
function removeTowerbase() {
	// ToDO: Remove the towers folders which will remove the subfolders, recreate a towers folder.
}

/*--------------------------------------------*/
/*---> Download question from Firebase <------*/
/*--------------------------------------------*/
function loadQuestions() {
	var questionHolder = [];
    var newQuestion;
    database.on('child_added', function(update) {
        var questionJSON = update.val();
        newQuestion = new Question({
            id: generateNewID('questions'),
            question: questionJSON['question'],
            answers: "["+questionJSON['correct']+", "+questionJSON['wa1']+", "+questionJSON['wa2']+", "+questionJSON['wa3']+"]"
        });
        questionHolder.push(newQuestion);
    });
    return questionHolder;
}

/*--------------------------------------------*/
/*---> Upload question to Firebase <----------*/
// ONE TIME push to update the questions on firebase
/*--------------------------------------------*/
function getData() {
    $.ajax({
        url: questionsLink,
        success: function(data){
            uploadFirebase(data);
        }
    });
}
// upload data to firebase
function uploadFirebase(data){
    var cells = data.feed.entry;
    rows = [];

    for (var i = 0; i < cells.length; i++){
        var rowObj = {};
        rowObj.timestamp = cells[i].title.$t;
        var rowCols = cells[i].content.$t.split(',');
        for (var j = 0; j < rowCols.length; j++){
            var keyVal = rowCols[j].split(':');
            rowObj[keyVal[0].trim()] = keyVal[1].trim();
        }
        rows.push(rowObj);
    }
    for (var i = 0; i < rows.length; i++) {
    	database.push({question: rows[i]['timestamp'], correct: rows[i]['correct'], wa1: rows[i]['wa1'], wa2: rows[i]['wa2'], wa3: rows[i]['wa3']});
    }
}

console.log('LOADED BACKEND');

/* Legacy code

$("#upload").click(function() { // If the user clicks on the input with the id="upload"
	var name = $("#nameInput").val();
	var text = $("#messageInput").val();
	if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
		console.log(name.length);
		console.log(text.length);

		database.push({name: name, text: text}); // Push the data onto the database

	}else { // warns user of their empty textbox
		console.log("Please input values into the textbox");
	}
});

function displayUpdate(name, text) {
	$("<div/>").text(text).prepend($("<em/>").text(name+": ")).appendTo($("#messageDiv"));
	$("#messageDiv")[0].scrollTop = $("#messageDiv")[0].scrollHeight;
};

database.on("child_added", function(update) { // Get an update once the database has new data
	console.log("Callback function: New data has been added to the database");
	var message = update.val();
	displayUpdate(message.name, message.text);
});

*/
<commit_msg>Console log<commit_after>
// Reference to the root of the Firebase database
var database = new Firebase("https://conquiz.firebaseio.com/");
var gamebase = new Firebase("https://towercoord.firebaseio.com/");
var coordbase = gamebase.child("-K2aUIZRYFI5l6Tov1JA");
var towerbase = coordbase.child("towers");
var playerbase = coordbase.child("players");
var troopbase = coordbase.child("troops");
// Reference to the google sheets of questions
var questionsLink = 'https://spreadsheets.google.com/feeds/list/1C1POJrIlpm1R3muE0ImmI_ifxpH_aEfPP-QSyl3o2Kg/1/public/basic?alt=json';

var question;
var questionJSON;
var rows;

/*--------------------------------------------*/
/*---> Get Game -> Whole game dir <-----------*/
/*--------------------------------------------*/
function getGame() {
	//var gameHolder = []; // for futre updates with multi-lobby
	var newGame;
	coordbase.on('child_added', function(update){
		var gameJSON = update.val();
		newGame = new Game({
			id: gameJSON['id'],
			moode: gameJSON['mode'],
			name: gameJSON['name'],
			players: loadPlayers(),
			questions: loadQuestions(),
			questionLength: gameJSON['questionLength'],
			rounds: gameJSON['spawnRate'],
			spawnRate: gameJSON['spawnRate'],
			//taskManager: JSON.parse(gameJSON['taskManager']),
			towers: loadTowers(),
			troops: loadTroops()
		});
	});
	console.log(newGame)
	return newGame;
}

/*--------------------------------------------*/
/*---> Download Task from Firebase <----------*/
/*--------------------------------------------*/
function loadTasks() {

}

/*--------------------------------------------*/
/*---> Download troops from Firebase <--------*/
/*--------------------------------------------*/
function loadTroops() {
	var troopHolder = [];
	var newTroop;
	troopbase.on('child_added', function(update){
		if (update['Empty'] != "DoNotDelete") { //Stops the empty from being pulled
			var troopJSON = update.val();
			newTroop = new Troop({
				id: update['id'],
				name: update['name'],
				playerID: update['playerID'],
				towerID: update['towerID'],
				question: update['question'],
				alive: update['alive']
			});
			troopHolder.push(newTroop);
		}

	});
	return troopHolder;
}

/*--------------------------------------------*/
/*---> Upload troops to Firebase <------------*/
/*--------------------------------------------*/
function uploadTroops(data) {
	$.each(data, function(index, value){
		troopbase.push({
			id: value['id'],
			name: value['name'],
			playerID: value['playerID'],
			towerID: value['towerID'],
			question: value['question'],
			alive: value['alive']
		});
	});
	setDefaultTroops();
}
function setDefaultTroops(){
		towerbase.once('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			var child = childSnapshot.val();
			var path = new Firebase(towerbase.child(childSnapshot.key()).toString());
			path.set({
				id: childSnapshot.key(),
				name: child['name'],
				playerID: child['playerID'],
				towerID: child['towerID'],
				question: child['question'],
				alive: child['child']
			});
		});
	});
}
function updateTroops(data) {
	$.each(data, function(index, value){
		var path = new Firebase(troopbase.child(value['id']).toString());
		path.set({
			id: value['id'],
			name: value['name'],
			playerID: value['playerID'],
			towerID: value['towerID'],
			question: value['question'],
			alive: value['alive']
		});
	});
}
// This will remove all the troops in the troops folder
function removeTroops(data) {
	$.each(data, function(index, value){

	});
	troopbase.once('value', function(snapshot) {
		snapshot.forEach(function(childSnapshot){
			// You can also get the key and the value of the child in the troopbase folder
			//var key = childSnapshot.key();
			//var childData = childSnapshot.val();
			if (childSnapshot.val()!="DoNotDelete") {
				var path = new Firebase(troopbase.child(childSnapshot.key()).toString());
				path.remove();
			}
		});
	});
}

/*--------------------------------------------*/
/*---> Download player from Firebase <--------*/
/*--------------------------------------------*/
function loadPlayers() {
	var playerHolder = [];
	var newPlayer;
	playerbase.on('child_added', function(update) {
		var playerJSON = update.val();
		newPlayer = new Player({
			id: playerJSON['id'],
			icon: playerJSON['team']['icon'],
			color: playerJSON['team']['color'],
			coordinate: { latitude: playerJSON['latitude'], longitude: playerJSON['longitude']},
			troops: JSON.stringify(playerJSON['troops'])
		});
		playerHolder.push(newPlayer);
	});
	return playerHolder;
}

/*--------------------------------------------*/
/*---> Upload player to Firebase <------------*/
/*--------------------------------------------*/
function uploadPlayerbase(data) {
	$.each(data, function(index, value){
		playerbase.push({
			id: value['id'],
			name: value['name'],
			team: {icon: value['icon'], color: value['color']},
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			troops: JSON.Stringify(value['troops'])
		});
	});
}

/*--------------------------------------------*/
/*---> Download towers from Firebase <--------*/
/*--------------------------------------------*/
function loadTowers() {
	var towerHolder = [];
	var newTower;
	towerbase.on('child_added', function(update) {
		var towerJSON = update.val();
		//console.log(towerJSON);
		newTower = new Tower({
			id: towerJSON['id'],
			name: towerJSON['name'],
			coordinate: {latitude: towerJSON['latitude'], longitude: towerJSON['longitude']},
			size: towerJSON['size'],
			player: JSON.stringify(towerJSON['player']),
			troops: "[]"
		});
		towerHolder.push(newTower);
	});
	return towerHolder;
}

/*--------------------------------------------*/
/*---> Upload towers to Firebase <------------*/
/*--------------------------------------------*/
function uploadTowerbase(data) {
	$.each(data, function(index, value){
		towerbase.push({id: value['id'],
			name: value['name'],
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			size: value['size'],
			player: value['player'] });
	});
	setDefaultTower();
}
function setDefaultTower(){
	towerbase.once('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			var path = new Firebase(towerbase.child(childSnapshot.key()).toString());
			path.set({
				id: childSnapshot.key(),
				name: "",
				latitude: 0,
				longitude: 0,
				size: 10,
				player: ""
			});
		});
	});
}

function updateTowerbase(data) {
	$.each(data, function(index, value){
		var path = new Firebase(towerbase.child(value['id']).toString());
		path.set({
			id: value['id'],
			name: value['name'],
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			size: value['size'],
			player: value['player']
		});
	});
}
// Don't have time - going for hard code
function removeTowerbase() {
	// ToDO: Remove the towers folders which will remove the subfolders, recreate a towers folder.
}

/*--------------------------------------------*/
/*---> Download question from Firebase <------*/
/*--------------------------------------------*/
function loadQuestions() {
	var questionHolder = [];
    var newQuestion;
    database.on('child_added', function(update) {
        var questionJSON = update.val();
        newQuestion = new Question({
            id: generateNewID('questions'),
            question: questionJSON['question'],
            answers: "["+questionJSON['correct']+", "+questionJSON['wa1']+", "+questionJSON['wa2']+", "+questionJSON['wa3']+"]"
        });
        questionHolder.push(newQuestion);
    });
    return questionHolder;
}

/*--------------------------------------------*/
/*---> Upload question to Firebase <----------*/
// ONE TIME push to update the questions on firebase
/*--------------------------------------------*/
function getData() {
    $.ajax({
        url: questionsLink,
        success: function(data){
            uploadFirebase(data);
        }
    });
}
// upload data to firebase
function uploadFirebase(data){
    var cells = data.feed.entry;
    rows = [];

    for (var i = 0; i < cells.length; i++){
        var rowObj = {};
        rowObj.timestamp = cells[i].title.$t;
        var rowCols = cells[i].content.$t.split(',');
        for (var j = 0; j < rowCols.length; j++){
            var keyVal = rowCols[j].split(':');
            rowObj[keyVal[0].trim()] = keyVal[1].trim();
        }
        rows.push(rowObj);
    }
    for (var i = 0; i < rows.length; i++) {
    	database.push({question: rows[i]['timestamp'], correct: rows[i]['correct'], wa1: rows[i]['wa1'], wa2: rows[i]['wa2'], wa3: rows[i]['wa3']});
    }
}

console.log('LOADED BACKEND');

/* Legacy code

$("#upload").click(function() { // If the user clicks on the input with the id="upload"
	var name = $("#nameInput").val();
	var text = $("#messageInput").val();
	if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
		console.log(name.length);
		console.log(text.length);

		database.push({name: name, text: text}); // Push the data onto the database

	}else { // warns user of their empty textbox
		console.log("Please input values into the textbox");
	}
});

function displayUpdate(name, text) {
	$("<div/>").text(text).prepend($("<em/>").text(name+": ")).appendTo($("#messageDiv"));
	$("#messageDiv")[0].scrollTop = $("#messageDiv")[0].scrollHeight;
};

database.on("child_added", function(update) { // Get an update once the database has new data
	console.log("Callback function: New data has been added to the database");
	var message = update.val();
	displayUpdate(message.name, message.text);
});

*/
<|endoftext|>


<commit_before>// takes an IR function object and returns a list of Scratch blocks

module.exports.ffi = {};

module.exports.generateFunctionHat = function(func) {
	var spec = func.funcName;
	var inputs = [];
	var defaults = [];

	for(var i = 0; i < func.paramList.length; ++i) {
		if(func.paramList[i][1])
			inputs.push(func.paramList[i][1]);
		else
			inputs.push("param"+i);

		defaults.push(defaultForType(func.paramList[i][0]));
		spec += " "+specifierForType(func.paramList[i][0]);
	}

	return ["procDef", spec, inputs, defaults, false];

}

module.exports.compileFunction = function(func) {
	console.log("Compiling "+JSON.stringify(func)+"...");

	var blockList = [module.exports.generateFunctionHat(func)];

	for(var i = 0; i < func.code.length; ++i) {
		console.log(func.code[i]);
		if(func.code[i].type == "call") {
			// calling a (potentially foreign) function
			// stub

			console.log(func.code[i]);

			var spec = func.code[i].funcName;
			var args = [];

			for(var a = 0; a < func.code[i].paramList.length; ++a) {
				args.push(formatValue(func.code[i].paramList[a][0], func.code[i].paramList[a][1]));
				spec += " "+specifierForType(func.code[i].paramList[a][0]);
			}

			blockList.push(
				[
					"call",
					spec
				].concat(args)
			)
		} else if(func.code[i].type == "ffi") {
			// FFI block
			// load the code from the options
			blockList = blockList.concat(module.exports.ffi[func.code[i].ffiBlock]);
		}
	}

	return blockList;
}

// fixme: stub
function defaultForType(type) {
	console.log(type);
	return 0;
}

// fixme: stub
function specifierForType(type) {
	return "%s";
}

// fixme: stub
function formatValue(type, value) {
	return value;
}

// higher-level code generation
function allocateLocal(val) {
	return [
		["setLine:ofList:to:", "last", "# of locals", ["+", ["getLine:ofList:", "last", "# of locals"], 1]],
		["append:toList:", val, "Stack"]]],
	];
}

function freeLocals() {
	return [
		["doRepeat", ["getLine:ofList:", "last", "# of locals"], [["deleteLine:ofList:", "last", "Stack"]]],
		["deleteLine:ofList:", "last", "# of locals"]
	];
}

function return(val) {
	var proc = freeLocals();

	if(val) {
		proc.push(["setVar:to:", "return value", val]);
	}

	proc.push(["stopScripts", "this script"]);

	return proc;
}<commit_msg>Iniitalize locals code<commit_after>// takes an IR function object and returns a list of Scratch blocks

module.exports.ffi = {};

module.exports.generateFunctionHat = function(func) {
	var spec = func.funcName;
	var inputs = [];
	var defaults = [];

	for(var i = 0; i < func.paramList.length; ++i) {
		if(func.paramList[i][1])
			inputs.push(func.paramList[i][1]);
		else
			inputs.push("param"+i);

		defaults.push(defaultForType(func.paramList[i][0]));
		spec += " "+specifierForType(func.paramList[i][0]);
	}

	return ["procDef", spec, inputs, defaults, false];

}

module.exports.compileFunction = function(func) {
	console.log("Compiling "+JSON.stringify(func)+"...");

	var blockList = [module.exports.generateFunctionHat(func)];

	for(var i = 0; i < func.code.length; ++i) {
		console.log(func.code[i]);
		if(func.code[i].type == "call") {
			// calling a (potentially foreign) function
			// stub

			console.log(func.code[i]);

			var spec = func.code[i].funcName;
			var args = [];

			for(var a = 0; a < func.code[i].paramList.length; ++a) {
				args.push(formatValue(func.code[i].paramList[a][0], func.code[i].paramList[a][1]));
				spec += " "+specifierForType(func.code[i].paramList[a][0]);
			}

			blockList.push(
				[
					"call",
					spec
				].concat(args)
			)
		} else if(func.code[i].type == "ffi") {
			// FFI block
			// load the code from the options
			blockList = blockList.concat(module.exports.ffi[func.code[i].ffiBlock]);
		}
	}

	return blockList;
}

// fixme: stub
function defaultForType(type) {
	console.log(type);
	return 0;
}

// fixme: stub
function specifierForType(type) {
	return "%s";
}

// fixme: stub
function formatValue(type, value) {
	return value;
}

// higher-level code generation
function initLocal() {
	return [
		["append:toList:", "0", "# of locals"]
	]
}

function allocateLocal(val) {
	return [
		["setLine:ofList:to:", "last", "# of locals", ["+", ["getLine:ofList:", "last", "# of locals"], 1]],
		["append:toList:", val, "Stack"]]],
	];
}

function freeLocals() {
	return [
		["doRepeat", ["getLine:ofList:", "last", "# of locals"], [["deleteLine:ofList:", "last", "Stack"]]],
		["deleteLine:ofList:", "last", "# of locals"]
	];
}

function return(val) {
	var proc = freeLocals();

	if(val) {
		proc.push(["setVar:to:", "return value", val]);
	}

	proc.push(["stopScripts", "this script"]);

	return proc;
}<|endoftext|>


<commit_before>import zeroFill from '../utils/zero-fill';
import { createDuration } from '../duration/create';
import { addSubtract } from '../moment/add-subtract';
import { isMoment, copyConfig } from '../moment/constructor';
import { addFormatToken } from '../format/format';
import { addRegexToken, matchOffset, matchShortOffset } from '../parse/regex';
import { addParseToken } from '../parse/token';
import { createLocal } from '../create/local';
import { prepareConfig } from '../create/from-anything';
import { createUTC } from '../create/utc';
import isDate from '../utils/is-date';
import toInt from '../utils/to-int';
import isUndefined from '../utils/is-undefined';
import compareArrays from '../utils/compare-arrays';
import { hooks } from '../utils/hooks';

// FORMATTING

function offset (token, separator) {
    addFormatToken(token, 0, 0, function () {
        var offset = this.utcOffset();
        var sign = '+';
        if (offset < 0) {
            offset = -offset;
            sign = '-';
        }
        return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
    });
}

offset('Z', ':');
offset('ZZ', '');

// PARSING

addRegexToken('Z',  matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
    config._useUTC = true;
    config._tzm = offsetFromString(matchShortOffset, input);
});

// HELPERS

// timezone chunker
// '+10:00' > ['10',  '00']
// '-1530'  > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;

function offsetFromString(matcher, string) {
    var matches = (string || '').match(matcher);

    if (matches === null) {
        return null;
    }

    var chunk   = matches[matches.length - 1] || [];
    var parts   = (chunk + '').match(chunkOffset) || ['-', 0, 0];
    var minutes = +(parts[1] * 60) + toInt(parts[2]);

    return minutes === 0 ?
      0 :
      parts[0] === '+' ? minutes : -minutes;
}

// Return a moment from input, that is local/utc/zone equivalent to model.
export function cloneWithOffset(input, model) {
    var res, diff;
    if (model._isUTC) {
        res = model.clone();
        diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
        // Use low-level api, because this fn is low-level api.
        res._d.setTime(res._d.valueOf() + diff);
        hooks.updateOffset(res, false);
        return res;
    } else {
        return createLocal(input).local();
    }
}

function getDateOffset (m) {
    // On Firefox.24 Date#getTimezoneOffset returns a floating point.
    // https://github.com/moment/moment/pull/1871
    return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
}

// HOOKS

// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};

// MOMENTS

// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
export function getSetOffset (input, keepLocalTime, keepMinutes) {
    var offset = this._offset || 0,
        localAdjust;
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }
    if (input != null) {
        if (typeof input === 'string') {
            input = offsetFromString(matchShortOffset, input);
            if (input === null) {
                return this;
            }
        } else if (Math.abs(input) < 16 && !keepMinutes) {
            input = input * 60;
        }
        if (!this._isUTC && keepLocalTime) {
            localAdjust = getDateOffset(this);
        }
        this._offset = input;
        this._isUTC = true;
        if (localAdjust != null) {
            this.add(localAdjust, 'm');
        }
        if (offset !== input) {
            if (!keepLocalTime || this._changeInProgress) {
                addSubtract(this, createDuration(input - offset, 'm'), 1, false);
            } else if (!this._changeInProgress) {
                this._changeInProgress = true;
                hooks.updateOffset(this, true);
                this._changeInProgress = null;
            }
        }
        return this;
    } else {
        return this._isUTC ? offset : getDateOffset(this);
    }
}

export function getSetZone (input, keepLocalTime) {
    if (input != null) {
        if (typeof input !== 'string') {
            input = -input;
        }

        this.utcOffset(input, keepLocalTime);

        return this;
    } else {
        return -this.utcOffset();
    }
}

export function setOffsetToUTC (keepLocalTime) {
    return this.utcOffset(0, keepLocalTime);
}

export function setOffsetToLocal (keepLocalTime) {
    if (this._isUTC) {
        this.utcOffset(0, keepLocalTime);
        this._isUTC = false;

        if (keepLocalTime) {
            this.subtract(getDateOffset(this), 'm');
        }
    }
    return this;
}

export function setOffsetToParsedOffset () {
    if (this._tzm != null) {
        this.utcOffset(this._tzm, false, true);
    } else if (typeof this._i === 'string') {
        var tZone = offsetFromString(matchOffset, this._i);
        if (tZone != null) {
            this.utcOffset(tZone);
        }
        else {
            this.utcOffset(0, true);
        }
    }
    return this;
}

export function hasAlignedHourOffset (input) {
    if (!this.isValid()) {
        return false;
    }
    input = input ? createLocal(input).utcOffset() : 0;

    return (this.utcOffset() - input) % 60 === 0;
}

export function isDaylightSavingTime () {
    return (
        this.utcOffset() > this.clone().month(0).utcOffset() ||
        this.utcOffset() > this.clone().month(5).utcOffset()
    );
}

export function isDaylightSavingTimeShifted () {
    if (!isUndefined(this._isDSTShifted)) {
        return this._isDSTShifted;
    }

    var c = {};

    copyConfig(c, this);
    c = prepareConfig(c);

    if (c._a) {
        var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
        this._isDSTShifted = this.isValid() &&
            compareArrays(c._a, other.toArray()) > 0;
    } else {
        this._isDSTShifted = false;
    }

    return this._isDSTShifted;
}

export function isLocal () {
    return this.isValid() ? !this._isUTC : false;
}

export function isUtcOffset () {
    return this.isValid() ? this._isUTC : false;
}

export function isUtc () {
    return this.isValid() ? this._isUTC && this._offset === 0 : false;
}
<commit_msg>[bugfix] Support unusual historic timezone offsets (fixes #5236) (#5237)<commit_after>import zeroFill from '../utils/zero-fill';
import { createDuration } from '../duration/create';
import { addSubtract } from '../moment/add-subtract';
import { isMoment, copyConfig } from '../moment/constructor';
import { addFormatToken } from '../format/format';
import { addRegexToken, matchOffset, matchShortOffset } from '../parse/regex';
import { addParseToken } from '../parse/token';
import { createLocal } from '../create/local';
import { prepareConfig } from '../create/from-anything';
import { createUTC } from '../create/utc';
import isDate from '../utils/is-date';
import toInt from '../utils/to-int';
import isUndefined from '../utils/is-undefined';
import compareArrays from '../utils/compare-arrays';
import { hooks } from '../utils/hooks';

// FORMATTING

function offset (token, separator) {
    addFormatToken(token, 0, 0, function () {
        var offset = this.utcOffset();
        var sign = '+';
        if (offset < 0) {
            offset = -offset;
            sign = '-';
        }
        return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
    });
}

offset('Z', ':');
offset('ZZ', '');

// PARSING

addRegexToken('Z',  matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
    config._useUTC = true;
    config._tzm = offsetFromString(matchShortOffset, input);
});

// HELPERS

// timezone chunker
// '+10:00' > ['10',  '00']
// '-1530'  > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;

function offsetFromString(matcher, string) {
    var matches = (string || '').match(matcher);

    if (matches === null) {
        return null;
    }

    var chunk   = matches[matches.length - 1] || [];
    var parts   = (chunk + '').match(chunkOffset) || ['-', 0, 0];
    var minutes = +(parts[1] * 60) + toInt(parts[2]);

    return minutes === 0 ?
      0 :
      parts[0] === '+' ? minutes : -minutes;
}

// Return a moment from input, that is local/utc/zone equivalent to model.
export function cloneWithOffset(input, model) {
    var res, diff;
    if (model._isUTC) {
        res = model.clone();
        diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
        // Use low-level api, because this fn is low-level api.
        res._d.setTime(res._d.valueOf() + diff);
        hooks.updateOffset(res, false);
        return res;
    } else {
        return createLocal(input).local();
    }
}

function getDateOffset (m) {
    // On Firefox.24 Date#getTimezoneOffset returns a floating point.
    // https://github.com/moment/moment/pull/1871
    return -Math.round(m._d.getTimezoneOffset());
}

// HOOKS

// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};

// MOMENTS

// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
export function getSetOffset (input, keepLocalTime, keepMinutes) {
    var offset = this._offset || 0,
        localAdjust;
    if (!this.isValid()) {
        return input != null ? this : NaN;
    }
    if (input != null) {
        if (typeof input === 'string') {
            input = offsetFromString(matchShortOffset, input);
            if (input === null) {
                return this;
            }
        } else if (Math.abs(input) < 16 && !keepMinutes) {
            input = input * 60;
        }
        if (!this._isUTC && keepLocalTime) {
            localAdjust = getDateOffset(this);
        }
        this._offset = input;
        this._isUTC = true;
        if (localAdjust != null) {
            this.add(localAdjust, 'm');
        }
        if (offset !== input) {
            if (!keepLocalTime || this._changeInProgress) {
                addSubtract(this, createDuration(input - offset, 'm'), 1, false);
            } else if (!this._changeInProgress) {
                this._changeInProgress = true;
                hooks.updateOffset(this, true);
                this._changeInProgress = null;
            }
        }
        return this;
    } else {
        return this._isUTC ? offset : getDateOffset(this);
    }
}

export function getSetZone (input, keepLocalTime) {
    if (input != null) {
        if (typeof input !== 'string') {
            input = -input;
        }

        this.utcOffset(input, keepLocalTime);

        return this;
    } else {
        return -this.utcOffset();
    }
}

export function setOffsetToUTC (keepLocalTime) {
    return this.utcOffset(0, keepLocalTime);
}

export function setOffsetToLocal (keepLocalTime) {
    if (this._isUTC) {
        this.utcOffset(0, keepLocalTime);
        this._isUTC = false;

        if (keepLocalTime) {
            this.subtract(getDateOffset(this), 'm');
        }
    }
    return this;
}

export function setOffsetToParsedOffset () {
    if (this._tzm != null) {
        this.utcOffset(this._tzm, false, true);
    } else if (typeof this._i === 'string') {
        var tZone = offsetFromString(matchOffset, this._i);
        if (tZone != null) {
            this.utcOffset(tZone);
        }
        else {
            this.utcOffset(0, true);
        }
    }
    return this;
}

export function hasAlignedHourOffset (input) {
    if (!this.isValid()) {
        return false;
    }
    input = input ? createLocal(input).utcOffset() : 0;

    return (this.utcOffset() - input) % 60 === 0;
}

export function isDaylightSavingTime () {
    return (
        this.utcOffset() > this.clone().month(0).utcOffset() ||
        this.utcOffset() > this.clone().month(5).utcOffset()
    );
}

export function isDaylightSavingTimeShifted () {
    if (!isUndefined(this._isDSTShifted)) {
        return this._isDSTShifted;
    }

    var c = {};

    copyConfig(c, this);
    c = prepareConfig(c);

    if (c._a) {
        var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
        this._isDSTShifted = this.isValid() &&
            compareArrays(c._a, other.toArray()) > 0;
    } else {
        this._isDSTShifted = false;
    }

    return this._isDSTShifted;
}

export function isLocal () {
    return this.isValid() ? !this._isUTC : false;
}

export function isUtcOffset () {
    return this.isValid() ? this._isUTC : false;
}

export function isUtc () {
    return this.isValid() ? this._isUTC && this._offset === 0 : false;
}
<|endoftext|>


<commit_before>$(function() {

    var headerSelect = $("select[name=header]");
    var mainBodySelect = $("select[name=mainBody]");
    var sidebarSelect = $("select[name=sidebar]");
    var backgroundSelect = $("select[name=background]");
    var resetter = $("#resetButton");

    function ColorSet(headerHex, mainHex, sideHex, bgHex) {
        // Constructor for an object that stores a set of the hexcodes
        // for a specified color scheme
        this.headerHex = headerHex;
        this.mainHex = mainHex;
        this.sideHex = sideHex;
        this.bgHex = bgHex;
    }

    function defaultColorSet() {
        return new ColorSet('#0000FF', '#FFFFFF', '#808080',
                            '#B0C4DE');
    }

    function save() {
        var newColors = new ColorSet(headerSelect.val(),
                                     mainBodySelect.val(),
                                     sidebarSelect.val(),
                                     backgroundSelect.val());
        $.cookie("colorCookie", JSON.stringify(newColors),{expires: 7});
    }

    headerSelect.change(function() {
        $("header").css("background-color", $(this).val());
        save();
    });

    mainBodySelect.change(function() {
        $("#mainText").css("background-color", $(this).val());
        save();
    });

    sidebarSelect.change(function() {
        $("nav").css("background-color", $(this).val());
        // In case the user highlighted nav li's via
        // highlightNav.js, change them too
        $("nav li").css("background-color", $(this).val());
        save();
    });

    backgroundSelect.change(function() {
        $("body").css("background-color", $(this).val());
        save();
    });

    function set(colSet) {
        // sets the selects' names and the background colors as
        // specified by colSet
        var defaultColors = defaultColorSet();
        colSet = $.extend(defaultColors, colSet);//remove null values just in case

        headerSelect.val(colSet.headerHex);
        mainBodySelect.val(colSet.mainHex);
        sidebarSelect.val(colSet.sideHex);
        backgroundSelect.val(colSet.bgHex);

        $("header").css("background-color", colSet.headerHex);
        $("#mainText").css("background-color", colSet.mainHex);
        $("nav").css("background-color", colSet.sideHex);

        // In case the user highlighted nav li's via highlightNav.js
        // nav li's CSS overrides nav's so it must be updated manually
        $("nav li").css("background-color", colSet.sideHex);

        $("body").css("background-color", colSet.bgHex);
        return true;
    }

    function resetCookie() {
        $.cookie("colorCookie", null);
    }

    resetter.click(function() {
        var resetColors = defaultColorSet();
        set(resetColors);
        resetCookie();
    });

    function setColorsFromCookie() {
        // reads colorCookie and sets the colors accordingly
        set(JSON.parse($.cookie("colorCookie")));
    }

    setColorsFromCookie();
});
<commit_msg>Combined a selector in colors.js<commit_after>$(function() {

    var headerSelect = $("select[name=header]");
    var mainBodySelect = $("select[name=mainBody]");
    var sidebarSelect = $("select[name=sidebar]");
    var backgroundSelect = $("select[name=background]");
    var resetter = $("#resetButton");

    function ColorSet(headerHex, mainHex, sideHex, bgHex) {
        // Constructor for an object that stores a set of the hexcodes
        // for a specified color scheme
        this.headerHex = headerHex;
        this.mainHex = mainHex;
        this.sideHex = sideHex;
        this.bgHex = bgHex;
    }

    function defaultColorSet() {
        return new ColorSet('#0000FF', '#FFFFFF', '#808080',
                            '#B0C4DE');
    }

    function save() {
        var newColors = new ColorSet(headerSelect.val(),
                                     mainBodySelect.val(),
                                     sidebarSelect.val(),
                                     backgroundSelect.val());
        $.cookie("colorCookie", JSON.stringify(newColors),{expires: 7});
    }

    headerSelect.change(function() {
        $("header").css("background-color", $(this).val());
        save();
    });

    mainBodySelect.change(function() {
        $("#mainText").css("background-color", $(this).val());
        save();
    });

    sidebarSelect.change(function() {
        $("nav, nav li").css("background-color", $(this).val());
        // In case the user highlighted nav li's via
        // highlightNav.js, change them too
        save();
    });

    backgroundSelect.change(function() {
        $("body").css("background-color", $(this).val());
        save();
    });

    function set(colSet) {
        // sets the selects' names and the background colors as
        // specified by colSet
        var defaultColors = defaultColorSet();
        colSet = $.extend(defaultColors, colSet);//remove null values just in case

        headerSelect.val(colSet.headerHex);
        mainBodySelect.val(colSet.mainHex);
        sidebarSelect.val(colSet.sideHex);
        backgroundSelect.val(colSet.bgHex);

        $("header").css("background-color", colSet.headerHex);
        $("#mainText").css("background-color", colSet.mainHex);
        $("nav").css("background-color", colSet.sideHex);

        // In case the user highlighted nav li's via highlightNav.js
        // nav li's CSS overrides nav's so it must be updated manually
        $("nav li").css("background-color", colSet.sideHex);

        $("body").css("background-color", colSet.bgHex);
        return true;
    }

    function resetCookie() {
        $.cookie("colorCookie", null);
    }

    resetter.click(function() {
        var resetColors = defaultColorSet();
        set(resetColors);
        resetCookie();
    });

    function setColorsFromCookie() {
        // reads colorCookie and sets the colors accordingly
        set(JSON.parse($.cookie("colorCookie")));
    }

    setColorsFromCookie();
});
<|endoftext|>


<commit_before>
'use strict';

// Modules
var path                           = require('path');
var fs                             = require('fs');
var moment                         = require('moment');
var remove_image_content_directory = require('../functions/remove_image_content_directory.js');

function route_home (config, raneto) {
  return function (req, res, next) {

    var suffix = 'edit';
    var slug = '/index';

    var pageList     = remove_image_content_directory(config, raneto.getPages(slug));
    var filePath     = path.normalize(raneto.config.content_dir + slug);

    if (fs.existsSync(filePath + '.md')) {
      return next();
    }

    if (filePath.indexOf(suffix, filePath.length - suffix.length) !== -1) {
      filePath = filePath.slice(0, - suffix.length - 1);
    }

    var stat = fs.lstatSync(path.join(config.theme_dir, config.theme_name, 'templates', 'home.html'));

    return res.render('home', {
      config        : config,
      pages         : pageList,
      body_class    : 'page-home',
      meta          : config.home_meta,
      last_modified : moment(stat.mtime).format('Do MMM YYYY'),
      lang          : config.lang,
      loggedIn      : (config.authentication ? req.session.loggedIn : false)
    });

  };
}

// Exports
module.exports = route_home;
<commit_msg>Refactor: Converting home page to use get_filepath()<commit_after>
'use strict';

// Modules
var fs                             = require('fs');
var moment                         = require('moment');
var get_filepath                   = require('../functions/get_filepath.js');
var remove_image_content_directory = require('../functions/remove_image_content_directory.js');

function route_home (config, raneto) {
  return function (req, res, next) {

    // Generate Filepath
    var filepath = get_filepath({
      content  : raneto.config.content_dir,
      filename : 'index'
    });

    // Do we have an index.md file?
    // If so, use that.
    if (fs.existsSync(filepath + '.md')) {
      return next();
    }

    // Otherwise, we're generating the home page listing
    var suffix = 'edit';
    if (filepath.indexOf(suffix, filepath.length - suffix.length) !== -1) {
      filepath = filepath.slice(0, - suffix.length - 1);
    }

    var template_filepath = get_filepath({
      content  : [config.theme_dir, config.theme_name, 'templates'].join('/'),
      filename : 'home.html'
    });

    var stat     = fs.lstatSync(template_filepath);
    var pageList = remove_image_content_directory(config, raneto.getPages('/index'));

    return res.render('home', {
      config        : config,
      pages         : pageList,
      body_class    : 'page-home',
      meta          : config.home_meta,
      last_modified : moment(stat.mtime).format('Do MMM YYYY'),
      lang          : config.lang,
      loggedIn      : (config.authentication ? req.session.loggedIn : false)
    });

  };
}

// Exports
module.exports = route_home;
<|endoftext|>


<commit_before>var userController = require('./../controllers/user.controller');
var roleController = require('./../controllers/role.controller');

// create rout definitions
module.exports = function(router) {

 // route for sign in. This requires autheentication
 router.route('/signIn')
  .post(userController.signIn);

 // route for logout. This requires that a user is signIn
 router.route('/logOut')
  .post(userController.logOut);

 // route to create new user requires no authentication but viewing users does.
 router.route('/users')
  .post(userController.createUser)
  .get(userController.getAllUsers);

 // routes to GET, UPDATE and DELETE users.
 // This requires authentication
 router.route('/users/:id')
  .get(userController.getUser)
  .put(userController.Auth, userController.updateUser)
  .delete(userController.Auth, userController.deleteUser);
};
<commit_msg>fix(userRoute): modify signIn method<commit_after>var userController = require('./../controllers/user.controller');
var roleController = require('./../controllers/role.controller');

// create rout definitions
module.exports = function(router) {

 // route for sign in. This requires autheentication
 router.route('/signIn')
  .post(userController.signIn);

 // route for logout. This requires that a user is signIn
 router.route('/logOut')
  .post(userController.logOut);

 // route to create new user requires no authentication but viewing users does.
 router.route('/users')
  .post(userController.createUser)
  .get(userController.Auth, userController.getAllUsers);

 // routes to GET, UPDATE and DELETE users.
 // This requires authentication
 router.route('/users/:id')
  .get(userController.Auth, userController.getUser)
  .put(userController.Auth, userController.updateUser)
  .delete(userController.Auth, userController.deleteUser);
};
<|endoftext|>


<commit_before>;(function(window) {

    var rgb2hex = function(color) {

        if(typeof color !== 'string') {
            // throw error of input isn't typeof string
            throw new Error('color has to be type of `string`');
        } else if (color.substr(0, 1) === '#') {
            // or return if already rgb color
            return {
                hex: color,
                alpha: 1
            };
        }

        // parse input
        var digits = /(.*?)rgb(a)*\((\d+),(\d+),(\d+)(,[0-9]*\.*[0-9]+)*\)/.exec(color.replace(/\s+/g,''));

        if(!digits) {
            // or throw error if input isn't a valid rgb(a) color
            throw new Error('given color (' + color + ') isn\'t a valid rgb or rgba color');
        }

        var red = parseInt(digits[3]);
        var green = parseInt(digits[4]);
        var blue = parseInt(digits[5]);
        var alpha = digits[6] ? /([0-9\.]+)/.exec(digits[6])[0] : '1';
        var rgb = ((blue | green << 8 | red << 16) | 1 << 24).toString(16).slice(1);

        // parse alpha value into float
        if(alpha.substr(0,1) === '.') {
            alpha = parseFloat('0' + alpha, 10);
        }

        // limit alpha value to 1
        if(alpha > 1) {
            alpha = 1;
        }

        // cut alpha value after 2 digits after comma
        alpha = parseFloat(Math.round(alpha * 100), 10) / 100;

        return {
            hex: digits[1] + '#' + rgb.toString(16),
            alpha: alpha
        }

    };

    if(typeof define === 'function' && define.amd) {
        define('rgb2hex', function () {
            return rgb2hex;
        });
    } else {
        window.rgb2hex = rgb2hex;
    }

}(window));<commit_msg>fixes regex to avoid catastrophic backtracking<commit_after>;(function(window) {

    var rgb2hex = function(color) {

        if(typeof color !== 'string') {
            // throw error of input isn't typeof string
            throw new Error('color has to be type of `string`');
        } else if (color.substr(0, 1) === '#') {
            // or return if already rgb color
            return {
                hex: color,
                alpha: 1
            };
        }

        // parse input
        var digits = /^rgba?\((\d+),(\d+),(\d+)(,[0-1]?\.?[0-9]+)?\)$/.exec(color.replace(/\s+/g,''));

        if(!digits) {
            // or throw error if input isn't a valid rgb(a) color
            throw new Error('given color (' + color + ') isn\'t a valid rgb or rgba color');
        }

        var red = parseInt(digits[1]);
        var green = parseInt(digits[2]);
        var blue = parseInt(digits[3]);
        var alpha = digits[4] ? /([0-9\.]+)/.exec(digits[4])[0] : '1';
        var rgb = ((blue | green << 8 | red << 16) | 1 << 24).toString(16).slice(1);

        // parse alpha value into float
        if(alpha.substr(0,1) === '.') {
            alpha = parseFloat('0' + alpha, 10);
        }

        // limit alpha value to 1
        if(alpha > 1) {
            alpha = 1;
        }

        // cut alpha value after 2 digits after comma
        alpha = parseFloat(Math.round(alpha * 100), 10) / 100;

        return {
            hex: '#' + rgb.toString(16),
            alpha: alpha
        };

    };

    if(typeof define === 'function' && define.amd) {
        define('rgb2hex', function () {
            return rgb2hex;
        });
    } else {
        window.rgb2hex = rgb2hex;
    }

}(window));
<|endoftext|>