<commit_before>'use strict';

var sut = require('../../lib/LxCrypto')();

describe('LxCrypto', function () {
    describe('.hashWithRandomSalt()', function () {
        it('should hash the password', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(typeof res.salt).toBe('string');
                expect(res.salt.length).toBeGreaterThan(0);
                expect(res.password).toBeDefined();
                expect(typeof res.password).toBe('string');
                expect(res.password.length).toBeGreaterThan(0);
                expect(res.password === 'test').toBeFalsy();

                done();
            });
        });

        it('should return an error when the password is a number', function (done) {
            sut.hashWithRandomSalt(123, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Param "password" is of type number! Type string expected');
                expect(res).toBeUndefined();

                done();
            });
        });

        it('should return an error when the password is null', function (done) {
            sut.hashWithRandomSalt(null, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Param "password" is of type null! Type string expected');
                expect(res).toBeUndefined();

                done();
            });
        });

        it('should return an error when the password is undefined', function (done) {
            sut.hashWithRandomSalt(undefined, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Param "password" is of type undefined! Type string expected');
                expect(res).toBeUndefined();

                done();
            });
        });
    });

    describe('.randomBytes()', function () {
        it('should create random bytes', function () {
            sut.randomBytes(10, function (err, res) {
                expect(err).toBeNull();
                expect(res).toBeDefined();
                expect(typeof res).toBe('object');
            });
        });

        it('should return an error when param length is a string', function () {
            sut.randomBytes('dd', function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is a string', function () {
            sut.randomBytes('10', function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is null', function () {
            sut.randomBytes(null, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is undefined', function () {
            sut.randomBytes(undefined, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is an object', function () {
            sut.randomBytes({}, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });
    });

    describe('.randomString()', function () {
        it('should create a random string', function () {
            sut.randomString(10, function (err, res) {
                expect(err).toBeNull();
                expect(res).toBeDefined();
                expect(typeof res).toBe('string');
            });
        });

        it('should return an error when param length is a string', function () {
            sut.randomString('dd', function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is a string', function () {
            sut.randomString('10', function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is null', function () {
            sut.randomString(null, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is undefined', function () {
            sut.randomString(undefined, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is an object', function () {
            sut.randomString({}, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });
    });

    describe('.compare()', function () {
        it('should compare a password with a hash', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('test', res.password, res.salt, function (err, res) {
                    expect(err).toBeNull();
                    expect(res).toEqual({is_equal: true});

                    done();
                });
            });
        });

        it('should return false when the password is wrong', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('abc', res.password, res.salt, function (err, res) {
                    expect(err).toBeNull();
                    expect(res).toEqual({is_equal: false});

                    done();
                });
            });
        });

        it('should return false when the password is empty', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('', res.password, res.salt, function (err, res) {
                    expect(err).toBeNull();
                    expect(res).toEqual({is_equal: false});

                    done();
                });
            });
        });

        it('should return false when the password is a number', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare(123, res.password, res.salt, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "plain" is of type number! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the password is null', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare(null, res.password, res.salt, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "plain" is of type null! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the password is undefined', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare(undefined, res.password, res.salt, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "plain" is of type undefined! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the salt is a number', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('test', res.password, 123, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "salt" is of type number! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the salt is a null', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('test', res.password, null, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "salt" is of type null! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the salt is a null', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('test', res.password, undefined, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "salt" is of type undefined! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });
    });
});
<commit_msg>chore: fix tests for io.js<commit_after>'use strict';

var sut = require('../../lib/LxCrypto')();

describe('LxCrypto', function () {
    describe('.hashWithRandomSalt()', function () {
        it('should hash the password', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(typeof res.salt).toBe('string');
                expect(res.salt.length).toBeGreaterThan(0);
                expect(res.password).toBeDefined();
                expect(typeof res.password).toBe('string');
                expect(res.password.length).toBeGreaterThan(0);
                expect(res.password === 'test').toBeFalsy();

                done();
            });
        });

        it('should return an error when the password is a number', function (done) {
            sut.hashWithRandomSalt(123, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Param "password" is of type number! Type string expected');
                expect(res).toBeUndefined();

                done();
            });
        });

        it('should return an error when the password is null', function (done) {
            sut.hashWithRandomSalt(null, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Param "password" is of type null! Type string expected');
                expect(res).toBeUndefined();

                done();
            });
        });

        it('should return an error when the password is undefined', function (done) {
            sut.hashWithRandomSalt(undefined, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Param "password" is of type undefined! Type string expected');
                expect(res).toBeUndefined();

                done();
            });
        });
    });

    describe('.randomBytes()', function () {
        it('should create random bytes', function () {
            sut.randomBytes(10, function (err, res) {
                expect(err).toBeNull();
                expect(res).toBeDefined();
                expect(typeof res).toBe('object');
            });
        });

        it('should return an error when param length is a string', function () {
            sut.randomBytes('dd', function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is a string', function () {
            sut.randomBytes('10', function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is null', function () {
            sut.randomBytes(null, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is undefined', function () {
            sut.randomBytes(undefined, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is an object', function () {
            sut.randomBytes({}, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });
    });

    describe('.randomString()', function () {
        it('should create a random string', function () {
            sut.randomString(10, function (err, res) {
                expect(err).toBeNull();
                expect(res).toBeDefined();
                expect(typeof res).toBe('string');
            });
        });

        it('should return an error when param length is a string', function () {
            sut.randomString('dd', function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toBe('Argument #1 must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is a string', function () {
            sut.randomString('10', function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is null', function () {
            sut.randomString(null, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is undefined', function () {
            sut.randomString(undefined, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });

        it('should return an error when param length is an object', function () {
            sut.randomString({}, function (err, res) {
                expect(err instanceof TypeError).toBeTruthy();
                expect(err.message).toContain('must be number > 0');
                expect(res).toBeUndefined();
            });
        });
    });

    describe('.compare()', function () {
        it('should compare a password with a hash', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('test', res.password, res.salt, function (err, res) {
                    expect(err).toBeNull();
                    expect(res).toEqual({is_equal: true});

                    done();
                });
            });
        });

        it('should return false when the password is wrong', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('abc', res.password, res.salt, function (err, res) {
                    expect(err).toBeNull();
                    expect(res).toEqual({is_equal: false});

                    done();
                });
            });
        });

        it('should return false when the password is empty', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('', res.password, res.salt, function (err, res) {
                    expect(err).toBeNull();
                    expect(res).toEqual({is_equal: false});

                    done();
                });
            });
        });

        it('should return false when the password is a number', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare(123, res.password, res.salt, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "plain" is of type number! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the password is null', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare(null, res.password, res.salt, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "plain" is of type null! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the password is undefined', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare(undefined, res.password, res.salt, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "plain" is of type undefined! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the salt is a number', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('test', res.password, 123, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "salt" is of type number! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the salt is a null', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('test', res.password, null, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "salt" is of type null! Type string expected');
                    expect(res).toBeUndefined();

                    done();
                });
            });
        });

        it('should return false when the salt is a null', function (done) {
            sut.hashWithRandomSalt('test', function (err, res) {
                expect(err).toBeUndefined();
                expect(res.salt).toBeDefined();
                expect(res.password).toBeDefined();
                expect(res.password === 'test').toBeFalsy();

                sut.compare('test', res.password, undefined, function (err, res) {
                    expect(err instanceof TypeError).toBeTruthy();
                    expect(err.message).toBe('Param "salt" is of type undefined! Type string expected');
                    expect(res).toBeUndefined();

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


<commit_before>// Karma configuration

var path = require('path');

module.exports = function(config) {

  var DEV_OUT = 'resources/public/cljs/out';

  config.set({
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: [ 'cljsTest'],

    // list of files / patterns to load in the browser
    files: [
      'test-js/test-render-context.js',
      'http://circlehost:8080/assets/js/om-dev.js.stefon',
      path.join(DEV_OUT, 'goog/base.js'),
      path.join(DEV_OUT, 'frontend-dev.js'),
      'test-js/require-karma.js',
      { pattern: path.join(DEV_OUT, '**/*.js'), included: false},
      { pattern: path.join(DEV_OUT, '**/*.cljs'), included: false}
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
	'frontend-dev.js': ['sourcemap']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>Use om-dev-xxxx.js directly from the filesystem.<commit_after>// Karma configuration

var path = require('path');

module.exports = function(config) {

  var DEV_OUT = 'resources/public/cljs/out';

  config.set({
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: [ 'cljsTest'],

    // list of files / patterns to load in the browser
    files: [
      'test-js/test-render-context.js',
      'resources/public/assets/js/om-dev*.js',
      path.join(DEV_OUT, 'goog/base.js'),
      path.join(DEV_OUT, 'frontend-dev.js'),
      'test-js/require-karma.js',
      { pattern: path.join(DEV_OUT, '**/*.js'), included: false},
      { pattern: path.join(DEV_OUT, '**/*.cljs'), included: false}
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
	'frontend-dev.js': ['sourcemap']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>const Debug = require('debug');

const debug = Debug('@feathersjs/authentication-oauth2:verify');

class OAuth2Verifier {
  constructor (app, options = {}) {
    this.app = app;
    this.options = options;
    this.service = typeof options.service === 'string' ? app.service(options.service) : options.service;

    if (!this.service) {
      throw new Error(`options.service does not exist.\n\tMake sure you are passing a valid service path or service instance and it is initialized before @feathersjs/authentication-oauth2.`);
    }

    this._createEntity = this._createEntity.bind(this);
    this._updateEntity = this._updateEntity.bind(this);
    this._normalizeResult = this._normalizeResult.bind(this);
    this.verify = this.verify.bind(this);
  }

  _normalizeResult (results) {
    // Paginated services return the array of results in the data attribute.
    let entities = results.data ? results.data : results;
    let entity = entities[0];

    // Handle entity not found.
    if (!entity) {
      return Promise.resolve(null);
    }

    // Handle updating mongoose models
    if (typeof entity.toObject === 'function') {
      entity = entity.toObject();
    } else if (typeof entity.toJSON === 'function') {
      // Handle updating Sequelize models
      entity = entity.toJSON();
    }

    debug(`${this.options.entity} found`);
    return Promise.resolve(entity);
  }

  _updateEntity (entity, data) {
    const options = this.options;
    const name = options.name;
    const id = entity[this.service.id];
    debug(`Updating ${options.entity}: ${id}`);

    const newData = {
      [options.idField]: data.profile.id,
      [name]: data
    };

    return this.service.patch(id, newData, { oauth: { provider: name } });
  }

  _createEntity (data) {
    const options = this.options;
    const name = options.name;
    const entity = {
      [options.idField]: data.profile.id,
      [name]: data
    };

    const id = entity[options.idField];
    debug(`Creating new ${options.entity} with ${options.idField}: ${id}`);

    return this.service.create(entity, { oauth: { provider: name } });
  }

  verify (req, accessToken, refreshToken, profile, done) {
    debug('Checking credentials');
    const options = this.options;
    const query = {
      [options.idField]: profile.id, // facebookId: profile.id
      $limit: 1
    };
    const data = { profile, accessToken, refreshToken };
    let existing;

    if (this.service.id === null || this.service.id === undefined) {
      debug('failed: the service.id was not set');
      return done(new Error('the `id` property must be set on the entity service for authentication'));
    }

    // Check request object for an existing entity
    if (req && req[options.entity]) {
      existing = req[options.entity];
    }

    // Check the request that came from a hook for an existing entity
    if (!existing && req && req.params && req.params[options.entity]) {
      existing = req.params[options.entity];
    }

    // If there is already an entity on the request object (ie. they are
    // already authenticated) attach the profile to the existing entity
    // because they are likely "linking" social accounts/profiles.
    if (existing) {
      return this._updateEntity(existing, data)
        .then(entity => done(null, entity))
        .catch(error => error ? done(error) : done(null, error));
    }

    // Find or create the user since they could have signed up via facebook.
    this.service
      .find({ query })
      .then(this._normalizeResult)
      .then(entity => entity ? this._updateEntity(entity, data) : this._createEntity(data))
      .then(entity => {
        const id = entity[this.service.id];
        const payload = { [`${this.options.entity}Id`]: id };
        done(null, entity, payload);
      })
      .catch(error => error ? done(error) : done(null, error));
  }
}

module.exports = OAuth2Verifier;
<commit_msg>Allowing return type of _createEntity to be an Array (#88)<commit_after>const Debug = require('debug');

const debug = Debug('@feathersjs/authentication-oauth2:verify');

class OAuth2Verifier {
  constructor (app, options = {}) {
    this.app = app;
    this.options = options;
    this.service = typeof options.service === 'string' ? app.service(options.service) : options.service;

    if (!this.service) {
      throw new Error(`options.service does not exist.\n\tMake sure you are passing a valid service path or service instance and it is initialized before @feathersjs/authentication-oauth2.`);
    }

    this._createEntity = this._createEntity.bind(this);
    this._updateEntity = this._updateEntity.bind(this);
    this._normalizeResult = this._normalizeResult.bind(this);
    this.verify = this.verify.bind(this);
  }

  _normalizeResult (results) {
    // Paginated services return the array of results in the data attribute.
    let entities = results.data ? results.data : results;
    let entity = entities[0];

    // Handle entity not found.
    if (!entity) {
      return Promise.resolve(null);
    }

    // Handle updating mongoose models
    if (typeof entity.toObject === 'function') {
      entity = entity.toObject();
    } else if (typeof entity.toJSON === 'function') {
      // Handle updating Sequelize models
      entity = entity.toJSON();
    }

    debug(`${this.options.entity} found`);
    return Promise.resolve(entity);
  }

  _updateEntity (entity, data) {
    const options = this.options;
    const name = options.name;
    const id = entity[this.service.id];
    debug(`Updating ${options.entity}: ${id}`);

    const newData = {
      [options.idField]: data.profile.id,
      [name]: data
    };

    return this.service.patch(id, newData, { oauth: { provider: name } });
  }

  _createEntity (data) {
    const options = this.options;
    const name = options.name;
    const entity = {
      [options.idField]: data.profile.id,
      [name]: data
    };

    const id = entity[options.idField];
    debug(`Creating new ${options.entity} with ${options.idField}: ${id}`);

    return this.service.create(entity, { oauth: { provider: name } });
  }

  verify (req, accessToken, refreshToken, profile, done) {
    debug('Checking credentials');
    const options = this.options;
    const query = {
      [options.idField]: profile.id, // facebookId: profile.id
      $limit: 1
    };
    const data = { profile, accessToken, refreshToken };
    let existing;

    if (this.service.id === null || this.service.id === undefined) {
      debug('failed: the service.id was not set');
      return done(new Error('the `id` property must be set on the entity service for authentication'));
    }

    // Check request object for an existing entity
    if (req && req[options.entity]) {
      existing = req[options.entity];
    }

    // Check the request that came from a hook for an existing entity
    if (!existing && req && req.params && req.params[options.entity]) {
      existing = req.params[options.entity];
    }

    // If there is already an entity on the request object (ie. they are
    // already authenticated) attach the profile to the existing entity
    // because they are likely "linking" social accounts/profiles.
    if (existing) {
      return this._updateEntity(existing, data)
        .then(entity => done(null, entity))
        .catch(error => error ? done(error) : done(null, error));
    }

    // Find or create the user since they could have signed up via facebook.
    this.service
      .find({ query })
      .then(this._normalizeResult)
      .then(entity => entity ? this._updateEntity(entity, data) : this._createEntity(data))
      .then(entity => {
        const id = Array.isArray(entity) ? entity[0][this.service.id] : entity[this.service.id];
        const payload = { [`${this.options.entity}Id`]: id };
        done(null, entity, payload);
      })
      .catch(error => error ? done(error) : done(null, error));
  }
}

module.exports = OAuth2Verifier;
<|endoftext|>


<commit_before>define('gapper/client/login', ['jquery', 'bootbox', 'css!../../../css/gapper-choose-group'], function($, bootbox) {
    var dialog, loadingDialog;
    var isWaitingLogin = false;
    var clearDialog = function() {
        if (!dialog || ! dialog.length) return;
        dialog.prev('.modal-backdrop').remove();
        dialog.remove();
        dialog = undefined;
    };
    var clearLoadingDialog = function() {
        if (!loadingDialog || ! loadingDialog.length) return;
        loadingDialog.prev('.modal-backdrop').remove();
        loadingDialog.remove();
    };
    var showLoadingDialog = function() {
        clearLoadingDialog();
        loadingDialog = $('

');
        loadingDialog.modal({
            show: true
            ,backdrop: 'static'
        });
    };
    var showDialog = function(html, callback) {
        clearDialog();
        try {
            dialog = $(html);
        } catch(err) {}
        if (!dialog || ! dialog.hasClass('modal')) {
            dialog = $(['

<button class="close" data-dismiss="modal">×Close</button>
', html, '

'].join(''));
        }
        dialog.modal({
            show: true
            ,backdrop: 'static'
        });
        callback && callback();
    };
    var showLogin = function() {
        if (isWaitingLogin) return false;
        isWaitingLogin = true;
        var url = 'ajax/gapper/client/sources';
        showLoadingDialog();
        $.get(url, {
            _t: (new Date()).getTime()
        }, function(data) {
            clearLoadingDialog();
            if (data === true) {
                return window.location.reload();
            }
            if ($.isPlainObject(data) && data.redirect && data.message) {
                var redirectURL = data.redirect;
                var message = data.message;
                var callback = function() {
                    setTimeout(function() {
                        window.location.href = redirectURL;
                    }, 10);
                    setTimeout(function() {
                        isWaitingLogin = false;
                    }, 2000);
                };

                if (message) {
                    showDialog(message, callback);
                }
                else {
                    callback();
                }
                return;
            }
            if ($.isPlainObject(data) && data.type == 'modal' && data.message) {
                data = data.message;
            }
            showDialog(data, function() {
                setTimeout(function() {
                    isWaitingLogin = false;
                }, 2000);
            });
        });
    };

    var classBox = 'gapper-client-checkbox';
    var classLi = 'gapper-client-checkbox-li';
    var isWaitingClick = false;
    $('body').on('click', '.' + classBox + ' .' + classLi, function() {
        if (isWaitingClick) return false;
        isWaitingClick = true;
        var $that = $(this);
        if ($that.attr('data-gapper-auth-source')) {
            var source = $that.attr('data-gapper-auth-source');
            var url = 'ajax/gapper/auth/get-form/' + source;
            showLoadingDialog();
            $.get(url, {
                _t: (new Date()).getTime()
            }, function(data) {
                clearLoadingDialog();
                if ($.isPlainObject(data) && data.redirect) {
                    window.location.href = data.redirect;
                    return;
                }
                if ($.isPlainObject(data) && data.type == 'modal' && data.message) {
                    data = data.message;
                }
                clearDialog();
                dialog = $(data);
                dialog.modal({
                    show: true
                    ,backdrop: 'static'
                });
                dialog.on('hide.bs.modal', function() {
                    setTimeout(showLogin, 1);
                });
                setTimeout(function() {
                    isWaitingClick = false;
                }, 2000);
            });
        }
        if ($that.attr('data-gapper-client-group')) {
            showLoadingDialog();
            $.post('ajax/gapper/auth/gapper/choose', {
                id: $that.attr('data-gapper-client-group')
            }, function(data) {
                setTimeout(function() {
                    isWaitingClick = false;
                }, 2000);
                if (true === data) {
                    window.location.reload();
                }
                if ($.isPlainObject(data) && data.redirect) {
                    window.location.href = data.redirect;
                    return;
                }
                clearLoadingDialog();
                if ($.isPlainObject(data) && data.type == 'modal' && data.message) {
                    data = data.message;
                }
                showDialog(data);
            });
        }
    });

    var classForm = '.gapper-auth-form';
    var isWaitingSubmit = false;
    $('body').on('click', classForm + ' input[type=submit]', function(evt) {
        evt.preventDefault();
        if (isWaitingSubmit) return false;
        isWaitingSubmit = true;
        var $that = $(this).parents(classForm);
        var url = $that.attr('action');
        var data = $that.serialize();
        showLoadingDialog();
        $.post(url, data, function(pData) {
            if (true === pData) {
                window.location.reload();
            }
            else {
                var tData = $.isPlainObject(pData) ? pData: {
                    type: 'alert'
                    ,message: pData
                };
                switch (tData.type) {
                    case 'modal':
                        clearLoadingDialog();
                        clearDialog();
                        dialog = $(tData.message);
                        dialog.modal({
                            show: true
                            ,backdrop: 'static'
                        });
                        dialog.on('hide.bs.modal', function() {
                            setTimeout(showLogin, 1);
                        });
                        break;
                    case 'alert':
                        clearLoadingDialog();
                        showDialog(pData);
                        break;
                    default:
                        if (pData.redirect) {
                            var callback = function() {
                                setTimeout(function() {
                                    window.location.href = pData.redirect;
                                }, 10);
                            };
                            if (pData.message) {
                                clearLoadingDialog();
                                showDialog(pData.message, callback);
                            }
                            else {
                                callback();
                            }
                        }
                }
            }
            setTimeout(function() {
                isWaitingSubmit = false;
            }, 2000);
        });
        return false;
    });

    $(document).on('click', '.login-modal .close', function() {
        isWaitingLogin = true;
        $.get('ajax/gapper/client/logout', {
            _t: (new Date()).getTime()
        }, function() {
            isWaitingLogin = false;
            setTimeout(showLogin, 10);
        });
    });

    var data = {
        show: showLogin
    };
    return data;
});

<commit_msg>所有的登录弹窗都增加login-modal的类，用来绑定close事件的登出机制<commit_after>define('gapper/client/login', ['jquery', 'bootbox', 'css!../../../css/gapper-choose-group'], function($, bootbox) {
    var dialog, loadingDialog;
    var isWaitingLogin = false;
    var clearDialog = function() {
        if (!dialog || ! dialog.length) return;
        dialog.prev('.modal-backdrop').remove();
        dialog.remove();
        dialog = undefined;
    };
    var clearLoadingDialog = function() {
        if (!loadingDialog || ! loadingDialog.length) return;
        loadingDialog.prev('.modal-backdrop').remove();
        loadingDialog.remove();
    };
    var showLoadingDialog = function() {
        clearLoadingDialog();
        loadingDialog = $('

');
        loadingDialog.modal({
            show: true
            ,backdrop: 'static'
        });
    };
    var showDialog = function(html, callback) {
        clearDialog();
        try {
            dialog = $(html);
        } catch(err) {}
        if (!dialog || ! dialog.hasClass('modal')) {
            dialog = $(['

<button class="close" data-dismiss="modal">×Close</button>
', html, '

'].join(''));
        }
        if (!dialog.hasClass('login-modal')) {
            dialog.addClass('login-modal');
        }
        dialog.modal({
            show: true
            ,backdrop: 'static'
        });
        callback && callback();
    };
    var showLogin = function() {
        if (isWaitingLogin) return false;
        isWaitingLogin = true;
        var url = 'ajax/gapper/client/sources';
        showLoadingDialog();
        $.get(url, {
            _t: (new Date()).getTime()
        }, function(data) {
            clearLoadingDialog();
            if (data === true) {
                return window.location.reload();
            }
            if ($.isPlainObject(data) && data.redirect && data.message) {
                var redirectURL = data.redirect;
                var message = data.message;
                var callback = function() {
                    setTimeout(function() {
                        window.location.href = redirectURL;
                    }, 10);
                    setTimeout(function() {
                        isWaitingLogin = false;
                    }, 2000);
                };

                if (message) {
                    showDialog(message, callback);
                }
                else {
                    callback();
                }
                return;
            }
            if ($.isPlainObject(data) && data.type == 'modal' && data.message) {
                data = data.message;
            }
            showDialog(data, function() {
                setTimeout(function() {
                    isWaitingLogin = false;
                }, 2000);
            });
        });
    };

    var classBox = 'gapper-client-checkbox';
    var classLi = 'gapper-client-checkbox-li';
    var isWaitingClick = false;
    $('body').on('click', '.' + classBox + ' .' + classLi, function() {
        if (isWaitingClick) return false;
        isWaitingClick = true;
        var $that = $(this);
        if ($that.attr('data-gapper-auth-source')) {
            var source = $that.attr('data-gapper-auth-source');
            var url = 'ajax/gapper/auth/get-form/' + source;
            showLoadingDialog();
            $.get(url, {
                _t: (new Date()).getTime()
            }, function(data) {
                clearLoadingDialog();
                if ($.isPlainObject(data) && data.redirect) {
                    window.location.href = data.redirect;
                    return;
                }
                if ($.isPlainObject(data) && data.type == 'modal' && data.message) {
                    data = data.message;
                }
                clearDialog();
                dialog = $(data);
                dialog.modal({
                    show: true
                    ,backdrop: 'static'
                });
                dialog.on('hide.bs.modal', function() {
                    setTimeout(showLogin, 1);
                });
                setTimeout(function() {
                    isWaitingClick = false;
                }, 2000);
            });
        }
        if ($that.attr('data-gapper-client-group')) {
            showLoadingDialog();
            $.post('ajax/gapper/auth/gapper/choose', {
                id: $that.attr('data-gapper-client-group')
            }, function(data) {
                setTimeout(function() {
                    isWaitingClick = false;
                }, 2000);
                if (true === data) {
                    window.location.reload();
                }
                if ($.isPlainObject(data) && data.redirect) {
                    window.location.href = data.redirect;
                    return;
                }
                clearLoadingDialog();
                if ($.isPlainObject(data) && data.type == 'modal' && data.message) {
                    data = data.message;
                }
                showDialog(data);
            });
        }
    });

    var classForm = '.gapper-auth-form';
    var isWaitingSubmit = false;
    $('body').on('click', classForm + ' input[type=submit]', function(evt) {
        evt.preventDefault();
        if (isWaitingSubmit) return false;
        isWaitingSubmit = true;
        var $that = $(this).parents(classForm);
        var url = $that.attr('action');
        var data = $that.serialize();
        showLoadingDialog();
        $.post(url, data, function(pData) {
            if (true === pData) {
                window.location.reload();
            }
            else {
                var tData = $.isPlainObject(pData) ? pData: {
                    type: 'alert'
                    ,message: pData
                };
                switch (tData.type) {
                    case 'modal':
                        clearLoadingDialog();
                        clearDialog();
                        dialog = $(tData.message);
                        dialog.modal({
                            show: true
                            ,backdrop: 'static'
                        });
                        dialog.on('hide.bs.modal', function() {
                            setTimeout(showLogin, 1);
                        });
                        break;
                    case 'alert':
                        clearLoadingDialog();
                        showDialog(pData);
                        break;
                    default:
                        if (pData.redirect) {
                            var callback = function() {
                                setTimeout(function() {
                                    window.location.href = pData.redirect;
                                }, 10);
                            };
                            if (pData.message) {
                                clearLoadingDialog();
                                showDialog(pData.message, callback);
                            }
                            else {
                                callback();
                            }
                        }
                }
            }
            setTimeout(function() {
                isWaitingSubmit = false;
            }, 2000);
        });
        return false;
    });

    $(document).on('click', '.login-modal .close', function() {
        isWaitingLogin = true;
        $.get('ajax/gapper/client/logout', {
            _t: (new Date()).getTime()
        }, function() {
            isWaitingLogin = false;
            setTimeout(showLogin, 10);
        });
    });

    var data = {
        show: showLogin
    };
    return data;
});

<|endoftext|>


<commit_before>function round(value, digits) //digits 1 for 1 digit after comma
{
	var factor = Math.pow(10, digits);
	value = Math.round(value*factor);
	return value/factor;
}

function logEC3000(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='22'){                    // Für jeden Datensatz mit dem fixen Eintrag WS
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,21);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
            var id = ((buf.readIntLE(0)*256) + (buf.readIntLE(1))).toString(16);

                console.log('Station ID   : '+ id );
                console.log('total time   : '+ ( (buf.readIntLE(2) *16777216 ) + (buf.readIntLE(3) *65536)+ (buf.readIntLE(4) *256) + (buf.readIntLE(5))  ) );
                console.log('on time      : '+ ( (buf.readIntLE(6) *16777216  ) + (buf.readIntLE(7) *65536)+ (buf.readIntLE(8) *256) + (buf.readIntLE(9))  ) );
                console.log('energy       : '+ ( (buf.readIntLE(10) *16777216  ) + (buf.readIntLE(11) *65536)+ (buf.readIntLE(12)  *256) + (buf.readIntLE(13))  ) );
                console.log('power        : '+ ( (buf.readIntLE(14) *256 ) + (buf.readIntLE(15))  ) );
                console.log('max power    : '+ ( (buf.readIntLE(16) *256 ) + (buf.readIntLE(17))  ) );
                console.log('resets       : '+ ( buf.readIntLE(18))  );

        }
    }
}

logEC3000('OK 22 188 129 0 209 209 102 0 174 89 187 0 1 123 102 0 0 10 117 2 0');

// Weather Station
//OK WS 60  1   4   193 52    2 88  4   101 15  20          ID=60  21.7°C  52%rH  600mm  Dir.: 112.5°  Wind:15m/s  Gust:20m/s
//OK WS ID  XXX TTT TTT HHH RRR RRR DDD DDD SSS SSS GGG GGG FFF PPP PPP
//|  |  |   |   |   |   |   |   |   |   |   |   |   |   |   |-- Flags *
//|  |  |   |   |   |   |   |   |   |   |   |   |   |   |------ WindGust * 10 LSB (0.0 ... 50.0 m/s)           FF/FF = none
//|  |  |   |   |   |   |   |   |   |   |   |   |   |---------- WindGust * 10 MSB
//|  |  |   |   |   |   |   |   |   |   |   |   |-------------- WindSpeed  * 10 LSB(0.0 ... 50.0 m/s)          FF/FF = none
//|  |  |   |   |   |   |   |   |   |   |   |------------------ WindSpeed  * 10 MSB
//|  |  |   |   |   |   |   |   |   |   |---------------------- WindDirection * 10 LSB (0.0 ... 365.0 Degrees) FF/FF = none
//|  |  |   |   |   |   |   |   |   |-------------------------- WindDirection * 10 MSB
//|  |  |   |   |   |   |   |   |------------------------------ Rain LSB (0 ... 9999 mm)                       FF/FF = none
//|  |  |   |   |   |   |   |---------------------------------- Rain MSB
//|  |  |   |   |   |   |-------------------------------------- Humidity (1 ... 99 %rH)                        FF = none
//|  |  |   |   |   |------------------------------------------ Temp * 10 + 1000 LSB (-40 ... +60 ∞C)          FF/FF = none
//|  |  |   |   |---------------------------------------------- Temp * 10 + 1000 MSB
//|  |  |   |-------------------------------------------------- Sensor type (1=TX22IT, 2=NodeSensor, 3=WS1080)
//|  |  |------------------------------------------------------ Sensor ID (1 ... 63)
//|  |--------------------------------------------------------- fix "WS"
//|------------------------------------------------------------ fix "OK"
//* Flags: 128  64  32  16  8   4   2   1
//                              |   |   |
//                              |   |   |-- New battery
//                              |   |------ ERROR
//                              |---------- Low battery

function logLaCrosseWS(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='WS'){                    // Für jeden Datensatz mit dem fixen Eintrag WS
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,18);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
                console.log('Station ID    : '+ (buf.readIntLE(0)) );
                console.log('Type         : '+ (buf.readIntLE(1)) ); //should be 3 otherwise it is only temperature
		if ((buf.readIntLE(2)) === 254){
		    console.log('Temperature   : no data (255)');
		    }
		else {
					console.log('Temperature   : '+ ((((buf.readIntLE(2))*256)+(buf.readIntLE(3))-1000)/10) ) ; // Vorzeichen fehlt noch
					console.log('Temperature2   : '+ ((((buf.readIntLE(2))*256)+(buf.readIntLE(3))-1000)/10) ) ; // Vorzeichen fehlt noch
	    	}
		if  ((buf.readIntLE(4)) === 254){
		    console.log('Humidty   : no data (255)');
		    }
		else {
               		console.log('Humidty      : '+ ((buf.readIntLE(4))*1) );
		}
		if  ((buf.readIntLE(5)) === 254){
		    console.log('Rain   : no data (255)');
		    }
		else {
					console.log('Rain         : '+ ((((buf.readIntLE(5))*256)+(buf.readIntLE(6)))/10 ) );
                	console.log('Rain         : '+ ((((buf.readIntLE(5))*256)+(buf.readIntLE(6)))/2 ) );
		    }
		if  ((buf.readIntLE(9)) === 254){
		    console.log('Wind Speed   : no data (255)');
		    }
		else {
					console.log('WindSpeed    : '+ ((((buf.readIntLE(9))*256)+(buf.readIntLE(10)))/10) + 'm/s');
					console.log('WindSpeed    : '+ round( ((((buf.readIntLE(9))*256)+(buf.readIntLE(10)))/10)*3.6 , 3) + 'km/h');
		}
		if  ((buf.readIntLE(7)) === 254){
		    console.log('WindDirection   : no data (255)');
		    }
		else {
                	console.log('WindDirection: '+ ((((buf.readIntLE(7))*256)+(buf.readIntLE(8)))/10) );
		}
		if  ((buf.readIntLE(11)) === 254){
		    console.log('WindGust   : no data (255)');
		    }
		else {
                	console.log('WindGust     : '+ ((((buf.readIntLE(11))*256)+(buf.readIntLE(12)))/10) );
		}
                console.log('NewBattery   : '+ (buf.readIntLE(13) & 0x01) );
                console.log('LowBattery   : '+ ((buf.readIntLE(13) & 0x04) >> 2) );

        }
    }
}

logLaCrosseWS('OK WS 60 1 4 193 52 2 88 4 101 15 20 255 255');
console.log('ID=60  21.7°C  52%rH  600mm  Dir.: 112.5°  Wind:15m/s  Gust:20m/s');
logLaCrosseWS('OK WS 34 1 4 199 65 0 29 7 8 0 0 255 255');
console.log('ID=34  21.8°C  66%rH  600mm  Dir.: 180°  Wind:0m/s  Gust:--m/s');
logLaCrosseWS('OK WS 34 1 4 199 65 0 129 2 163 0 9 0 19');
console.log('ID=34  21.8°C  66%rH  600mm  Dir.: 67,5°  Wind:0,9m/s  Gust:1,9m/s');
logLaCrosseWS('OK WS 34 1 5 21 43 0 168 3 132 0 9 0 19');
console.log('ID=34  30,1°C  43%rH  600mm  Dir.: 90°  Wind:0,9m/s  Gust:1,9m/s');

function logEMT7110(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='EMT7110'){                    // Für jeden Datensatz mit dem fixen Eintrag WS
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,13);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
            var id = (buf.readIntLE(0)*256 + buf.readIntLE(1)).toString(16);

                console.log('Station ID   : '+ id );
                console.log('voltage   : '+ ( (buf.readIntLE(2) *256) + (buf.readIntLE(3))  )/10 );
                console.log('current      : '+ ( (buf.readIntLE(4) *256) + (buf.readIntLE(5))  ) );
                console.log('power       : '+ ( (buf.readIntLE(6)  *256) + (buf.readIntLE(7))  ) );
                console.log('energy        : '+ ( (buf.readIntLE(8) *256 ) + (buf.readIntLE(9))  )/100 );
        }
    }
}
logEMT7110('OK EMT7110 84 81 8 237 0 13 0 2 1 6 1');
console.log('ID 5451   228,5V   13mA   2W   2,62kWh')
logEMT7110('OK EMT7110 84 162 8 207 0 76 0 7 0 0 1');
console.log('ID 5451   228,5V   13mA   2W   2,62kWh')

function logLevel(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='LS'){                    // Für jeden Datensatz mit dem fixen Eintrag WS
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,8);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
                console.log('Sensor ID    : '+ (buf.readIntLE(0)) );
                console.log('Type         : '+ (buf.readIntLE(1)) );
                console.log('Level        : '+ ((((buf.readIntLE(2))*256)+(buf.readIntLE(3))-1000)/10) );
                console.log('Temperatur   : '+ ((((buf.readIntLE(4))*256)+(buf.readIntLE(5))-1000)/10) );
                console.log('Voltage      : '+ ((buf.readIntLE(6))/10 ) );

        }
    }
}

logLevel('OK LS 1 0 5 100 4 191 60');
console.log('  38,0cm    21,5°C   6,0V ');
logLevel('OK LS 1 0 8 167 4 251 57');
console.log('   121,5cm    27,5°C   5,7V ');
<commit_msg>Update simple_test.js<commit_after>function round(value, digits) //digits 1 for 1 digit after comma
{
	var factor = Math.pow(10, digits);
	value = Math.round(value*factor);
	return value/factor;
}

function logEC3000(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='22'){                    // Für jeden Datensatz mit dem fixen Eintrag WS
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,21);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
            var id = ((buf.readIntLE(0)*256) + (buf.readIntLE(1))).toString(16);

                console.log('Station ID   : '+ id );
                console.log('total time   : '+ ( (buf.readIntLE(2) *16777216 ) + (buf.readIntLE(3) *65536)+ (buf.readIntLE(4) *256) + (buf.readIntLE(5))  ) );
                console.log('on time      : '+ ( (buf.readIntLE(6) *16777216  ) + (buf.readIntLE(7) *65536)+ (buf.readIntLE(8) *256) + (buf.readIntLE(9))  ) );
                console.log('energy       : '+ ( (buf.readIntLE(10) *16777216  ) + (buf.readIntLE(11) *65536)+ (buf.readIntLE(12)  *256) + (buf.readIntLE(13))  ) );
                console.log('power        : '+ ( (buf.readIntLE(14) *256 ) + (buf.readIntLE(15))  ) );
                console.log('max power    : '+ ( (buf.readIntLE(16) *256 ) + (buf.readIntLE(17))  ) );
                console.log('resets       : '+ ( buf.readIntLE(18))  );

        }
    }
}
/*
logEC3000('OK 22 188 129 0 209 209 102 0 174 89 187 0 1 123 102 0 0 10 117 2 0');
*/

// Weather Station
//OK WS 60  1   4   193 52    2 88  4   101 15  20          ID=60  21.7°C  52%rH  600mm  Dir.: 112.5°  Wind:15m/s  Gust:20m/s
//OK WS ID  XXX TTT TTT HHH RRR RRR DDD DDD SSS SSS GGG GGG FFF PPP PPP
//|  |  |   |   |   |   |   |   |   |   |   |   |   |   |   |-- Flags *
//|  |  |   |   |   |   |   |   |   |   |   |   |   |   |------ WindGust * 10 LSB (0.0 ... 50.0 m/s)           FF/FF = none
//|  |  |   |   |   |   |   |   |   |   |   |   |   |---------- WindGust * 10 MSB
//|  |  |   |   |   |   |   |   |   |   |   |   |-------------- WindSpeed  * 10 LSB(0.0 ... 50.0 m/s)          FF/FF = none
//|  |  |   |   |   |   |   |   |   |   |   |------------------ WindSpeed  * 10 MSB
//|  |  |   |   |   |   |   |   |   |   |---------------------- WindDirection * 10 LSB (0.0 ... 365.0 Degrees) FF/FF = none
//|  |  |   |   |   |   |   |   |   |-------------------------- WindDirection * 10 MSB
//|  |  |   |   |   |   |   |   |------------------------------ Rain LSB (0 ... 9999 mm)                       FF/FF = none
//|  |  |   |   |   |   |   |---------------------------------- Rain MSB
//|  |  |   |   |   |   |-------------------------------------- Humidity (1 ... 99 %rH)                        FF = none
//|  |  |   |   |   |------------------------------------------ Temp * 10 + 1000 LSB (-40 ... +60 ∞C)          FF/FF = none
//|  |  |   |   |---------------------------------------------- Temp * 10 + 1000 MSB
//|  |  |   |-------------------------------------------------- Sensor type (1=TX22IT, 2=NodeSensor, 3=WS1080)
//|  |  |------------------------------------------------------ Sensor ID (1 ... 63)
//|  |--------------------------------------------------------- fix "WS"
//|------------------------------------------------------------ fix "OK"
//* Flags: 128  64  32  16  8   4   2   1
//                              |   |   |
//                              |   |   |-- New battery
//                              |   |------ ERROR
//                              |---------- Low battery

function logLaCrosseWS(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='WS'){                    // Für jeden Datensatz mit dem fixen Eintrag WS
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,18);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
                console.log('Station ID    : '+ (buf.readIntLE(0)) );
                console.log('Type         : '+ (buf.readIntLE(1)) ); //should be 3 otherwise it is only temperature
		if ((buf.readIntLE(2)) === 254){
		    console.log('Temperature   : no data (255)');
		    }
		else {
					console.log('Temperature   : '+ ((((buf.readIntLE(2))*256)+(buf.readIntLE(3))-1000)/10) ) ; // Vorzeichen fehlt noch
					console.log('Temperature2   : '+ ((((buf.readIntLE(2))*256)+(buf.readIntLE(3))-1000)/10) ) ; // Vorzeichen fehlt noch
	    	}
		if  ((buf.readIntLE(4)) === 254){
		    console.log('Humidty   : no data (255)');
		    }
		else {
               		console.log('Humidty      : '+ ((buf.readIntLE(4))*1) );
		}
		if  ((buf.readIntLE(5)) === 254){
		    console.log('Rain   : no data (255)');
		    }
		else {
					console.log('Rain         : '+ ((((buf.readIntLE(5))*256)+(buf.readIntLE(6)))/10 ) );
                	console.log('Rain         : '+ ((((buf.readIntLE(5))*256)+(buf.readIntLE(6)))/2 ) );
		    }
		if  ((buf.readIntLE(9)) === 254){
		    console.log('Wind Speed   : no data (255)');
		    }
		else {
					console.log('WindSpeed    : '+ ((((buf.readIntLE(9))*256)+(buf.readIntLE(10)))/10) + 'm/s');
					console.log('WindSpeed    : '+ round( ((((buf.readIntLE(9))*256)+(buf.readIntLE(10)))/10)*3.6 , 3) + 'km/h');
		}
		if  ((buf.readIntLE(7)) === 254){
		    console.log('WindDirection   : no data (255)');
		    }
		else {
                	console.log('WindDirection: '+ ((((buf.readIntLE(7))*256)+(buf.readIntLE(8)))/10) );
		}
		if  ((buf.readIntLE(11)) === 254){
		    console.log('WindGust   : no data (255)');
		    }
		else {
                	console.log('WindGust     : '+ ((((buf.readIntLE(11))*256)+(buf.readIntLE(12)))/10) );
		}
                console.log('NewBattery   : '+ (buf.readIntLE(13) & 0x01) );
                console.log('LowBattery   : '+ ((buf.readIntLE(13) & 0x04) >> 2) );

        }
    }
}
/*
logLaCrosseWS('OK WS 60 1 4 193 52 2 88 4 101 15 20 255 255');
console.log('ID=60  21.7°C  52%rH  600mm  Dir.: 112.5°  Wind:15m/s  Gust:20m/s');
logLaCrosseWS('OK WS 34 1 4 199 65 0 29 7 8 0 0 255 255');
console.log('ID=34  21.8°C  66%rH  600mm  Dir.: 180°  Wind:0m/s  Gust:--m/s');
logLaCrosseWS('OK WS 34 1 4 199 65 0 129 2 163 0 9 0 19');
console.log('ID=34  21.8°C  66%rH  600mm  Dir.: 67,5°  Wind:0,9m/s  Gust:1,9m/s');
logLaCrosseWS('OK WS 34 1 5 21 43 0 168 3 132 0 9 0 19');
console.log('ID=34  30,1°C  43%rH  600mm  Dir.: 90°  Wind:0,9m/s  Gust:1,9m/s');
*/

function logEMT7110(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='EMT7110'){                    // Für jeden Datensatz mit dem fixen Eintrag WS
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,13);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
            var id = (buf.readIntLE(0)*256 + buf.readIntLE(1)).toString(16);

                console.log('Station ID   : '+ id );
                console.log('voltage   : '+ ( (buf.readIntLE(2) *256) + (buf.readIntLE(3))  )/10 );
                console.log('current      : '+ ( (buf.readIntLE(4) *256) + (buf.readIntLE(5))  ) );
                console.log('power       : '+ ( (buf.readIntLE(6)  *256) + (buf.readIntLE(7))  ) );
                console.log('energy        : '+ ( (buf.readIntLE(8) *256 ) + (buf.readIntLE(9))  )/100 );
        }
    }
}
/*
logEMT7110('OK EMT7110 84 81 8 237 0 13 0 2 1 6 1');
console.log('ID 5451   228,5V   13mA   2W   2,62kWh')
logEMT7110('OK EMT7110 84 162 8 207 0 76 0 7 0 0 1');
console.log('ID 5451   228,5V   13mA   2W   2,62kWh')
*/
function logLevel(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='LS'){                    // Für jeden Datensatz mit dem fixen Eintrag WS
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,8);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
                console.log('Sensor ID    : '+ (buf.readIntLE(0)) );
                console.log('Type         : '+ (buf.readIntLE(1)) );
                console.log('Level        : '+ ((((buf.readIntLE(2))*256)+(buf.readIntLE(3))-1000)/10) );
                console.log('Temperatur   : '+ ((((buf.readIntLE(4))*256)+(buf.readIntLE(5))-1000)/10) );
                console.log('Voltage      : '+ ((buf.readIntLE(6))/10 ) );

        }
    }
}
/*
logLevel('OK LS 1 0 5 100 4 191 60');
console.log('  38,0cm    21,5°C   6,0V ');
logLevel('OK LS 1 0 8 167 4 251 57');
console.log('   121,5cm    27,5°C   5,7V ');
*/

function logLaCrosseDTH(data){
    var tmp = data.split(' ');
    if(tmp[0]==='OK'){                      // Wenn ein Datensatz sauber gelesen wurde
        if(tmp[1]=='9'){                    // Für jeden Datensatz mit dem fixen Eintrag 9
            // somit werden alle SenderIDs bearbeitet
            var tmpp=tmp.splice(2,6);       // es werden die vorderen Blöcke (0,1,2) entfernt
            console.log('splice       : '+ tmpp);
            var buf = new Buffer(tmpp);
            var buf = Buffer.from(tmpp);

                console.log('Buffer    : '+ buf.inspect());
                console.log('Buffer    : '+ tmpp[0]+' '+tmpp[2]);
                console.log('Sensor ID    : '+ (buf.readIntLE(0)));
                console.log('Type         : '+ ((buf.readIntLE(1) & 0x70) >> 4));
                console.log('NewBattery   : '+ ((buf.readIntLE(1) & 0x80) >> 7));       // wenn "100000xx" dann NewBatt # xx = SensorType 1 oder 2
                console.log('Temperatur   : '+ ((((buf.readIntLE(2))*256)+(buf.readIntLE(3))-1000)/10));
                console.log('Humidty      : '+ (buf.readIntLE(4) & 0x7f));
                console.log('LowBattery   : '+ ((buf.readIntLE(4) & 0x80) >> 7));       // Hier muss noch "incl. WeakBatteryFlag" ausgewertet werden

                console.log('Buffer    : '+ tmpp[0]+' '+tmpp[2]);
                console.log('Sensor ID    : '+ (tmpp[0]));
                console.log('Type         : '+ ((tmpp[1] & 0x70) >> 4));
                console.log('NewBattery   : '+ ((tmpp[1] & 0x80) >> 7));       // wenn "100000xx" dann NewBatt # xx = SensorType 1 oder 2
                console.log('Temperatur   : '+ (((parseInt(tmpp[2])*256)+parseInt(tmpp[3])-1000)/10));
                console.log('Humidty      : '+ (tmpp[4] & 0x7f));
                console.log('LowBattery   : '+ ((tmpp[4] & 0x80) >> 7));       // Hier muss noch "incl. WeakBatteryFlag" ausgewertet werden

                 //absolute Feuchte und Taupunkt
                var temp = ((((buf.readIntLE(2))*256)+(buf.readIntLE(3))-1000)/10);
                var rel = (buf.readIntLE(4) & 0x7f);
                var vappress =rel/100 * 6.1078 * Math.exp(((7.5*temp)/(237.3+temp))/Math.LOG10E);
                var v = Math.log(vappress/6.1078) * Math.LOG10E;
                var dewp = (237.3 * v) / (7.5 - v);
                var habs = 1000 * 18.016 / 8314.3 * 100*vappress/(273.15 + temp );
                console.log('LaCrosse_abshumid'+ round(habs, 1));
                console.log('LaCrosse_dewpoint'+round(dewp, 1));

        }
    }
}

logLaCrosseDTH('OK 9 22 1 4 179 106');
console.log('  ID = 22 T: 20,2 H: 106 no NewBatt ');
logLaCrosseDTH('OK 9 56 1 4 156 37');
console.log('  ID = 56 T: 18.0 H: 37 no NewBatt ');
logLaCrosseDTH('OK 9 2 129 4 220 52');
console.log('  ID = 2 T: 24,4 H: 52 NewBatt now weak Battery');
<|endoftext|>


<commit_before>define([
	"src/core",
	"src/supplemental/main",
	"json!cldr-data/supplemental/likelySubtags.json",
	"json!cldr-data/supplemental/timeData.json",
	"json!cldr-data/supplemental/weekData.json"
], function( Cldr, supplemental, likelySubtagsJson, timeDataJson, weekDataJson ) {

	describe( "Supplemental", function() {
		var en, enGb, fr, ptBr, ty;

		before(function() {
			Cldr.load(
				likelySubtagsJson,
				timeDataJson,
				weekDataJson
			);

			en = new Cldr( "en" ),
			enGb = new Cldr( "en_GB" ),
			fr = new Cldr( "fr" ),
			ptBr = new Cldr( "pt_BR" ),
			ty = new Cldr( "ty" );

			en.supplemental = supplemental( en );
			enGb.supplemental = supplemental( enGb );
			fr.supplemental = supplemental( fr );
			ptBr.supplemental = supplemental( ptBr );
			ty.supplemental = supplemental( ty );
		});

		it( "should get weekData.firstDay", function() {
			// Explicitly defined firstDay.
			expect( en.supplemental.weekData.firstDay() ).to.equal( "sun" );

			// Or default (001).
			expect( ty.supplemental.weekData.firstDay() ).to.equal( "mon" );
		});

		it( "should get weekData.minDays", function() {
			// Explicitly defined minDays.
			expect( fr.supplemental.weekData.minDays() ).to.equal( 4 );

			// Or default (001).
			expect( en.supplemental.weekData.minDays() ).to.equal( 1 );
		});

		it( "should get timeData.allowed", function() {
			// Explicitly defined allowed.
			expect( en.supplemental.timeData.allowed() ).to.equal( "H h" );
			expect( ptBr.supplemental.timeData.allowed() ).to.equal( "H" );

			// Or default (001).
			expect( enGb.supplemental.timeData.allowed() ).to.equal( "H h" );
		});

		it( "should get timeData.preferred", function() {
			// Explicitly defined preferred.
			expect( en.supplemental.timeData.preferred() ).to.equal( "h" );
			expect( ptBr.supplemental.timeData.preferred() ).to.equal( "H" );

			// Or default (001).
			expect( enGb.supplemental.timeData.preferred() ).to.equal( "H" );
		});

	});

});
<commit_msg>Tests: Content update based on CLDR 30<commit_after>define([
	"src/core",
	"src/supplemental/main",
	"json!cldr-data/supplemental/likelySubtags.json",
	"json!cldr-data/supplemental/timeData.json",
	"json!cldr-data/supplemental/weekData.json"
], function( Cldr, supplemental, likelySubtagsJson, timeDataJson, weekDataJson ) {

	describe( "Supplemental", function() {
		var en, enGb, fr, ptBr, ty;

		before(function() {
			Cldr.load(
				likelySubtagsJson,
				timeDataJson,
				weekDataJson
			);

			en = new Cldr( "en" ),
			enGb = new Cldr( "en_GB" ),
			fr = new Cldr( "fr" ),
			ptBr = new Cldr( "pt_BR" ),
			ty = new Cldr( "ty" );

			en.supplemental = supplemental( en );
			enGb.supplemental = supplemental( enGb );
			fr.supplemental = supplemental( fr );
			ptBr.supplemental = supplemental( ptBr );
			ty.supplemental = supplemental( ty );
		});

		it( "should get weekData.firstDay", function() {
			// Explicitly defined firstDay.
			expect( en.supplemental.weekData.firstDay() ).to.equal( "sun" );

			// Or default (001).
			expect( ty.supplemental.weekData.firstDay() ).to.equal( "mon" );
		});

		it( "should get weekData.minDays", function() {
			// Explicitly defined minDays.
			expect( fr.supplemental.weekData.minDays() ).to.equal( 4 );

			// Or default (001).
			expect( en.supplemental.weekData.minDays() ).to.equal( 1 );
		});

		it( "should get timeData.allowed", function() {
			// Explicitly defined allowed.
			expect( en.supplemental.timeData.allowed() ).to.equal( "h hb H hB" );
			expect( ptBr.supplemental.timeData.allowed() ).to.equal( "H hB" );

			// Or default (001).
			expect( enGb.supplemental.timeData.allowed() ).to.equal( "H h hb hB" );
		});

		it( "should get timeData.preferred", function() {
			// Explicitly defined preferred.
			expect( en.supplemental.timeData.preferred() ).to.equal( "h" );
			expect( ptBr.supplemental.timeData.preferred() ).to.equal( "H" );

			// Or default (001).
			expect( enGb.supplemental.timeData.preferred() ).to.equal( "H" );
		});

	});

});
<|endoftext|>


<commit_before>function getCheckboxRulesByFocus(themeData) {
  return {
    borderColor: themeData["checkbox.focus.borderColor"],
    boxShadow: `0 0 0 ${themeData["checkbox.focus.halo.width"]}
      ${themeData["checkbox.focus.halo.color"]}`
  };
}

function getCheckboxRulesByHover(themeData) {
  return {
    borderColor: themeData["checkbox.borderColor"],
    boxShadow: `0 0 0 ${themeData["checkbox.hover.halo.width"]} ${
      themeData["checkbox.hover.halo.color"]
    }`
  };
}

function getCheckboxRulesByPressed(themeData) {
  return {
    borderColor: themeData["checkbox.borderColor"],
    boxShadow: `0 0 0 ${themeData["checkbox.pressed.halo.width"]} ${
      themeData["checkbox.pressed.halo.color"]
    }`
  };
}

function getCheckboxRulesByDisabled(themeData) {
  return {
    opacity: themeData["component.disabled.opacity"],
    boxShadow: `none`,
    pointerEvents: `none`
  };
}

function getCheckboxRulesByChecked(themeData) {
  return {
    border: `none`,
    backgroundColor: themeData["checkbox.checked.backgroundColor"]
  };
}

function getCheckboxRulesByIndeterminate(themeData) {
  return {
    border: `none`,
    backgroundColor: themeData["checkbox.indeterminate.backgroundColor"]
  };
}

function getCheckboxRulesByLegacyTheme(themeData, props) {
  const { checked, disabled, hasFocus, indeterminate } = props;

  return {
    ...(!checked && !hasFocus && !indeterminate
      ? {
          backgroundColor: themeData["checkbox.backgroundColor"]
        }
      : {}),
    ...(hasFocus
      ? {
          backgroundColor: themeData["checkbox.backgroundColor"]
        }
      : {}),
    ...(checked
      ? {
          backgroundColor: themeData["checkbox.checked.backgroundColor"],
          borderColor: themeData["checkbox.checked.borderColor"]
        }
      : {}),
    ...(checked && hasFocus
      ? {
          backgroundColor: themeData["checkbox.focus.checked.backgroundColor"],
          borderColor: themeData["checkbox.focus.checked.borderColor"]
        }
      : {}),
    ...(indeterminate
      ? {
          backgroundColor: themeData["checkbox.indeterminate.backgroundColor"],
          borderColor: themeData["checkbox.indeterminate.borderColor"]
        }
      : {}),
    ...(indeterminate && hasFocus
      ? {
          borderColor: themeData["checkbox.focus.indeterminate.borderColor"]
        }
      : {}),
    ...(disabled
      ? {
          borderStyle: `dotted`,
          opacity: themeData["component.disabled.opacity"]
        }
      : {}),
    ...(disabled && indeterminate
      ? {
          opacity: themeData["component.disabled.opacity"]
        }
      : {}),
    ...(disabled && checked && !indeterminate
      ? {
          backgroundColor: themeData["checkbox.backgroundColor"],
          opacity: themeData["component.disabled.opacity"]
        }
      : {})
  };
}

export default function stylesheet(props, themeData, theme) {
  const {
    checked,
    disabled,
    hasFocus,
    hasHover,
    indeterminate,
    isPressed
  } = props;

  return {
    checkboxWrapper: {
      boxSizing: `border-box`,
      display: `inline-block`,
      position: `relative`,
      height: themeData["checkbox.height"],
      width: themeData["checkbox.width"]
    },
    checkboxCheckWrapper: {
      position: `relative`,
      display: `block`,
      boxSizing: `border-box`,
      color: `transparent`,
      border: `${themeData["checkbox.borderWidth"]} solid
        ${themeData["checkbox.borderColor"]}`,
      backgroundColor: `transparent`,
      textAlign: `center`,
      fontSize: `25px`,
      lineHeight: `14px`,
      height: themeData["checkbox.height"],
      width: themeData["checkbox.width"],
      borderRadius: themeData["checkbox.borderRadius"],
      cursor: hasHover ? `pointer` : `default`,
      // eslint-disable-next-line prettier/prettier
      "svg": {
        position: `absolute`,
        left: `50%`,
        top: `50%`,
        transform: `translateX(-50%) translateY(-50%)`,
        pointerEvents: `none`,
        "*": {
          fill: themeData["checkbox.iconColor"]
        }
      },
      ...(hasFocus ? getCheckboxRulesByFocus(themeData) : {}),
      ...(hasHover ? getCheckboxRulesByHover(themeData) : {}),
      ...(isPressed ? getCheckboxRulesByPressed(themeData) : {}),
      ...(disabled ? getCheckboxRulesByDisabled(themeData) : {}),
      ...(checked ? getCheckboxRulesByChecked(themeData) : {}),
      ...(indeterminate ? getCheckboxRulesByIndeterminate(themeData) : {}),
      ...(theme === `hig-light`
        ? getCheckboxRulesByLegacyTheme(themeData, props)
        : {})
    },
    checkboxInput: {
      opacity: 0,
      position: `absolute`,
      width: `100%`,
      height: `100%`,
      top: 0,
      left: 0,
      zIndex: 1,
      padding: 0,
      margin: 0
    },
    checkboxCheck: {
      display: checked && !indeterminate ? `block` : `none`
    },
    checkboxIndeterminate: {
      display: indeterminate ? `block` : `none`
    }
  };
}
<commit_msg>fix: halo transition<commit_after>function getCheckboxRulesByFocus(themeData) {
  return {
    borderColor: themeData["checkbox.focus.borderColor"],
    boxShadow: `0 0 0 ${themeData["checkbox.focus.halo.width"]}
      ${themeData["checkbox.focus.halo.color"]}`
  };
}

function getCheckboxRulesByHover(themeData) {
  return {
    borderColor: themeData["checkbox.borderColor"],
    boxShadow: `0 0 0 ${themeData["checkbox.hover.halo.width"]} ${
      themeData["checkbox.hover.halo.color"]
    }`
  };
}

function getCheckboxRulesByPressed(themeData) {
  return {
    borderColor: themeData["checkbox.borderColor"],
    boxShadow: `0 0 0 ${themeData["checkbox.pressed.halo.width"]} ${
      themeData["checkbox.pressed.halo.color"]
    }`
  };
}

function getCheckboxRulesByDisabled(themeData) {
  return {
    opacity: themeData["component.disabled.opacity"],
    boxShadow: `none`,
    pointerEvents: `none`
  };
}

function getCheckboxRulesByChecked(themeData) {
  return {
    border: `none`,
    backgroundColor: themeData["checkbox.checked.backgroundColor"]
  };
}

function getCheckboxRulesByIndeterminate(themeData) {
  return {
    border: `none`,
    backgroundColor: themeData["checkbox.indeterminate.backgroundColor"]
  };
}

function getCheckboxRulesByLegacyTheme(themeData, props) {
  const { checked, disabled, hasFocus, indeterminate } = props;

  return {
    ...(!checked && !hasFocus && !indeterminate
      ? {
          backgroundColor: themeData["checkbox.backgroundColor"]
        }
      : {}),
    ...(hasFocus
      ? {
          backgroundColor: themeData["checkbox.backgroundColor"]
        }
      : {}),
    ...(checked
      ? {
          backgroundColor: themeData["checkbox.checked.backgroundColor"],
          borderColor: themeData["checkbox.checked.borderColor"]
        }
      : {}),
    ...(checked && hasFocus
      ? {
          backgroundColor: themeData["checkbox.focus.checked.backgroundColor"],
          borderColor: themeData["checkbox.focus.checked.borderColor"]
        }
      : {}),
    ...(indeterminate
      ? {
          backgroundColor: themeData["checkbox.indeterminate.backgroundColor"],
          borderColor: themeData["checkbox.indeterminate.borderColor"]
        }
      : {}),
    ...(indeterminate && hasFocus
      ? {
          borderColor: themeData["checkbox.focus.indeterminate.borderColor"]
        }
      : {}),
    ...(disabled
      ? {
          borderStyle: `dotted`,
          opacity: themeData["component.disabled.opacity"]
        }
      : {}),
    ...(disabled && indeterminate
      ? {
          opacity: themeData["component.disabled.opacity"]
        }
      : {}),
    ...(disabled && checked && !indeterminate
      ? {
          backgroundColor: themeData["checkbox.backgroundColor"],
          opacity: themeData["component.disabled.opacity"]
        }
      : {})
  };
}

export default function stylesheet(props, themeData, theme) {
  const {
    checked,
    disabled,
    hasFocus,
    hasHover,
    indeterminate,
    isPressed
  } = props;

  return {
    checkboxWrapper: {
      boxSizing: `border-box`,
      display: `inline-block`,
      position: `relative`,
      height: themeData["checkbox.height"],
      width: themeData["checkbox.width"]
    },
    checkboxCheckWrapper: {
      position: `relative`,
      display: `block`,
      boxSizing: `border-box`,
      color: `transparent`,
      border: `${themeData["checkbox.borderWidth"]} solid
        ${themeData["checkbox.borderColor"]}`,
      backgroundColor: `transparent`,
      textAlign: `center`,
      fontSize: `25px`,
      lineHeight: `14px`,
      height: themeData["checkbox.height"],
      width: themeData["checkbox.width"],
      borderRadius: themeData["checkbox.borderRadius"],
      cursor: hasHover ? `pointer` : `default`,
      transitionDuration: "0.3s, 0.3s",
      transitionProperty: "box-shadow, border",
      transitionTimingFunction:
        "cubic-bezier(0.4, 0, 0.2, 1), cubic-bezier(0.4, 0, 0.2, 1)",
      // eslint-disable-next-line prettier/prettier
      "svg": {
        position: `absolute`,
        left: `50%`,
        top: `50%`,
        transform: `translateX(-50%) translateY(-50%)`,
        pointerEvents: `none`,
        "*": {
          fill: themeData["checkbox.iconColor"]
        }
      },
      ...(hasFocus ? getCheckboxRulesByFocus(themeData) : {}),
      ...(hasHover ? getCheckboxRulesByHover(themeData) : {}),
      ...(isPressed ? getCheckboxRulesByPressed(themeData) : {}),
      ...(disabled ? getCheckboxRulesByDisabled(themeData) : {}),
      ...(checked ? getCheckboxRulesByChecked(themeData) : {}),
      ...(indeterminate ? getCheckboxRulesByIndeterminate(themeData) : {}),
      ...(theme === `hig-light`
        ? getCheckboxRulesByLegacyTheme(themeData, props)
        : {})
    },
    checkboxInput: {
      opacity: 0,
      position: `absolute`,
      width: `100%`,
      height: `100%`,
      top: 0,
      left: 0,
      zIndex: 1,
      padding: 0,
      margin: 0
    },
    checkboxCheck: {
      display: checked && !indeterminate ? `block` : `none`
    },
    checkboxIndeterminate: {
      display: indeterminate ? `block` : `none`
    }
  };
}
<|endoftext|>


<commit_before>module.exports = {
  "env": {
    "node": true,
    "es6": true
  },
  "parserOptions": {
    "ecmaVersion": 8,
    "sourceType": "module",
    "ecmaFeatures": {
      "modules": true
    }
  },
  "globals": {
    "window": false,
    "define": false,
    "document": false,
    "process": false,
    "console": false,
    "_t": false,
    "angular": false
  },
  "rules": {
    "curly": [2, "all"],
    "indent": [2, 2, {"SwitchCase": 1}],
    "quotes": [2, "single"],
    "max-params": [2, 4],
    "max-depth": [2, 3],
    "max-statements": [2, 20],
    "max-len": [2, 100, 2, {ignoreComments: true, ignoreUrls: true}],
    "no-undef": 2,
    "no-unused-vars": 2,
    "operator-linebreak": [2, "after"],
    "no-multi-str": 2,
    "no-mixed-spaces-and-tabs": 2,
    "no-trailing-spaces": 2,
    "space-unary-ops": 2,
    "one-var": [2, {uninitialized: "always", initialized: "never"}],
    "brace-style": [2, "1tbs", {"allowSingleLine": true}],
    "keyword-spacing": 2,
    "space-infix-ops": 2,
    "space-before-blocks": [2, "always"],
    "eol-last": 2,
    "array-bracket-spacing": [2, "never"],
    "object-curly-spacing": [2, "never"],
    "space-in-parens": [2, "never"],
    "no-multiple-empty-lines": 2,
    "semi-spacing": [2, {"before": false, "after": true}]
  }
};
<commit_msg>fix(eol-last): set eol-last to 'always'<commit_after>module.exports = {
  "env": {
    "node": true,
    "es6": true
  },
  "parserOptions": {
    "ecmaVersion": 8,
    "sourceType": "module",
    "ecmaFeatures": {
      "modules": true
    }
  },
  "globals": {
    "window": false,
    "define": false,
    "document": false,
    "process": false,
    "console": false,
    "_t": false,
    "angular": false
  },
  "rules": {
    "curly": [2, "all"],
    "indent": [2, 2, {"SwitchCase": 1}],
    "quotes": [2, "single"],
    "max-params": [2, 4],
    "max-depth": [2, 3],
    "max-statements": [2, 20],
    "max-len": [2, 100, 2, {ignoreComments: true, ignoreUrls: true}],
    "no-undef": 2,
    "no-unused-vars": 2,
    "operator-linebreak": [2, "after"],
    "no-multi-str": 2,
    "no-mixed-spaces-and-tabs": 2,
    "no-trailing-spaces": 2,
    "space-unary-ops": 2,
    "one-var": [2, {uninitialized: "always", initialized: "never"}],
    "brace-style": [2, "1tbs", {"allowSingleLine": true}],
    "keyword-spacing": 2,
    "space-infix-ops": 2,
    "space-before-blocks": [2, "always"],
    "eol-last": [2, "always"],
    "array-bracket-spacing": [2, "never"],
    "object-curly-spacing": [2, "never"],
    "space-in-parens": [2, "never"],
    "no-multiple-empty-lines": 2,
    "semi-spacing": [2, {"before": false, "after": true}]
  }
};
<|endoftext|>


<commit_before>new Test.Unit.Runner({
  testToolbarWithBasicButtonSet: function() {
    var runner = this;

    var editor = WysiHat.Editor.attach('content');
    var toolbar = new WysiHat.Toolbar(editor);
    toolbar.addButtonSet(WysiHat.Toolbar.ButtonSets.Basic);

    editor.whenReady(function() {
      runner.assertEqual(editor, toolbar.editor);
      runner.assertEqual(toolbar.element, $$('div.editor_toolbar').first());

      runner.assert($$('div.editor_toolbar').first());
      runner.assert($$('div.editor_toolbar a.bold').first());
      runner.assertEqual("Bold", $$('div.editor_toolbar a.bold').first().text);
      runner.assert($$('div.editor_toolbar a.underline').first());
      runner.assertEqual("Underline", $$('div.editor_toolbar a.underline').first().text);
      runner.assert($$('div.editor_toolbar a.italic').first());
      runner.assertEqual("Italic", $$('div.editor_toolbar a.italic').first().text);
    });

    runner.wait(1000, function() {});
  }
});
<commit_msg>normalize tests for IE<commit_after>new Test.Unit.Runner({
  testToolbarWithBasicButtonSet: function() {
    var runner = this;

    var editor = WysiHat.Editor.attach('content');
    var toolbar = new WysiHat.Toolbar(editor);
    toolbar.addButtonSet(WysiHat.Toolbar.ButtonSets.Basic);

    editor.whenReady(function() {
      runner.assertEqual(editor, toolbar.editor);
      runner.assertEqual(toolbar.element, $$('div.editor_toolbar').first());

      runner.assert($$('div.editor_toolbar').first());
      runner.assert($$('div.editor_toolbar a.bold').first());
      runner.assertEqual("bold", $$('div.editor_toolbar a.bold').first().innerHTML.toLowerCase());
      runner.assert($$('div.editor_toolbar a.underline').first());
      runner.assertEqual("underline", $$('div.editor_toolbar a.underline').first().innerHTML.toLowerCase());
      runner.assert($$('div.editor_toolbar a.italic').first());
      runner.assertEqual("italic", $$('div.editor_toolbar a.italic').first().innerHTML.toLowerCase());
    });

    runner.wait(1000, function() {});
  }
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017, Hugo Freire <hugo@exec.sh>.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

const { SQLite } = require('../../src/database')

describe('Tinder', () => {
  let subject

  afterEach(() => td.reset())

  describe('when getting updates', () => {
    beforeEach(() => {
      subject = require('../../src/channels/tinder')
    })
  })
})
<commit_msg>test: remove tinder test<commit_after><|endoftext|>