<commit_before>
// installed version

function checkAllInstalledVersions() {
  var delayBetweenRequests = 250; // in ms
  var currentDelay = 0;

  $(".js-app").not(".js-new-app").each(function() {
    var app = $(this);
    setTimeout(function() {
      checkInstalledVersionForApplication(app);
    }, currentDelay);
    currentDelay += delayBetweenRequests;
  });
}

function checkInstalledVersionForApplication(app) {
  var dirId = $(app).data("dir-id");
  var installedVersionUrl = "/installations/"+dirId+"/installed_version.json";

  $(app).find(".js-installed-app .js-busy").show(); // show busy
  $(app).find(".js-installed-version").html(""); // erase version + link
  $.getJSON(installedVersionUrl).success(function(data) {
    updateInstalledVersionFor(app, data.installed_version);
    updateAssessments(app);
  }).error(function(xhr, error, exception) {
    console.log(xhr);
    console.log(error);
    console.log(exception);
    error = titelize(error);
    updateInstalledVersionFor(app, Render.ajaxError(error, exception));
  });
}

function updateInstalledVersionFor(dir, html) {
  var ia = $(dir).find(".js-installed-app");
  $(ia).find(".js-busy").hide();
  $(ia).find(".js-installed-version").html(html); // set installed version text
  // update button
  $(ia).find(".js-check-installed-version-button").html(Render.recheckButtonFace());
}

// newest version

function checkAllNewestVersions() {
  var delayBetweenRequests = 250; // in ms
  var currentDelay = 0;

  var basicNames = $.unique($(".js-app").map(function() {
      return $(this).data("basic-name");
  }));
  $(basicNames).each(function() {
    var basicName = this;
    if (!isEmpty($("[data-basic-name='"+basicName+"']").toArray())) {
      setTimeout(function() {
        checkNewestVersionForApplicationByName(basicName);
      }, currentDelay);
      currentDelay += delayBetweenRequests;
    }
  });
}

function checkNewestVersionForApplicationByName(basicName) {
  var apps = $("[data-basic-name='"+basicName+"']");
  var newestVersionUrl = "/applications/"+basicName+"/newest_version.json";

  $(apps).find(".js-newest-app .js-busy").show(); // show busy
  $(apps).find(".js-newest-version").html(""); // erase version + link
  $.getJSON(newestVersionUrl).success(function(data) {
    updateNewestVersionFor(apps, data.newest_version);
    updateAssessments(apps);
  }).error(function(xhr, error, exception) {
    console.log(xhr);
    console.log(error);
    console.log(exception);
    error = titelize(error);
    updateNewestVersionFor(apps, Render.ajaxError(error, exception));
  });
}

function updateNewestVersionFor(inst, html) {
  var na = $(inst).find(".js-newest-app");
  $(na).find(".js-busy").hide();
  $(na).find(".js-newest-version").html(html); // set newest version text
  // update button
  $(na).find(".js-check-newest-version-button").html(Render.recheckButtonFace());
}

// global

function checkAllVersions() {
  checkAllInstalledVersions();
  checkAllNewestVersions();
}

function loadInstallations() {
  $(".js-refresh-installations-button .js-busy").show();
  $(".js-check-all-versions-button").fadeOut();
  $(".js-load-errors").slideUp();
  $(".js-dir-errors").slideUp();
  $(".js-app-dirs").slideUp();

  $.getJSON("/installations.json").success(function(data) {
    // update content
    if (!isEmpty(data.error_dirs)) {
      Render.missingDirs(data.error_dirs).slideDown();
    }
    Render.appDirs(data.app_dirs).slideDown();

    // show content
    $(".js-refresh-installations-button .js-busy").hide();
    $(".js-check-all-versions-button").fadeIn();
  }).error(function(xhr, error, exception) {
    $(".js-busy").hide();
    $(".js-load-errors").html(Render.loadErrors(error, exception)).slideDown();
  });
}

function updateAssessments(inst) {
  $(inst).each(function() {
    var installed_version = $(this).find(".js-installed-app .js-installed-version").text();
    var newest_version = $(this).find(".js-newest-app .js-newest-version").text();
    var as = $(this).find(".js-assessment-summary");

    // reset styles
    $(this).removeClass("alert-success");
    $(this).removeClass("alert-warning");
    $(as).removeClass("btn-success");
    $(as).removeClass("btn-warning");
    $(as).html(Render.appStatusUnknown());

    if(!isEmpty(installed_version) &&
       installed_version != "unknown" &&
       !isEmpty(newest_version) &&
       newest_version != "unknown"
    ) {
      $(this).addClass("alert");
      if(installed_version == newest_version) {
        $(this).addClass("alert-success");
        $(as).addClass("btn-success");
        $(as).html(Render.appStatusUpToDate());
      } else {
        $(this).addClass("alert-warning");
        $(as).addClass("btn-warning");
        $(as).html(Render.appStatusNeedsAttention());
      }
      $(this).find(".js-check-app-button").html(Render.recheckButtonFace());
    }
  });
}

// on load

$(function() {
  $(".js-check-all-versions-button").click(checkAllVersions);
  $(".js-refresh-installations-button").click(loadInstallations);

  // make sure the trigger for the collapse (i.e. the collapser) does get the
  // "same" treatment (i.e. toggling the "in" class) as the target
  $("body").on("click", ".js-collapser", function() {
    $(this).toggleClass("in");
  });

  $("body").on("click", ".js-check-app-button", function(e) {
    e.stopPropagation(); // to prevent .collapser to trigger
    checkInstalledVersionForApplication($(this).parents(".js-app"));
    checkNewestVersionForApplicationByName($(this).parents(".js-app").data('basic-name'));
  });
  $("body").on("click", ".js-check-installed-version-button", function() {
    checkInstalledVersionForApplication($(this).parents(".js-app"));
  });
  $("body").on("click", ".js-check-newest-version-button", function() {
    checkNewestVersionForApplicationByName($(this).parents(".js-app").data('basic-name'));
  });

  loadInstallations();
});
<commit_msg>Fix handlers<commit_after>
// installed version

function checkAllInstalledVersions() {
  var delayBetweenRequests = 250; // in ms
  var currentDelay = 0;

  $(".js-app").each(function() {
    var app = $(this);
    setTimeout(function() {
      checkInstalledVersionForApplication(app);
    }, currentDelay);
    currentDelay += delayBetweenRequests;
  });
}

function checkInstalledVersionForApplication(app) {
  var dirId = $(app).data("dir-id");
  var installedVersionUrl = "/installations/"+dirId+"/installed_version.json";

  $(app).find(".js-installed-app .js-busy").removeClass("hidden"); // show busy
  $(app).find(".js-installed-version").html(""); // erase version + link
  $.getJSON(installedVersionUrl).success(function(data) {
    updateInstalledVersionFor(app, data.installed_version);
    updateAssessments(app);
  }).error(function(xhr, error, exception) {
    console.log(xhr);
    console.log(error);
    console.log(exception);
    error = titelize(error);
    updateInstalledVersionFor(app, Render.ajaxError(error, exception));
  });
}

function updateInstalledVersionFor(dir, html) {
  var ia = $(dir).find(".js-installed-app");
  $(ia).find(".js-busy").addClass("hidden");
  $(ia).find(".js-installed-version").html(html); // set installed version text
  // update button
  $(ia).find(".js-check-installed-version-button").html(Render.recheckButtonFace());
}

// newest version

function checkAllNewestVersions() {
  var delayBetweenRequests = 250; // in ms
  var currentDelay = 0;

  var basicNames = $.unique($(".js-app").map(function() {
      return $(this).data("basic-name");
  }));
  $(basicNames).each(function() {
    var basicName = this;
    if (!isEmpty($("[data-basic-name='"+basicName+"']").toArray())) {
      setTimeout(function() {
        checkNewestVersionForApplicationByName(basicName);
      }, currentDelay);
      currentDelay += delayBetweenRequests;
    }
  });
}

function checkNewestVersionForApplicationByName(basicName) {
  var apps = $("[data-basic-name='"+basicName+"']");
  var newestVersionUrl = "/applications/"+basicName+"/newest_version.json";

  $(apps).find(".js-newest-app .js-busy").removeClass("hidden"); // show busy
  $(apps).find(".js-newest-version").html(""); // erase version + link
  $.getJSON(newestVersionUrl).success(function(data) {
    updateNewestVersionFor(apps, data.newest_version);
    updateAssessments(apps);
  }).error(function(xhr, error, exception) {
    console.log(xhr);
    console.log(error);
    console.log(exception);
    error = titelize(error);
    updateNewestVersionFor(apps, Render.ajaxError(error, exception));
  });
}

function updateNewestVersionFor(inst, html) {
  var na = $(inst).find(".js-newest-app");
  $(na).find(".js-busy").addClass("hidden");
  $(na).find(".js-newest-version").html(html); // set newest version text
  // update button
  $(na).find(".js-check-newest-version-button").html(Render.recheckButtonFace());
}

// global

function checkAllVersions() {
  checkAllInstalledVersions();
  checkAllNewestVersions();
}

function loadInstallations() {
  $(".js-refresh-installations-button .js-busy").removeClass("hidden");
  $(".js-check-all-versions-button").fadeOut();
  $(".js-load-errors").slideUp();
  $(".js-missing-dirs").slideUp();
  $(".js-app-dirs").slideUp();

  $.getJSON("/installations.json").success(function(data) {
    // update content
    if (!isEmpty(data.error_dirs)) {
      Render.missingDirs(data.error_dirs).slideDown();
    }
    Render.appDirs(data.app_dirs).slideDown();

    $(".js-refresh-installations-button .js-busy").addClass("hidden");
    $(".js-check-all-versions-button").removeClass("hidden").fadeIn();
  }).error(function(xhr, error, exception) {
    $(".js-busy").addClass("hidden");
    $(".js-load-errors").html(Render.loadErrors(error, exception)).slideDown();
  });
}

function updateAssessments(inst) {
  $(inst).each(function() {
    var installed_version = $(this).find(".js-installed-app .js-installed-version").text();
    var newest_version = $(this).find(".js-newest-app .js-newest-version").text();
    var as = $(this).find(".js-assessment-summary");

    // reset styles
    $(this).removeClass("alert-success");
    $(this).removeClass("alert-warning");
    $(as).removeClass("btn-success");
    $(as).removeClass("btn-warning");
    $(as).html(Render.appStatusUnknown());

    if(!isEmpty(installed_version) &&
       installed_version != "unknown" &&
       !isEmpty(newest_version) &&
       newest_version != "unknown"
    ) {
      $(this).addClass("alert");
      if(installed_version == newest_version) {
        $(this).addClass("alert-success");
        $(as).addClass("btn-success");
        $(as).html(Render.appStatusUpToDate());
      } else {
        $(this).addClass("alert-warning");
        $(as).addClass("btn-warning");
        $(as).html(Render.appStatusNeedsAttention());
      }
      $(this).find(".js-check-app-button").html(Render.recheckButtonFace());
    }
  });
}

// on load

$(function() {
  $(".js-check-all-versions-button").click(checkAllVersions);
  $(".js-refresh-installations-button").click(loadInstallations);

  // make sure the trigger for the collapse (i.e. the collapser) does get the
  // "same" treatment (i.e. toggling the "in" class) as the target
  $("body").on("click", ".js-collapser", function() {
    $(this).toggleClass("in");
  });

  $("body").on("click", ".js-check-app-button", function(e) {
    e.stopPropagation(); // to prevent .collapser to trigger
    checkInstalledVersionForApplication($(this).parents(".js-app"));
    checkNewestVersionForApplicationByName($(this).parents(".js-app").data('basic-name'));
  });
  $("body").on("click", ".js-check-installed-version-button", function() {
    checkInstalledVersionForApplication($(this).parents(".js-app"));
  });
  $("body").on("click", ".js-check-newest-version-button", function() {
    checkNewestVersionForApplicationByName($(this).parents(".js-app").data('basic-name'));
  });

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


<commit_before>'use strict';

var React = require('react');
var ReactNative = require('react-native');
var SQLite = require('react-native-sqlite-storage');

const database_name = "DLIR.db";
const database_version = "1.0";
const database_displayname = "DontLetItRot";
const database_size = 200000;
let db;

const RESET_DB = false;
var myProductsList = [];

var DatabaseManager = React.createClass({

    componentWillUnmount: function () {
      this.closeDatabase();
    },

    openDatabase: function () {
      db = SQLite.openDatabase(database_name, database_version, database_displayname, database_size, () => console.log("OK: OPEN Database"), () => alert("FAIL: OPEN Database"));
      this.setupDatabase(db);
    },

    closeDatabase: function () {
      var that = this;
      if (db) {
        console.log("Closing database...");
        db.close(() => console.log("OK: CLOSE Database"), () => alert("FAIL: CLOSE Database"));
      } else {
        console.log("Database was not OPENED");
      }
    },

    addProductName: function (name,callback) {
      db.transaction((pdb) => this.checkDuplicatesToAddProductName(pdb,name,callback),() => alert("FAIL: Transaction checkDuplicatesToAddProductName"),function() {
        console.log("OK: Transaction checkDuplicatesToAddProductName");
      });
    },

    checkDuplicatesToAddProductName: function (db,name,callback) {
      db.executeSql('SELECT * FROM ProductName WHERE name="' + name + '"', [],
        (pdb,presults) => this.checkDuplicatesResultsToAddProductName(pdb,presults,name,callback), () => alert("FAIL: SELECT FROM ProductName"));
    },

    checkDuplicatesResultsToAddProductName: function (db,results,name,callback) {
      if (results != undefined) {
        var len = results.rows.length;
        if (len > 0) {
          console.log('Product "' + name + '" is already registered!');
          alert('O produto "' + name + '" já está cadastrado!');
        }
        else {
          db.executeSql('INSERT INTO ProductName (name) VALUES ("' + name + '");', [], () => this.addedSuccesfully(callback), () => alert("FAIL: Insert ProductName"));
        }
      }
      else alert("Results is undefined!");
    },

    addMyProduct: function (id,qtty,expireDate,callback) {
      db.transaction((pdb) => this.checkDuplicatesToAddMyProduct(pdb,id,qtty,expireDate,callback),() => alert("FAIL: Transaction checkDuplicatesToAddMyProduct"),function() {
        console.log("OK: Transaction checkDuplicatesToAddMyProduct");
      });
    },

    checkDuplicatesToAddMyProduct: function (db,id,qtty,expireDate,callback) {
      db.executeSql('SELECT * FROM MyProduct WHERE fk_product_id=' + id +
                    ' AND expireDate="' + expireDate + '"', [],
        (pdb,presults) => this.checkDuplicatesResultsToAddMyProduct(pdb,presults,id,qtty,expireDate,callback), () => alert("FAIL: SELECT FROM ProductName"));
    },

    checkDuplicatesResultsToAddMyProduct: function (db,results,id,qtty,expireDate,callback) {
      if (results != undefined) {
        var len = results.rows.length;
        if (len > 0) {
          db.executeSql('UPDATE MyProduct SET quantity=quantity+' + qtty + ' WHERE fk_product_id=' + id + ' AND expireDate="' + expireDate + '";', [], () => this.addedSuccesfully(callback), () => alert("FAIL: Update MyProduct"));
        }
        else {
          db.executeSql('INSERT INTO MyProduct (fk_product_id, quantity, expireDate) VALUES (' + id + ', ' + qtty + ', "' + expireDate + '");', [], () => this.addedSuccesfully(callback), () => alert("FAIL: Insert MyProduct"));
        }
      }
      else alert("Results is undefined!");
    },

    addedSuccesfully: function (callback) {
      console.log("OK: INSERT");
      callback();
    },

    decreaseMyProduct: function (id,expireDate,callback) {
      db.executeSql('UPDATE MyProduct SET quantity=quantity-1 WHERE fk_product_id=' + id + ' AND expireDate="' + expireDate + '";', [], () => callback(), () => alert("FAIL: Decrease MyProduct"));
    },

    removeMyProduct: function (id,expireDate,callback) {
      db.executeSql('DELETE FROM MyProduct WHERE fk_product_id=' + id + ' AND expireDate="' + expireDate + '";', [], () => callback(), () => alert("FAIL: Remove MyProduct"));
    },

    requestProductNamesList: function (callback) {
      db.transaction((pdb) => this.queryProducts(pdb,callback),() => alert("FAIL: Transaction queryMyProducts"),function() {
        console.log("OK: Transaction queryMyProducts");
      });
    },

    queryProducts: function (db, callback) {
      db.executeSql('SELECT * FROM ProductName', [],
        (pdb,presults) => this.queryProductsSuccess(pdb,presults,callback), () => alert("FAIL: SELECT FROM ProductName"));
    },

    queryProductsSuccess: function (db,results, callback) {
      if (results != undefined) {
        var len = results.rows.length;
        var data = [];
        var result = "Result:";
        for (let i = 0; i < len; i++) {
          let row = results.rows.item(i);
          data.push({productId: row.product_id, name: row.name});
          result = result + " " + row.name + ";";
        }
        callback(data);
        console.log(result);
        // alert(result);
      }
      else alert("Results is undefined!");
    },

    requestMyProductsList: function (callback) {
      db.transaction((pdb) => this.queryMyProducts(pdb,callback),() => alert("FAIL: Transaction queryMyProducts"),function() {
        console.log("OK: Transaction queryMyProducts");
      });
    },

    queryMyProducts: function (db,callback) {
      db.executeSql('SELECT MyProduct.*, ProductName.name FROM MyProduct, ProductName WHERE ProductName.product_id = MyProduct.fk_product_id', [],
        (pdb,presults) => this.queryMyProductsSuccess(pdb,presults,callback), () => alert("FAIL: SELECT FROM ProductName"));
    },

    queryMyProductsSuccess: function (db,results,callback) {
      if (results != undefined) {
        var len = results.rows.length;
        var data = [];
        var result = "Result:";
        for (let i = 0; i < len; i++) {
          let row = results.rows.item(i);
          data.push({productId: row.fk_product_id, name: row.name, quantity: row.quantity, expireDate: row.expireDate});
          result = result + " " + row.fk_product_id + " " + row.quantity + " " + row.expireDate + " " + row.name + ";";
        }
        callback(data);
        console.log(result);
        // alert(result);
      }
      else alert("Results is undefined!");
    },

    setupDatabase: function (db) {
      var that = this;
      if (RESET_DB)
        db.executeSql('DROP TABLE IF EXISTS Version;', [], () => console.log("OK: DROP TABLE Version"), () => alert("FAIL: DROP TABLE Version"));
      db.executeSql('SELECT 1 FROM Version LIMIT 1', [],
        function () {
          console.log("Database is ready!");
          // alert("Database is ready!");
          db.transaction(that.queryProducts,() => alert("FAIL: Transaction queryProducts"),function() {
            console.log("OK: Transaction queryProducts");
          });
        },
        function (error) {
          console.log("received version error:", error);
          db.transaction(that.createDatabase, () => alert("Could not create database!"), function () {
            console.log("Database created!");
            // alert("Database created!");
            db.transaction(that.queryProducts,() => alert("FAIL: Transaction queryProducts"),function() {
              console.log("OK: Transaction queryProducts");
            });
          });
      });
    },

    createDatabase: function (db) {
      console.log("Trying to create database...");

      db.executeSql('DROP TABLE IF EXISTS ProductName;', [], () => console.log("OK: DROP TABLE ProductName"), () => alert("FAIL: DROP TABLE ProductName"));
      db.executeSql('DROP TABLE IF EXISTS MyProduct;', [], () => console.log("OK: DROP TABLE MyProduct"), () => alert("FAIL: DROP TABLE MyProduct"));

      db.executeSql('CREATE TABLE IF NOT EXISTS Version( '
        + 'version_id INTEGER PRIMARY KEY NOT NULL); ', [], () => console.log("OK: CREATE TABLE Version"), () => alert("FAIL: CREATE TABLE Version"));

      db.executeSql('CREATE TABLE IF NOT EXISTS ProductName( '
        + 'product_id INTEGER PRIMARY KEY AUTOINCREMENT, '
        + 'name VARCHAR(30) ); ', [], () => console.log("OK: CREATE TABLE ProductName"), () => alert("FAIL: CREATE TABLE ProductName"));

      db.executeSql('CREATE TABLE IF NOT EXISTS MyProduct( '
        + 'id INTEGER PRIMARY KEY AUTOINCREMENT, '
        + 'fk_product_id INTEGER, '
        + 'quantity INTEGER, '
        + 'expireDate VARCHAR(10), '
        + 'FOREIGN KEY ( fk_product_id ) REFERENCES ProductName ( product_id )); ', [], () => console.log("OK: CREATE TABLE MyProduct"), () => alert("FAIL: CREATE TABLE MyProduct"));

      db.executeSql('INSERT INTO ProductName (name) VALUES ("Abóbora");', [], () => console.log("OK: Insert ProductName Abóbora"), () => alert("FAIL: Insert ProductName Abóbora"));
      db.executeSql('INSERT INTO ProductName (name) VALUES ("Fraldinha");', [], () => console.log("OK: Insert ProductName Fraldinha"), () => alert("FAIL: Insert ProductName Fraldinha"));

      console.log("Database was created successfully!");
    },

    render: function() {},
});

module.exports = DatabaseManager;<commit_msg>Added sorting to productNames lists also.<commit_after>'use strict';

var React = require('react');
var ReactNative = require('react-native');
var SQLite = require('react-native-sqlite-storage');

const database_name = "DLIR.db";
const database_version = "1.0";
const database_displayname = "DontLetItRot";
const database_size = 200000;
let db;

const RESET_DB = false;
var myProductsList = [];

var DatabaseManager = React.createClass({

    componentWillUnmount: function () {
      this.closeDatabase();
    },

    openDatabase: function () {
      db = SQLite.openDatabase(database_name, database_version, database_displayname, database_size, () => console.log("OK: OPEN Database"), () => alert("FAIL: OPEN Database"));
      this.setupDatabase(db);
    },

    closeDatabase: function () {
      var that = this;
      if (db) {
        console.log("Closing database...");
        db.close(() => console.log("OK: CLOSE Database"), () => alert("FAIL: CLOSE Database"));
      } else {
        console.log("Database was not OPENED");
      }
    },

    addProductName: function (name,callback) {
      db.transaction((pdb) => this.checkDuplicatesToAddProductName(pdb,name,callback),() => alert("FAIL: Transaction checkDuplicatesToAddProductName"),function() {
        console.log("OK: Transaction checkDuplicatesToAddProductName");
      });
    },

    checkDuplicatesToAddProductName: function (db,name,callback) {
      db.executeSql('SELECT * FROM ProductName WHERE name="' + name + '"', [],
        (pdb,presults) => this.checkDuplicatesResultsToAddProductName(pdb,presults,name,callback), () => alert("FAIL: SELECT FROM ProductName"));
    },

    checkDuplicatesResultsToAddProductName: function (db,results,name,callback) {
      if (results != undefined) {
        var len = results.rows.length;
        if (len > 0) {
          console.log('Product "' + name + '" is already registered!');
          alert('O produto "' + name + '" já está cadastrado!');
        }
        else {
          db.executeSql('INSERT INTO ProductName (name) VALUES ("' + name + '");', [], () => this.addedSuccesfully(callback), () => alert("FAIL: Insert ProductName"));
        }
      }
      else alert("Results is undefined!");
    },

    addMyProduct: function (id,qtty,expireDate,callback) {
      db.transaction((pdb) => this.checkDuplicatesToAddMyProduct(pdb,id,qtty,expireDate,callback),() => alert("FAIL: Transaction checkDuplicatesToAddMyProduct"),function() {
        console.log("OK: Transaction checkDuplicatesToAddMyProduct");
      });
    },

    checkDuplicatesToAddMyProduct: function (db,id,qtty,expireDate,callback) {
      db.executeSql('SELECT * FROM MyProduct WHERE fk_product_id=' + id +
                    ' AND expireDate="' + expireDate + '"', [],
        (pdb,presults) => this.checkDuplicatesResultsToAddMyProduct(pdb,presults,id,qtty,expireDate,callback), () => alert("FAIL: SELECT FROM ProductName"));
    },

    checkDuplicatesResultsToAddMyProduct: function (db,results,id,qtty,expireDate,callback) {
      if (results != undefined) {
        var len = results.rows.length;
        if (len > 0) {
          db.executeSql('UPDATE MyProduct SET quantity=quantity+' + qtty + ' WHERE fk_product_id=' + id + ' AND expireDate="' + expireDate + '";', [], () => this.addedSuccesfully(callback), () => alert("FAIL: Update MyProduct"));
        }
        else {
          db.executeSql('INSERT INTO MyProduct (fk_product_id, quantity, expireDate) VALUES (' + id + ', ' + qtty + ', "' + expireDate + '");', [], () => this.addedSuccesfully(callback), () => alert("FAIL: Insert MyProduct"));
        }
      }
      else alert("Results is undefined!");
    },

    addedSuccesfully: function (callback) {
      console.log("OK: INSERT");
      callback();
    },

    decreaseMyProduct: function (id,expireDate,callback) {
      db.executeSql('UPDATE MyProduct SET quantity=quantity-1 WHERE fk_product_id=' + id + ' AND expireDate="' + expireDate + '";', [], () => callback(), () => alert("FAIL: Decrease MyProduct"));
    },

    removeMyProduct: function (id,expireDate,callback) {
      db.executeSql('DELETE FROM MyProduct WHERE fk_product_id=' + id + ' AND expireDate="' + expireDate + '";', [], () => callback(), () => alert("FAIL: Remove MyProduct"));
    },

    requestProductNamesList: function (callback) {
      db.transaction((pdb) => this.queryProducts(pdb,callback),() => alert("FAIL: Transaction queryMyProducts"),function() {
        console.log("OK: Transaction queryMyProducts");
      });
    },

    queryProducts: function (db, callback) {
      db.executeSql('SELECT * FROM ProductName ORDER BY name', [],
        (pdb,presults) => this.queryProductsSuccess(pdb,presults,callback), () => alert("FAIL: SELECT FROM ProductName"));
    },

    queryProductsSuccess: function (db,results, callback) {
      if (results != undefined) {
        var len = results.rows.length;
        var data = [];
        var result = "Result:";
        for (let i = 0; i < len; i++) {
          let row = results.rows.item(i);
          data.push({productId: row.product_id, name: row.name});
          result = result + " " + row.name + ";";
        }
        callback(data);
        console.log(result);
        // alert(result);
      }
      else alert("Results is undefined!");
    },

    requestMyProductsList: function (callback) {
      db.transaction((pdb) => this.queryMyProducts(pdb,callback),() => alert("FAIL: Transaction queryMyProducts"),function() {
        console.log("OK: Transaction queryMyProducts");
      });
    },

    queryMyProducts: function (db,callback) {
      db.executeSql('SELECT MyProduct.*, ProductName.name FROM MyProduct, ProductName WHERE ProductName.product_id = MyProduct.fk_product_id', [],
        (pdb,presults) => this.queryMyProductsSuccess(pdb,presults,callback), () => alert("FAIL: SELECT FROM ProductName"));
    },

    queryMyProductsSuccess: function (db,results,callback) {
      if (results != undefined) {
        var len = results.rows.length;
        var data = [];
        var result = "Result:";
        for (let i = 0; i < len; i++) {
          let row = results.rows.item(i);
          data.push({productId: row.fk_product_id, name: row.name, quantity: row.quantity, expireDate: row.expireDate});
          result = result + " " + row.fk_product_id + " " + row.quantity + " " + row.expireDate + " " + row.name + ";";
        }
        callback(data);
        console.log(result);
        // alert(result);
      }
      else alert("Results is undefined!");
    },

    setupDatabase: function (db) {
      var that = this;
      if (RESET_DB)
        db.executeSql('DROP TABLE IF EXISTS Version;', [], () => console.log("OK: DROP TABLE Version"), () => alert("FAIL: DROP TABLE Version"));
      db.executeSql('SELECT 1 FROM Version LIMIT 1', [],
        function () {
          console.log("Database is ready!");
          // alert("Database is ready!");
          db.transaction(that.queryProducts,() => alert("FAIL: Transaction queryProducts"),function() {
            console.log("OK: Transaction queryProducts");
          });
        },
        function (error) {
          console.log("received version error:", error);
          db.transaction(that.createDatabase, () => alert("Could not create database!"), function () {
            console.log("Database created!");
            // alert("Database created!");
            db.transaction(that.queryProducts,() => alert("FAIL: Transaction queryProducts"),function() {
              console.log("OK: Transaction queryProducts");
            });
          });
      });
    },

    createDatabase: function (db) {
      console.log("Trying to create database...");

      db.executeSql('DROP TABLE IF EXISTS ProductName;', [], () => console.log("OK: DROP TABLE ProductName"), () => alert("FAIL: DROP TABLE ProductName"));
      db.executeSql('DROP TABLE IF EXISTS MyProduct;', [], () => console.log("OK: DROP TABLE MyProduct"), () => alert("FAIL: DROP TABLE MyProduct"));

      db.executeSql('CREATE TABLE IF NOT EXISTS Version( '
        + 'version_id INTEGER PRIMARY KEY NOT NULL); ', [], () => console.log("OK: CREATE TABLE Version"), () => alert("FAIL: CREATE TABLE Version"));

      db.executeSql('CREATE TABLE IF NOT EXISTS ProductName( '
        + 'product_id INTEGER PRIMARY KEY AUTOINCREMENT, '
        + 'name VARCHAR(30) ); ', [], () => console.log("OK: CREATE TABLE ProductName"), () => alert("FAIL: CREATE TABLE ProductName"));

      db.executeSql('CREATE TABLE IF NOT EXISTS MyProduct( '
        + 'id INTEGER PRIMARY KEY AUTOINCREMENT, '
        + 'fk_product_id INTEGER, '
        + 'quantity INTEGER, '
        + 'expireDate VARCHAR(10), '
        + 'FOREIGN KEY ( fk_product_id ) REFERENCES ProductName ( product_id )); ', [], () => console.log("OK: CREATE TABLE MyProduct"), () => alert("FAIL: CREATE TABLE MyProduct"));

      db.executeSql('INSERT INTO ProductName (name) VALUES ("Abóbora");', [], () => console.log("OK: Insert ProductName Abóbora"), () => alert("FAIL: Insert ProductName Abóbora"));
      db.executeSql('INSERT INTO ProductName (name) VALUES ("Fraldinha");', [], () => console.log("OK: Insert ProductName Fraldinha"), () => alert("FAIL: Insert ProductName Fraldinha"));

      console.log("Database was created successfully!");
    },

    render: function() {},
});

module.exports = DatabaseManager;<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('homeCtrl', ['$scope', function($scope){
      $scope.title = "Home PAGE";

      $scope.d3OnClick = function(item){
        alert(item.name);
      };
    }]);

}());

(function () {
  'use strict';

  angular.module('RkyApp.controllers')

  .service("Sensors", function($http) {
    this.getSensors = function() {
      return $http.get("/api/v1/name").
        then(function(response) {
          console.log(response);
            return response;
        }, function(response) {
            alert("Error retrieving name of sensors.");
        });
    }
  })

    .controller('listCapteur',['Sensors','$scope' , function(Sensors, $scope) {
        $scope.sensors = Sensors.data;
    }]);

}());

(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('newRky', ['$scope', '$http', function($scope, $http){
      $scope.title = "Listes des Capteurs";
      $scope.capteur = { tag:'', info:'', name:'', unit:''};
      $scope.clickButton = function(){
        alert($scope.capteur.name,'/',$scope.capteur.tag);
        console.log($scope.capteur);
      };

            $scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON
            var data = $.param({
                fName: $scope.firstName,
                lName: $scope.lastName
            });

            var config = {
                headers : {
                    'Content-Type': 'application/json;'
                }
            }

            $http.post('/api/v1/scale', data, config)
            .success(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "
status: " + status +
                    "
headers: " + header +
                    "
config: " + config;
            });
        };

    }]);

}());<commit_msg>sensors<commit_after>(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('homeCtrl', ['$scope', function($scope){
      $scope.title = "Home PAGE";

      $scope.d3OnClick = function(item){
        alert(item.name);
      };
    }]);

}());

(function () {
  'use strict';

  angular.module('RkyApp.controllers')

  .service("Sensors", function($http) {
    this.getSensors = function() {
      return $http.get("/api/v1/name").
        then(function(response) {
          console.log(response);
            return response;
        }, function(response) {
            alert("Error retrieving name of sensors.");
        });
    }
  })

    .controller('listCapteur',['sensors','$scope' , function(sensors, $scope) {
        $scope.sensors = sensors.data;
    }]);

}());

(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('newRky', ['$scope', '$http', function($scope, $http){
      $scope.title = "Listes des Capteurs";
      $scope.capteur = { tag:'', info:'', name:'', unit:''};
      $scope.clickButton = function(){
        alert($scope.capteur.name,'/',$scope.capteur.tag);
        console.log($scope.capteur);
      };

            $scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON
            var data = $.param({
                fName: $scope.firstName,
                lName: $scope.lastName
            });

            var config = {
                headers : {
                    'Content-Type': 'application/json;'
                }
            }

            $http.post('/api/v1/scale', data, config)
            .success(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "
status: " + status +
                    "
headers: " + header +
                    "
config: " + config;
            });
        };

    }]);

}());<|endoftext|>


<commit_before>MyHomeworkSpace.Pages.homework = {
	init: function() {},

	edit: function(id) {
		MHSBridge.default.openModal("loading", {});
		MyHomeworkSpace.API.get("homework/get/" + id, {}, function(data) {
			MHSBridge.default.openModal("homework", data.homework);
		});
	},

	handleNew: function() {
		if (MyHomeworkSpace.Page.current() == "homework" || MyHomeworkSpace.Page.current() == "planner") {
			MyHomeworkSpace.Page.show(MyHomeworkSpace.Page.current());
		}
	},

	markComplete: function(id, complete) {
		MyHomeworkSpace.API.get("homework/get/" + id, {}, function(data) {
			var hwItem = data.homework;
			hwItem.complete = complete;
			MyHomeworkSpace.API.post("homework/edit", hwItem, function(data) {
				// yay
			});
		});
	},

	open: function() {
		MHSBridge.default.render(MHSBridge.default.h(MHSBridge.default.pages.homework.HomeworkPage, {}), document.querySelector("#homework"));
	}
};
<commit_msg>fix homework items in a class's details page not updating when edited<commit_after>MyHomeworkSpace.Pages.homework = {
	init: function() {},

	edit: function(id) {
		MHSBridge.default.openModal("loading", {});
		MyHomeworkSpace.API.get("homework/get/" + id, {}, function(data) {
			MHSBridge.default.openModal("homework", data.homework);
		});
	},

	handleNew: function() {
		if (MyHomeworkSpace.Page.current() == "homework" || MyHomeworkSpace.Page.current() == "planner" || MyHomeworkSpace.Page.current() == "classes") {
			MyHomeworkSpace.Page.show(MyHomeworkSpace.Page.current());
		}
	},

	markComplete: function(id, complete) {
		MyHomeworkSpace.API.get("homework/get/" + id, {}, function(data) {
			var hwItem = data.homework;
			hwItem.complete = complete;
			MyHomeworkSpace.API.post("homework/edit", hwItem, function(data) {
				// yay
			});
		});
	},

	open: function() {
		MHSBridge.default.render(MHSBridge.default.h(MHSBridge.default.pages.homework.HomeworkPage, {}), document.querySelector("#homework"));
	}
};
<|endoftext|>


<commit_before>$(function() {
  var myEmail = decodeURIComponent(window.location.search).split("=")[1];
  console.log(myEmail);
  var cardCount = 1;
  appendSubject()
  $('.showDeckClass').on('click', function() {
      window.location = `/showDecks.html?email=${myEmail}`
  });
  $('.showStudyClass').on('click', function() {
      window.location = `/study.html?email=${myEmail}`
  });
  $('.showPlayClass').on('click', function() {
      window.location = `/play.html?email=${myEmail}`
  });
  $('.showDashboardClass').on('click', function() {
      window.location = `/dashboard.html?email=${myEmail}`
  });

  $('.addCard').on('click', function(event) {
    event.preventDefault();
    ++cardCount;
    $('.card-section').append(`

          <input id="Question-${cardCount}" type="text" class="validate">
          Question

          <input id="Answer-${cardCount}" type="text" class="validate">
          Answer

      `)
  })

  $('.submit-deck').on('click', function(event) {
    event.preventDefault();
    var deckObject = {};
    deckObject.name = $('#NameOfDeck').val();
    deckObject.email = myEmail;
    deckObject.subject = $('#Subject option:selected').val();

    $.post('https://rhinocards.herokuapp.com/deck', deckObject)
      .then(function(data, status) {
        console.log(data);
      })
      .catch(function(error) {
        console.log(error);
      })

    var subject = deckObject.subject;
    for (let i = 0; i < cardCount; i++) {
      var cardFront = $('#Question-' + (i + 1)).val();
      var cardBack = $('#Answer-' + (i + 1)).val();
      var cardObject = {front: cardFront, back: cardBack, name: subject};
      $.post('https://rhinocards.herokuapp.com/flashcard', cardObject)
        .then(function(data, status) {
          console.log(data);
        })
        .catch(function(error) {
          console.log(error);
        })
    }

  })

  // $("form").on("submit", function(event) {
  //     event.preventDefault();
  //     console.log($(this));
  //     console.log($('#NameOfDeck').val())
  //     var myNewDeck = {
  //         subject: $('#Subject').val(),
  //         email: `${myEmail}`,
  //         front: $('#Question').val(),
  //         back: $('#Answer').val(),
  //         name: $('#NameOfDeck').val()
  //     }
  //     $.ajax({
  //         method: "POST",
  //         url: "https://rhinocards.herokuapp.com/deck",
  //         data: JSON.stringify(myNewDeck),
  //         contentType: "application/json"
  //     }).then(response => {
  //         console.log(response)
  //     })
  // });

  let cardPost = {};
  cardPost['email'] = myEmail;
  let subjectPost = {};

  function appendSubject() {
      $.ajax({
          method: 'GET',
          url: 'https://rhinocards.herokuapp.com/subject',
          contentType: 'application/json',
          data: JSON.stringify()
      }).then(function(subject) {
          for (var i = 0; i < subject.length; i++) {
              $('.subjectSelection')
                  .append(`<option class="dropval" id="${subject[i].name}">${subject[i].name}</option>`);
          }
      })
  }

  // $(document).ready(function() {
  //     appendSubject()
  //     $('select').material_select();
  // });

  // $(document).on('click', '.dropval', function() {
  //     var id = $(this).text();
  //     cardPost['name'] = id;
  //     console.log("cardPost", cardPost);
  //     console.log(id)
  // });

  // $("#addDeck").click(function() {
  //     $.ajax({
  //             url: 'https://rhinocards.herokuapp.com/deck',
  //             method: 'POST',
  //             data: JSON.stringify(cardPost),
  //             contentType: 'application/json; charset=utf-8',
  //
  //         })
  //         .then((response) => {
  //             console.log('response', response);
  //         })
  //         .catch((response) => {
  //             console.log('error');
  //         });
  // });
})
<commit_msg>Added dashboard redirect to make deck submission<commit_after>$(function() {
  var myEmail = decodeURIComponent(window.location.search).split("=")[1];
  console.log(myEmail);
  var cardCount = 1;
  appendSubject()
  $('.showDeckClass').on('click', function() {
      window.location = `/showDecks.html?email=${myEmail}`
  });
  $('.showStudyClass').on('click', function() {
      window.location = `/study.html?email=${myEmail}`
  });
  $('.showPlayClass').on('click', function() {
      window.location = `/play.html?email=${myEmail}`
  });
  $('.showDashboardClass').on('click', function() {
      window.location = `/dashboard.html?email=${myEmail}`
  });

  $('.addCard').on('click', function(event) {
    event.preventDefault();
    ++cardCount;
    $('.card-section').append(`

          <input id="Question-${cardCount}" type="text" class="validate">
          Question

          <input id="Answer-${cardCount}" type="text" class="validate">
          Answer

      `)
  })

  $('.submit-deck').on('click', function(event) {
    event.preventDefault();
    var deckObject = {};
    deckObject.name = $('#NameOfDeck').val();
    deckObject.email = myEmail;
    deckObject.subject = $('#Subject option:selected').val();

    $.post('https://rhinocards.herokuapp.com/deck', deckObject)
      .then(function(data, status) {
        console.log(data);
      })
      .catch(function(error) {
        console.log(error);
      })

    var subject = deckObject.subject;
    for (let i = 0; i < cardCount; i++) {
      var cardFront = $('#Question-' + (i + 1)).val();
      var cardBack = $('#Answer-' + (i + 1)).val();
      var cardObject = {front: cardFront, back: cardBack, name: subject};
      $.post('https://rhinocards.herokuapp.com/flashcard', cardObject)
        .then(function(data, status) {
          console.log(data);
        })
        .catch(function(error) {
          console.log(error);
        })
    }
    window.location.href = 'http://flashrhino.com/dashboard.html?email=' + myEmail;
  })

  // $("form").on("submit", function(event) {
  //     event.preventDefault();
  //     console.log($(this));
  //     console.log($('#NameOfDeck').val())
  //     var myNewDeck = {
  //         subject: $('#Subject').val(),
  //         email: `${myEmail}`,
  //         front: $('#Question').val(),
  //         back: $('#Answer').val(),
  //         name: $('#NameOfDeck').val()
  //     }
  //     $.ajax({
  //         method: "POST",
  //         url: "https://rhinocards.herokuapp.com/deck",
  //         data: JSON.stringify(myNewDeck),
  //         contentType: "application/json"
  //     }).then(response => {
  //         console.log(response)
  //     })
  // });

  let cardPost = {};
  cardPost['email'] = myEmail;
  let subjectPost = {};

  function appendSubject() {
      $.ajax({
          method: 'GET',
          url: 'https://rhinocards.herokuapp.com/subject',
          contentType: 'application/json',
          data: JSON.stringify()
      }).then(function(subject) {
          for (var i = 0; i < subject.length; i++) {
              $('.subjectSelection')
                  .append(`<option class="dropval" id="${subject[i].name}">${subject[i].name}</option>`);
          }
      })
  }

  // $(document).ready(function() {
  //     appendSubject()
  //     $('select').material_select();
  // });

  // $(document).on('click', '.dropval', function() {
  //     var id = $(this).text();
  //     cardPost['name'] = id;
  //     console.log("cardPost", cardPost);
  //     console.log(id)
  // });

  // $("#addDeck").click(function() {
  //     $.ajax({
  //             url: 'https://rhinocards.herokuapp.com/deck',
  //             method: 'POST',
  //             data: JSON.stringify(cardPost),
  //             contentType: 'application/json; charset=utf-8',
  //
  //         })
  //         .then((response) => {
  //             console.log('response', response);
  //         })
  //         .catch((response) => {
  //             console.log('error');
  //         });
  // });
})
<|endoftext|>


<commit_before>(function() {
  angular.module('pokedex.services', [])
    .factory('pokemonService', ['$http', '$q', '$filter', function($http, $q, $filter) {
      var normalize = $filter('normalize');

      function all() {
      	var deferred = $q.defer();

      	$http.get('/data/pokemons.json')
      	  .success(function(data) {
            deferred.resolve(data);
      	  });

      	return deferred.promise;
      }

      function byName(name) {
        name = normalize(name);
      	var deferred = $q.defer();

        all().then(function(data) {
          var results = data.filter(function(pokemon) {
          	return normalize(pokemon.name) === name;
          });

          if (results.length > 0) {
          	deferred.resolve(results[0]);
          } else {
          	deferred.reject();
          }
        });

        return deferred.promise;
      }

      function byType(type) {
        type = normalize(type);
        var deferred = $q.defer();

        all().then(function(data) {
          var results = data.filter(function(pokemon) {
            return pokemon.type.some(function(t) {
              return normalize(t) === type;
            });
          });

          deferred.resolve(results);
        });

        return deferred.promise;
      }

      return {
      	all: all,
      	byName: byName,
        byType: byType
      };
    }])
})();<commit_msg>Add local storage to pokemon service.<commit_after>(function() {
  angular.module('pokedex.services', [])
    .factory('pokemonService', ['$http', '$q', '$filter', '$window', function($http, $q, $filter, $window) {
      var localStorage = $window.localStorage;
      var normalize = $filter('normalize');

      function all() {
      	var deferred = $q.defer();

      	$http.get('/data/pokemons.json')
      	  .success(function(data) {
            deferred.resolve(data);
      	  });

      	return deferred.promise;
      }

      function byName(name) {
        name = normalize(name);
      	var deferred = $q.defer();

        all().then(function(data) {
          var results = data.filter(function(pokemon) {
          	return normalize(pokemon.name) === name;
          });

          if (results.length > 0) {
          	deferred.resolve(results[0]);
          } else {
          	deferred.reject();
          }
        });

        return deferred.promise;
      }

      function byType(type) {
        type = normalize(type);
        var deferred = $q.defer();

        all().then(function(data) {
          var results = data.filter(function(pokemon) {
            return pokemon.type.some(function(t) {
              return normalize(t) === type;
            });
          });

          deferred.resolve(results);
        });

        return deferred.promise;
      }

      function saveComment(pokemon, comment) {
        var comments = getComments(pokemon);

        comments.push(comment);
        localStorage.setItem(pokemon, JSON.stringify(comments));
      }

      function getComments(pokemon) {
        var comments = localStorage.getItem(pokemon);

        if (!comments) {
          comments = [];
        } else {
          comments = JSON.parse(comments);
        }

        return comments;
      }

      return {
      	all: all,
      	byName: byName,
        byType: byType,
        saveComment: saveComment,
        getComments: getComments
      };
    }])
})();<|endoftext|>


<commit_before>"use strict";

(function () {
    angular
        .module("argo")
        .directive("argoCharts", argoCharts);

    argoCharts.$inject = [];
    function argoCharts() {
        var directive = {
            restrict: "E",
            scope: {
                instrument: "=",
                granularity: "=",
                data: "=",
                feed: "=",
                trades: "="
            },
            link: link
        };

        return directive;

        function link(scope, element) {
            var myInstrument,
                myGranularity,
                data,
                lastHistUpdate,
                lastData,
                lastClose,
                feedVolume = 0,
                refreshChart;

            scope.$watch("data", function (csv) {
                if (csv && csv.length > 0) {
                    myInstrument = scope.instrument;
                    myGranularity = scope.granularity;

                    data = d3.csvParse(csv).map(function (d) {
                        return {
                            date: new Date(d.Date),
                            o: +d.Open,
                            h: +d.High,
                            l: +d.Low,
                            c: +d.Close,
                            v: +d.Volume
                        };
                    });
                    data = data.slice(data.length - 130, data.length);

                    refreshChart = ohlcChart(element[0], data);

                    lastData = data && data[data.length - 1];
                    lastClose = lastData.c;
                    feedVolume = lastData.v;
                    lastHistUpdate = getLastHistUpdate(myGranularity);
                }
            });

            scope.$watch("feed", function (feed) {
                var tick = feed[myInstrument],
                    nextHistUpdate = getLastHistUpdate(myGranularity, tick),
                    midPrice;

                if (tick && data && lastHistUpdate !== nextHistUpdate) {
                    data.shift();
                    midPrice = (tick.bid + tick.ask) / 2;
                    feedVolume = 0;
                    data.push({
                        o: midPrice,
                        c: midPrice,
                        h: midPrice,
                        l: midPrice,
                        date: new Date(nextHistUpdate),
                        v: feedVolume
                    });

                    lastHistUpdate = nextHistUpdate;
                }

                if (tick && data) {

                    if (lastData.c !== lastClose) {
                        feedVolume += 1;
                    }

                    midPrice = (tick.bid + tick.ask) / 2;

                    lastData = data && data[data.length - 1];
                    lastClose = lastData.c;
                    lastData.c = midPrice;
                    lastData.v = feedVolume;

                    if (lastData.c > lastData.h) {
                        lastData.h = lastData.c;
                    }

                    if (lastData.c < lastData.l) {
                        lastData.l = lastData.c;
                    }

                    refreshChart();
                }

            }, true);

            function getLastHistUpdate(granularity, tick) {
                var time = tick && tick.time,
                    now = time ? new Date(time) : new Date(),
                    coeff;

                if (granularity === "S5") {
                    coeff = 1000 * 5;
                } else if (granularity === "S10") {
                    coeff = 1000 * 10;
                } else if (granularity === "S15") {
                    coeff = 1000 * 15;
                } else if (granularity === "S30") {
                    coeff = 1000 * 30;
                } else if (granularity === "M1") {
                    coeff = 1000 * 60;
                } else if (granularity === "M2") {
                    coeff = 1000 * 60 * 2;
                } else if (granularity === "M3") {
                    coeff = 1000 * 60 * 3;
                } else if (granularity === "M4") {
                    coeff = 1000 * 60 * 4;
                } else if (granularity === "M5") {
                    coeff = 1000 * 60 * 5;
                } else if (granularity === "M10") {
                    coeff = 1000 * 60 * 10;
                } else if (granularity === "M15") {
                    coeff = 1000 * 60 * 15;
                } else if (granularity === "M30") {
                    coeff = 1000 * 60 * 30;
                } else if (granularity === "H1") {
                    coeff = 1000 * 60 * 60;
                } else if (granularity === "H2") {
                    coeff = 1000 * 60 * 60 * 2;
                } else if (granularity === "H3") {
                    coeff = 1000 * 60 * 60 * 3;
                } else if (granularity === "H4") {
                    coeff = 1000 * 60 * 60 * 4;
                } else if (granularity === "H6") {
                    coeff = 1000 * 60 * 60 * 6;
                } else if (granularity === "H8") {
                    coeff = 1000 * 60 * 60 * 8;
                } else if (granularity === "H12") {
                    coeff = 1000 * 60 * 60 * 12;
                } else {
                    // for D / W / M
                    coeff = 1000 * 60 * 60 * 12;
                }

                return Math.floor(now / (coeff)) * coeff;
            }

            function ohlcChart(el, myData) {
                var margin = {
                        top: 0,
                        right: 75,
                        bottom: 30,
                        left: 75
                    },
                    width = 960 - margin.left - margin.right,
                    height = 400 - margin.top - margin.bottom,
                    svg;

                d3.select(el).select("svg").remove();
                svg = d3.select(el).append("svg")
                    .attr("height", height + margin.top + margin.bottom)
                    .attr("width", width + margin.right + margin.left)
                    .append("g")
                    .attr("transform", "translate(" +
                        margin.left + "," + margin.top + ")");

                redraw();

                function redraw() {
                    var ocWidth = 3,
                        bars,
                        x,
                        xTicks,
                        xAxis,
                        y,
                        yAxis;

                    svg.selectAll("*").remove();

                    x = d3.scaleLinear()
                            .range([0, width]).domain([0, myData.length]);
                    xTicks = d3.scaleTime().range([0, width]).domain([
                        myData[0].date, myData[myData.length - 1].date
                    ]);

                    y = d3.scaleLinear().range([height, 0]).domain([
                        (d3.min(myData, function (d) {
                            return d.l;
                        })),
                        (d3.max(myData, function (d) {
                            return d.h;
                        }))
                    ]);

                    xAxis = function () {
                        return d3.axisBottom(xTicks);
                    };

                    yAxis = function () {
                        return d3.axisRight(y);
                    };

                    svg.append("g").attr("class", "grid")
                        .call(xAxis().tickSize(height, 0, 0).tickFormat(""));

                    svg.append("g")
                        .attr("class", "x axis")
                        .attr("transform", "translate(0, " + height + ")")
                        .call(xAxis());

                    svg.append("g").attr("class", "grid")
                        .call(yAxis().tickSize(width, 0, 0).tickFormat(""));

                    svg.append("g").attr("class", "y axis")
                        .attr("transform", "translate(" + width + ", 0)")
                        .call(yAxis());

                    bars = svg.selectAll(".bar")
                        .data(myData).enter().append("g")
                        .attr("class", function (d) {
                            return "bar " + (d.c > d.o ? "green" : "red");
                        });

                    bars.append("path").attr("class", "hl-line")
                        .attr("d", function (d, ndx) {
                            return "M" + x(ndx) + "," + y(d.h) +
                                " L" + x(ndx) + "," + y(d.l);
                        });

                    bars.append("path").attr("class", "c-tick")
                        .attr("d", function (d, ndx) {
                            return "M" + x(ndx) + "," + y(d.c) + " L" +
                                (x(ndx) + ocWidth) + "," + y(d.c);
                        });

                    bars.append("path").attr("class", "o-tick")
                        .attr("d", function (d, ndx) {
                            return "M" + (x(ndx) - ocWidth) + "," +
                                y(d.o) + " L" + x(ndx) + "," + y(d.o);
                        });

                    bars.exit().remove();

                    svg.append("g")
                            .attr("class", "y axis")
                        .append("text")
                            .attr("transform", "rotate(-90)")
                            .attr("y", 6)
                            .attr("dy", ".71em")
                            .style("font-weight", "bold")
                            .style("text-anchor", "end")
                            .text("Price (" +
                                myInstrument + " / " + myGranularity + ")");
                }

                return redraw;
            }

        }
    }

}());
<commit_msg>fix(charts): refresh only last bar in OHLC chart<commit_after>"use strict";

(function () {
    angular
        .module("argo")
        .directive("argoCharts", argoCharts);

    argoCharts.$inject = [];
    function argoCharts() {
        var directive = {
            restrict: "E",
            scope: {
                instrument: "=",
                granularity: "=",
                data: "=",
                feed: "=",
                trades: "="
            },
            link: link
        };

        return directive;

        function link(scope, element) {
            var myInstrument,
                myGranularity,
                data,
                lastHistUpdate,
                lastData,
                lastClose,
                feedVolume = 0,
                refreshChart;

            scope.$watch("data", function (csv) {
                if (csv && csv.length > 0) {
                    myInstrument = scope.instrument;
                    myGranularity = scope.granularity;

                    data = d3.csvParse(csv).map(function (d) {
                        return {
                            date: new Date(d.Date),
                            o: +d.Open,
                            h: +d.High,
                            l: +d.Low,
                            c: +d.Close,
                            v: +d.Volume
                        };
                    });
                    data = data.slice(data.length - 130, data.length);

                    refreshChart = ohlcChart(element[0], data);

                    lastData = data && data[data.length - 1];
                    lastClose = lastData.c;
                    feedVolume = lastData.v;
                    lastHistUpdate = getLastHistUpdate(myGranularity);
                }
            });

            scope.$watch("feed", function (feed) {
                var tick = feed[myInstrument],
                    nextHistUpdate = getLastHistUpdate(myGranularity, tick),
                    midPrice;

                if (tick && data && lastHistUpdate !== nextHistUpdate) {
                    data.shift();
                    midPrice = (tick.bid + tick.ask) / 2;
                    feedVolume = 0;
                    data.push({
                        o: midPrice,
                        c: midPrice,
                        h: midPrice,
                        l: midPrice,
                        date: new Date(nextHistUpdate),
                        v: feedVolume
                    });

                    lastHistUpdate = nextHistUpdate;
                    refreshChart(true);
                }

                if (tick && data) {

                    if (lastData.c !== lastClose) {
                        feedVolume += 1;
                    }

                    midPrice = (tick.bid + tick.ask) / 2;

                    lastData = data && data[data.length - 1];
                    lastClose = lastData.c;
                    lastData.c = midPrice;
                    lastData.v = feedVolume;

                    if (lastData.c > lastData.h) {
                        lastData.h = lastData.c;
                    }

                    if (lastData.c < lastData.l) {
                        lastData.l = lastData.c;
                    }

                    refreshChart(false);
                }

            }, true);

            function getLastHistUpdate(granularity, tick) {
                var time = tick && tick.time,
                    now = time ? new Date(time) : new Date(),
                    coeff;

                if (granularity === "S5") {
                    coeff = 1000 * 5;
                } else if (granularity === "S10") {
                    coeff = 1000 * 10;
                } else if (granularity === "S15") {
                    coeff = 1000 * 15;
                } else if (granularity === "S30") {
                    coeff = 1000 * 30;
                } else if (granularity === "M1") {
                    coeff = 1000 * 60;
                } else if (granularity === "M2") {
                    coeff = 1000 * 60 * 2;
                } else if (granularity === "M3") {
                    coeff = 1000 * 60 * 3;
                } else if (granularity === "M4") {
                    coeff = 1000 * 60 * 4;
                } else if (granularity === "M5") {
                    coeff = 1000 * 60 * 5;
                } else if (granularity === "M10") {
                    coeff = 1000 * 60 * 10;
                } else if (granularity === "M15") {
                    coeff = 1000 * 60 * 15;
                } else if (granularity === "M30") {
                    coeff = 1000 * 60 * 30;
                } else if (granularity === "H1") {
                    coeff = 1000 * 60 * 60;
                } else if (granularity === "H2") {
                    coeff = 1000 * 60 * 60 * 2;
                } else if (granularity === "H3") {
                    coeff = 1000 * 60 * 60 * 3;
                } else if (granularity === "H4") {
                    coeff = 1000 * 60 * 60 * 4;
                } else if (granularity === "H6") {
                    coeff = 1000 * 60 * 60 * 6;
                } else if (granularity === "H8") {
                    coeff = 1000 * 60 * 60 * 8;
                } else if (granularity === "H12") {
                    coeff = 1000 * 60 * 60 * 12;
                } else {
                    // for D / W / M
                    coeff = 1000 * 60 * 60 * 12;
                }

                return Math.floor(now / (coeff)) * coeff;
            }

            function ohlcChart(el, myData) {
                var margin = {
                        top: 0,
                        right: 60,
                        bottom: 30,
                        left: 90
                    },
                    width = 960 - margin.left - margin.right,
                    height = 400 - margin.top - margin.bottom,
                    svg;

                d3.select(el).select("svg").remove();
                svg = d3.select(el).append("svg")
                    .attr("height", height + margin.top + margin.bottom)
                    .attr("width", width + margin.right + margin.left)
                    .append("g")
                    .attr("transform", "translate(" +
                        margin.left + "," + margin.top + ")");

                redraw(true);

                function redraw(isShiftingBars) {
                    var ocWidth = 3,
                        bars,
                        x,
                        xAxis,
                        y,
                        yAxis;

                    svg.selectAll(".grid").remove();
                    svg.selectAll(".x.axis").remove();
                    svg.selectAll(".y.axis").remove();
                    if (isShiftingBars) {
                        svg.selectAll(".bar").remove();
                    } else {
                        svg.select(".lastBar").remove();
                    }

                    x = d3.scaleLinear()
                            .range([0, width]).domain([0, myData.length]);

                    y = d3.scaleLinear().range([height, 0]).domain([
                        (d3.min(myData, function (d) {
                            return d.l;
                        })),
                        (d3.max(myData, function (d) {
                            return d.h;
                        }))
                    ]);

                    xAxis = function () {
                        var xTicks = d3.scaleTime().range([0, width]).domain([
                            myData[0].date, myData[myData.length - 1].date
                        ]);

                        return d3.axisBottom(xTicks);
                    };

                    yAxis = function () {
                        return d3.axisRight(y);
                    };

                    svg.append("g").attr("class", "grid")
                        .call(xAxis().tickSize(height, 0, 0).tickFormat(""));

                    svg.append("g")
                        .attr("class", "x axis")
                        .attr("transform", "translate(0, " + height + ")")
                        .call(xAxis());

                    svg.append("g").attr("class", "grid")
                        .call(yAxis().tickSize(width, 0, 0).tickFormat(""));

                    svg.append("g").attr("class", "y axis")
                        .attr("transform", "translate(" + width + ", 0)")
                        .call(yAxis());

                    bars = svg.selectAll(".bar").data(myData)
                        .enter().append("g")
                        .attr("class", function (d, i) {
                            var lastBar = i === myData.length - 1,
                                attr = "bar " + (d.c > d.o ? "green" : "red");

                            attr += lastBar ? " lastBar" : "";

                            return attr;
                        });

                    bars.append("path").attr("class", "path hl-line")
                        .attr("d", function (d, i) {
                            return "M" + x(i) + "," + y(d.h) +
                                " L" + x(i) + "," + y(d.l);
                        });

                    bars.append("path").attr("class", "path c-tick")
                        .attr("d", function (d, i) {
                            return "M" + x(i) + "," + y(d.c) +
                                " L" + (x(i) + ocWidth) + "," + y(d.c);
                        });

                    bars.append("path").attr("class", "path o-tick")
                        .attr("d", function (d, i) {
                            return "M" + (x(i) - ocWidth) + "," + y(d.o) +
                                " L" + x(i) + "," + y(d.o);
                        });

                    svg.append("g")
                            .attr("class", "y axis")
                        .append("text")
                            .attr("transform", "rotate(-90)")
                            .attr("y", 6)
                            .attr("dy", ".71em")
                            .style("font-weight", "bold")
                            .style("text-anchor", "end")
                            .text("Price (" +
                                myInstrument + " / " + myGranularity + ")");
                }

                return redraw;
            }

        }
    }

}());
<|endoftext|>


<commit_before>const fs = require('fs');
const discord = require('discord.js');
const config = require('../config/config.json');
const alias = require('../events/message.js').alias;

exports.run = async (bot, msg, args) => {
    const embedClass = require('../classes/embedMessage.js');
    let embedMessage = new embedClass(msg);

    if (args[0]) {
        msg.delete();
        if (args[0].toLowerCase() === 'fun') {
            let comm = [];
            fs.readdir('./commands/', (err, files) => {
                if (err) {
                    logger.error(err);
                }
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'fun') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`);
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend,
                    color: 0x1FBAED
                });
            });
        } else if (args[0].toLowerCase() === 'util') {
            let comm = [];
            fs.readdir('./commands/', (err, files) => {
                if (err) {
                    logger.error(err);
                }
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'util') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`);
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend,
                    color: 0x1FBAED
                });
            });
        } else if (args[0].toLowerCase() === 'moderation') {
            let comm = [];
            fs.readdir('./commands/', (err, files) => {
                if (err) {
                    logger.error(err);
                }
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'moderation') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`);
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend,
                    color: 0x1FBAED
                });
            });
        } else if (args[0].toLowerCase() === 'music') {
            let comm = [];
            fs.readdir('./commands/', (err, files) => {
                if (err) {
                    logger.error(err);
                }
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'music') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`);
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend,
                    color: 0x1FBAED
                });
            });
        } else {
            try {
                let cmd = require('./' + args[0]);
                let help = cmd.help;
                let usageCheck = help.usage === true ? help.usage : '';
                let usage = config.PREFIX + args[0] + ' ' + usageCheck;
                let detail = help.detail;
                let alias3 = help.alias.join(', ');
                let embed = new discord.RichEmbed()
                    .setTitle('Command Information | ' + args[0])
                    .setDescription(detail)
                    .addField('Usage', usage)
                    .addField('Alias', alias3 ? alias3 : 'None')
                    .setTimestamp()
                    .setFooter(bot.user.username);
                if (help.example) {
                    embed.addField('Example', '`' + config.PREFIX + args[0] + ' ' + help.example + '`');
                }
                msg.channel.send({embed});
            } catch (err) {
                if (alias[args[0]]) {
                    let cmd = require('./' + alias[args[0]] + '.js');
                    let help = cmd.help;
                    let usageCheck = help.usage === true ? help.usage : '';
                    let usage = config.PREFIX + args[0] + ' ' + usageCheck;
                    let detail = help.detail;
                    let alias2 = help.alias.join(', ');
                    let embed = new discord.RichEmbed()
                        .setTitle('Command Information | ' + alias[args[0]])
                        .setDescription(detail)
                        .addField('Usage', usage)
                        .addField('Alias', alias2 ? alias2 : 'None')
                        .setTimestamp()
                        .setFooter(bot.user.username);
                    if (help.example) {
                        embed.addField('Example', '`' + config.PREFIX + alias[args[0]] + ' ' + help.example + '`');
                    }
                    msg.channel.send({embed});
                } else {
                    msg.channel.send(`:x: ${config.PREFIX}${args[0]} is not a command`);
                }
            }
        }
    } else {
        msg.delete();
        let count = 0;
        // Let batch = '';
        let funCat = [];
        let utilCat = [];
        let modCat = [];
        let musicCat = [];
        fs.readdir('./commands/', (err, files) => {
            if (err) {
                return logger.error(err);
            }
            files.forEach(file => {
                let help = '';
                count++;
                let helpInfo = require('./' + file);
                let helpName = file.split('.')[0];
                let info = helpInfo.help;
                let description = info.description;
                if (info.category === 'fun') {
                    funCat.push(`**${config.PREFIX}${helpName}** ${description}`);
                } else if (info.category === 'util') {
                    utilCat.push(`**${config.PREFIX}${helpName}** ${description}`);
                } else if (info.category === 'moderation') {
                    modCat.push(`**${config.PREFIX}${helpName}** ${description}`);
                } else if (info.category === 'music') {
                    musicCat.push(`**${config.PREFIX}${helpName}** ${description}`);
                }
            });
            // TODO: More checks if we ever have too many commands lol
            if ((funCat.join() + utilCat.join() + modCat.join() + musicCat.join()).length > 1950) {
                if ((funCat.join() + utilCat.join()).length > 1950) {
                    const embed = new discord.RichEmbed()
                        .addField('Fun Commands', funCat.join('\n'))
                        .setColor('#1FBAED');
                    if ((utilCat.join() + modCat.join() + musicCat.join()).length < 1950) {
                        const embed2 = new discord.RichEmbed()
                            .addField('Util Commands', utilCat.join('\n'))
                            .addField('Moderation Commands', modCat.join('\n'))
                            .addField('Music Commands', musicCat.join('\n') ? musicCat.join('\n') : 'None')
                            .setColor('#1FBAED');

                        msg.channel.send({embed});
                        msg.channel.send({embed: embed2});
                    } else {
                        msg.channel.send({embed});
                    }
                } else {
                    const embed = new discord.RichEmbed()
                        .addField('Fun Commands', funCat.join('\n'))
                        .addField('Util Commands', utilCat.join('\n'))
                        .setColor('#1FBAED');
                    const embed2 = new discord.RichEmbed()
                        .addField('Moderation Commands', modCat.join('\n'))
                        .addField('Music Commands', musicCat.join('\n') ? musicCat.join('\n') : 'None')
                        .setColor('#1FBAED');

                    msg.channel.send({embed});
                    msg.channel.send({embed: embed2});
                }
            } else {
                const embed = new discord.RichEmbed()
                    .addField('Fun Commands', funCat.join('\n'))
                    .addField('Util Commands', utilCat.join('\n'))
                    .addField('Moderation Commands', modCat.join('\n'))
                    .addField('Music Commands', musicCat.join('\n') ? musicCat.join('\n') : 'None')
                    .setColor('#1FBAED');
                msg.channel.send({embed});
            }
        });
    }
};

exports.help = {
    category: 'util',
    usage: '[command Name]',
    description: 'shows the commands',
    detail: 'shows the commands',
    botPerm: ['SEND_MESSAGES', 'EMBED_LINKS'],
    authorPerm: [],
    alias: [
        'h',
        'halp'
    ]
};
<commit_msg>Fixed whole help now displaying the usage<commit_after>const fs = require('fs');
const discord = require('discord.js');
const config = require('../config/config.json');
const alias = require('../events/message.js').alias;

exports.run = async (bot, msg, args) => {
    const embedClass = require('../classes/embedMessage.js');
    let embedMessage = new embedClass(msg);

    if (args[0]) {
        msg.delete();
        if (args[0].toLowerCase() === 'fun') {
            let comm = [];
            fs.readdir('./commands/', (err, files) => {
                if (err) {
                    logger.error(err);
                }
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'fun') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`);
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend,
                    color: 0x1FBAED
                });
            });
        } else if (args[0].toLowerCase() === 'util') {
            let comm = [];
            fs.readdir('./commands/', (err, files) => {
                if (err) {
                    logger.error(err);
                }
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'util') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`);
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend,
                    color: 0x1FBAED
                });
            });
        } else if (args[0].toLowerCase() === 'moderation') {
            let comm = [];
            fs.readdir('./commands/', (err, files) => {
                if (err) {
                    logger.error(err);
                }
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'moderation') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`);
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend,
                    color: 0x1FBAED
                });
            });
        } else if (args[0].toLowerCase() === 'music') {
            let comm = [];
            fs.readdir('./commands/', (err, files) => {
                if (err) {
                    logger.error(err);
                }
                files.forEach(file => {
                    let info = require('./' + file);
                    if (info.help.category === 'music') {
                        comm.push(`**${config.PREFIX}${file.split('.')[0]}** ${info.help.description}`);
                    }
                });
                let toSend = comm.join('\n');
                embedMessage.descEmbed({
                    type: 'desc',
                    content: toSend,
                    color: 0x1FBAED
                });
            });
        } else {
            try {
                let cmd = require('./' + args[0]);
                let help = cmd.help;
                let usageCheck = cmd.help.usage ? cmd.help.usage : '';
                let usage = config.PREFIX + args[0] + ' ' + usageCheck;
                let detail = help.detail;
                let alias3 = help.alias.join(', ');
                let embed = new discord.RichEmbed()
                    .setTitle('Command Information | ' + args[0])
                    .setDescription(detail)
                    .addField('Usage', usage)
                    .addField('Alias', alias3 ? alias3 : 'None')
                    .setTimestamp()
                    .setColor(0xb7c767)
                    .setFooter(bot.user.username);
                if (help.example) {
                    embed.addField('Example', '`' + config.PREFIX + args[0] + ' ' + help.example + '`');
                }
                msg.channel.send({embed});
            } catch (err) {
                if (alias[args[0]]) {
                    let cmd = require('./' + alias[args[0]] + '.js');
                    let help = cmd.help;
                    let usageCheck = cmd.help.usage ? cmd.help.usage : '';
                    let usage = config.PREFIX + args[0] + ' ' + usageCheck;
                    let detail = help.detail;
                    let alias2 = help.alias.join(', ');
                    let embed = new discord.RichEmbed()
                        .setTitle('Command Information | ' + alias[args[0]])
                        .setDescription(detail)
                        .addField('Usage', usage)
                        .setColor(0xb7c767)
                        .addField('Alias', alias2 ? alias2 : 'None')
                        .setTimestamp()
                        .setFooter(bot.user.username);
                    if (help.example) {
                        embed.addField('Example', '`' + config.PREFIX + alias[args[0]] + ' ' + help.example + '`');
                    }
                    msg.channel.send({embed});
                } else {
                    msg.channel.send(`:x: ${config.PREFIX}${args[0]} is not a command`);
                }
            }
        }
    } else {
        msg.delete();
        let count = 0;
        // Let batch = '';
        let funCat = [];
        let utilCat = [];
        let modCat = [];
        let musicCat = [];
        fs.readdir('./commands/', (err, files) => {
            if (err) {
                return logger.error(err);
            }
            files.forEach(file => {
                let help = '';
                count++;
                let helpInfo = require('./' + file);
                let helpName = file.split('.')[0];
                let info = helpInfo.help;
                let description = info.description;
                if (info.category === 'fun') {
                    funCat.push(`**${config.PREFIX}${helpName}** ${description}`);
                } else if (info.category === 'util') {
                    utilCat.push(`**${config.PREFIX}${helpName}** ${description}`);
                } else if (info.category === 'moderation') {
                    modCat.push(`**${config.PREFIX}${helpName}** ${description}`);
                } else if (info.category === 'music') {
                    musicCat.push(`**${config.PREFIX}${helpName}** ${description}`);
                }
            });
            // TODO: More checks if we ever have too many commands lol
            if ((funCat.join() + utilCat.join() + modCat.join() + musicCat.join()).length > 1950) {
                if ((funCat.join() + utilCat.join()).length > 1950) {
                    const embed = new discord.RichEmbed()
                        .addField('Fun Commands', funCat.join('\n'))
                        .setColor('#1FBAED');
                    if ((utilCat.join() + modCat.join() + musicCat.join()).length < 1950) {
                        const embed2 = new discord.RichEmbed()
                            .addField('Util Commands', utilCat.join('\n'))
                            .addField('Moderation Commands', modCat.join('\n'))
                            .addField('Music Commands', musicCat.join('\n') ? musicCat.join('\n') : 'None')
                            .setColor('#1FBAED');

                        msg.channel.send({embed});
                        msg.channel.send({embed: embed2});
                    } else {
                        msg.channel.send({embed});
                    }
                } else {
                    const embed = new discord.RichEmbed()
                        .addField('Fun Commands', funCat.join('\n'))
                        .addField('Util Commands', utilCat.join('\n'))
                        .setColor('#1FBAED');
                    const embed2 = new discord.RichEmbed()
                        .addField('Moderation Commands', modCat.join('\n'))
                        .addField('Music Commands', musicCat.join('\n') ? musicCat.join('\n') : 'None')
                        .setColor('#1FBAED');

                    msg.channel.send({embed});
                    msg.channel.send({embed: embed2});
                }
            } else {
                const embed = new discord.RichEmbed()
                    .addField('Fun Commands', funCat.join('\n'))
                    .addField('Util Commands', utilCat.join('\n'))
                    .addField('Moderation Commands', modCat.join('\n'))
                    .addField('Music Commands', musicCat.join('\n') ? musicCat.join('\n') : 'None')
                    .setColor('#1FBAED');
                msg.channel.send({embed});
            }
        });
    }
};

exports.help = {
    category: 'util',
    usage: '[command Name]',
    description: 'shows the commands',
    detail: 'shows the commands',
    botPerm: ['SEND_MESSAGES', 'EMBED_LINKS'],
    authorPerm: [],
    alias: [
        'h',
        'halp'
    ]
};
<|endoftext|>


<commit_before><commit_msg>IMCMS-134 - Text History adjustments: Added DateFormat library to fix date formatting in all browsers.<commit_after><|endoftext|>


<commit_before>//RANDOMIZE returns a random integer between 'min' - 'max', but will not return 'not'.
function randomize(min, max, not = NaN, identifier = 'none set') {
    var loopBreak = 0;
    var loopStop = 100;
    //throw errors if input is no good
    console.assert(min<max, 'Please place the greater value in the "max" perameter')
    console.assert(typeof not === 'number', '3rd Parameter - "not" - must be a number')
    console.assert(typeof identifier === 'string', '4th Parameter - "identifier" -  must be a string')
    do {
        //Pick a number
        var randomNumber = Math.floor(Math.random() * (max - min + 1) + min);
        loopBreak++;
    } while (loopBreak < loopStop && randomNumber === not);
        //write error if randomNumber still === not
        console.assert(randomNumber !== not, 'Randomized number equals "not" - randomize function - identifier = ' + identifier)
    if (randomNumber !== not) {
        return randomNumber;
    } else {
        //Return error if Infinite loop has been prevented
        console.log('Randomization Loop Ended on attempt # ' + loopBreak + ' | min = ' + min + ' | max = ' + max + ' | not =' + not);
        return min
    }
}
<commit_msg>Improved error information<commit_after>//RANDOMIZE returns a random integer between 'min' - 'max', but will not return 'not'.
function randomize(min = 0, max = 1, not = NaN, identifier = 'none set') {
    var loopBreak = 0;
    var loopStop = 100;
    //throw errors if input is no good
    console.assert(min <= max, 'Please place the greater value in the "max" perameter | min = ' + min + ' | max = ' + max + ' | not =' + not + ' | identifier = ' + identifier)
    console.assert(typeof not === 'number', '3rd Parameter - "not" - must be a number | min = ' + min + ' | max = ' + max + ' | not =' + not + ' | identifier = ' + identifier)
    console.assert(typeof identifier === 'string', '4th Parameter - "identifier" -  must be a string | min = ' + min + ' | max = ' + max + ' | not =' + not + ' | identifier = ' + identifier)
    do {
        //Pick a number
        var randomNumber = Math.floor(Math.random() * (max - min + 1) + min);
        loopBreak++;
    } while (loopBreak < loopStop && randomNumber === not);
    //write error if randomNumber still === not
    console.assert(randomNumber !== not, 'Randomized number equals "not" - randomize function | min = ' + min + ' | max = ' + max + ' | not =' + not + ' | identifier = ' + identifier)
    if (randomNumber !== not) {
        return randomNumber;
    } else {
        //Return error if Infinite loop has been prevented
        console.log('Randomization Loop Ended on attempt # ' + loopBreak + ' | min = ' + min + ' | max = ' + max + ' | not =' + not);
        return min
    }
}
<|endoftext|>


<commit_before>(function (angular, undefined) {
	'user strict';

	var url = 'http://pokeapi.co/';
	angular.module('pokeApp')
	.constant('API',
		{
			rattata: 	url + 'api/v1/pokemon/19/'
		  ,	charmander: url + 'api/v1/pokemon/4/'
		  ,	wartortle: 	url + 'api/v1/pokemon/8/'
		  , blastoise: 	url + 'api/v1/pokemon/9/'
		  , caterpie: 	url + 'api/v1/pokemon/10/'
		  , metapod: 	url + 'api/v1/pokemon/11/'
		  , butterfree: url + 'api/v1/pokemon/12/'
		  ,	spearow: 	url + 'api/v1/pokemon/21/'
		  ,	kakuna: 	url + 'api/v1/pokemon/14/'
		  ,	beedrill: 	url + 'api/v1/pokemon/15/'
		  ,	pidgey: 	url + 'api/v1/pokemon/16/'
		  ,	raticate: 	url + 'api/v1/pokemon/20/'
		  ,	fearow: 	url + 'api/v1/pokemon/22/'
		  ,	pikachu: 	url + 'api/v1/pokemon/25/'
		  ,	arbok: 		url + 'api/v1/pokemon/24/'
		  ,	ekans: 		url + 'api/v1/pokemon/23/'
		  ,	nidorina: 	url + 'api/v1/pokemon/30/'
		  ,	sandshrew: 	url + 'api/v1/pokemon/27/'
		  ,	nidoranm: 	url + 'api/v1/pokemon/32/'
		  ,	nidoranf: 	url + 'api/v1/pokemon/29/'
		  ,	clefabe: 	url + 'api/v1/pokemon/36/'
		  ,	jigglypuff: url + 'api/v1/pokemon/39/'
		  ,	vulpix: 	url + 'api/v1/pokemon/37/'
		  ,	ninetales: 	url + 'api/v1/pokemon/38/'
		  ,	zubat: 		url + 'api/v1/pokemon/41/'
		  ,	venonat: 	url + 'api/v1/pokemon/48/'
		  ,	meowth: 	url + 'api/v1/pokemon/52/'
		  ,	oddish: 	url + 'api/v1/pokemon/43/'
		  ,	gloom: 		url + 'api/v1/pokemon/44/'
		  ,	vileplume: 	url + 'api/v1/pokemon/45/'
		  ,	paras: 		url + 'api/v1/pokemon/46/'
		  ,	parasect: 	url + 'api/v1/pokemon/47/'
		  ,	venomoth: 	url + 'api/v1/pokemon/49/'
		  ,	diglett: 	url + 'api/v1/pokemon/50/'
		  ,	dugtrio: 	url + 'api/v1/pokemon/51/'
		  ,	persian: 	url + 'api/v1/pokemon/53/'
		  ,	psyduck: 	url + 'api/v1/pokemon/54/'
		  ,	mankey: 	url + 'api/v1/pokemon/56/'
		  ,	growlithe: 	url + 'api/v1/pokemon/58/'
		  ,	arcanine: 	url + 'api/v1/pokemon/59/'
		  ,	poliwag: 	url + 'api/v1/pokemon/60/'
		  ,	abra: 		url + 'api/v1/pokemon/63/'
		  ,	machop: 	url + 'api/v1/pokemon/66/'
		  ,	bellsprout: url + 'api/v1/pokemon/69/'
		  ,	ivysaur: 	url + 'api/v1/pokemon/2/'
		  ,	squirtle: 	url + 'api/v1/pokemon/7/'
		  ,	weedle: 	url + 'api/v1/pokemon/13/'
		  ,	graveler: 	url + 'api/v1/pokemon/75/'
		  ,	geodude: 	url + 'api/v1/pokemon/74/'
		  ,	ponyta: 	url + 'api/v1/pokemon/77/'
		  ,	rapidash: 	url + 'api/v1/pokemon/78/'
		  ,	slowbro: 	url + 'api/v1/pokemon/80/'
		  ,	grimer: 	url + 'api/v1/pokemon/88/'
		  ,	farfetchd: 	url + 'api/v1/pokemon/83/'
		  ,	magnemite: 	url + 'api/v1/pokemon/81/'
		  ,	doduo: 		url + 'api/v1/pokemon/84/'
		  ,	seel: 		url + 'api/v1/pokemon/86/'
		  ,	dodrio: 	url + 'api/v1/pokemon/85/'
		  ,	dewgong: 	url + 'api/v1/pokemon/87/'
		  ,	gastly: 	url + 'api/v1/pokemon/92/'
		  ,	cloyster: 	url + 'api/v1/pokemon/91/'
		  ,	muk: 		url + 'api/v1/pokemon/89/'
		  ,	krabby: 	url + 'api/v1/pokemon/98/'
		  ,	haunter: 	url + 'api/v1/pokemon/93/'
		  ,	gengar: 	url + 'api/v1/pokemon/94/'
		  ,	onix: 		url + 'api/v1/pokemon/95/'
		  ,	drowzee: 	url + 'api/v1/pokemon/96/'
		  ,	hypno: 		url + 'api/v1/pokemon/97/'
		});
})(angular);<commit_msg>Update api.js<commit_after>(function (angular, undefined) {
	'user strict';

	var url = 'http://pokeapi.co/';
	angular.module('pokeApp')
	.constant('API',
		{
		    rattata: 	url + 'api/v1/pokemon/19/'
		  , charmander: url + 'api/v1/pokemon/4/'
		  , wartortle: 	url + 'api/v1/pokemon/8/'
		  , blastoise: 	url + 'api/v1/pokemon/9/'
		  , caterpie: 	url + 'api/v1/pokemon/10/'
		  , metapod: 	url + 'api/v1/pokemon/11/'
		  , butterfree: url + 'api/v1/pokemon/12/'
		  , spearow: 	url + 'api/v1/pokemon/21/'
		  , kakuna: 	url + 'api/v1/pokemon/14/'
		  , beedrill: 	url + 'api/v1/pokemon/15/'
		  , pidgey: 	url + 'api/v1/pokemon/16/'
		  , raticate: 	url + 'api/v1/pokemon/20/'
		  , fearow: 	url + 'api/v1/pokemon/22/'
		  , pikachu: 	url + 'api/v1/pokemon/25/'
		  , arbok: 	url + 'api/v1/pokemon/24/'
		  , ekans: 	url + 'api/v1/pokemon/23/'
		  , nidorina: 	url + 'api/v1/pokemon/30/'
		  , sandshrew: 	url + 'api/v1/pokemon/27/'
		  , nidoranm: 	url + 'api/v1/pokemon/32/'
		  , nidoranf: 	url + 'api/v1/pokemon/29/'
		  , clefabe: 	url + 'api/v1/pokemon/36/'
		  , jigglypuff: url + 'api/v1/pokemon/39/'
		  , vulpix: 	url + 'api/v1/pokemon/37/'
		  , ninetales: 	url + 'api/v1/pokemon/38/'
		  , zubat: 	url + 'api/v1/pokemon/41/'
		  , venonat: 	url + 'api/v1/pokemon/48/'
		  , meowth: 	url + 'api/v1/pokemon/52/'
		  , oddish: 	url + 'api/v1/pokemon/43/'
		  , gloom: 	url + 'api/v1/pokemon/44/'
		  , vileplume: 	url + 'api/v1/pokemon/45/'
		  , paras: 	url + 'api/v1/pokemon/46/'
		  , parasect: 	url + 'api/v1/pokemon/47/'
		  , venomoth: 	url + 'api/v1/pokemon/49/'
		  , diglett: 	url + 'api/v1/pokemon/50/'
		  , dugtrio: 	url + 'api/v1/pokemon/51/'
		  , persian: 	url + 'api/v1/pokemon/53/'
		  , psyduck: 	url + 'api/v1/pokemon/54/'
		  , mankey: 	url + 'api/v1/pokemon/56/'
		  , growlithe: 	url + 'api/v1/pokemon/58/'
		  , arcanine: 	url + 'api/v1/pokemon/59/'
		  , poliwag: 	url + 'api/v1/pokemon/60/'
		  , abra: 	url + 'api/v1/pokemon/63/'
		  , machop: 	url + 'api/v1/pokemon/66/'
		  , bellsprout: url + 'api/v1/pokemon/69/'
		  , ivysaur: 	url + 'api/v1/pokemon/2/'
		  , squirtle: 	url + 'api/v1/pokemon/7/'
		  , weedle: 	url + 'api/v1/pokemon/13/'
		  , graveler: 	url + 'api/v1/pokemon/75/'
		  , geodude: 	url + 'api/v1/pokemon/74/'
		  , ponyta: 	url + 'api/v1/pokemon/77/'
		  , rapidash: 	url + 'api/v1/pokemon/78/'
		  , slowbro: 	url + 'api/v1/pokemon/80/'
		  , grimer: 	url + 'api/v1/pokemon/88/'
		  , farfetchd: 	url + 'api/v1/pokemon/83/'
		  , magnemite: 	url + 'api/v1/pokemon/81/'
		  , doduo: 	url + 'api/v1/pokemon/84/'
		  , seel: 	url + 'api/v1/pokemon/86/'
		  , dodrio: 	url + 'api/v1/pokemon/85/'
		  , dewgong: 	url + 'api/v1/pokemon/87/'
		  , gastly: 	url + 'api/v1/pokemon/92/'
		  , cloyster: 	url + 'api/v1/pokemon/91/'
		  , muk: 	url + 'api/v1/pokemon/89/'
		  , krabby: 	url + 'api/v1/pokemon/98/'
		  , haunter: 	url + 'api/v1/pokemon/93/'
		  , gengar: 	url + 'api/v1/pokemon/94/'
		  , onix: 	url + 'api/v1/pokemon/95/'
		  , drowzee: 	url + 'api/v1/pokemon/96/'
		  , hypno: 	url + 'api/v1/pokemon/97/'
		});
})(angular);
<|endoftext|>