<commit_before>var PhotoFactory = Factories.photo,
    UserFactory = Factories.user;

describe('Photo', function () {
    //this has been tested because createdAt is not done automatically for photos (see photo class)
    describe('createdAt', function () {
        it('is set after creating date', function () {
            var date = new Date(); //The date when ~ the photo is created
            var promise = PhotoFactory.basic();

            return promise.then(function (photo) {
                photo.createdAt.should.be.approximately(date, 1000);
            });
        });

        it('is not changed after update', function () {
            var promise = PhotoFactory.basic();

            return promise.then(function (photo) {
                //Change property of photo
                photo.description = 'new description';

                //Save photo, and ensure createdAt isn't changed
                return photo.save().then(function (updatedPhoto) {
                    photo.createdAt.should.equal(updatedPhoto.createdAt).and.not.equal(null);
                });
            });
        });
    });

    describe('user', function () {
        it('allows the setting of user', function () {
            //Create test objects to use
            var promise = q.all([
                UserFactory.basic(),
                PhotoFactory.basic()
            ]);

            return promise.spread(function (user, photo) {
                return photo.setUser(user).then(function () {
                    //Ensure relationship was established
                    return photo.getUser().then(function (userFound) {
                        userFound.id.should.equal(user.id);
                    });
                });
            });
        });
    });

    describe('uploadSave', function () {
        it('creates a thumbnail version of the file', function () {
            return PhotoFactory.basic().then(function (photo) {
                photo.setPhotoByPath(system.pathTo('test/unit/fixtures/models/photo/image.png'));

                //Perform image upload
                return photo.uploadSave().then(function () {
                    //Ensure thumbnail was added
                    photo.id.should.be.a.Number;
                    photo.imagePath.should.equal('/photos/' + photo.id + '.png');
                    photo.thumbnailPath.should.equal('/photos/thumbnail/' + photo.id + '.png');
                });
            });
        });

//        it('notifies followers of the photo upload', function (done) {
//            //TODO fix & restore test
//            q.all([
//                    //Create test users
//                    UserFactory.basic(),
//                    UserFactory.basic()
//                ])
//                .spread(function (user, follower) {
//                    //Simulate following of followee
//                    user.addFollower(follower).then(function (follower) {
//                        //Create test photo
//                        PhotoFactory.basic({userID: user.id}).then(function (photo) {
//                            photo.setPhotoByPath(system.pathTo('test/unit/fixtures/models/photo/image.png'));
//
//                            //Perform image upload
//                            photo.uploadSave().then(function () {
//                                //Get followee's feed
//                                follower.getFeedItems().then(function (feedPhotos) {
//                                    feedPhotos.length.should.equal(1, done);
//                                    done();
//                                });
//                            })
//                        });
//                    });
//                });
//        });
    })
});<commit_msg>Update photo.js<commit_after>var PhotoFactory = Factories.photo,
    UserFactory = Factories.user;

describe('Photo', function () {
    //this has been tested because createdAt is not done automatically for photos (see photo class)
    describe('createdAt', function () {
        it('is set after creating date', function () {
            var date = new Date(); //The date when ~ the photo is created
            var promise = PhotoFactory.basic();

            return promise.then(function (photo) {
                photo.createdAt.should.be.approximately(date, 1000);
            });
        });

        it('is not changed after update', function () {
            var promise = PhotoFactory.basic();

            return promise.then(function (photo) {
                //Change property of photo
                photo.description = 'new description';

                //Save photo, and ensure createdAt isn't changed
                return photo.save().then(function (updatedPhoto) {
                    photo.createdAt.should.equal(updatedPhoto.createdAt).and.not.equal(null);
                });
            });
        });
    });

    describe('user', function () {
        it('allows the setting of user', function () {
            //Create test objects to use
            var promise = q.all([
                UserFactory.basic(),
                PhotoFactory.basic()
            ]);

            return promise.spread(function (user, photo) {
                return photo.setUser(user).then(function () {
                    //Ensure relationship was established
                    return photo.getUser().then(function (userFound) {
                        userFound.id.should.equal(user.id);
                    });
                });
            });
        });
    });

    describe('uploadSave', function () {
        it('creates a thumbnail version of the file', function () {
            return PhotoFactory.basic().then(function (photo) {
                photo.setPhotoByPath(system.pathTo('test/unit/fixtures/models/photo/image.png'));

                //Perform image upload
                return photo.uploadSave().then(function () {
                    //Ensure thumbnail was added
                    photo.id.should.be.a.Number;
                    photo.imagePath.should.equal('/photos/' + photo.id + '.png');
                    photo.thumbnailPath.should.equal('/photos/thumbnail/' + photo.id + '.png');
                });
            });
        });

//        it('notifies followers of the photo upload', function (done) {
//            //TODO fix & restore test
//            q.all([
//                    //Create test users
//                    UserFactory.basic(),
//                    UserFactory.basic()
//                ])
//                .spread(function (user, follower) {
//                    //Simulate following of followee
//                    user.addFollower(follower).then(function (follower) {
//                        //Create test photo
//                        PhotoFactory.basic({userID: user.id}).then(function (photo) {
//                            photo.setPhotoByPath(system.pathTo('test/unit/fixtures/models/photo/image.png'));
//
//                            //Perform image upload
//                            photo.uploadSave().then(function () {
//                                //Get followee's feed
//                                follower.getFeedItems().then(function (feedPhotos) {
//                                    feedPhotos.length.should.equal(1, done);
//                                    done();
//                                });
//                            })
//                        });
//                    });
//                });
//        });
    })

    // processPhotoUpload UNIT TESTS
    describe('processPhotoUpload', function(){

        // Successfully creates image and thumbnail and write
        //      correct paths to database
        it('creates versions of file upload and writes paths to db',function(){

            return PhotoFactory.basic().then(function (photo) {

                // setup valid pre-requisites
                photo.setImageUpload(this._photoUpload);
                photo.setPhotoByPath(system.pathTo('test/unit/fixtures/models/photo/image.png'));
                photo.processPhotoUpload().then(function(){

                    // Verify valid photo id and self reference
                    photo.id.should.be.a.Number;

                    // Verify that photo paths are correctly added
                    photo.imagePath.should.equal('/photos/' + photo.id + '.png');
                    photo.thumbnailPath.should.equal('/photos/thumbnail/' + photo.id + '.png');

                });

            });

        });

        // Pass a photo with invalid id, throws invalid id
        it('non-valid id',function(){

            return PhotoFactory.basic().then(function (photo) {

                // setup valid pre-requisites
                photo.setImageUpload(this._photoUpload);
                photo.setPhotoByPath(system.pathTo('test/unit/fixtures/models/photo/image.png'));

                // Set photo id to invalid value
                photo.id = null;

                // Call processPhotoUpload
                //  function should throw invalid id error
                photo.processPhotoUpload().should.throw(new Error('Invalid call - ID must be set'));

            });

        });

        // Pass invalid photo, throws invalid photo
        it('invalid image',function(){

            return PhotoFactory.basic().then(function (photo) {
                photo.setImageUpload(this._photoUpload);
                photo.setPhotoByPath(system.pathTo('test/unit/fixtures/models/photo/image.png'));

                // Set photo to invalid
                this.photo = null;

                // Call processPhotoUpload with invalid photo,
                //      should throw Error
                photo.processPhotoUpload().should.throw(Error('Invalid call - setImageUpload() must be called'));

            });

        });

    });
});
<|endoftext|>


<commit_before><commit_msg>JsonCreator unit test - tweak name<commit_after><|endoftext|>


<commit_before>const validate = require('../../../src/lib/validate');

describe('unit test lib/validate.js', () => {
    test('validate username locally', () => {
        let response;
        expect(typeof validate.validateUsernameLocally).toBe('function');
        response = validate.validateUsernameLocally('abc');
        expect(response).toEqual({valid: true});
        response = validate.validateUsernameLocally('abcdefghijklmnopqrst');
        expect(response).toEqual({valid: true});
        response = validate.validateUsernameLocally('abc-def-ghi');
        expect(response).toEqual({valid: true});
        response = validate.validateUsernameLocally('');
        expect(response).toEqual({valid: false, errMsgId: 'general.required'});
        response = validate.validateUsernameLocally('ab');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameMinLength'});
        response = validate.validateUsernameLocally('abcdefghijklmnopqrstu');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameMaxLength'});
        response = validate.validateUsernameLocally('abc def');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameRegexp'});
        response = validate.validateUsernameLocally('abc!def');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameRegexp'});
        response = validate.validateUsernameLocally('abc😄def');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameRegexp'});
    });

    test('validate password', () => {
        let response;
        expect(typeof validate.validatePassword).toBe('function');
        response = validate.validatePassword('abcdef');
        expect(response).toEqual({valid: true});
        response = validate.validatePassword('abcdefghijklmnopqrst');
        expect(response).toEqual({valid: true});
        response = validate.validatePassword('passwo');
        expect(response).toEqual({valid: true});
        response = validate.validatePassword('');
        expect(response).toEqual({valid: false, errMsgId: 'general.required'});
        response = validate.validatePassword('abcde');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordLength'});
        response = validate.validatePassword('password');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordNotEquals'});
        response = validate.validatePassword('abcdefg', 'abcdefg');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordNotUsername'});
        response = validate.validatePassword('abcdefg', 'abcdefG');
        expect(response).toEqual({valid: true});
    });

    test('validate password confirm', () => {
        let response;
        expect(typeof validate.validatePasswordConfirm).toBe('function');
        response = validate.validatePasswordConfirm('abcdef', 'abcdef');
        expect(response).toEqual({valid: true});
        response = validate.validatePasswordConfirm('abcdefghijklmnopqrst', 'abcdefghijklmnopqrst');
        expect(response).toEqual({valid: true});
        response = validate.validatePasswordConfirm('passwo', 'passwo');
        expect(response).toEqual({valid: true});
        response = validate.validatePasswordConfirm('', '');
        expect(response).toEqual({valid: false, errMsgId: 'general.required'});
        response = validate.validatePasswordConfirm('abcdef', 'abcdefg');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordConfirmNotEquals'});
        response = validate.validatePasswordConfirm('abcdef', '123456');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordConfirmNotEquals'});
        response = validate.validatePasswordConfirm('', 'abcdefg');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordConfirmNotEquals'});
    });
});
<commit_msg>add tests for local email validation<commit_after>const validate = require('../../../src/lib/validate');

describe('unit test lib/validate.js', () => {
    test('validate username locally', () => {
        let response;
        expect(typeof validate.validateUsernameLocally).toBe('function');
        response = validate.validateUsernameLocally('abc');
        expect(response).toEqual({valid: true});
        response = validate.validateUsernameLocally('abcdefghijklmnopqrst');
        expect(response).toEqual({valid: true});
        response = validate.validateUsernameLocally('abc-def-ghi');
        expect(response).toEqual({valid: true});
        response = validate.validateUsernameLocally('');
        expect(response).toEqual({valid: false, errMsgId: 'general.required'});
        response = validate.validateUsernameLocally('ab');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameMinLength'});
        response = validate.validateUsernameLocally('abcdefghijklmnopqrstu');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameMaxLength'});
        response = validate.validateUsernameLocally('abc def');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameRegexp'});
        response = validate.validateUsernameLocally('abc!def');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameRegexp'});
        response = validate.validateUsernameLocally('abc😄def');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationUsernameRegexp'});
    });

    test('validate password', () => {
        let response;
        expect(typeof validate.validatePassword).toBe('function');
        response = validate.validatePassword('abcdef');
        expect(response).toEqual({valid: true});
        response = validate.validatePassword('abcdefghijklmnopqrst');
        expect(response).toEqual({valid: true});
        response = validate.validatePassword('passwo');
        expect(response).toEqual({valid: true});
        response = validate.validatePassword('');
        expect(response).toEqual({valid: false, errMsgId: 'general.required'});
        response = validate.validatePassword('abcde');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordLength'});
        response = validate.validatePassword('password');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordNotEquals'});
        response = validate.validatePassword('abcdefg', 'abcdefg');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordNotUsername'});
        response = validate.validatePassword('abcdefg', 'abcdefG');
        expect(response).toEqual({valid: true});
    });

    test('validate password confirm', () => {
        let response;
        expect(typeof validate.validatePasswordConfirm).toBe('function');
        response = validate.validatePasswordConfirm('abcdef', 'abcdef');
        expect(response).toEqual({valid: true});
        response = validate.validatePasswordConfirm('abcdefghijklmnopqrst', 'abcdefghijklmnopqrst');
        expect(response).toEqual({valid: true});
        response = validate.validatePasswordConfirm('passwo', 'passwo');
        expect(response).toEqual({valid: true});
        response = validate.validatePasswordConfirm('', '');
        expect(response).toEqual({valid: false, errMsgId: 'general.required'});
        response = validate.validatePasswordConfirm('abcdef', 'abcdefg');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordConfirmNotEquals'});
        response = validate.validatePasswordConfirm('abcdef', '123456');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordConfirmNotEquals'});
        response = validate.validatePasswordConfirm('', 'abcdefg');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationPasswordConfirmNotEquals'});
    });

    test('validate email address locally', () => {
        let response;
        expect(typeof validate.validateEmailLocally).toBe('function');

        // permitted addresses:
        response = validate.validateEmailLocally('abc@def.com');
        expect(response).toEqual({valid: true});
        response = validate.validateEmailLocally('abcdefghijklmnopqrst@abcdefghijklmnopqrst.info');
        expect(response).toEqual({valid: true});
        response = validate.validateEmailLocally('abc-def-ghi@jkl-mno.org');
        expect(response).toEqual({valid: true});
        response = validate.validateEmailLocally('_______@example.com');
        expect(response).toEqual({valid: true});
        response = validate.validateEmailLocally('email@example.museum');
        expect(response).toEqual({valid: true});
        response = validate.validateEmailLocally('email@example.co.jp');
        expect(response).toEqual({valid: true});

        // non-permitted addresses:
        response = validate.validateEmailLocally('');
        expect(response).toEqual({valid: false, errMsgId: 'general.required'});
        response = validate.validateEmailLocally('a');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('abc@def');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('abc@def.c');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('abc😄def@emoji.pizza');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('あいうえお@example.com');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('Abc..123@example.com');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('Joe Smith <email@example.com>');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('email@example@example.com');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('email@example..com');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});

        // edge cases:
        // these are strictly legal according to email addres spec, but rejected by library we use:
        response = validate.validateEmailLocally('email@123.123.123.123');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
        response = validate.validateEmailLocally('much."more unusual"@example.com');
        expect(response).toEqual({valid: false, errMsgId: 'registration.validationEmailInvalid'});
    });
});
<|endoftext|>


<commit_before>suite('Trigonometry', function() {
  var theta = 90;
  var x = 0;
  var y = 1;
  var ratio = 0.5;
  var RADIANS = 'radians';
  var DEGREES = 'degrees';
  var myp5;

  setup(function(done) {
    new p5(function(p) {
      p.setup = function() {
        myp5 = p;
        done();
      };
    });
  });

  teardown(function() {
    myp5.remove();
  });

  var handleDegreesAndRadians = function(func) {
    test('should handle degrees', function() {
      myp5.angleMode(DEGREES);
      var degToRad = myp5.radians(theta);
      assert.equal(Math[func](degToRad), myp5[func](theta));
    });

    test('should handle radians', function() {
      myp5.angleMode(RADIANS);
      assert.equal(Math[func](theta), myp5[func](theta));
    });
  };

  var ahandleDegreesAndRadians = function(func) {
    test('should handle degrees', function() {
      myp5.angleMode(DEGREES);
      assert.equal(myp5.degrees(Math[func](ratio)), myp5[func](ratio));
    });

    test('should handle radians', function() {
      myp5.angleMode(RADIANS);
      assert.equal(Math[func](ratio), myp5[func](ratio));
    });
  };

  suite('p5.prototype.angleMode', function() {
    test('should set constant to DEGREES', function() {
      myp5.angleMode(DEGREES);
      assert.equal(myp5._angleMode, 'degrees');
    });

    test('should set constant to RADIANS', function() {
      myp5.angleMode(RADIANS);
      assert.equal(myp5._angleMode, 'radians');
    });

    test('should always be RADIANS or DEGREES', function() {
      myp5.angleMode('wtflolzkk');
      assert.equal(myp5._angleMode, 'radians');
    });

    test('should return radians', function() {
      myp5.angleMode(RADIANS);
      assert.equal(myp5.angleMode(), 'radians');
    });

    test('should return degrees', function() {
      myp5.angleMode(DEGREES);
      assert.equal(myp5.angleMode(), 'degrees');
    });
  });

  suite('p5.prototype.degrees', function() {
    test('should return the angle in radians when angleMode is DEGREES', function() {
      myp5.angleMode(DEGREES);
      var angleInRad = 360 * theta / (2 * Math.PI); // This is degToRad conversion
      assert.equal(myp5.degrees(theta), angleInRad);
    });

    test('should return the angle in radians when angleMode is RADIANS', function() {
      myp5.angleMode(RADIANS);
      var angleInRad = 360 * theta / (2 * Math.PI); // This is degToRad conversion
      assert.equal(myp5.degrees(theta), angleInRad);
    });
  });

  suite('p5.prototype.radians', function() {
    test('should return the angle in degrees when angleMode is RADIANS', function() {
      myp5.angleMode(RADIANS);
      var angleInDeg = 2 * Math.PI * theta / 360; // This is RadToDeg conversion
      assert.equal(myp5.radians(theta), angleInDeg);
    });

    test('should return the angle in degrees when angleMode is DEGREES', function() {
      myp5.angleMode(DEGREES);
      var angleInDeg = 2 * Math.PI * theta / 360; // This is RadToDeg conversion
      assert.equal(myp5.radians(theta), angleInDeg);
    });
  });

  suite('p5.prototype.asin', function() {
    ahandleDegreesAndRadians('asin');
  });

  suite('p5.prototype.atan', function() {
    ahandleDegreesAndRadians('atan');
  });

  suite('p5.prototype.acos', function() {
    ahandleDegreesAndRadians('acos');
  });

  suite('p5.prototype.sin', function() {
    handleDegreesAndRadians('sin');
  });

  suite('p5.prototype.cos', function() {
    handleDegreesAndRadians('cos');
  });

  suite('p5.prototype.tan', function() {
    handleDegreesAndRadians('tan');
  });

  suite('p5.prototype.atan2', function() {
    test('should handle degrees', function() {
      myp5.angleMode(DEGREES);
      assert.equal(myp5.degrees(Math.atan2(y, x)), myp5.atan2(y, x));
    });

    test('should handle radians', function() {
      myp5.angleMode(RADIANS);
      assert.equal(Math.atan2(y, x), myp5.atan2(y, x));
    });
  });
});
<commit_msg>added new test and fixed test<commit_after>suite('Trigonometry', function() {
  var theta = 90;
  var x = 0;
  var y = 1;
  var ratio = 0.5;
  var RADIANS = 'radians';
  var DEGREES = 'degrees';
  var myp5;

  setup(function(done) {
    new p5(function(p) {
      p.setup = function() {
        myp5 = p;
        done();
      };
    });
  });

  teardown(function() {
    myp5.remove();
  });

  var handleDegreesAndRadians = function(func) {
    test('should handle degrees', function() {
      myp5.angleMode(DEGREES);
      var degToRad = myp5.radians(theta);
      assert.equal(Math[func](degToRad), myp5[func](theta));
    });

    test('should handle radians', function() {
      myp5.angleMode(RADIANS);
      assert.equal(Math[func](theta), myp5[func](theta));
    });
  };

  var ahandleDegreesAndRadians = function(func) {
    test('should handle degrees', function() {
      myp5.angleMode(DEGREES);
      assert.equal(myp5.degrees(Math[func](ratio)), myp5[func](ratio));
    });

    test('should handle radians', function() {
      myp5.angleMode(RADIANS);
      assert.equal(Math[func](ratio), myp5[func](ratio));
    });
  };

  suite('p5.prototype.angleMode', function() {
    test('should set constant to DEGREES', function() {
      myp5.angleMode(DEGREES);
      assert.equal(myp5.angleMode(), 'degrees');
    });

    test('should set constant to RADIANS', function() {
      myp5.angleMode(RADIANS);
      assert.equal(myp5.angleMode(), 'radians');
    });

    test('wrong param type', function() {
      assert.validationError(function() {
        myp5.angleMode('wtflolzkk');
      });
    });

    test('should return radians', function() {
      myp5.angleMode(RADIANS);
      assert.equal(myp5.angleMode(), 'radians');
    });

    test('should return degrees', function() {
      myp5.angleMode(DEGREES);
      assert.equal(myp5.angleMode(), 'degrees');
    });

    test('should always be RADIANS or DEGREES', function() {
      myp5.angleMode('wtflolzkk');
      assert.equal(myp5.angleMode(), 'radians');
    });
  });

  suite('p5.prototype.degrees', function() {
    test('should return the angle in radians when angleMode is DEGREES', function() {
      myp5.angleMode(DEGREES);
      var angleInRad = 360 * theta / (2 * Math.PI); // This is degToRad conversion
      assert.equal(myp5.degrees(theta), angleInRad);
    });

    test('should return the angle in radians when angleMode is RADIANS', function() {
      myp5.angleMode(RADIANS);
      var angleInRad = 360 * theta / (2 * Math.PI); // This is degToRad conversion
      assert.equal(myp5.degrees(theta), angleInRad);
    });
  });

  suite('p5.prototype.radians', function() {
    test('should return the angle in degrees when angleMode is RADIANS', function() {
      myp5.angleMode(RADIANS);
      var angleInDeg = 2 * Math.PI * theta / 360; // This is RadToDeg conversion
      assert.equal(myp5.radians(theta), angleInDeg);
    });

    test('should return the angle in degrees when angleMode is DEGREES', function() {
      myp5.angleMode(DEGREES);
      var angleInDeg = 2 * Math.PI * theta / 360; // This is RadToDeg conversion
      assert.equal(myp5.radians(theta), angleInDeg);
    });
  });

  suite('p5.prototype.asin', function() {
    ahandleDegreesAndRadians('asin');
  });

  suite('p5.prototype.atan', function() {
    ahandleDegreesAndRadians('atan');
  });

  suite('p5.prototype.acos', function() {
    ahandleDegreesAndRadians('acos');
  });

  suite('p5.prototype.sin', function() {
    handleDegreesAndRadians('sin');
  });

  suite('p5.prototype.cos', function() {
    handleDegreesAndRadians('cos');
  });

  suite('p5.prototype.tan', function() {
    handleDegreesAndRadians('tan');
  });

  suite('p5.prototype.atan2', function() {
    test('should handle degrees', function() {
      myp5.angleMode(DEGREES);
      assert.equal(myp5.degrees(Math.atan2(y, x)), myp5.atan2(y, x));
    });

    test('should handle radians', function() {
      myp5.angleMode(RADIANS);
      assert.equal(Math.atan2(y, x), myp5.atan2(y, x));
    });
  });
});
<|endoftext|>


<commit_before>import StringManipulator from 'src/database/stringManipulation';
import exceptions from 'src/database/exceptions';
import constants from 'src/database/constants';
import DateTime from 'src/database/generated-data/dateTime';

const alasql = require('alasql');

const stringManipulator = new StringManipulator();
const dateTime = new DateTime();

function getDataOutOfAlasql(data) {
  return Object.values(data[0][0])[0];
}

function getSecondDataOutOfAlasql(data) {
  return Object.values(data[0][0])[1];
}

function getArray(data) {
  return data[0];
}

function getCurrentFilePath(fileId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(filePath => resolve(filePath))
    .catch(sqlErr => reject(sqlErr))
  );
}

function getCurrentFolderPath(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FOLDER_PATH,
                                                   ' FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(folderPath => resolve(folderPath))
    .catch(sqlErr => reject(sqlErr))
  );
}

// duplicate private function to help with cascadeChangeFilePath
function changeSingleFilePath(fileId, newPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FILE_MANAGER,
                                                   ' SET ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' = "', newPath,
                                                   '" WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeChangeFilePath(index, prevBasePath, newBasePath, fileArr) {
  return new Promise((resolve, reject) => {
    if (index >= fileArr.length) {
      return true;
    }
    const fileToChangePathIndex = Object.values(fileArr[index])[0];
    let newPath;
    return getCurrentFilePath(fileToChangePathIndex)
    .then((currentFilePath) => {
      const childPath = currentFilePath.toString().split(prevBasePath)[1];
      newPath = stringManipulator.stringConcat(newBasePath, childPath);
      return changeSingleFilePath(fileToChangePathIndex, newPath)
      .catch(sqlErr => reject(sqlErr));
    })
    .then(() => {
      cascadeChangeFilePath(index + 1, prevBasePath, newBasePath, fileArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function changeSingleFolderPath(folderId, newPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FOLDER,
                                                   ' SET ', constants.HEADER_FOLDER_PATH,
                                                   ' = "', newPath,
                                                   '" WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function changeSingleFolderName(folderId, newFolderName) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FOLDER,
                                                   ' SET ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                   ' = "', newFolderName,
                                                   '" WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeChangeFolderPath(index, prevBasePath, newBasePath, folderArr) {
  return new Promise((resolve, reject) => {
    if (index >= folderArr.length) {
      return true;
    }
    const folderToChangePathIndex = Object.values(folderArr[index])[0];
    let newPath;
    return getCurrentFolderPath(folderToChangePathIndex)
    .then((currentFolderPath) => {
      const childPath = currentFolderPath.toString().split(prevBasePath)[1];
      newPath = stringManipulator.stringConcat(newBasePath, childPath);
      return changeSingleFolderPath(folderToChangePathIndex, newPath)
      .catch(sqlErr => reject(sqlErr));
    })
    .then(() => {
      cascadeChangeFolderPath(index + 1, prevBasePath, newBasePath, folderArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function deleteSingleFolder(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeDeleteFolder(index, folderArr) {
  return new Promise((resolve, reject) => {
    if (index >= folderArr.length) {
      return true;
    }
    const folderToDeleteIndex = Object.values(folderArr[index])[0];
    return deleteSingleFolder(folderToDeleteIndex)
    .then(() => {
      cascadeDeleteFolder(index + 1, folderArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

// duplicate private function to help with cascadeDeleteFile
function deleteSingleFile(fileId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeDeleteFile(index, fileArr) {
  return new Promise((resolve, reject) => {
    if (index >= fileArr.length) {
      return true;
    }
    const fileToDeleteIndex = Object.values(fileArr[index])[0];
    return deleteSingleFile(fileToDeleteIndex)
    .then(() => {
      cascadeDeleteFile(index + 1, fileArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function getFolderPathAndNameFromId(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FOLDER_PATH,
                                                   ', ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                   ' FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(data => resolve(data))
    .catch(sqlErr => reject(sqlErr))
  );
}

function getListOfFolderIdsWithSamePath(folderPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_PATH,
                                                   ' LIKE "', folderPath, '%"')])
    .then(folderList => resolve(folderList))
    .catch(sqlErr => reject(sqlErr))
  );
}

function getListOfFilesIdsWithSamePath(folderPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' LIKE "', folderPath, '%"')])
    .then(fileList => resolve(fileList))
    .catch(sqlErr => reject(sqlErr))
  );
}

export default function sqlCommands() {
  this.linkDatabaseToIndexedDB = function linkDatabaseToIndexedDB(databaseName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const databaseRequestStr = stringManipulator.stringConcat(
          'CREATE INDEXEDDB DATABASE IF NOT EXISTS ', databaseName, ';',
          'ATTACH INDEXEDDB DATABASE ', databaseName, ';',
          'USE ', databaseName, ';');
        return alasql.promise([databaseRequestStr])
        .then(() => resolve(true))
        .catch(sqlError => reject(sqlError));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.getFullTableData = function getFullTableData(tableName) {
    // ensure working in browsers that support Promise
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', tableName)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.createTable = function createTable(sqlStatement) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('CREATE TABLE IF NOT EXISTS ', sqlStatement)])
        .then(() => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.insertContent = function insertContent(tableName, alasqlArray) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise(stringManipulator.stringConcat('INSERT INTO ', tableName,
                                                       ' VALUES ?'), alasqlArray)
        .then(data => resolve(data))
        .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.partialSearchFileName = function partialSearchFileName(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_NAME,
                                                       ' LIKE "%', searchString, '%"')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
  this.getMaxFileId = function getMaxFileId() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT max(', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ') FROM ', constants.ENTITIES_FILE_MANAGER)])
        .then((data) => {
          const maxFileId = getDataOutOfAlasql(data);
          if (typeof maxFileId === 'number') {
            resolve(maxFileId);
          } else {
            resolve(-1);
          }
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
  this.getMaxFolderId = function getMaxFolderId() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT MAX(', constants.HEADER_FOLDER_FOLDER_ID,
                                                       ') FROM ', constants.ENTITIES_FOLDER)])
        .then((data) => {
          const maxFolderId = getDataOutOfAlasql(data);
          if (typeof maxFolderId === 'number') {
            resolve(maxFolderId);
          } else {
            resolve(0);
          }
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.partialSearchFolderName = function partialSearchFolderName(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                       ' LIKE "%', searchString, '%"')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFilesFromFolder = function loadFilesFromFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFoldersFromFolder = function loadFoldersFromFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_PARENT_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFile = function loadFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_FILE_MARKDOWN,
                                                       ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ' = ', fileId)])
        .then(data => resolve(getDataOutOfAlasql(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.saveFile = function saveFile(fileId, markdownFile) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        .then(() => {
          const currentDateTime = dateTime.getCurrentDateTime();
          alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FILE_MANAGER,
                                                         ' SET ', constants.HEADER_FILE_MANAGER_LAST_MODIFIED_DATE,
                                                         ' = "', currentDateTime,
                                                         '" WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                         ' = ', fileId)])
          .catch(sqlError => reject(sqlError));
        })
        .then(() => resolve(true))
        .catch(sqlErr => reject(sqlErr)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.deleteFile = function deleteFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ' = ', fileId)])
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.deleteFolder = function deleteFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(() => resolve())
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  // external library not functioning so I cannot do anything here
  this.deleteTable = function deleteTable(tableName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DROP TABLE IF EXISTS ', tableName)])
        .then(isSuccess => resolve(isSuccess))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
}
<commit_msg>Add exactSearchStartFileNameInFolder function to sqlCommands.js<commit_after>import StringManipulator from 'src/database/stringManipulation';
import exceptions from 'src/database/exceptions';
import constants from 'src/database/constants';
import DateTime from 'src/database/generated-data/dateTime';

const alasql = require('alasql');

const stringManipulator = new StringManipulator();
const dateTime = new DateTime();

function getDataOutOfAlasql(data) {
  return Object.values(data[0][0])[0];
}

function getSecondDataOutOfAlasql(data) {
  return Object.values(data[0][0])[1];
}

function getArray(data) {
  return data[0];
}

function getCurrentFilePath(fileId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(filePath => resolve(filePath))
    .catch(sqlErr => reject(sqlErr))
  );
}

function getCurrentFolderPath(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FOLDER_PATH,
                                                   ' FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(folderPath => resolve(folderPath))
    .catch(sqlErr => reject(sqlErr))
  );
}

// duplicate private function to help with cascadeChangeFilePath
function changeSingleFilePath(fileId, newPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FILE_MANAGER,
                                                   ' SET ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' = "', newPath,
                                                   '" WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeChangeFilePath(index, prevBasePath, newBasePath, fileArr) {
  return new Promise((resolve, reject) => {
    if (index >= fileArr.length) {
      return true;
    }
    const fileToChangePathIndex = Object.values(fileArr[index])[0];
    let newPath;
    return getCurrentFilePath(fileToChangePathIndex)
    .then((currentFilePath) => {
      const childPath = currentFilePath.toString().split(prevBasePath)[1];
      newPath = stringManipulator.stringConcat(newBasePath, childPath);
      return changeSingleFilePath(fileToChangePathIndex, newPath)
      .catch(sqlErr => reject(sqlErr));
    })
    .then(() => {
      cascadeChangeFilePath(index + 1, prevBasePath, newBasePath, fileArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function changeSingleFolderPath(folderId, newPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FOLDER,
                                                   ' SET ', constants.HEADER_FOLDER_PATH,
                                                   ' = "', newPath,
                                                   '" WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function changeSingleFolderName(folderId, newFolderName) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FOLDER,
                                                   ' SET ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                   ' = "', newFolderName,
                                                   '" WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeChangeFolderPath(index, prevBasePath, newBasePath, folderArr) {
  return new Promise((resolve, reject) => {
    if (index >= folderArr.length) {
      return true;
    }
    const folderToChangePathIndex = Object.values(folderArr[index])[0];
    let newPath;
    return getCurrentFolderPath(folderToChangePathIndex)
    .then((currentFolderPath) => {
      const childPath = currentFolderPath.toString().split(prevBasePath)[1];
      newPath = stringManipulator.stringConcat(newBasePath, childPath);
      return changeSingleFolderPath(folderToChangePathIndex, newPath)
      .catch(sqlErr => reject(sqlErr));
    })
    .then(() => {
      cascadeChangeFolderPath(index + 1, prevBasePath, newBasePath, folderArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function deleteSingleFolder(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeDeleteFolder(index, folderArr) {
  return new Promise((resolve, reject) => {
    if (index >= folderArr.length) {
      return true;
    }
    const folderToDeleteIndex = Object.values(folderArr[index])[0];
    return deleteSingleFolder(folderToDeleteIndex)
    .then(() => {
      cascadeDeleteFolder(index + 1, folderArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

// duplicate private function to help with cascadeDeleteFile
function deleteSingleFile(fileId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeDeleteFile(index, fileArr) {
  return new Promise((resolve, reject) => {
    if (index >= fileArr.length) {
      return true;
    }
    const fileToDeleteIndex = Object.values(fileArr[index])[0];
    return deleteSingleFile(fileToDeleteIndex)
    .then(() => {
      cascadeDeleteFile(index + 1, fileArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function getFolderPathAndNameFromId(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FOLDER_PATH,
                                                   ', ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                   ' FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(data => resolve(data))
    .catch(sqlErr => reject(sqlErr))
  );
}

function getListOfFolderIdsWithSamePath(folderPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_PATH,
                                                   ' LIKE "', folderPath, '%"')])
    .then(folderList => resolve(folderList))
    .catch(sqlErr => reject(sqlErr))
  );
}

function getListOfFilesIdsWithSamePath(folderPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' LIKE "', folderPath, '%"')])
    .then(fileList => resolve(fileList))
    .catch(sqlErr => reject(sqlErr))
  );
}

export default function sqlCommands() {
  this.linkDatabaseToIndexedDB = function linkDatabaseToIndexedDB(databaseName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const databaseRequestStr = stringManipulator.stringConcat(
          'CREATE INDEXEDDB DATABASE IF NOT EXISTS ', databaseName, ';',
          'ATTACH INDEXEDDB DATABASE ', databaseName, ';',
          'USE ', databaseName, ';');
        return alasql.promise([databaseRequestStr])
        .then(() => resolve(true))
        .catch(sqlError => reject(sqlError));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.getFullTableData = function getFullTableData(tableName) {
    // ensure working in browsers that support Promise
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', tableName)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.createTable = function createTable(sqlStatement) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('CREATE TABLE IF NOT EXISTS ', sqlStatement)])
        .then(() => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.insertContent = function insertContent(tableName, alasqlArray) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise(stringManipulator.stringConcat('INSERT INTO ', tableName,
                                                       ' VALUES ?'), alasqlArray)
        .then(data => resolve(data))
        .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.partialSearchFileName = function partialSearchFileName(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_NAME,
                                                       ' LIKE "%', searchString, '%"')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.exactSearchStartFileNameInFolder = function exactSearchStartFileNameInFolder(searchString, filePath) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_FILE_NAME,
                                                       ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_PATH,
                                                       ' LIKE "', filePath, '%"',
                                                       ' ORDER BY ', constants.HEADER_FILE_MANAGER_FILE_NAME,
                                                       ' ASC')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.getMaxFileId = function getMaxFileId() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT max(', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ') FROM ', constants.ENTITIES_FILE_MANAGER)])
        .then((data) => {
          const maxFileId = getDataOutOfAlasql(data);
          if (typeof maxFileId === 'number') {
            resolve(maxFileId);
          } else {
            resolve(-1);
          }
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
  this.getMaxFolderId = function getMaxFolderId() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT MAX(', constants.HEADER_FOLDER_FOLDER_ID,
                                                       ') FROM ', constants.ENTITIES_FOLDER)])
        .then((data) => {
          const maxFolderId = getDataOutOfAlasql(data);
          if (typeof maxFolderId === 'number') {
            resolve(maxFolderId);
          } else {
            resolve(0);
          }
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.partialSearchFolderName = function partialSearchFolderName(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                       ' LIKE "%', searchString, '%"')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFilesFromFolder = function loadFilesFromFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFoldersFromFolder = function loadFoldersFromFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_PARENT_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFile = function loadFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_FILE_MARKDOWN,
                                                       ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ' = ', fileId)])
        .then(data => resolve(getDataOutOfAlasql(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.saveFile = function saveFile(fileId, markdownFile) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        .then(() => {
          const currentDateTime = dateTime.getCurrentDateTime();
          alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FILE_MANAGER,
                                                         ' SET ', constants.HEADER_FILE_MANAGER_LAST_MODIFIED_DATE,
                                                         ' = "', currentDateTime,
                                                         '" WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                         ' = ', fileId)])
          .catch(sqlError => reject(sqlError));
        })
        .then(() => resolve(true))
        .catch(sqlErr => reject(sqlErr)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.deleteFile = function deleteFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ' = ', fileId)])
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.deleteFolder = function deleteFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(() => resolve())
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  // external library not functioning so I cannot do anything here
  this.deleteTable = function deleteTable(tableName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DROP TABLE IF EXISTS ', tableName)])
        .then(isSuccess => resolve(isSuccess))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
}
<|endoftext|>


<commit_before>var Article = require('../model/articles');
var Cluster = require('../model/clusters');
var Feed = require('../model/feeds');

module.exports = (function() {
    var getCluster = function(id, promise) {
        console.log(id);
        // .populate({feed: 'feed_id', select: 'feed'})
        Cluster.findById(id).populate({path: 'articles', populate: {path: 'feed_id'}}).exec(function(err, res) {
            if (err) return handleError(err, promise);
            console.log(res);
            promise.resolve(res);
        });
    }

    function handleError(err, promise) {
        console.log(err);
        if (promise) promise.reject(err);
    }

    return {
        getCluster: getCluster
    }
})();
<commit_msg>Remove log<commit_after>var Article = require('../model/articles');
var Cluster = require('../model/clusters');
var Feed = require('../model/feeds');

module.exports = (function() {
    var getCluster = function(id, promise) {
        console.log(id);
        // .populate({feed: 'feed_id', select: 'feed'})
        Cluster.findById(id).populate({path: 'articles', populate: {path: 'feed_id'}}).exec(function(err, res) {
            if (err) return handleError(err, promise);

            promise.resolve(res);
        });
    }

    function handleError(err, promise) {
        console.log(err);
        if (promise) promise.reject(err);
    }

    return {
        getCluster: getCluster
    }
})();
<|endoftext|>


<commit_before>var glimpse = require('glimpse');
var store = require('store.js');

var _storeSummaryKey = 'glimpse.data.summary',
    _storeDetailKey = 'glimpse.data.request';
// store Found Summary
(function() {
    function storeFoundSummary(data) {
      store.set(_storeSummaryKey, data);
    }

    glimpse.on('data.request.summary.found.remote', storeFoundSummary);
    glimpse.on('data.request.summary.found.stream', storeFoundSummary);
})();

// store Found Detail
(function() {
    function storeFoundDetail(data) {
      var key = _storeDetailKey + '.' + data.id;
      store.set(key, data);
    }

    glimpse.on('data.request.detail.found.remote', storeFoundDetail);
})();

module.exports = {
    triggerGetLastestSummaries: function() {
        var data = store.get(_storeSummaryKey);
        if(data && data.length > 0)
          glimpse.emit('data.request.summary.found.local', data);
    },
    triggerGetDetailsFor: function(requestId) {
        var data = store.get(_storeDetailKey + '.' + requestId);
        if(data && data.length > 0)
          glimpse.emit('data.request.detail.found.local', data);
    }
};
<commit_msg>Add todo comments for local storage request repository<commit_after>var glimpse = require('glimpse');
var store = require('store.js');

var _storeSummaryKey = 'glimpse.data.summary',
    _storeDetailKey = 'glimpse.data.request';
// store Found Summary
(function() {
    //TODO: Need to complete
    //Push into local storage
    //address error handling, flushing out old data
    function storeFoundSummary(data) {
      store.set(_storeSummaryKey, data);
    }

    glimpse.on('data.request.summary.found.remote', storeFoundSummary);
    glimpse.on('data.request.summary.found.stream', storeFoundSummary);
})();

// store Found Detail
(function() {
    //TODO: Need to complete
    //Push into local storage
    //address error handling, flushing out old data
    function storeFoundDetail(data) {
      var key = _storeDetailKey + '.' + data.id;
      store.set(key, data);
    }

    glimpse.on('data.request.detail.found.remote', storeFoundDetail);
})();

module.exports = {
    triggerGetLastestSummaries: function() {
      //TODO: Need to complete
      //Pull from local storage
      //address error handling
        var data = store.get(_storeSummaryKey);
        if(data && data.length > 0)
          glimpse.emit('data.request.summary.found.local', data);
    },
    triggerGetDetailsFor: function(requestId) {
      //TODO: Need to complete
      //Pull from local storage
      //address error handling
        var data = store.get(_storeDetailKey + '.' + requestId);
        if(data && data.length > 0)
          glimpse.emit('data.request.detail.found.local', data);
    }
};
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2010 Orbeon, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation; either version
 * 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
 */
(function() {

    var $ = ORBEON.jQuery;
    var AS = ORBEON.xforms.server.AjaxServer;
    var Document = ORBEON.xforms.Document;

    YAHOO.namespace('xbl.fr');
    YAHOO.xbl.fr.Number = function() {};
    ORBEON.xforms.XBL.declareClass(YAHOO.xbl.fr.Number, 'xbl-fr-number');
    YAHOO.xbl.fr.Number.prototype = {

        xformsInputElement: null,
        xformsOutputElement: null,
        visibleInputElement: null,

        decimalSeparatorElement: null,
        decimalSeparator: null,

        init: function() {

            this.xformsInputElement  = $(this.container).find('.xbl-fr-number-xforms-input')[0];
            this.xformsOutputElement = $(this.container).find('.xbl-fr-number-xforms-output')[0];
            this.visibleInputElement = $(this.container).find('.xbl-fr-number-visible-input')[0];

            // Find prefix based on class/control name, as this JS can be used with fr:number and fr:currency and properties use the control name
            var controlClassPrefix = null;
            var containerClasses = this.container.className.split(' ');
            for (var classIndex = 0; classIndex < containerClasses.length; classIndex++) {
                var currentClass = containerClasses[classIndex];
                if (currentClass.indexOf('xbl-fr-') == 0) {
                    controlClassPrefix = currentClass;
                    break;
                }
            }

            this.decimalSeparatorElement  = $(this.container).find('.' + controlClassPrefix + '-decimal-separator')[0];
            this.decimalSeparator         = Document.getValue(this.decimalSeparatorElement);

            // Register listeners

            // Switch the input type after cleaning up the value for edition
            $(this.visibleInputElement).on('touchstart focus', _.bind(function(e) {

                this.visibleInputElement.value = this.getEditString();

                // See https://github.com/orbeon/orbeon-forms/issues/2545
                function hasNativeDecimalSeparator(separator) {
                    return ! _.isUndefined(Number.toLocaleString) &&
                        1.1.toLocaleString().substring(1, 2) == separator;
                }

                if (hasNativeDecimalSeparator(this.decimalSeparator)) {
                    // With Firefox, changing the type synchronously interferes with the focus
                    window.setTimeout(_.bind(function() {
                        $(this.visibleInputElement).attr('type', 'number');
                    }, this), 0);
                }
            }, this));

            // Restore input type, send the value to the server, and updates value after server response
            $(this.visibleInputElement).on('blur', _.bind(function(e) {

                // With Firefox, changing the type synchronously interferes with the focus
                window.setTimeout(_.bind(function() {
                    $(this.visibleInputElement).attr('type', 'text');
                }, this), 0);

                this.sendValueToServer();
                var formId = $(this.container).parents('form').attr('id');

                // Always update visible value with XForms value
                // - relying just value change event from server is not enough
                // - value change not dispatched if server value hasn't changed
                // - if visible changed, but XForms hasn't, we still need to show XForms value
                // - see: https://github.com/orbeon/orbeon-forms/issues/1026
                AS.nextAjaxResponse(formId).then(_.bind(this.updateWithServerValue, this));
            }, this));

            $(this.visibleInputElement).on('keypress', _.bind(function(e) {
                if (e.which == 13)
                    this.sendValueToServer();
            }, this));
        },

        setFocus: function() {
            this.visibleInputElement.focus();
         },

        sendValueToServer: function() {
            var newValue = this.visibleInputElement.value;
            Document.setValue(this.xformsInputElement, newValue);
        },

        getEditString: function() {
            return Document.getValue(this.xformsOutputElement);
        },

        updateWithServerValue: function() {

            var hasFocus = this.visibleInputElement == document.activeElement;

            this.visibleInputElement.value =
                hasFocus ?
                this.getEditString() :
                Document.getValue(this.xformsInputElement);

            // Also update disabled because this might be called upon an iteration being moved, in which case all the control properties must be updated
            this.visibleInputElement.disabled = $(this.xformsInputElement).hasClass('xforms-readonly');
        },

        readonly: function() {
            this.visibleInputElement.disabled = true;
        },

        readwrite: function() {
            this.visibleInputElement.disabled = false;
        },

        parameterDecimalSeparatorChanged: function() {
            this.decimalSeparator = Document.getValue(this.decimalSeparatorElement);
            this.updateWithServerValue();
        }
    };
})();
<commit_msg>Fix #2553 "fr:number: Chrome clears value upon entering say `..` in field"<commit_after>/**
 * Copyright (C) 2010 Orbeon, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation; either version
 * 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
 */
(function() {

    var $ = ORBEON.jQuery;
    var AS = ORBEON.xforms.server.AjaxServer;
    var Document = ORBEON.xforms.Document;

    YAHOO.namespace('xbl.fr');
    YAHOO.xbl.fr.Number = function() {};
    ORBEON.xforms.XBL.declareClass(YAHOO.xbl.fr.Number, 'xbl-fr-number');
    YAHOO.xbl.fr.Number.prototype = {

        xformsInputElement: null,
        xformsOutputElement: null,
        visibleInputElement: null,

        decimalSeparatorElement: null,
        decimalSeparator: null,

        init: function() {

            this.xformsInputElement  = $(this.container).find('.xbl-fr-number-xforms-input')[0];
            this.xformsOutputElement = $(this.container).find('.xbl-fr-number-xforms-output')[0];
            this.visibleInputElement = $(this.container).find('.xbl-fr-number-visible-input')[0];

            // Find prefix based on class/control name, as this JS can be used with fr:number and fr:currency and properties use the control name
            var controlClassPrefix = null;
            var containerClasses = this.container.className.split(' ');
            for (var classIndex = 0; classIndex < containerClasses.length; classIndex++) {
                var currentClass = containerClasses[classIndex];
                if (currentClass.indexOf('xbl-fr-') == 0) {
                    controlClassPrefix = currentClass;
                    break;
                }
            }

            this.decimalSeparatorElement  = $(this.container).find('.' + controlClassPrefix + '-decimal-separator')[0];
            this.decimalSeparator         = Document.getValue(this.decimalSeparatorElement);

            // Register listeners

            // Switch the input type after cleaning up the value for edition
            $(this.visibleInputElement).on('touchstart focus', _.bind(function(e) {

                this.visibleInputElement.value = this.getEditString();

                // See https://github.com/orbeon/orbeon-forms/issues/2545
                function hasNativeDecimalSeparator(separator) {
                    return ! _.isUndefined(Number.toLocaleString) &&
                        1.1.toLocaleString().substring(1, 2) == separator;
                }

                if ($('body').is('.xforms-mobile') && hasNativeDecimalSeparator(this.decimalSeparator)) {
                    // With Firefox, changing the type synchronously interferes with the focus
                    window.setTimeout(_.bind(function() {
                        $(this.visibleInputElement).attr('type', 'number');
                    }, this), 0);
                }
            }, this));

            // Restore input type, send the value to the server, and updates value after server response
            $(this.visibleInputElement).on('blur', _.bind(function(e) {

                // With Firefox, changing the type synchronously interferes with the focus
                window.setTimeout(_.bind(function() {
                    $(this.visibleInputElement).attr('type', 'text');
                }, this), 0);

                this.sendValueToServer();
                var formId = $(this.container).parents('form').attr('id');

                // Always update visible value with XForms value
                // - relying just value change event from server is not enough
                // - value change not dispatched if server value hasn't changed
                // - if visible changed, but XForms hasn't, we still need to show XForms value
                // - see: https://github.com/orbeon/orbeon-forms/issues/1026
                AS.nextAjaxResponse(formId).then(_.bind(this.updateWithServerValue, this));
            }, this));

            $(this.visibleInputElement).on('keypress', _.bind(function(e) {
                if (e.which == 13)
                    this.sendValueToServer();
            }, this));
        },

        setFocus: function() {
            this.visibleInputElement.focus();
         },

        sendValueToServer: function() {
            var newValue = this.visibleInputElement.value;
            Document.setValue(this.xformsInputElement, newValue);
        },

        getEditString: function() {
            return Document.getValue(this.xformsOutputElement);
        },

        updateWithServerValue: function() {

            var hasFocus = this.visibleInputElement == document.activeElement;

            this.visibleInputElement.value =
                hasFocus ?
                this.getEditString() :
                Document.getValue(this.xformsInputElement);

            // Also update disabled because this might be called upon an iteration being moved, in which case all the control properties must be updated
            this.visibleInputElement.disabled = $(this.xformsInputElement).hasClass('xforms-readonly');
        },

        readonly: function() {
            this.visibleInputElement.disabled = true;
        },

        readwrite: function() {
            this.visibleInputElement.disabled = false;
        },

        parameterDecimalSeparatorChanged: function() {
            this.decimalSeparator = Document.getValue(this.decimalSeparatorElement);
            this.updateWithServerValue();
        }
    };
})();
<|endoftext|>


<commit_before>import Ember from 'ember';
import Cattle from 'ui/utils/cattle';
import DownloadMachineConfig from 'ui/mixins/download-machine-config';

var HostController = Cattle.TransitioningResourceController.extend(DownloadMachineConfig, {
  actions: {
    activate: function() {
      return this.doAction('activate');
    },

    deactivate: function() {
      return this.doAction('deactivate');
    },

    delete: function() {
      var machine = this.get('machine');
      if ( machine )
      {
        return machine.delete();
      }
      else
      {
        return this.delete();
      }
    },

    purge: function() {
      return this.doAction('purge');
    },

    newContainer: function() {
      this.transitionToRoute('containers.new', {queryParams: {hostId: this.get('id')}});
    },

    detail: function() {
      this.transitionToRoute('host', this.get('id'));
    },

    clone: function() {
      var machine = this.get('machine');
      var driver = machine.get('driver');
      this.transitionToRoute('hosts.new.'+driver, {queryParams: {machineId: machine.get('id')}});
    },

    edit: function() {
      this.transitionToRoute('host.edit', this.get('id'));
    },
  },

  availableActions: function() {
    var a = this.get('actions');

    var out = [
//      { label: 'Add Container', icon: 'ss-plus',      action: 'newContainer', enabled: true,            color: 'text-primary' },
      { label: 'Activate',      icon: 'ss-play',      action: 'activate',     enabled: !!a.activate,    color: 'text-success'},
      { label: 'Deactivate',    icon: 'ss-pause',     action: 'deactivate',   enabled: !!a.deactivate,  color: 'text-danger'},
      { label: 'Delete',        icon: 'ss-trash',     action: 'promptDelete', enabled: !!a.remove, altAction: 'delete', color: 'text-warning' },
      { label: 'Purge',         icon: '',   action: 'purge',        enabled: !!a.purge, color: 'text-danger'},
      { divider: true },
      { label: 'View in API',   icon: '', action: 'goToApi',      enabled: true},
    ];

    if ( this.get('machine') )
    {
      if ( this.get('machine.links.config') )
      {
        out.push({ label: 'Machine Config',   icon: 'ss-download', action: 'machineConfig',      enabled: true});
      }

      out.push({ label: 'Clone',         icon: 'ss-copier',           action: 'clone',        enabled: true });
    }

    out.push({ label: 'Edit',          icon: 'ss-write',            action: 'edit',         enabled: !!a.update });

    return out;
  }.property('actions.{activate,deactivate,remove,purge,update}','machine','machine.links.config'),

  triedToGetIp: false,
  displayIp: function() {
    var obj = (this.get('ipAddresses')||[]).get('firstObject');
    if ( obj )
    {
      return obj.get('address');
    }
    else if ( this && this.hasLink && this.hasLink('ipAddresses') && !this.get('triedToGetIp'))
    {
      this.set('triedToGetIp',true);
      this.importLink('ipAddresses');
    }

    return null;
  }.property('ipAddresses','ipAddresses.[]'),

  arrangedInstances: function() {
    return Ember.ArrayController.create({
      content: this.get('instances'),
      sortProperties: ['name','id']
    });
  }.property('instances.[]','instances.@each.{name,id}'),

  machine: function() {
    var phid = this.get('physicalHostId');
    if ( !phid )
    {
      return null;
    }

    var machine = this.get('store').getById('machine', phid);
    return machine;
  }.property('physicalHostId'),

  osBlurb: function() {
    // @TODO this always sends back Ubuntu
    if ( false && this.get('info.osInfo') )
    {
      return this.get('info.osInfo.distribution') + ' ' + this.get('info.osInfo.version');
    }
  }.property('info.osInfo.{distribution,version}'),

  dockerBlurb: function() {
    // @TODO this always sends back Ubuntu
    if ( this.get('info.osInfo') )
    {
      return this.get('info.osInfo.dockerVersion').replace(/^Docker version\s*/i,'');
    }
  }.property('info.osInfo.{dockerVersion}'),

  cpuBlurb: function() {
    if ( this.get('info.cpuInfo.count') )
    {
      var ghz = Math.round(this.get('info.cpuInfo.mhz')/10)/100;

      if ( this.get('info.cpuInfo.count') > 1 )
      {
        return this.get('info.cpuInfo.count')+'x' + ghz + ' GHz';
      }
      else
      {
        return ghz + ' GHz';
      }
    }
  }.property('info.cpuInfo.{count,mhz}'),

  memoryBlurb: function() {
    if ( this.get('info.memoryInfo') )
    {
      var gb = Math.round((this.get('info.memoryInfo.memTotal')/1024)*100)/100;

      return gb + ' GiB';
    }
  }.property('info.memoryInfo.memTotal'),

  diskBlurb: function() {
    if ( this.get('info.diskInfo.mountPoints') )
    {
      var totalMb = 0;
      var mounts = this.get('info.diskInfo.mountPoints')||[];
      Object.keys(mounts).forEach((mountPoint) => {
        totalMb += mounts[mountPoint].total;
      });

      var gb = Math.round((totalMb/1024)*10)/10;
      return gb + ' GiB';
    }
  }.property('info.diskInfo.mountPoints.@each.total'),
});

HostController.reopenClass({
  stateMap: {
    'requested':        {icon: 'ss-tag',            color: 'text-danger'},
    'registering':      {icon: 'ss-tag',            color: 'text-danger'},
    'activating':       {icon: 'ss-tag',            color: 'text-danger'},
    'active':           {icon: 'ss-database',       color: 'text-success'},
    'reconnecting':     {icon: 'fa fa-circle-o-notch fa-spin', color: 'text-danger'},
    'updating-active':  {icon: 'ss-database',       color: 'text-success'},
    'updating-inactive':{icon: 'ss-alert',          color: 'text-danger'},
    'deactivating':     {icon: 'ss-down',           color: 'text-danger'},
    'inactive':         {icon: 'fa fa-circle',      color: 'text-danger'},
    'removing':         {icon: 'ss-trash',          color: 'text-danger'},
    'removed':          {icon: 'ss-trash',          color: 'text-danger'},
    'purging':          {icon: 'ss-tornado',        color: 'text-danger'},
    'purged':           {icon: 'ss-tornado',        color: 'text-danger'},
    'restoring':        {icon: 'ss-medicalcross',   color: 'text-danger'},
  }
});

export default HostController;
<commit_msg>Delete host instead of machine<commit_after>import Ember from 'ember';
import Cattle from 'ui/utils/cattle';
import DownloadMachineConfig from 'ui/mixins/download-machine-config';

var HostController = Cattle.TransitioningResourceController.extend(DownloadMachineConfig, {
  actions: {
    activate: function() {
      return this.doAction('activate');
    },

    deactivate: function() {
      return this.doAction('deactivate');
    },

    purge: function() {
      return this.doAction('purge');
    },

    newContainer: function() {
      this.transitionToRoute('containers.new', {queryParams: {hostId: this.get('id')}});
    },

    detail: function() {
      this.transitionToRoute('host', this.get('id'));
    },

    clone: function() {
      var machine = this.get('machine');
      var driver = machine.get('driver');
      this.transitionToRoute('hosts.new.'+driver, {queryParams: {machineId: machine.get('id')}});
    },

    edit: function() {
      this.transitionToRoute('host.edit', this.get('id'));
    },
  },

  availableActions: function() {
    var a = this.get('actions');

    var out = [
//      { label: 'Add Container', icon: 'ss-plus',      action: 'newContainer', enabled: true,            color: 'text-primary' },
      { label: 'Activate',      icon: 'ss-play',      action: 'activate',     enabled: !!a.activate,    color: 'text-success'},
      { label: 'Deactivate',    icon: 'ss-pause',     action: 'deactivate',   enabled: !!a.deactivate,  color: 'text-danger'},
      { label: 'Delete',        icon: 'ss-trash',     action: 'promptDelete', enabled: !!a.remove, altAction: 'delete', color: 'text-warning' },
      { label: 'Purge',         icon: '',   action: 'purge',        enabled: !!a.purge, color: 'text-danger'},
      { divider: true },
      { label: 'View in API',   icon: '', action: 'goToApi',      enabled: true},
    ];

    if ( this.get('machine') )
    {
      if ( this.get('machine.links.config') )
      {
        out.push({ label: 'Machine Config',   icon: 'ss-download', action: 'machineConfig',      enabled: true});
      }

      out.push({ label: 'Clone',         icon: 'ss-copier',           action: 'clone',        enabled: true });
    }

    out.push({ label: 'Edit',          icon: 'ss-write',            action: 'edit',         enabled: !!a.update });

    return out;
  }.property('actions.{activate,deactivate,remove,purge,update}','machine','machine.links.config'),

  triedToGetIp: false,
  displayIp: function() {
    var obj = (this.get('ipAddresses')||[]).get('firstObject');
    if ( obj )
    {
      return obj.get('address');
    }
    else if ( this && this.hasLink && this.hasLink('ipAddresses') && !this.get('triedToGetIp'))
    {
      this.set('triedToGetIp',true);
      this.importLink('ipAddresses');
    }

    return null;
  }.property('ipAddresses','ipAddresses.[]'),

  arrangedInstances: function() {
    return Ember.ArrayController.create({
      content: this.get('instances'),
      sortProperties: ['name','id']
    });
  }.property('instances.[]','instances.@each.{name,id}'),

  machine: function() {
    var phid = this.get('physicalHostId');
    if ( !phid )
    {
      return null;
    }

    var machine = this.get('store').getById('machine', phid);
    return machine;
  }.property('physicalHostId'),

  osBlurb: function() {
    // @TODO this always sends back Ubuntu
    if ( false && this.get('info.osInfo') )
    {
      return this.get('info.osInfo.distribution') + ' ' + this.get('info.osInfo.version');
    }
  }.property('info.osInfo.{distribution,version}'),

  dockerBlurb: function() {
    // @TODO this always sends back Ubuntu
    if ( this.get('info.osInfo') )
    {
      return this.get('info.osInfo.dockerVersion').replace(/^Docker version\s*/i,'');
    }
  }.property('info.osInfo.{dockerVersion}'),

  cpuBlurb: function() {
    if ( this.get('info.cpuInfo.count') )
    {
      var ghz = Math.round(this.get('info.cpuInfo.mhz')/10)/100;

      if ( this.get('info.cpuInfo.count') > 1 )
      {
        return this.get('info.cpuInfo.count')+'x' + ghz + ' GHz';
      }
      else
      {
        return ghz + ' GHz';
      }
    }
  }.property('info.cpuInfo.{count,mhz}'),

  memoryBlurb: function() {
    if ( this.get('info.memoryInfo') )
    {
      var gb = Math.round((this.get('info.memoryInfo.memTotal')/1024)*100)/100;

      return gb + ' GiB';
    }
  }.property('info.memoryInfo.memTotal'),

  diskBlurb: function() {
    if ( this.get('info.diskInfo.mountPoints') )
    {
      var totalMb = 0;
      var mounts = this.get('info.diskInfo.mountPoints')||[];
      Object.keys(mounts).forEach((mountPoint) => {
        totalMb += mounts[mountPoint].total;
      });

      var gb = Math.round((totalMb/1024)*10)/10;
      return gb + ' GiB';
    }
  }.property('info.diskInfo.mountPoints.@each.total'),
});

HostController.reopenClass({
  stateMap: {
    'requested':        {icon: 'ss-tag',            color: 'text-danger'},
    'registering':      {icon: 'ss-tag',            color: 'text-danger'},
    'activating':       {icon: 'ss-tag',            color: 'text-danger'},
    'active':           {icon: 'ss-database',       color: 'text-success'},
    'reconnecting':     {icon: 'fa fa-circle-o-notch fa-spin', color: 'text-danger'},
    'updating-active':  {icon: 'ss-database',       color: 'text-success'},
    'updating-inactive':{icon: 'ss-alert',          color: 'text-danger'},
    'deactivating':     {icon: 'ss-down',           color: 'text-danger'},
    'inactive':         {icon: 'fa fa-circle',      color: 'text-danger'},
    'removing':         {icon: 'ss-trash',          color: 'text-danger'},
    'removed':          {icon: 'ss-trash',          color: 'text-danger'},
    'purging':          {icon: 'ss-tornado',        color: 'text-danger'},
    'purged':           {icon: 'ss-tornado',        color: 'text-danger'},
    'restoring':        {icon: 'ss-medicalcross',   color: 'text-danger'},
  }
});

export default HostController;
<|endoftext|>


<commit_before>// Here we test the authentication function is called as needed.

require.paths.unshift(__dirname + '/../../../');

var http = require("http"),
    querystring = require("querystring"),

    CLB = require("nodetk/orchestration/callbacks"),
    assert = require("nodetk/testing/custom_assert"),

    rest_server = require('rest-mongo/http_rest/server'),
    rest_mongo = require('rest-mongo/core'),
    mongo_backend = require('rest-mongo/mongo_backend'),
    schema = require('rest-mongo/tests/schema').schema;

var server;
var client;
var backend = mongo_backend.get_backend({db_name: 'test-rest-mongo'});
    RFactory = rest_mongo.getRFactory(schema, backend);

var auth_check = function(req, res, next, info) {
  if(info.pathname == '/animals') {
    if(info.method == 'GET') res.writeHead(401, {});
    else res.writeHead(403, {});
    res.end();
  }
  else {
    next();
  }
}

exports.module_init = function(callback) {
  // init some stuff
  var connector = rest_server.connector(RFactory, schema, auth_check);
  var next = function(req, res) {
    res.writeHead(404, {});
    res.end('next() called.');
  };
  server = http.createServer(function(req, resp) {
    connector(req, resp, function() {
      next(req, resp);
    });
  });
  server.listen(8555, function() {
    client = http.createClient(8555, '127.0.0.1');
    client.addListener('error', function(err) {
      console.log(err.message, err.stack);
    });
    callback();
  })
};

exports.module_close = function(callback) {
  server.close();
  callback();
};

exports.tests = [

['AUTH, GET authorized', 1, function() {
  var request = client.request('GET', '/people', {});
  request.addListener('response', function(response) {
    assert.equal(response.statusCode, 200);
  });
  request.end();
}],

['AUTH, POST authorized', 1, function() {
  var request = client.request('DELETE', '/people', {});
  request.addListener('response', function(response) {
    assert.equal(response.statusCode, 200);
  });
  request.end();
}],

['AUTH, GET 401', 1, function() {
  var request = client.request('GET', '/animals', {});
  request.addListener('response', function(response) {
    assert.equal(response.statusCode, 401);
  });
  request.end();
}],

['AUTH, POST 403', 1, function() {
  var request = client.request('DELETE', '/animals', {});
  request.addListener('response', function(response) {
    assert.equal(response.statusCode, 403);
  });
  request.end();
}],

];

<commit_msg>Fix test.<commit_after>// Here we test the authentication function is called as needed.

require.paths.unshift(__dirname + '/../../../');

var http = require("http"),
    querystring = require("querystring"),

    CLB = require("nodetk/orchestration/callbacks"),
    assert = require("nodetk/testing/custom_assert"),

    rest_server = require('rest-mongo/http_rest/server'),
    rest_mongo = require('rest-mongo/core'),
    mongo_backend = require('rest-mongo/mongo_backend'),
    schema = require('rest-mongo/tests/schema').schema;

var server;
var client;
var backend = mongo_backend.get_backend({db_name: 'test-rest-mongo'});
var RFactory = rest_mongo.getRFactory(schema, backend);

var auth_check = function(req, res, next, info) {
  if(info.pathname == '/animals') {
    if(info.method == 'GET') res.writeHead(401, {});
    else res.writeHead(403, {});
    res.end();
  }
  else {
    next();
  }
}

exports.module_init = function(callback) {
  // init some stuff
  var connector = rest_server.connector(RFactory, schema, {
    auth_check: auth_check
  });
  var next = function(req, res) {
    res.writeHead(404, {});
    res.end('next() called.');
  };
  server = http.createServer(function(req, resp) {
    connector(req, resp, function() {
      next(req, resp);
    });
  });
  server.listen(8555, function() {
    client = http.createClient(8555, '127.0.0.1');
    client.addListener('error', function(err) {
      console.log(err.message, err.stack);
    });
    callback();
  })
};

exports.module_close = function(callback) {
  server.close();
  callback();
};

exports.tests = [

['AUTH, GET authorized', 1, function() {
  var request = client.request('GET', '/people', {});
  request.addListener('response', function(response) {
    assert.equal(response.statusCode, 200);
  });
  request.end();
}],

['AUTH, POST authorized', 1, function() {
  var request = client.request('DELETE', '/people', {});
  request.addListener('response', function(response) {
    assert.equal(response.statusCode, 200);
  });
  request.end();
}],

['AUTH, GET 401', 1, function() {
  var request = client.request('GET', '/animals', {});
  request.addListener('response', function(response) {
    assert.equal(response.statusCode, 401);
  });
  request.end();
}],

['AUTH, POST 403', 1, function() {
  var request = client.request('DELETE', '/animals', {});
  request.addListener('response', function(response) {
    assert.equal(response.statusCode, 403);
  });
  request.end();
}],

];

<|endoftext|>