<commit_before>// Array randomization helper function
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var cachedLocations = new SubsManager({
  cacheLimit: 9999,
  expireIn: 9999
});

var listItemImage = new SubsManager({
  cacheLimit: 9999,
  expireIn: 9999
});

Template.ooBanner.created = function () {
  var self = this;
  if (!self.data) {
    console.log('%c ooBanner no data passed to component   ',  'background: #5D76DB; color: white; padding: 1px 15px 1px 5px;');
    return
  }
  if (self.data.image) {
    self.activeImageLocal = new Blaze.ReactiveVar(self.data.localImg);
    self.activeImage = new Blaze.ReactiveVar(self.data.image);
    self.activeBackground = new Blaze.ReactiveVar(self.data.bannerBackground)
    self.activeImageId = new Blaze.ReactiveVar(self.data.docId)
    self.fullWidth = new Blaze.ReactiveVar(false);

  } else {
    self.activeImage = new Blaze.ReactiveVar('')
    self.activeImageLocal = new Blaze.ReactiveVar('')
    self.activeBackground = new Blaze.ReactiveVar('')
    self.currentPosition = new Blaze.ReactiveVar(0);
    self.activeImageId = new Blaze.ReactiveVar();
    self.fullWidth = new Blaze.ReactiveVar(false);
    self.bannerList = new Blaze.ReactiveVar([]);

    self.ready = new ReactiveVar(false);
    var dataSourceArray = [];
    if (self.data.subscription) {
      self.autorun(function () {
        var subscription = listItemImage.subscribe(self.data.subscription, self.data.location, Session.get('active_APP'));

        if (subscription.ready()) {
          if (self.data.multi) {
            dataSourceArray = Collection[self.data.collection].find({locationNames: self.data.location}).fetch()
          } else {
            dataSourceArray = Collection[self.data.collection].find({locationNames: self.data.location, appId: Session.get('active_APP')}).fetch()

          }
          // console.log(subscription.ready())

          self.ready.set(true);
        } else {
          if (self.data.multi && Meteor.isCordova) {

            Meteor.setTimeout(() => {
              if (!self.ready.get()) {
                dataSourceArray = Collection[self.data.collection].find({locationNames: self.data.location}).fetch();
                if (dataSourceArray.length > 0) {
                  self.ready.set(true);
                }
              }
            }, 1000);
          }
          self.ready.set(false);
        }
      });
    } else {
      if (self.data.cursor)
        dataSourceArray =  self.data.cursor

      self.ready.set(true);

    }
    self.autorun(function() {
      // XXX use cursor on pub ready
      if (self.data.rotating && self.ready.get()) {
        // console.log('firina')
        // console.log(self.data.rotating && self.ready.get())
         // dataSourceArray = ["http://i.imgur.com/ynHObxS.png", "http://i.imgur.com/jseTTKB.png","http://i.imgur.com/jv4Rx9Q.png", "http://i.imgur.com/T8GVrs3.png"];
        self.bannerList.set(shuffle(dataSourceArray));

        var currentItem = 0;

        self.currentPosition.set(currentItem);
        if (self.bannerList.get().length > 0) {
          self.activeImage.set(self.bannerList.get()[currentItem][self.data.imageField]);
          self.activeImageLocal.set(self.bannerList.get()[currentItem].localImg);
          self.activeImageId.set(self.bannerList.get()[currentItem]._id)
          self.activeBackground.set(self.bannerList.get()[currentItem].bannerBackground)
          self.fullWidth.set(!!self.bannerList.get()[currentItem].fullWidth)
          // console.log(self.bannerList.get()[currentItem])
          // console.log(self.bannerList.get()[currentItem]._id)
          if (!self.InsideInterval) {
            self.InsideInterval = Meteor.setInterval(function(){
              // console.log('setInterval', self.InsideInterval)
              var numberOfItems = self.bannerList.get().length
              if (numberOfItems > 1) {
                if (currentItem == numberOfItems -1){
                    currentItem = 0;
                } else {
                    currentItem++;
                }
              } else {
                currentItem = 0;
              }

              self.currentPosition.set(currentItem);
              self.activeImage.set(self.bannerList.get()[currentItem][self.data.imageField])
              self.activeImageLocal.set(self.bannerList.get()[currentItem].localImg)
              self.activeImageId.set(self.bannerList.get()[currentItem]._id)
            }, 8000)
          }
        }

      }
    })

  }

};

Template.ooBanner.destroyed = function () {
  var self = this;
  Meteor.clearInterval(self.InsideInterval)
}

Template.ooBanner.helpers({
  backgroundColor: function() {
    return Template.instance().activeBackground.get() ? Template.instance().activeBackground.get() : 'white'
  },
  ifAnyDataPassed: function() {
    return this.image || this.title || Template.instance().activeImage.get() ? true : false;
  },
  titlePassed: function() {
    return (typeof this.title !== 'undefined') ? true : false;
  },
  image:function () {
    return this.image ? this.image : Template.instance().activeImage.get();
  },
  imageLocal: function() {
    return this.localImg ? `/images/${this.localImg}` : `/images/${Template.instance().activeImageLocal.get()}`;
  },
  fullWidth: function() {
    return this.fullWidth ? this.fullWidth : !!Template.instance().fullWidth.get();
  },
  loadFromLocal: function() {
    return Meteor.isCordova;
  }
});

Template.ooBanner.events({
  'click .js-goToSponsor' : function (e, t) {
    var sponsor = Sponsors.findOne({_id: Template.instance().activeImageId.get()});
    if (sponsor._id) {

      if (sponsor.activeWebsite) {
        var httpLink = sponsor.urlLink.indexOf('http://') === -1 ? 'http://' + sponsor.urlLink : sponsor.urlLink;
        window.open(httpLink, '_system', 'location=yes')
        return;
      } else {
        if (!sponsor.disableProfile) {
          var catName= '';
          if (!sponsor.categoryName) {
            var cat = SponsorsCategory.findOne({_id: sponsor.sponsorCategory});
            catName = cat && cat.catName ? cat.catName : 'Sponsor'
            // console.log('cat')
            // console.log(cat)
          } else {
            catName = sponsor.categoryName;
          }
          ViewsControl.go('sponsorView', sponsor._id, sponsor.categoryName ? sponsor.categoryName : catName , 'offlineSponsors');
          statisticsAddCount('Sponsors', sponsor._id);
        }
      }

    }

    // ViewsControl.go('sponsorView', Template.instance().activeImageId.get(), this.catName, 'Sponsors');
  }
})
<commit_msg>use reactive cursor<commit_after>// Array randomization helper function
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var cachedLocations = new SubsManager({
  cacheLimit: 9999,
  expireIn: 9999
});

var listItemImage = new SubsManager({
  cacheLimit: 9999,
  expireIn: 9999
});

Template.ooBanner.created = function () {
  var self = this;
  if (!self.data) {
    console.log('%c ooBanner no data passed to component   ',  'background: #5D76DB; color: white; padding: 1px 15px 1px 5px;');
    return
  }
  if (self.data.image) {
    self.activeImageLocal = new Blaze.ReactiveVar(self.data.localImg);
    self.activeImage = new Blaze.ReactiveVar(self.data.image);
    self.activeBackground = new Blaze.ReactiveVar(self.data.bannerBackground)
    self.activeImageId = new Blaze.ReactiveVar(self.data.docId)
    self.fullWidth = new Blaze.ReactiveVar(false);

  } else {
    self.activeImage = new Blaze.ReactiveVar('')
    self.activeImageLocal = new Blaze.ReactiveVar('')
    self.activeBackground = new Blaze.ReactiveVar('')
    self.currentPosition = new Blaze.ReactiveVar(0);
    self.activeImageId = new Blaze.ReactiveVar();
    self.fullWidth = new Blaze.ReactiveVar(false);
    self.bannerList = new Blaze.ReactiveVar([]);

    self.ready = new ReactiveVar(false);
    self.dataSourceArray = new Blaze.ReactiveVar([]);;
    if (self.data.subscription) {
      self.autorun(function () {
        var subscription = listItemImage.subscribe(self.data.subscription, self.data.location, Session.get('active_APP'));

        if (subscription.ready()) {
          if (self.data.multi) {
            self.dataSourceArray.set(Collection[self.data.collection].find({locationNames: self.data.location}).fetch());
          } else {
            self.dataSourceArray.set(Collection[self.data.collection].find({locationNames: self.data.location, appId: Session.get('active_APP')}).fetch());

          }
          // console.log(subscription.ready())

          self.ready.set(true);
        } else {
          if (self.data.multi && Meteor.isCordova) {

            Meteor.setTimeout(() => {
              if (!self.ready.get()) {
                self.dataSourceArray.set(Collection[self.data.collection].find({locationNames: self.data.location}).fetch());
                if (dataSourceArray.length > 0) {
                  self.ready.set(true);
                }
              }
            }, 1000);
          }
          self.ready.set(false);
        }
      });
    } else {
      if (self.data.cursor) {
        self.autorun(() => {
          self.dataSourceArray.set(self.data.cursor.fetch());
          self.ready.set(false);
          self.ready.set(true);

        })
      }
    }
    self.autorun(function() {
      // XXX use cursor on pub ready
      if (self.data.rotating && self.ready.get()) {
        // console.log('firina')
        // console.log(self.data.rotating && self.ready.get())
         // dataSourceArray = ["http://i.imgur.com/ynHObxS.png", "http://i.imgur.com/jseTTKB.png","http://i.imgur.com/jv4Rx9Q.png", "http://i.imgur.com/T8GVrs3.png"];
        self.bannerList.set(shuffle(self.dataSourceArray.get()));

        var currentItem = 0;

        self.currentPosition.set(currentItem);
        if (self.bannerList.get().length > 0) {
          self.activeImage.set(self.bannerList.get()[currentItem][self.data.imageField]);
          self.activeImageLocal.set(self.bannerList.get()[currentItem].localImg);
          self.activeImageId.set(self.bannerList.get()[currentItem]._id)
          self.activeBackground.set(self.bannerList.get()[currentItem].bannerBackground)
          self.fullWidth.set(!!self.bannerList.get()[currentItem].fullWidth)
          // console.log(self.bannerList.get()[currentItem])
          // console.log(self.bannerList.get()[currentItem]._id)
          if (!self.InsideInterval) {
            self.InsideInterval = Meteor.setInterval(function(){
              // console.log('setInterval', self.InsideInterval)
              var numberOfItems = self.bannerList.get().length
              if (numberOfItems > 1) {
                if (currentItem == numberOfItems -1){
                    currentItem = 0;
                } else {
                    currentItem++;
                }
              } else {
                currentItem = 0;
              }

              self.currentPosition.set(currentItem);
              self.activeImage.set(self.bannerList.get()[currentItem][self.data.imageField])
              self.activeImageLocal.set(self.bannerList.get()[currentItem].localImg)
              self.activeImageId.set(self.bannerList.get()[currentItem]._id)
            }, 8000)
          }
        }

      } else {
        if (self.InsideInterval) {
          Meteor.clearInterval(self.InsideInterval);
        }
      }
    })

  }

};

Template.ooBanner.destroyed = function () {
  var self = this;
  Meteor.clearInterval(self.InsideInterval)
}

Template.ooBanner.helpers({
  backgroundColor: function() {
    return Template.instance().activeBackground.get() ? Template.instance().activeBackground.get() : 'white'
  },
  ifAnyDataPassed: function() {
    return this.image || this.title || Template.instance().activeImage.get() ? true : false;
  },
  titlePassed: function() {
    return (typeof this.title !== 'undefined') ? true : false;
  },
  image:function () {
    return this.image ? this.image : Template.instance().activeImage.get();
  },
  imageLocal: function() {
    return this.localImg ? `/images/${this.localImg}` : `/images/${Template.instance().activeImageLocal.get()}`;
  },
  fullWidth: function() {
    return this.fullWidth ? this.fullWidth : !!Template.instance().fullWidth.get();
  },
  loadFromLocal: function() {
    return Meteor.isCordova;
  }
});

Template.ooBanner.events({
  'click .js-goToSponsor' : function (e, t) {
    var sponsor = Sponsors.findOne({_id: Template.instance().activeImageId.get()});
    if (sponsor._id) {

      if (sponsor.activeWebsite) {
        var httpLink = sponsor.urlLink.indexOf('http://') === -1 ? 'http://' + sponsor.urlLink : sponsor.urlLink;
        window.open(httpLink, '_system', 'location=yes')
        return;
      } else {
        if (!sponsor.disableProfile) {
          var catName= '';
          if (!sponsor.categoryName) {
            var cat = SponsorsCategory.findOne({_id: sponsor.sponsorCategory});
            catName = cat && cat.catName ? cat.catName : 'Sponsor'
            // console.log('cat')
            // console.log(cat)
          } else {
            catName = sponsor.categoryName;
          }
          ViewsControl.go('sponsorView', sponsor._id, sponsor.categoryName ? sponsor.categoryName : catName , 'offlineSponsors');
          statisticsAddCount('Sponsors', sponsor._id);
        }
      }

    }

    // ViewsControl.go('sponsorView', Template.instance().activeImageId.get(), this.catName, 'Sponsors');
  }
})
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.studentId = $("#saveBtn").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.assessCompletementNumberToSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberToSubmit");}, gvm);
    gvm.projectWeight = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectWeight");}, gvm);
    gvm.assessCompletementNumberSubmitted = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberSubmitted");}, gvm);
    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);
    gvm.documentScore = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentScore");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);
    gvm.userData = ko.observableArray([]);

    gvm.addDocument = function(id,parentId, description, weight, pointType,score) {
        gvm.documents.push(new Document(id,parentId,description,weight,pointType,score));
    };

    gvm.getAllData = function()
    {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents/' + gvm.studentId, function(data) {
            console.log("getAllData");
            console.log(data);
            $.each(data, function(i, item) {
                gvm.enterData(item);
                gvm.userData.push(item);
            });
        });
    };

    gvm.enterData = function(data)
    {
        gvm.documents().forEach(function(item) {
            console.log(data);
            console.log(item);
           if(data.document == item.parentId()) {
               item.id(data.id);
               item.score(data.score);
           }
        });
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(0, item.id, item.description, item.weight, item.point_type, 0);
            });
            gvm.getAllData();
        });
    };

    gvm.clearStructure = function()
    {
        gvm.userData.destroyAll();
        gvm.documents.destroyAll();
    }
}

function Document(id,parentId,description ,weight,pointType, score)
{
    return {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        description: ko.observable(description),
        pointType: ko.observable(pointType),
        weight: ko.observable(weight),
        score: ko.observable(score),

        voteYes: function(event,target) {
            if(this.score() == 0) {
                this.score(100);
            }
            target.target.checked = true;
            console.log(target.target);
        },

        voteNo: function(event,target) {
            if(this.score() == 100) {
                this.score(0);
            }
            target.currentTarget.checked = true;
            console.log(target.currentTarget.checked);
        }
    }
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();

    $("#saveBtn").click(function() {
        $.ajax({
            type: "POST",
            url: "/api/documents/" + projectid + "/user/" + viewModel.studentId + "/save",
            data: ko.toJSON(viewModel.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved document completeness to server");
                viewModel.clearStructure();
                viewModel.getProjectInfo();
                viewModel.getDocumentsToSubmit();
            }
        });
    });

    var url = '/assess/project/' + projectid + '/students';
    $("#cancelBtn").click(function()
    {
        window.location.href = url;
    });
}
<commit_msg>Grade documents<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.studentId = $("#saveBtn").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.assessCompletementNumberToSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberToSubmit");}, gvm);
    gvm.projectWeight = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectWeight");}, gvm);
    gvm.assessCompletementNumberSubmitted = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberSubmitted");}, gvm);
    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);
    gvm.documentScore = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentScore");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);
    gvm.userData = ko.observableArray([]);

    gvm.addDocument = function(id,parentId, description, weight, pointType,score) {
        gvm.documents.push(new Document(id,parentId,description,weight,pointType,score));
    };

    gvm.getAllData = function()
    {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents/' + gvm.studentId, function(data) {
            console.log("getAllData");
            console.log(data);
            $.each(data, function(i, item) {
                gvm.enterData(item);
                gvm.userData.push(item);
            });
        });
    };

    gvm.enterData = function(data)
    {
        gvm.documents().forEach(function(item) {
            console.log(data);
            console.log(item);
           if(data.document == item.parentId()) {
               item.id(data.id);
               item.score(data.score);
           }
        });
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(0, item.id, item.description, item.weight, item.point_type, 0);
            });
            gvm.getAllData();
        });
    };

    gvm.clearStructure = function()
    {
        gvm.userData.destroyAll();
        gvm.documents.destroyAll();
    }
}

function Document(id,parentId,description ,weight,pointType, score)
{
    return {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        description: ko.observable(description),
        pointType: ko.observable(pointType),
        weight: ko.observable(weight),
        score: ko.observable(score),

        voteYes: function(event,target) {
            if(this.score() == 0) {
                this.score(100);
            }
            target.target.checked = true;
            console.log(target);
        },

        voteNo: function(event,target) {
            if(this.score() == 100) {
                this.score(0);
            }
            target.currentTarget.checked = true;
            console.log(target.currentTarget.checked);
        }
    }
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();

    $("#saveBtn").click(function() {
        $.ajax({
            type: "POST",
            url: "/api/documents/" + projectid + "/user/" + viewModel.studentId + "/save",
            data: ko.toJSON(viewModel.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved document completeness to server");
                viewModel.clearStructure();
                viewModel.getProjectInfo();
                viewModel.getDocumentsToSubmit();
            }
        });
    });

    var url = '/assess/project/' + projectid + '/students';
    $("#cancelBtn").click(function()
    {
        window.location.href = url;
    });
}
<|endoftext|>


<commit_before>/**
 * Created by Scott on 2/25/2015.
 */
define(['testharness', '../lib/request', '../lib/SQLish'],
    function(harness, request, SQLish) {
        return {
            run: function () {
                "use strict";

                var db, table, query;

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    harness.assert_true(SQLish.getDB('Library') !== undefined);
                }, "CREATE DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = SQLish.dropDB('Library');
                    harness.assert_true(db && SQLish.getDB('Library') === undefined);
                }, "DROP DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    table = db.createTable('Books')('title');
                    harness.assert_true(table.hasOwnProperty('title'));
                    db = SQLish.dropDB('Library');
                }, "CREATE TABLE Books (title)");

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    db.createTable('Books')('title');
                    db.insertInto('Books')('title').values('Book of Foo');
                    query = db.select('title').from('Books').go();
                    harness.assert_true(query[0].title === 'Book of Foo');
                    db = SQLish.dropDB('Library');
                }, "INSERT INTO Books (title) VALUES ('Book of Foo')");

                // setup for next test
                db = SQLish.createDB('Library');
                table = db.createTable('Books')('title');

                harness.test(function () {
                    var insertValues = db.insertInto('Books')('title').values('Alphabet Soup')('Aliens')('Baseball')('Bats')('Cats')('Soup for the Soul'),
                        testPassed = false,
                        titlesArray;

                    titlesArray = db.select('title').from('Books').go();
                    testPassed = titlesArray.every(function (rowObj) {
                        var title = rowObj.title,
                            a = ['Alphabet Soup', 'Aliens', 'Baseball', 'Bats', 'Cats', 'Soup for the Soul'];

                        return title && a.indexOf(title) >= 0;
                    });
                    harness.assert_true(testPassed);
                    // do not tear down Library
                }, "INSERT INTO Books (title) VALUES ('Alphabet Soup'),('Aliens'),('Baseball'),('Bats'),('Cats'),('Soup for the Soul')");

                // next test uses prerequisites from previous test...
                harness.test(function () {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens').go();
                    harness.assert_true(query[0] && query[0].title === 'Aliens');
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title = 'Aliens'");

                // keep going...
                harness.test(function () {
                    var where,
                        returnSet,
                        passedTest = false;

                    query = db.select('title').from('Books');
                    where = query.where;
                    returnSet = where('title', 'like', 'soup').go();
                    passedTest = returnSet.length === 0;
                    if (passedTest) {
                        returnSet = where('title', 'like', '.*soup').go();
                        passedTest = returnSet.length === 1 && returnSet[0].title === 'Alphabet Soup';
                    }
                    if (passedTest) {
                        returnSet = where('title', 'like', 'ba.*').go();
                        passedTest = returnSet.length === 2 && returnSet[0].title === 'Baseball' && returnSet[1].title === 'Bats';
                    }
                    if (passedTest) {
                        returnSet = where('title', 'like', '.*ou.*ou.*').go();
                        passedTest = returnSet.length === 1 && returnSet[0].title === 'Soup for the Soul';
                    }
                    harness.assert_true(passedTest);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title LIKE %ou%ou%  => plus 3 more 'LIKE' tests");

                harness.test(function () {
                    var where = query.where,
                        returnSet,
                        passedTest = false;

                    returnSet = where('title', 'not like', '.*b.*').go();
                    passedTest = returnSet.length === 3 && returnSet[0].title === 'Aliens' && returnSet[1].title === 'Cats' && returnSet[2].title === 'Soup for the Soul';
                    harness.assert_true(passedTest);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title NOT LIKE %b%");

                harness.test(function () {
                    query = db.select('*').from('Books').go();
                    harness.assert_true(query.length === 6);
                    db = SQLish.dropDB('Library');
                }, "SELECT * FROM Books");

                // setup for next test
                db = SQLish.createDB('Library');
                table = db.createTable('Books')('title', 'author');

                harness.test(function () {
                    var testPassed = false,
                        returnSet;

                    db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                                                                    ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')
                                                                    ('Soup for the Soul', 'Flora Ivy');
                    returnSet = db.select('title').from('Books').where('author', 'like', '.*o.*s.*').go();
                    testPassed = returnSet.length === 2 && returnSet[0].title === 'Alphabet Soup' && returnSet[1].title === 'Cats';
                    harness.assert_true(testPassed);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE author LIKE %o%s%  => condition based on field not in SELECT");

                harness.test(function () {
                    db.update('Books').set('title', 'Green Eggs & Ham')('author', 'Dr. Seuss').where('title', '===', 'Bats').go();
                    query = db.select('title', 'author').from('Books').go();
                    harness.assert_true(query.length === 7 && query[4].title === 'Green Eggs & Ham' && query[4].author === 'Dr. Seuss');
                    //db = SQLish.dropDB('Library');
                }, "UPDATE Books SET title = 'Green Eggs & Ham', author = 'Dr. Seuss' WHERE title = 'Bats'");

                harness.test(function() {
                    query = db.select('title').from('Books').where('title', 'like', '.*break').and('author', 'like', '.*Aaron').go();
                    harness.assert_true(query[0].title === 'Coffee Break');
                }, "SELECT title FROM Books WHERE title like %break AND author like %Aaron");

                harness.test(function() {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens').or('author', '===', 'Kaitlyn Rose').go();
                    harness.assert_true(query.length === 2 && query[0].title === 'Aliens' && query[1].title === 'Cats');
                }, "SELECT title FROM Books WHERE title = 'Aliens' OR author = 'Kaitlyn Rose'");
            }
        };
    }
);
<commit_msg>SQLishTests - new tests for DELETE and DELETE FROM<commit_after>/**
 * Created by Scott on 2/25/2015.
 */
define(['testharness', '../lib/request', '../lib/SQLish'],
    function(harness, request, SQLish) {
        return {
            run: function () {
                "use strict";

                var db, table, query;

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    harness.assert_true(SQLish.getDB('Library') !== undefined);
                }, "CREATE DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = SQLish.dropDB('Library');
                    harness.assert_true(db && SQLish.getDB('Library') === undefined);
                }, "DROP DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    table = db.createTable('Books')('title');
                    harness.assert_true(table.hasOwnProperty('title'));
                    db = SQLish.dropDB('Library');
                }, "CREATE TABLE Books (title)");

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    db.createTable('Books')('title');
                    db.insertInto('Books')('title').values('Book of Foo');
                    query = db.select('title').from('Books').go();
                    harness.assert_true(query[0].title === 'Book of Foo');
                    db = SQLish.dropDB('Library');
                }, "INSERT INTO Books (title) VALUES ('Book of Foo')");

                // setup for next test
                db = SQLish.createDB('Library');
                table = db.createTable('Books')('title');

                harness.test(function () {
                    var insertValues = db.insertInto('Books')('title').values('Alphabet Soup')('Aliens')('Baseball')('Bats')('Cats')('Soup for the Soul'),
                        testPassed = false,
                        titlesArray;

                    titlesArray = db.select('title').from('Books').go();
                    testPassed = titlesArray.every(function (rowObj) {
                        var title = rowObj.title,
                            a = ['Alphabet Soup', 'Aliens', 'Baseball', 'Bats', 'Cats', 'Soup for the Soul'];

                        return title && a.indexOf(title) >= 0;
                    });
                    harness.assert_true(testPassed);
                    // do not tear down Library
                }, "INSERT INTO Books (title) VALUES ('Alphabet Soup'),('Aliens'),('Baseball'),('Bats'),('Cats'),('Soup for the Soul')");

                // next test uses prerequisites from previous test...
                harness.test(function () {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens').go();
                    harness.assert_true(query[0] && query[0].title === 'Aliens');
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title = 'Aliens'");

                // keep going...
                harness.test(function () {
                    var where,
                        returnSet,
                        passedTest = false;

                    query = db.select('title').from('Books');
                    where = query.where;
                    returnSet = where('title', 'like', 'soup').go();
                    passedTest = returnSet.length === 0;
                    if (passedTest) {
                        returnSet = where('title', 'like', '.*soup').go();
                        passedTest = returnSet.length === 1 && returnSet[0].title === 'Alphabet Soup';
                    }
                    if (passedTest) {
                        returnSet = where('title', 'like', 'ba.*').go();
                        passedTest = returnSet.length === 2 && returnSet[0].title === 'Baseball' && returnSet[1].title === 'Bats';
                    }
                    if (passedTest) {
                        returnSet = where('title', 'like', '.*ou.*ou.*').go();
                        passedTest = returnSet.length === 1 && returnSet[0].title === 'Soup for the Soul';
                    }
                    harness.assert_true(passedTest);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title LIKE %ou%ou%  => plus 3 more 'LIKE' tests");

                harness.test(function () {
                    var where = query.where,
                        returnSet,
                        passedTest = false;

                    returnSet = where('title', 'not like', '.*b.*').go();
                    passedTest = returnSet.length === 3 && returnSet[0].title === 'Aliens' && returnSet[1].title === 'Cats' && returnSet[2].title === 'Soup for the Soul';
                    harness.assert_true(passedTest);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title NOT LIKE %b%");

                harness.test(function () {
                    query = db.select('*').from('Books').go();
                    harness.assert_true(query.length === 6);
                    db = SQLish.dropDB('Library');
                }, "SELECT * FROM Books");

                // setup for next test
                db = SQLish.createDB('Library');
                table = db.createTable('Books')('title', 'author');

                harness.test(function () {
                    var testPassed = false,
                        returnSet;

                    db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                                                                    ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')
                                                                    ('Soup for the Soul', 'Flora Ivy');
                    returnSet = db.select('title').from('Books').where('author', 'like', '.*o.*s.*').go();
                    testPassed = returnSet.length === 2 && returnSet[0].title === 'Alphabet Soup' && returnSet[1].title === 'Cats';
                    harness.assert_true(testPassed);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE author LIKE %o%s%  => condition based on field not in SELECT");

                harness.test(function () {
                    db.update('Books').set('title', 'Green Eggs & Ham')('author', 'Dr. Seuss').where('title', '===', 'Bats').go();
                    query = db.select('title', 'author').from('Books').go();
                    harness.assert_true(query.length === 7 && query[4].title === 'Green Eggs & Ham' && query[4].author === 'Dr. Seuss');
                    //db = SQLish.dropDB('Library');
                }, "UPDATE Books SET title = 'Green Eggs & Ham', author = 'Dr. Seuss' WHERE title = 'Bats'");

                harness.test(function() {
                    query = db.select('title').from('Books').where('title', 'like', '.*break').and('author', 'like', '.*Aaron').go();
                    harness.assert_true(query[0].title === 'Coffee Break');
                }, "SELECT title FROM Books WHERE title like %break AND author like %Aaron");

                harness.test(function() {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens').or('author', '===', 'Kaitlyn Rose').go();
                    harness.assert_true(query.length === 2 && query[0].title === 'Aliens' && query[1].title === 'Cats');
                }, "SELECT title FROM Books WHERE title = 'Aliens' OR author = 'Kaitlyn Rose'");

                harness.test(function() {
                    db.deleteFrom('Books').where('author', '===', 'Hank Aaron').or('author', 'like', '.*ivy').go();
                    query = db.select('title', 'author').from('Books').where('author', '===', 'Hank Aaron').or('author', 'like', '.*ivy').go();
                    harness.assert_true(query.length === 0);
                }, "DELETE FROM Books WHERE author === 'Hank Aaron' OR author like %ivy");

                harness.test(function() {
                    db.deleteFrom('Books').go();
                    query = db.select('title', 'author').from('Books').go();
                    harness.assert_true(query.length === 0);
                }, "DELETE FROM Books");

                harness.test(function() {
                    db.delete('author').from('Books');
                    query = db.select('author').from('Books').go();
                    harness.assert_true(db.Books.author === undefined && query.length === 0);
                }, "DELETE author FROM Books");

                // setup for next test
                db = SQLish.createDB('Library');
                table = db.createTable('Books')('title', 'author');
                db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')
                ('Soup for the Soul', 'Flora Ivy');

                harness.test(function() {
                    db.delete('*').from('Books');
                    var q1 = db.select('title').from('Books').go(),
                        q2 = db.select('author').from('Books').go();

                    console.log('DB', db);
                    harness.assert_true(db.Books.author === undefined && db.Books.title === undefined && q1.length === 0 && q2.length === 0);
                }, "DELETE * FROM Books");
            }
        };
    }
);
<|endoftext|>


<commit_before> sap.ui.require([
    "openui5/StripToastr",
    "sap/ui/thirdparty/sinon",
    "sap/ui/thirdparty/sinon-qunit"
 ], function(StripToastr) {
    'use strict';
    QUnit.module("Basics", {
        teardown: function() {
            StripToastr.clear();
            sap.ui.getCore().applyChanges();
        }
    });

    QUnit.test('Rendered ', function(assert) {
        // Arrange
        var oToast = StripToastr.notify({
            text: "test1"
        });

        sap.ui.getCore().applyChanges();

        // Assert
        assert.ok(oToast, "created");
        assert.strictEqual(oToast.$().attr("role"), "alert", "The role is set");

    });

    QUnit.test("Newest first", function(assert) {
        // Arrange
        StripToastr._oSettings.newestFirst = true;

        // Act
        var aMessages = [
            StripToastr.notify({
                text: "test1"
            }), StripToastr.notify({
                text: "test2"
            }), StripToastr.notify({
                text: "test3"
            })
        ];

        sap.ui.getCore().applyChanges();

        // Assert
        var oContent = StripToastr.getContainer().getContent();
        assert.strictEqual(oContent[0].getText(), aMessages[2].getText(), "first is last");
        assert.strictEqual(oContent[2].getText(), aMessages[0].getText(), "last is first");
        StripToastr._oSettings.newestFirst = false;
    });

    QUnit.test("Close Callback", function(assert) {
        // Arrange
        var done = assert.async();
        var delay = 1000;
        var fnCloseCallBackSpy = this.spy();

        var oControl = StripToastr.notify({
            text: "test1",
            close: fnCloseCallBackSpy
        });

        // Act
        oControl.close();

        // Assert
        setTimeout(function() {
            assert.strictEqual(fnCloseCallBackSpy.callCount, 1, "Close Callback reached");
            done();
        }, delay);
    });

    QUnit.module("Clear", {
        teardown: function() {
            StripToastr.clear();
            sap.ui.getCore().applyChanges();
        }
    });

    QUnit.test('Clear empty container ', function(assert) {
        // Arrange
        var delay = 500;
        var done = assert.async();
        var oContainer = StripToastr.getContainer({
            position: "left bottom",
            anchor: document
        });
        sap.ui.getCore().applyChanges();
        assert.ok(oContainer.$(), "Container rendered");
        assert.strictEqual(oContainer.getContent().length, 0, "Container empty");

        // Act
        StripToastr.clear();
        // Assert
        setTimeout(function() {
            assert.strictEqual(oContainer.$().length, 0, "Container DOM was destroyed");
            done();
        }, delay);
    });

    QUnit.test('Clear all ', function(assert) {
        // Arrange
        var delay = 1000;
        var done = assert.async();

        StripToastr.notify({
            text: "test1"
        });
        StripToastr.notify({
            text: "test2"
        });
        StripToastr.notify({
            text: "test3"
        });

        sap.ui.getCore().applyChanges();
        // Act
        StripToastr.clear();
        // Assert
        setTimeout(function() {
            var oContainer = StripToastr.getContainer();
            assert.strictEqual(oContainer, undefined, "Container was destroyed");
            done();
        }, delay);

    });

    QUnit.test('Clear - 3 message remove 2nd only ', function(assert) {
        // Arrange
        var delay = 1000;
        var done = assert.async();

        var aMessages = [
            StripToastr.notify({
                text: "test1"
            }), StripToastr.notify({
                text: "test2"
            }), StripToastr.notify({
                text: "test3"
            })
        ];

        sap.ui.getCore().applyChanges();
        //Act
        StripToastr.clear(aMessages[1]);
        // Assert
        setTimeout(function() {
            var oContent = StripToastr.getContainer().getContent();
            assert.strictEqual(oContent.length, 2, "Container has 2 controls");
            assert.strictEqual(oContent[1].getText(), aMessages[2].getText(), "Container message 2 correct");
            done();
        }, delay);

    });

    QUnit.module("Positioning", {
        teardown: function() {
            StripToastr.destroyContainer();
            sap.ui.getCore().applyChanges();
        }
    });

    QUnit.test("Top right", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "right top"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        assert.strictEqual(oDomRef.css("right"), "0px", "Right 0px");
        assert.strictEqual(oDomRef.css("top"), "0px", "Top 0px");
    });

    QUnit.test("Top left", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "left top"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        assert.strictEqual(oDomRef.css("left"), "0px", "Left 0px");
        assert.strictEqual(oDomRef.css("top"), "0px", "Top 0px");
    });

    QUnit.test("Bottom right", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "right bottom"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        var iTop = (jQuery(window).height() - oDomRef.height());
        assert.strictEqual(oDomRef.css("right"), "0px", "Right 0px");
        assert.strictEqual(parseFloat(oDomRef.css("top")), iTop, "Top " + iTop + "px");
    });

    QUnit.test("Bottom left", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "left bottom"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        var iTop = (jQuery(window).height() - oDomRef.height());
        assert.strictEqual(oDomRef.css("left"), "0px", "Left 0px");
        assert.strictEqual(parseFloat(oDomRef.css("top")), iTop, "Top " + iTop + "px");
    });

    QUnit.test("Center center", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "center center"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        var iLeft = (jQuery(window).width() - oDomRef.width()) / 2;
        var iTop = (jQuery(window).height() - oDomRef.height()) / 2;
        assert.strictEqual(parseFloat(oDomRef.css("left")), iLeft, "Left " + iLeft + "px");
        assert.strictEqual(parseFloat(oDomRef.css("top")), iTop, "Top " + iTop + "px");
    });
 });
<commit_msg>[UPDATE] tests cleanup<commit_after> sap.ui.require([
    "openui5/StripToastr",
    "sap/ui/thirdparty/sinon",
    "sap/ui/thirdparty/sinon-qunit",
    "test/unit/js-coverage-filter"
 ], function(StripToastr) {
    'use strict';
    QUnit.module("Basics", {
        teardown: function() {
            StripToastr.clear();
            sap.ui.getCore().applyChanges();
        }
    });

    QUnit.test('Rendered ', function(assert) {
        // Arrange
        var oToast = StripToastr.notify({
            text: "test1"
        });

        sap.ui.getCore().applyChanges();

        // Assert
        assert.ok(oToast, "created");
        assert.strictEqual(oToast.$().attr("role"), "alert", "The role is set");

    });

    QUnit.test("Newest first", function(assert) {
        // Arrange
        StripToastr._oSettings.newestFirst = true;

        // Act
        var aMessages = [
            StripToastr.notify({
                text: "test1"
            }), StripToastr.notify({
                text: "test2"
            }), StripToastr.notify({
                text: "test3"
            })
        ];

        sap.ui.getCore().applyChanges();

        // Assert
        var oContent = StripToastr.getContainer().getContent();
        assert.strictEqual(oContent[0].getText(), aMessages[2].getText(), "first is last");
        assert.strictEqual(oContent[2].getText(), aMessages[0].getText(), "last is first");
        StripToastr._oSettings.newestFirst = false;
    });

    QUnit.test("Close Callback", function(assert) {
        // Arrange
        var done = assert.async();
        var delay = 1000;
        var fnCloseCallBackSpy = this.spy();

        var oControl = StripToastr.notify({
            text: "test1",
            close: fnCloseCallBackSpy
        });

        // Act
        oControl.close();

        // Assert
        setTimeout(function() {
            assert.strictEqual(fnCloseCallBackSpy.callCount, 1, "Close Callback reached");
            done();
        }, delay);
    });

    QUnit.module("Clear", {
        teardown: function() {
            StripToastr.clear();
            sap.ui.getCore().applyChanges();
        }
    });

    QUnit.test('Clear empty container ', function(assert) {
        // Arrange
        var delay = 500;
        var done = assert.async();
        var oContainer = StripToastr.getContainer({
            position: "left bottom",
            anchor: document
        });
        sap.ui.getCore().applyChanges();
        assert.ok(oContainer.$(), "Container rendered");
        assert.strictEqual(oContainer.getContent().length, 0, "Container empty");

        // Act
        StripToastr.clear();
        // Assert
        setTimeout(function() {
            assert.strictEqual(oContainer.$().length, 0, "Container DOM was destroyed");
            done();
        }, delay);
    });

    QUnit.test('Clear all ', function(assert) {
        // Arrange
        var delay = 1000;
        var done = assert.async();

        StripToastr.notify({
            text: "test1"
        });
        StripToastr.notify({
            text: "test2"
        });
        StripToastr.notify({
            text: "test3"
        });

        sap.ui.getCore().applyChanges();
        // Act
        StripToastr.clear();
        // Assert
        setTimeout(function() {
            var oContainer = StripToastr.getContainer();
            assert.strictEqual(oContainer, undefined, "Container was destroyed");
            done();
        }, delay);

    });

    QUnit.test('Clear - 3 message remove 2nd only ', function(assert) {
        // Arrange
        var delay = 1000;
        var done = assert.async();

        var aMessages = [
            StripToastr.notify({
                text: "test1"
            }), StripToastr.notify({
                text: "test2"
            }), StripToastr.notify({
                text: "test3"
            })
        ];

        sap.ui.getCore().applyChanges();
        //Act
        StripToastr.clear(aMessages[1]);
        // Assert
        setTimeout(function() {
            var oContent = StripToastr.getContainer().getContent();
            assert.strictEqual(oContent.length, 2, "Container has 2 controls");
            assert.strictEqual(oContent[1].getText(), aMessages[2].getText(), "Container message 2 correct");
            done();
        }, delay);

    });

    QUnit.module("Positioning", {
        teardown: function() {
            StripToastr.destroyContainer();
            sap.ui.getCore().applyChanges();
        }
    });

    QUnit.test("Top right", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "right top"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        assert.strictEqual(oDomRef.css("right"), "0px", "Right 0px");
        assert.strictEqual(oDomRef.css("top"), "0px", "Top 0px");
    });

    QUnit.test("Top left", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "left top"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        assert.strictEqual(oDomRef.css("left"), "0px", "Left 0px");
        assert.strictEqual(oDomRef.css("top"), "0px", "Top 0px");
    });

    QUnit.test("Bottom right", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "right bottom"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        var iTop = (jQuery(window).height() - oDomRef.height());
        assert.strictEqual(oDomRef.css("right"), "0px", "Right 0px");
        assert.strictEqual(parseFloat(oDomRef.css("top")), iTop, "Top " + iTop + "px");
    });

    QUnit.test("Bottom left", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "left bottom"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        var iTop = (jQuery(window).height() - oDomRef.height());
        assert.strictEqual(oDomRef.css("left"), "0px", "Left 0px");
        assert.strictEqual(parseFloat(oDomRef.css("top")), iTop, "Top " + iTop + "px");
    });

    QUnit.test("Center center", function(assert) {
        // Arrange
        StripToastr.notify({
            text: "test1",
            position: "center center"
        });

        sap.ui.getCore().applyChanges();

        //Act
        var oContainer = StripToastr.getContainer();
        var oDomRef = oContainer.$();

        // Assert
        var iLeft = (jQuery(window).width() - oDomRef.width()) / 2;
        var iTop = (jQuery(window).height() - oDomRef.height()) / 2;
        assert.strictEqual(parseFloat(oDomRef.css("left")), iLeft, "Left " + iLeft + "px");
        assert.strictEqual(parseFloat(oDomRef.css("top")), iTop, "Top " + iTop + "px");
    });
 });
<|endoftext|>


<commit_before>var buster      = require("buster");

var jsbn        = require('../src/js/jsbn.js');
var BigInteger  = jsbn.BigInteger;
var nbi         = jsbn.nbi;

var amount      = require("../src/js/amount.js");
var Amount      = require("../src/js/amount.js").Amount;
var UInt160     = require("../src/js/amount.js").UInt160;

require("../src/js/amount.js").config = require("./config.js");

var config  = require('./config.js');

// XXX Add test cases that push XRP vs non-XRP behavior.

buster.testCase("Amount", {
  "UInt160" : {
    "Parse 0" : function () {
      buster.assert.equals(nbi(), UInt160.from_json("0")._value);
    },
    "Parse 0 export" : function () {
      buster.assert.equals(amount.consts.address_xns, UInt160.from_json("0").to_json());
    },
    "Parse 1" : function () {
      buster.assert.equals(new BigInteger([1]), UInt160.from_json("1")._value);
    },
    "Parse rrrrrrrrrrrrrrrrrrrrrhoLvTp export" : function () {
      buster.assert.equals(amount.consts.address_xns, UInt160.from_json("rrrrrrrrrrrrrrrrrrrrrhoLvTp").to_json());
    },
    "Parse rrrrrrrrrrrrrrrrrrrrBZbvji export" : function () {
      buster.assert.equals(amount.consts.address_one, UInt160.from_json("rrrrrrrrrrrrrrrrrrrrBZbvji").to_json());
    },
    "Parse mtgox export" : function () {
      buster.assert.equals(config.accounts["mtgox"].account, UInt160.from_json("mtgox").to_json());
    },

    "is_valid('rrrrrrrrrrrrrrrrrrrrrhoLvTp')" : function () {
      buster.assert(UInt160.is_valid("rrrrrrrrrrrrrrrrrrrrrhoLvTp"));
    },

    "!is_valid('rrrrrrrrrrrrrrrrrrrrrhoLvT')" : function () {
      buster.refute(UInt160.is_valid("rrrrrrrrrrrrrrrrrrrrrhoLvT"));
    },
  },

  "Amount parsing" : {
    "Parse 800/USD/mtgox" : function () {
      buster.assert.equals("800/USD/"+config.accounts["mtgox"].account, Amount.from_json("800/USD/mtgox").to_text_full());
    },
    "Parse native 0" : function () {
      buster.assert.equals("0/XRP", Amount.from_json("0").to_text_full());
    },
    "Parse native 0.0" : function () {
      buster.assert.equals("0/XRP", Amount.from_json("0.0").to_text_full());
    },
    "Parse native -0" : function () {
      buster.assert.equals("0/XRP", Amount.from_json("-0").to_text_full());
    },
    "Parse native -0.0" : function () {
      buster.assert.equals("0/XRP", Amount.from_json("-0.0").to_text_full());
    },
    "Parse native 1000" : function () {
      buster.assert.equals("1000/XRP", Amount.from_json("1000").to_text_full());
    },
    "Parse native 12.3" : function () {
      buster.assert.equals("12300000/XRP", Amount.from_json("12.3").to_text_full());
    },
    "Parse native -12.3" : function () {
      buster.assert.equals("-12300000/XRP", Amount.from_json("-12.3").to_text_full());
    },
    "Parse 123./USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("123./USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse 12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse 12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse 1.2300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("1.23/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("1.2300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse -0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse -0.0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-0.0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
  },
  "Amount operations" : {
    "Negate native 123" : function () {
      buster.assert.equals("-123/XRP", Amount.from_json("123").negate().to_text_full());
    },
    "Negate native -123" : function () {
      buster.assert.equals("123/XRP", Amount.from_json("-123").negate().to_text_full());
    },
    "Negate non-native 123" : function () {
      buster.assert.equals("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").negate().to_text_full());
    },
    "Negate non-native -123" : function () {
      buster.assert.equals("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").negate().to_text_full());
    },
    "Clone non-native -123" : function () {
      buster.assert.equals("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").clone().to_text_full());
    },
    "Divide XRP by USD" : function () {
      buster.assert.equals("20/XRP", Amount.from_json("200").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD" : function () {
      buster.assert.equals("2000/XRP", Amount.from_json("20000").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD" : function () {
      buster.assert.equals("200000/XRP", Amount.from_json("2000000").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD, neg" : function () {
      buster.assert.equals("-20/XRP", Amount.from_json("200").divide(Amount.from_json("-10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD, neg, frac" : function () {
      buster.assert.equals("-162/XRP", Amount.from_json("-6000").divide(Amount.from_json("37/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide USD by USD" : function () {
      buster.assert.equals("200/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide USD by USD, fractional" : function () {
      buster.assert.equals("57142.85714285714/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("35/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide USD by USD" : function () {
      buster.assert.equals("20/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("100000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide EUR by USD, result < 1" : function () {
      buster.assert.equals("0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide EUR by USD, neg" : function () {
      buster.assert.equals("-12/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-24000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide EUR by USD, neg, <1" : function () {
      buster.assert.equals("-0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("-1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide EUR by XRP, result < 1" : function () {
      buster.assert.equals("0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000")).to_text_full());
    },
    "Divide EUR by XRP, neg" : function () {
      buster.assert.equals("-20/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("5")).to_text_full());
    },
    "Divide EUR by XRP, neg, <1" : function () {
      buster.assert.equals("-0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000")).to_text_full());
    }
  }
});

// vim:sw=2:sts=2:ts=8:et
<commit_msg>Added some test cases for Amount.add().<commit_after>var buster      = require("buster");

var jsbn        = require('../src/js/jsbn.js');
var BigInteger  = jsbn.BigInteger;
var nbi         = jsbn.nbi;

var amount      = require("../src/js/amount.js");
var Amount      = require("../src/js/amount.js").Amount;
var UInt160     = require("../src/js/amount.js").UInt160;

require("../src/js/amount.js").config = require("./config.js");

var config  = require('./config.js');

// XXX Add test cases that push XRP vs non-XRP behavior.

buster.testCase("Amount", {
  "UInt160" : {
    "Parse 0" : function () {
      buster.assert.equals(nbi(), UInt160.from_json("0")._value);
    },
    "Parse 0 export" : function () {
      buster.assert.equals(amount.consts.address_xns, UInt160.from_json("0").to_json());
    },
    "Parse 1" : function () {
      buster.assert.equals(new BigInteger([1]), UInt160.from_json("1")._value);
    },
    "Parse rrrrrrrrrrrrrrrrrrrrrhoLvTp export" : function () {
      buster.assert.equals(amount.consts.address_xns, UInt160.from_json("rrrrrrrrrrrrrrrrrrrrrhoLvTp").to_json());
    },
    "Parse rrrrrrrrrrrrrrrrrrrrBZbvji export" : function () {
      buster.assert.equals(amount.consts.address_one, UInt160.from_json("rrrrrrrrrrrrrrrrrrrrBZbvji").to_json());
    },
    "Parse mtgox export" : function () {
      buster.assert.equals(config.accounts["mtgox"].account, UInt160.from_json("mtgox").to_json());
    },

    "is_valid('rrrrrrrrrrrrrrrrrrrrrhoLvTp')" : function () {
      buster.assert(UInt160.is_valid("rrrrrrrrrrrrrrrrrrrrrhoLvTp"));
    },

    "!is_valid('rrrrrrrrrrrrrrrrrrrrrhoLvT')" : function () {
      buster.refute(UInt160.is_valid("rrrrrrrrrrrrrrrrrrrrrhoLvT"));
    },
  },

  "Amount parsing" : {
    "Parse 800/USD/mtgox" : function () {
      buster.assert.equals("800/USD/"+config.accounts["mtgox"].account, Amount.from_json("800/USD/mtgox").to_text_full());
    },
    "Parse native 0" : function () {
      buster.assert.equals("0/XRP", Amount.from_json("0").to_text_full());
    },
    "Parse native 0.0" : function () {
      buster.assert.equals("0/XRP", Amount.from_json("0.0").to_text_full());
    },
    "Parse native -0" : function () {
      buster.assert.equals("0/XRP", Amount.from_json("-0").to_text_full());
    },
    "Parse native -0.0" : function () {
      buster.assert.equals("0/XRP", Amount.from_json("-0.0").to_text_full());
    },
    "Parse native 1000" : function () {
      buster.assert.equals("1000/XRP", Amount.from_json("1000").to_text_full());
    },
    "Parse native 12.3" : function () {
      buster.assert.equals("12300000/XRP", Amount.from_json("12.3").to_text_full());
    },
    "Parse native -12.3" : function () {
      buster.assert.equals("-12300000/XRP", Amount.from_json("-12.3").to_text_full());
    },
    "Parse 123./USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("123./USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse 12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("12300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse 12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("12.3/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse 1.2300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("1.23/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("1.2300/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse -0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
    "Parse -0.0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" : function () {
      buster.assert.equals("0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-0.0/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").to_text_full());
    },
  },
  "Amount operations" : {
    "Negate native 123" : function () {
      buster.assert.equals("-123/XRP", Amount.from_json("123").negate().to_text_full());
    },
    "Negate native -123" : function () {
      buster.assert.equals("123/XRP", Amount.from_json("-123").negate().to_text_full());
    },
    "Negate non-native 123" : function () {
      buster.assert.equals("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").negate().to_text_full());
    },
    "Negate non-native -123" : function () {
      buster.assert.equals("123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").negate().to_text_full());
    },
    "Clone non-native -123" : function () {
      buster.assert.equals("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-123/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").clone().to_text_full());
    },
    "Add XRP to XRP" : function () {
      buster.assert.equals("200/XRP", Amount.from_json("150").add(Amount.from_json("50")).to_text_full());
    },
    "Add USD to USD" : function () {
      buster.assert.equals("200.52/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("150.02/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").add(Amount.from_json("50.5/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD" : function () {
      buster.assert.equals("20/XRP", Amount.from_json("200").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD" : function () {
      buster.assert.equals("2000/XRP", Amount.from_json("20000").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD" : function () {
      buster.assert.equals("200000/XRP", Amount.from_json("2000000").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD, neg" : function () {
      buster.assert.equals("-20/XRP", Amount.from_json("200").divide(Amount.from_json("-10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide XRP by USD, neg, frac" : function () {
      buster.assert.equals("-162/XRP", Amount.from_json("-6000").divide(Amount.from_json("37/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide USD by USD" : function () {
      buster.assert.equals("200/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("10/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide USD by USD, fractional" : function () {
      buster.assert.equals("57142.85714285714/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("35/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide USD by USD" : function () {
      buster.assert.equals("20/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("2000000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("100000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide EUR by USD, result < 1" : function () {
      buster.assert.equals("0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide EUR by USD, neg" : function () {
      buster.assert.equals("-12/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-24000/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide EUR by USD, neg, <1" : function () {
      buster.assert.equals("-0.1/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("-1000/USD/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")).to_text_full());
    },
    "Divide EUR by XRP, result < 1" : function () {
      buster.assert.equals("0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000")).to_text_full());
    },
    "Divide EUR by XRP, neg" : function () {
      buster.assert.equals("-20/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("5")).to_text_full());
    },
    "Divide EUR by XRP, neg, <1" : function () {
      buster.assert.equals("-0.05/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", Amount.from_json("-100/EUR/rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh").divide(Amount.from_json("2000")).to_text_full());
    }
  }
});

// vim:sw=2:sts=2:ts=8:et
<|endoftext|>


<commit_before>// @flow

import mockData from './mockData.json'

export function SRSpacedRepetition(
  easinessFactor: number = 2.5,
  interval: number = 0,
  repetition: number = 0
) {
  this.easinessFactor = easinessFactor
  this.interval = interval
  this.repetition = repetition
}

export const SRStudyTaskIntensity = {
  NORMAL: 'NORMAL'
}

export function SRStudyTask(
  id: string,
  taskName: string,
  notes: ?string,
  dates: Array<string> = [new Date().toDateString()],
  ratingHistory: Array<string> = [],
  srs: SRSpacedRepetition,
  intensity: typeof(SRStudyTaskIntensity)
) {

  this.id = id,
  this.taskName = taskName,
  this.notes = notes,
  this.dates = dates,
  this.ratingHistory = ratingHistory
  this.srs = srs,
  this.intensity = intensity
}

// Define action types
const types = {
  ADD: 'ADD',
  REMOVE: 'REMOVE'
}

// Helper functions to dispatch actions, optionally with payloads
export const actionCreators = {
  add: (item: SRStudyTask) => {
    return {type: types.ADD, payload: item}
  },
  remove: (index: number) => {
    return {type: types.REMOVE, payload: index}
  }
}

// Initial state of the store
const initialState = mockData

export const reducer = (state: object = initialState, action: { type: string, payload: any}) => {
  const {studyTasks: SRStudyTask} = state
  const {type, payload} = action

  switch (type) {
    case types.ADD: {
      return {
        studyTasks: [payload, ...studyTasks],
      }
    }
    case types.REMOVE: {
      return {
        studyTasks: studyTasks.filter((task, i) => i !== payload),
      }
    }
  }

  return state
}
<commit_msg>Fixed cause of failing tests that add tasks.<commit_after>// @flow

import mockData from './mockData.json'

export function SRSpacedRepetition(
  easinessFactor: number = 2.5,
  interval: number = 0,
  repetition: number = 0
) {
  this.easinessFactor = easinessFactor
  this.interval = interval
  this.repetition = repetition
}

export const SRStudyTaskIntensity = {
  NORMAL: 'NORMAL'
}

export function SRStudyTask(
  id: string,
  taskName: string,
  notes: ?string,
  dates: Array<string> = [new Date().toDateString()],
  ratingHistory: Array<string> = [],
  srs: SRSpacedRepetition,
  intensity: typeof(SRStudyTaskIntensity)
) {
  this.id = id,
  this.taskName = taskName,
  this.notes = notes,
  this.dates = dates,
  this.ratingHistory = ratingHistory
  this.srs = srs,
  this.intensity = intensity
}

// Define action types
const types = {
  ADD: 'ADD',
  REMOVE: 'REMOVE'
}

// Helper functions to dispatch actions, optionally with payloads
export const actionCreators = {
  add: (item: SRStudyTask) => {
    return {type: types.ADD, payload: item}
  },
  remove: (index: number) => {
    return {type: types.REMOVE, payload: index}
  }
}

// Initial state of the store
const initialState = mockData

export const reducer = (state: object = initialState, action: { type: string, payload: any}) => {
  const {studyTasks} = state
  const {type, payload} = action

  switch (type) {
    case types.ADD: {
      return {
        studyTasks: [payload, ...studyTasks],
      }
    }
    case types.REMOVE: {
      return {
        studyTasks: studyTasks.filter((task, i) => i !== payload),
      }
    }
  }

  return state
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

/**
 * Node.js : overwatch-js
 * Access overwatch heroes and profile informations
 *
 **/

const cheerio = require('cheerio');
const rp = require('request-promise');
const _ = require('lodash/core');

const url = 'https://playoverwatch.com/%LANG%/career/';
const searchUrl = 'https://playoverwatch.com/%LANG%/search/account-by-name/';

const GAMETYPES = ['competitive', 'quickplay'];
const PLATFORMS = {
    XboxLive: "xbl",
    Playstation: "psn",
    PC: "pc"
}
const LOCALES = [
    "de-de",
    "en-us",
    "en-gb",
    "es-es",
    "es-mx",
    "fr-fr",
    "it-it",
    "pt-br",
    "pt-pt",
    "pl-pl",
    "ru-ru",
    "ko-kr",
    "ja-jp",
    "zh-tw",
    "zh-cn"
]

const RANKS = {
    "1" : [], //// Season 1
    "2" : [  //// Season 2
        'Bronze',
        'Silver',
        'Gold',
        'Platinum',
        'Diamond',
        'Master',
        'Grandmaster',
        'Top500'
    ]
}

const TIERS = require('./registry/ranking');

let OverwatchProvider = function () {
    var self = this;

    String.prototype.sanitize = function () {
        return this.trim().replace(" - ", "_").replace(/\s/g, "_").toLowerCase();
    }

    String.prototype.toTimestamp = function () {
        if (this.indexOf(':') > 0) {
            let intervals = this.split(':').reverse();
            intervals.at0 = (idx) => intervals[idx] || 0;
            // UTC date gives us milliseconds since the unix epoch
            return Date.UTC(1970, 0, intervals.at0(3) + 1, intervals.at0(2), intervals.at0(1), intervals.at0(0));
        }

        var swap = this;
        if (swap.endsWith('s')) swap = this.substr(0, this.length - 1); // remove trailing s
        if (swap.endsWith("second")) return parseInt(swap) * 1000;
        if (swap.endsWith("minute")) return parseInt(swap) * 60000;
        if (swap.endsWith("hour")) return parseInt(swap) * 3600000;
        if (swap.endsWith("day")) return parseInt(swap) * 86400000;

        return parseInt(swap);
    }

    String.prototype.cast = function () {
        if (this.indexOf('.') > 0 && this.indexOf(',') > 0) return parseFloat(this.replace(',',''));
        if (this.indexOf('.') > 0) return parseFloat(this);
        if (this.indexOf(':') > 0 || this.split(' ').length > 1) return this.toTimestamp();
        return parseInt(this.replace(/,/g, ''));
    }

    let getAvailableLocales = () => { return LOCALES; }

    let getUrl = (platform, region, tag, lang = 'en-us') => {

        if(! LOCALES.includes(lang))
            throw new Error(`${lang}_INVALID_LOCALE`);

        switch (platform) {
            case PLATFORMS.PC:
                region = "/" + region
                break;
            case PLATFORMS.Playstation:
            case PLATFORMS.XboxLive:
            default:
                //// No region must be specified
                region = "";
                break;
        }

        return url.replace('%LANG%', lang) + `${platform}${region}/${encodeURIComponent(tag)}`;
    };

    let getSearchUrl = (nickname, lang = "en-us", encode = false) => {

        if(! LOCALES.includes(lang))
            throw new Error(`${lang}_INVALID_LOCALE`);

        return searchUrl.replace('%LANG%', lang) + (encode ? encodeURIComponent(nickname) : nickname);
    };

    let parseSeason = (url) => {
        if (!url)
            return {};
        var m = url.match(/season\-([0-9])\/rank-([0-9])/);

        if(!m || m.length <= 1)
            return {};

        return { id : parseInt(m[1]), rank : parseInt(m[2])};
    }

    let parseTiers = (img) => {
        if(!img)
            return '';

        var m = img.match(/playerlevelrewards\/(.*)_Border.png/);

        if(!m || m.length <= 1)
            return '';

        return TIERS[m[1]];
    }

    let parseProfile = ($) => {
        var stats = {};
        stats.nick = $('.header-masthead').text();
        stats.level = parseInt($('div.player-level div').first().text());
        stats.avatar = $('.player-portrait').attr('src');
        stats.rank = parseInt($('div.competitive-rank > div').first().text());
        stats.tier = parseTiers($('.player-level').attr('style').replace(/^url|[\(\)]/g, ''));

        if (stats.rank)
        {
            stats.rankPicture = $('div.competitive-rank > img').attr('src');
            stats.season = parseSeason(stats.rankPicture);
            stats.ranking = stats.season ? RANKS[stats.season.id][stats.season.rank-1] : '';
        }

        stats.platform = $('#profile-platforms > a').text();

        return stats;
    };

    let parseFeaturedStats = ($, gameType) => {
        var stats = {};

        stats.masteringHeroe = $('[data-js="heroMastheadImage"]').attr(`data-hero-${gameType}`);

        return stats;
    }

    let parseHeroesStats = ($, gametype, overallOnly = false) => {
        var heroesMap = [];
        var featuredMap = [];
        var stats = {};

        //// Master stats
        _.each($(`#${gametype} select[data-group-id='stats'] option`), (item) => {
            heroesMap.push({ name: item.attribs['option-id'].toLowerCase().sanitize(), value: item.attribs['value'] });

            if (overallOnly)
                return false;
        });

        //// Featured stats
        _.each($(`#${gametype} select[data-group-id='comparisons'] option`), (item) => {
            featuredMap.push({ name: item.attribs['option-id'].toLowerCase().sanitize(), value: item.attribs['value'] });
        });

        //// Seeking heroe datas
        _.each(heroesMap, (map) => {
            stats[map.name] = {};

            //// Carreer
            _.each($(`#${gametype} [data-category-id="${map.value}"]`), (slide) => {
                var e = $(slide);
                _.each(e.find('tbody > tr'), (stat) => {
                    stats[map.name][stat.children[0].children[0].data.sanitize()] = stat.children[1].children[0].data.cast();
                });
            });

            //// Featured
            _.each(featuredMap, (feat) => {
                _.each($(`#${gametype} [data-group-id="comparisons"][data-category-id="overwatch.guid.${feat.value}"]`), (slide) => {
                    var value = $(slide).find(`div [data-hero-guid="${map.value}"] .description`);
                    stats[map.name][feat.name.sanitize()] = value;
                });
            });

            if (overallOnly)
                return false;
        });

        return stats;
    }

    let parseAchievements = ($) => {
        var categories = [];
        var stats = {};
        var achievements = [];
        _.each($(`select[data-group-id="achievements"] option`), (item) => {
            categories.push({ name: item.attribs['option-id'].toLowerCase(), value: item.attribs['value'] });
        });

        // Seeking achievements stats
        _.each(categories, (category) => {
            var ctns  = $(`[data-category-id="${category.value}"] > ul > div`);

            _.each(ctns, (ctn) => {
                var ctn = $(ctn);
                achievements.push({
                    acquired : ctn.find('.achievement-card').attr('class').indexOf('m-disabled') < 0,
                    thumbnail : ctn.find('.media-card-fill').attr('src'),
                    title : ctn.find('.tooltip-tip > .h5').text(),
                    description : ctn.find('.tooltip-tip > .h6').text(),
                    category : category.name
                })
            });
        });

        return achievements;
    }

    let handle = (err) => {

        if (!err.response && err instanceof (Error))
            throw err;

        switch (err.response.statusCode) {
            case 404:
                throw new Error('PROFILE_NOT_FOUND');
            case 500:
                throw new Error('TECHNICAL_EXCEPTION_HTML_STRUCTURE_MAY_HAVE_CHANGED')
            case 502:
                throw new Error('TECHNICAL_EXCEPTION_NOT_REACHABLE')
            default:
                throw new Error('TECHNICAL_EXCEPTION_NOT_IDENTIFIED')
        }
    }

    self.getOverall = (platform, region, tag, lang = 'en-us') => {
        return self.get(platform, region, tag, true, lang);
    }

    self.getAll = (platform, region, tag, overallOnly, lang = 'en-us') => {
        return self.get(platform, region, tag, false, lang);
    }

    self.get = (platform, region, tag, overallOnly, lang = 'en-us') => {
        var baseurl = getUrl(platform, region, tag, lang);

        return rp(baseurl).then((context) => {

            var result = {};
            var promises = [];
            const $ = cheerio.load(context);

            //// Seeking if profile exists
            if (context.indexOf('Profile Not Found') > 0)
                throw new Error('PROFILE_NOT_FOUND');

            //// Getting profile
            var p = new Promise((resolve, reject) => {
                result.profile = parseProfile($);
                result.profile.url = baseurl;

                resolve(result);
            });
            promises.push(p);

            //// Getting stats
            _.each(GAMETYPES, (type) => {
                var p = new Promise((resolve, reject) => {
                    result[type] = {};
                    result[type].global = parseFeaturedStats($, type);
                    result[type].heroes = parseHeroesStats($, type, overallOnly);
                    result[type].global = Object.assign(result[type].global, result[type].heroes['all_heroes']);
                    delete result[type].heroes.all_heroes;

                    resolve(result);
                });
                promises.push(p);
            });

            promises.push(new Promise((resolve, reject) => {
                result.achievements = parseAchievements($);
                resolve(result);
            }));

            return Promise.all(promises).then(() => {
                return result;
            });
        })
        .catch(handle);
    };

    self.search = (username, lang = "en-us") => {

        //// Sanitize for new UI version
        username = username.replace("-", "#");

        var options = {
            uri: getSearchUrl(username, lang, true),
            headers: {
                'User-Agent': 'Overwatch-JS'
            },
            json: true
        };

        return rp(options).then((datas) => {
            _.each(datas, (player) => {
                //// Region is not longer provided in the result
                player.region = "";
                player.tier = (player.level - player.level % 100) / 100;
                player.level = player.level % 100;
            });

            return datas;
        })
            .catch(handle);
    }
};

module.exports = new OverwatchProvider();
<commit_msg>Fixed typeerror<commit_after>#!/usr/bin/env node
"use strict";

/**
 * Node.js : overwatch-js
 * Access overwatch heroes and profile informations
 *
 **/

const cheerio = require('cheerio');
const rp = require('request-promise');
const _ = require('lodash/core');

const url = 'https://playoverwatch.com/%LANG%/career/';
const searchUrl = 'https://playoverwatch.com/%LANG%/search/account-by-name/';

const GAMETYPES = ['competitive', 'quickplay'];
const PLATFORMS = {
    XboxLive: "xbl",
    Playstation: "psn",
    PC: "pc"
}
const LOCALES = [
    "de-de",
    "en-us",
    "en-gb",
    "es-es",
    "es-mx",
    "fr-fr",
    "it-it",
    "pt-br",
    "pt-pt",
    "pl-pl",
    "ru-ru",
    "ko-kr",
    "ja-jp",
    "zh-tw",
    "zh-cn"
]

const RANKS = {
    "1" : [], //// Season 1
    "2" : [  //// Season 2
        'Bronze',
        'Silver',
        'Gold',
        'Platinum',
        'Diamond',
        'Master',
        'Grandmaster',
        'Top500'
    ]
}

const TIERS = require('./registry/ranking');

let OverwatchProvider = function () {
    var self = this;

    String.prototype.sanitize = function () {
        return this.trim().replace(" - ", "_").replace(/\s/g, "_").toLowerCase();
    }

    String.prototype.toTimestamp = function () {
        if (this.indexOf(':') > 0) {
            let intervals = this.split(':').reverse();
            intervals.at0 = (idx) => intervals[idx] || 0;
            // UTC date gives us milliseconds since the unix epoch
            return Date.UTC(1970, 0, intervals.at0(3) + 1, intervals.at0(2), intervals.at0(1), intervals.at0(0));
        }

        var swap = this;
        if (swap.endsWith('s')) swap = this.substr(0, this.length - 1); // remove trailing s
        if (swap.endsWith("second")) return parseInt(swap) * 1000;
        if (swap.endsWith("minute")) return parseInt(swap) * 60000;
        if (swap.endsWith("hour")) return parseInt(swap) * 3600000;
        if (swap.endsWith("day")) return parseInt(swap) * 86400000;

        return parseInt(swap);
    }

    String.prototype.cast = function () {
        if (this.indexOf('.') > 0 && this.indexOf(',') > 0) return parseFloat(this.replace(',',''));
        if (this.indexOf('.') > 0) return parseFloat(this);
        if (this.indexOf(':') > 0 || this.split(' ').length > 1) return this.toTimestamp();
        return parseInt(this.replace(/,/g, ''));
    }

    let getAvailableLocales = () => { return LOCALES; }

    let getUrl = (platform, region, tag, lang = 'en-us') => {

        if(! LOCALES.includes(lang))
            throw new Error(`${lang}_INVALID_LOCALE`);

        switch (platform) {
            case PLATFORMS.PC:
                region = "/" + region
                break;
            case PLATFORMS.Playstation:
            case PLATFORMS.XboxLive:
            default:
                //// No region must be specified
                region = "";
                break;
        }

        return url.replace('%LANG%', lang) + `${platform}${region}/${encodeURIComponent(tag)}`;
    };

    let getSearchUrl = (nickname, lang = "en-us", encode = false) => {

        if(! LOCALES.includes(lang))
            throw new Error(`${lang}_INVALID_LOCALE`);

        return searchUrl.replace('%LANG%', lang) + (encode ? encodeURIComponent(nickname) : nickname);
    };

    let parseSeason = (url) => {
        if (!url)
            return {};
        var m = url.match(/season\-([0-9])\/rank-([0-9])/);

        console.log(url);

        if(!m || m.length <= 1)
            return {};

        return { id : parseInt(m[1]), rank : parseInt(m[2])};
    }

    let parseTiers = (img) => {
        if(!img)
            return '';

        var m = img.match(/playerlevelrewards\/(.*)_Border.png/);

        if(!m || m.length <= 1)
            return '';

        return TIERS[m[1]];
    }

    let parseProfile = ($) => {
        var stats = {};
        stats.nick = $('.header-masthead').text();
        stats.level = parseInt($('div.player-level div').first().text());
        stats.avatar = $('.player-portrait').attr('src');
        stats.rank = parseInt($('div.competitive-rank > div').first().text());
        stats.tier = parseTiers($('.player-level').attr('style').replace(/^url|[\(\)]/g, ''));

        if (stats.rank)
        {
            stats.rankPicture = $('div.competitive-rank > img').attr('src');
            stats.season = parseSeason(stats.rankPicture);
            //stats.ranking = stats.season ? RANKS[stats.season.id][stats.season.rank-1] : '';
        }

        stats.platform = $('#profile-platforms > a').text();

        return stats;
    };

    let parseFeaturedStats = ($, gameType) => {
        var stats = {};

        stats.masteringHeroe = $('[data-js="heroMastheadImage"]').attr(`data-hero-${gameType}`);

        return stats;
    }

    let parseHeroesStats = ($, gametype, overallOnly = false) => {
        var heroesMap = [];
        var featuredMap = [];
        var stats = {};

        //// Master stats
        _.each($(`#${gametype} select[data-group-id='stats'] option`), (item) => {
            heroesMap.push({ name: item.attribs['option-id'].toLowerCase().sanitize(), value: item.attribs['value'] });

            if (overallOnly)
                return false;
        });

        //// Featured stats
        _.each($(`#${gametype} select[data-group-id='comparisons'] option`), (item) => {
            featuredMap.push({ name: item.attribs['option-id'].toLowerCase().sanitize(), value: item.attribs['value'] });
        });

        //// Seeking heroe datas
        _.each(heroesMap, (map) => {
            stats[map.name] = {};

            //// Carreer
            _.each($(`#${gametype} [data-category-id="${map.value}"]`), (slide) => {
                var e = $(slide);
                _.each(e.find('tbody > tr'), (stat) => {
                    stats[map.name][stat.children[0].children[0].data.sanitize()] = stat.children[1].children[0].data.cast();
                });
            });

            //// Featured
            _.each(featuredMap, (feat) => {
                _.each($(`#${gametype} [data-group-id="comparisons"][data-category-id="overwatch.guid.${feat.value}"]`), (slide) => {
                    var value = $(slide).find(`div [data-hero-guid="${map.value}"] .description`);
                    stats[map.name][feat.name.sanitize()] = value;
                });
            });

            if (overallOnly)
                return false;
        });

        return stats;
    }

    let parseAchievements = ($) => {
        var categories = [];
        var stats = {};
        var achievements = [];
        _.each($(`select[data-group-id="achievements"] option`), (item) => {
            categories.push({ name: item.attribs['option-id'].toLowerCase(), value: item.attribs['value'] });
        });

        // Seeking achievements stats
        _.each(categories, (category) => {
            var ctns  = $(`[data-category-id="${category.value}"] > ul > div`);

            _.each(ctns, (ctn) => {
                var ctn = $(ctn);
                achievements.push({
                    acquired : ctn.find('.achievement-card').attr('class').indexOf('m-disabled') < 0,
                    thumbnail : ctn.find('.media-card-fill').attr('src'),
                    title : ctn.find('.tooltip-tip > .h5').text(),
                    description : ctn.find('.tooltip-tip > .h6').text(),
                    category : category.name
                })
            });
        });

        return achievements;
    }

    let handle = (err) => {

        if (!err.response && err instanceof (Error))
            throw err;

        switch (err.response.statusCode) {
            case 404:
                throw new Error('PROFILE_NOT_FOUND');
            case 500:
                throw new Error('TECHNICAL_EXCEPTION_HTML_STRUCTURE_MAY_HAVE_CHANGED')
            case 502:
                throw new Error('TECHNICAL_EXCEPTION_NOT_REACHABLE')
            default:
                throw new Error('TECHNICAL_EXCEPTION_NOT_IDENTIFIED')
        }
    }

    self.getOverall = (platform, region, tag, lang = 'en-us') => {
        return self.get(platform, region, tag, true, lang);
    }

    self.getAll = (platform, region, tag, overallOnly, lang = 'en-us') => {
        return self.get(platform, region, tag, false, lang);
    }

    self.get = (platform, region, tag, overallOnly, lang = 'en-us') => {
        var baseurl = getUrl(platform, region, tag, lang);

        return rp(baseurl).then((context) => {

            var result = {};
            var promises = [];
            const $ = cheerio.load(context);

            //// Seeking if profile exists
            if (context.indexOf('Profile Not Found') > 0)
                throw new Error('PROFILE_NOT_FOUND');

            //// Getting profile
            var p = new Promise((resolve, reject) => {
                result.profile = parseProfile($);
                result.profile.url = baseurl;

                resolve(result);
            });
            promises.push(p);

            //// Getting stats
            _.each(GAMETYPES, (type) => {
                var p = new Promise((resolve, reject) => {
                    result[type] = {};
                    result[type].global = parseFeaturedStats($, type);
                    result[type].heroes = parseHeroesStats($, type, overallOnly);
                    result[type].global = Object.assign(result[type].global, result[type].heroes['all_heroes']);
                    delete result[type].heroes.all_heroes;

                    resolve(result);
                });
                promises.push(p);
            });

            promises.push(new Promise((resolve, reject) => {
                result.achievements = parseAchievements($);
                resolve(result);
            }));

            return Promise.all(promises).then(() => {
                return result;
            });
        })
        .catch(handle);
    };

    self.search = (username, lang = "en-us") => {

        //// Sanitize for new UI version
        username = username.replace("-", "#");

        var options = {
            uri: getSearchUrl(username, lang, true),
            headers: {
                'User-Agent': 'Overwatch-JS'
            },
            json: true
        };

        return rp(options).then((datas) => {
            _.each(datas, (player) => {
                //// Region is not longer provided in the result
                player.region = "";
                player.tier = (player.level - player.level % 100) / 100;
                player.level = player.level % 100;
            });

            return datas;
        })
            .catch(handle);
    }
};

module.exports = new OverwatchProvider();
<|endoftext|>