<commit_before>'use strict';

var request = require('request'),
    _       = require('lodash'),
    url     = require('url'),
    fs      = require('fs');

var DM_API_ROOT = 'https://api.dailymotion.com';
var GRANT_TYPES = ['client_credentials', 'authorization_code', 'password'];

var DailymotionAPI = function(clientID, clientSecret, scope) {
    this.config = {};
    this.config.client_id = clientID;
    this.config.client_secret = clientSecret;
    this.config.scope = scope || null;

    this.credentials = {};
    this.grant_type = 'authorization_code';

    this._expirationTimestamp = null;
    this._authFailed = true;
};

/**
 * Sets access scope
 * @param {array} scope Array of scope permission strings
 */
DailymotionAPI.prototype.setScope = function(scope) {
    this.config.scope = scope;

    return this;
};

/**
 * Sets credentials
 * @param {string} grant_type  Can be either 'client_credentials', 'authorization_code' or 'password'
 * @param {object} credentials Credentials in the following structure
 *                                 password:
 *                                     - {string} username
 *                                     - {string} password
 *                                 authorization_code:
 *                                     - {string} access_token
 *                                     - {string} refresh_token
 *                                 client_credentials:
 *                                     leave it empty
 */
DailymotionAPI.prototype.setCredentials = function(grant_type, credentials) {
    if (GRANT_TYPES.indexOf(grant_type) === -1)
        throw 'DM.API :: Given grant_type in setCredentials() does not match any known type';

    this.grant_type = grant_type;

    if (this.grant_type === 'client_credentials')
        this.credentials = {};
    else
    {
        this.credentials = _.extend(this.credentials, credentials);
        if (this.grant_type === 'authorization_code')
        {
            this._expirationTimestamp = credentials.expires_at;
            delete this.credentials.expires_at;
        }
    }

    return this;
};

/**
 * Creates a token when you have 'password' grant type
 * @param  {Function} next Callback for when the token is indeed refreshed. Can be called with 1 param if error
 */
DailymotionAPI.prototype.createToken = function(next) {
    var payload = _.extend(this.config, this.credentials);
    payload.scope = payload.scope.join(' ');
    payload.grant_type = this.grant_type;

    request.post({
        url: DM_API_ROOT + '/oauth/token',
        form: payload
    }, function(e, r, body) {
        try         { var data = JSON.parse(body); }
        catch (e)   { return next(e); }
        this.credentials.accessToken = data.access_token;
        this.credentials.refreshToken = data.refresh_token;
        this._expirationTimestamp = Date.now() + data.expires_in * 1000;
        this._authFailed = false;
        next();
    }.bind(this));
};

/**
 * Refreshes an expired access_token with the help of a refresh_token
 * @param  {Function} next Callback for when the token is indeed refreshed. Can be called with 1 param if error
 */
DailymotionAPI.prototype.refreshToken = function(next) {
    if (!this.credentials.refreshToken)
        throw 'DM.API :: refresh_token not set!';

    request.post({
        url: DM_API_ROOT + '/oauth/token',
        form: {
            client_id: this.config.client_id,
            client_secret: this.config.client_secret,
            grant_type: 'refresh_token',
            refresh_token: this.credentials.refreshToken
        }
    }, function(e, r, body) {
        try         { var data = JSON.parse(body); }
        catch (e)   { return next(e); }
        this.credentials.accessToken = data.access_token;
        this.credentials.refreshToken = data.refresh_token;
        this._expirationTimestamp = Date.now() + data.expires_in * 1000;
        this._authFailed = false;
        next();
    }.bind(this));
};

/**
 * Authenticated API Request
 * @param  {string}   verb     HTTP Verb to be used
 * @param  {string}   endpoint Endpoint path
 * @param  {object}   data     Data to send to given endpoint
 * @param  {Function} callback Function called when request is done. Callback params are:
 *                                 - {Error} err - It should be null most of the time
 */
DailymotionAPI.prototype.api = function(verb, endpoint, data, callback) {

    if (typeof data === 'function')
    {
        if (!callback) // switch args around
        {
            callback = data;
            data = {};
        }
        else
            data = data();
    }
    else if (!data)
        data = {};

    // Token expiration check
    if (!!this._expirationTimestamp && this._expirationTimestamp <= Date.now())
    {
        if (this._authFailed)
            throw 'DM.API :: Authentication failed twice, check your credentials';

        this._authFailed = true;
        return this.refreshToken(function(e) {
            if (!!e) return callback(e, null, {});
            this.api(verb, endpoint, data, callback);
        }.bind(this));
    }

    var opts = {
        url: DM_API_ROOT + endpoint,
        method: verb.toUpperCase(), // always UPPERCASEPLS
        auth: { // DM auth
            bearer: this.credentials.accessToken
        }
    };

    // Automatic data passing
    switch (opts.method)
    {
        case 'GET': // append query string
            opts.url += url.format({ query: data });
            break;
        case 'POST': // use form param
            opts.form = data;
            break;
        default: // strip the first ?
            opts.body = url.format({ query: data }).substring(1);
    }

    // Perform actual api request
    return request(opts, function(e, r, body) {
        if (typeof callback === 'function')
        {
            try         { var res = JSON.parse(body); }
            catch (e)   { return callback(e, r, {}); }
            callback(e, r, res);
        }
    });
};

// Convenience methods for api()
DailymotionAPI.prototype.get     = function(endpoint, data, callback) { this.api('GET',    endpoint, data, callback); };
DailymotionAPI.prototype.post    = function(endpoint, data, callback) { this.api('POST',   endpoint, data, callback); };
DailymotionAPI.prototype.head    = function(endpoint, data, callback) { this.api('HEAD',   endpoint, data, callback); };
DailymotionAPI.prototype.put     = function(endpoint, data, callback) { this.api('PUT',    endpoint, data, callback); };
DailymotionAPI.prototype.patch   = function(endpoint, data, callback) { this.api('PATCH',  endpoint, data, callback); };
DailymotionAPI.prototype.del     = function(endpoint, data, callback) { this.api('DELETE', endpoint, data, callback); };
DailymotionAPI.prototype.options = function(endpoint, callback)       { this.api('OPTIONS', endpoint, callback); };

/**
 * Uploads a video using user's auth data
 * @param  {object} options - Contains the following fields :
 *                              - {string} filepath - System path to video
 *                              - {object} meta - Metadata for the new video (such as title, channel, tags, etc)
 *                              - OPTIONAL {function} progress - Progress callback for upload progression
 *                              - OPTIONAL {function} done - Called when upload is finished with new video ID and other data.
 */
DailymotionAPI.prototype.upload = function(options) {
    if (!options.filepath || !options.meta)
        throw 'DM.API :: Filepath or meta not given in upload method';

    if (!fs.fileExistsSync(options.filepath))
        throw 'DM.API :: Filepath not found';

    // Request upload URL
    this.get('/file/upload', function(err, req, res) {
        var uploadURL = res.upload_url;
        var progressURL = res.progress_url;
        var progresshwnd = null;
        if (typeof options.progress === 'function')
        {
            // Progress Handle - check progress every 3 seconds
            progresshwnd = setInterval(function() {
                request({
                    url: progressURL,
                    method: 'GET',
                    auth: {
                        bearer: this.credentials.accessToken
                    },
                }, function(e, r, body) {
                    try         { var res = JSON.parse(body); }
                    catch (e)   { return options.progress(e, r, {}); }
                    options.progress(null, r, res);
                });
            }, 3000);
        }

        // Proceed to upload
        request({
            url: uploadURL,
            method: 'POST',
            auth: {
                bearer: this.credentials.accessToken
            },
            formData: {
                file: fs.createReadStream(options.filepath)
            },
            headers: {
                'Content-Type': 'video/mp4'
            }
        }, function(e, r, body) {
            try         { var uploadRes = JSON.parse(body); }
            catch (e)   { return (typeof options.done === 'function' ? options.done(e, null) : undefined); }

            var videoURL = uploadRes.url;

            // Stop progress checked
            if (!!progresshwnd)
            {
                clearInterval(progresshwnd);
                progresshwnd = null;
            }

            // Associate newly uploaded video to account
            this.post('/me/videos', _.extend(options.meta, {
                url: videoURL
            }), function(err2, req2, videoCreated) {
                if (typeof options.done !== 'function')
                    return;

                if (!!err)
                    return options.done(err2, null);

                options.done(null, videoCreated);
            });
        });
    });
};

module.exports.client = DailymotionAPI;
<commit_msg>Make this code a little fancier to read<commit_after>'use strict';

var request = require('request'),
    _       = require('lodash'),
    url     = require('url'),
    fs      = require('fs');

var DM_API_ROOT = 'https://api.dailymotion.com';
var GRANT_TYPES = ['client_credentials', 'authorization_code', 'password'];

var DailymotionAPI = function(clientID, clientSecret, scope) {
    this.config = {
        client_id:      clientID,
        client_secret:  clientSecret,
        scope:          scope || []
    };

    this.credentials    = {};
    this.grant_type     = 'authorization_code';

    this._expirationTimestamp   = null;
    this._authFailed            = true;
};

/**
 * Sets access scope
 * @param {array|function|string} scope - Permission scopes. Can be array, function or string (separated by spaces)
 */
DailymotionAPI.prototype.setScope = function(scope) {
    if (typeof scope === 'function')
        scope = scope();

    if (typeof scope === 'string')
        scope = scope.split(' ');

    if (_.isArray(scope))
        this.config.scope = scope;

    return this;
};

/**
 * Sets credentials
 * @param {string} grant_type  Can be either 'client_credentials', 'authorization_code' or 'password'
 * @param {object} credentials Credentials in the following structure
 *                                 password:
 *                                     - {string} username
 *                                     - {string} password
 *                                 authorization_code:
 *                                     - {string} access_token
 *                                     - {string} refresh_token
 *                                 client_credentials:
 *                                     leave it empty
 */
DailymotionAPI.prototype.setCredentials = function(grant_type, credentials) {
    if (GRANT_TYPES.indexOf(grant_type) === -1)
        throw 'DM.API :: Given grant_type in setCredentials() does not match any known type';

    this.grant_type = grant_type;

    if (this.grant_type === 'client_credentials')
        this.credentials = {};
    else
    {
        this.credentials = _.extend(this.credentials, credentials);
        if (this.grant_type === 'authorization_code')
        {
            this._expirationTimestamp = credentials.expires_at;
            delete this.credentials.expires_at;
        }
    }

    return this;
};

/**
 * Creates a token when you have 'password' grant type
 * @param  {Function} next Callback for when the token is indeed refreshed. Can be called with 1 param if error
 */
DailymotionAPI.prototype.createToken = function(next) {
    var payload         = _.extend(this.config, this.credentials);
    payload.scope       = payload.scope.join(' ');
    payload.grant_type  = this.grant_type;

    request.post({
        url: DM_API_ROOT + '/oauth/token',
        form: payload
    }, function(e, r, body) {
        try         { var data = JSON.parse(body); }
        catch (e)   { return next(e); }

        this.credentials.accessToken    = data.access_token;
        this.credentials.refreshToken   = data.refresh_token;
        this._expirationTimestamp       = Date.now() + data.expires_in * 1000;
        this._authFailed                = false;

        next();
    }.bind(this));
};

/**
 * Refreshes an expired access_token with the help of a refresh_token
 * @param  {Function} next Callback for when the token is indeed refreshed. Can be called with 1 param if error
 */
DailymotionAPI.prototype.refreshToken = function(next) {
    if (!this.credentials.refreshToken)
        throw 'DM.API :: refresh_token not set!';

    request.post({
        url: DM_API_ROOT + '/oauth/token',
        form: {
            client_id:      this.config.client_id,
            client_secret:  this.config.client_secret,
            grant_type:     'refresh_token',
            refresh_token:  this.credentials.refreshToken
        }
    }, function(e, r, body) {
        try         { var data = JSON.parse(body); }
        catch (e)   { return next(e); }

        this.credentials.accessToken    = data.access_token;
        this.credentials.refreshToken   = data.refresh_token;
        this._expirationTimestamp       = Date.now() + data.expires_in * 1000;
        this._authFailed                = false;

        next();
    }.bind(this));
};

/**
 * Authenticated API Request
 * @param  {string}   verb     HTTP Verb to be used
 * @param  {string}   endpoint Endpoint path
 * @param  {object}   data     Data to send to given endpoint
 * @param  {Function} callback Function called when request is done. Callback params are:
 *                                 - {Error} err - It should be null most of the time
 */
DailymotionAPI.prototype.api = function(verb, endpoint, data, callback) {

    if (typeof data === 'function')
    {
        if (!callback) // switch args around
        {
            callback = data;
            data = {};
        }
        else
            data = data();
    }
    else if (!data)
        data = {};

    // Token expiration check
    if (!!this._expirationTimestamp && this._expirationTimestamp <= Date.now())
    {
        if (this._authFailed)
            throw 'DM.API :: Authentication failed twice, check your credentials';

        this._authFailed = true;
        return this.refreshToken(function(e) {
            if (!!e) return callback(e, null, {});
            this.api(verb, endpoint, data, callback);
        }.bind(this));
    }

    var opts = {
        url: DM_API_ROOT + endpoint,
        method: verb.toUpperCase(), // always UPPERCASEPLS
        auth: { // DM auth
            bearer: this.credentials.accessToken
        }
    };

    // Automatic data passing
    switch (opts.method)
    {
        case 'GET': // append query string
            opts.url += url.format({ query: data });
            break;
        case 'POST': // use form param
            opts.form = data;
            break;
        default: // strip the first ?
            opts.body = url.format({ query: data }).substring(1);
    }

    // Perform actual api request
    return request(opts, function(e, r, body) {
        if (typeof callback === 'function')
        {
            try         { var res = JSON.parse(body); }
            catch (e)   { return callback(e, r, {}); }
            callback(e, r, res);
        }
    });
};

// Convenience methods for api()
DailymotionAPI.prototype.get     = function(endpoint, data, callback) { this.api('GET',    endpoint, data, callback); };
DailymotionAPI.prototype.post    = function(endpoint, data, callback) { this.api('POST',   endpoint, data, callback); };
DailymotionAPI.prototype.head    = function(endpoint, data, callback) { this.api('HEAD',   endpoint, data, callback); };
DailymotionAPI.prototype.put     = function(endpoint, data, callback) { this.api('PUT',    endpoint, data, callback); };
DailymotionAPI.prototype.patch   = function(endpoint, data, callback) { this.api('PATCH',  endpoint, data, callback); };
DailymotionAPI.prototype.del     = function(endpoint, data, callback) { this.api('DELETE', endpoint, data, callback); };
DailymotionAPI.prototype.options = function(endpoint, callback)       { this.api('OPTIONS', endpoint, callback); };

/**
 * Uploads a video using user's auth data
 * @param  {object} options - Contains the following fields :
 *                              - {string} filepath - System path to video
 *                              - {object} meta - Metadata for the new video (such as title, channel, tags, etc)
 *                              - OPTIONAL {function} progress - Progress callback for upload progression
 *                              - OPTIONAL {function} done - Called when upload is finished with new video ID and other data.
 */
DailymotionAPI.prototype.upload = function(options) {
    if (!options.filepath || !options.meta)
        throw 'DM.API :: Filepath or meta not given in upload method';

    if (!fs.fileExistsSync(options.filepath))
        throw 'DM.API :: Filepath not found';

    // Request upload URL
    this.get('/file/upload', function(err, req, res) {
        var uploadURL       = res.upload_url;
        var progressURL     = res.progress_url;
        var progresshwnd    = null;

        if (typeof options.progress === 'function')
        {
            // Progress Handle - check progress every 3 seconds
            progresshwnd = setInterval(function() {
                request({
                    url: progressURL,
                    method: 'GET',
                    auth: {
                        bearer: this.credentials.accessToken
                    },
                }, function(e, r, body) {
                    try         { var res = JSON.parse(body); }
                    catch (e)   { return options.progress(e, r, {}); }
                    options.progress(null, r, res);
                });
            }, 3000);
        }

        // Proceed to upload
        request({
            url: uploadURL,
            method: 'POST',
            auth: {
                bearer: this.credentials.accessToken
            },
            formData: {
                file: fs.createReadStream(options.filepath)
            },
            headers: {
                'Content-Type': 'video/mp4'
            }
        }, function(e, r, body) {
            try         { var uploadRes = JSON.parse(body); }
            catch (e)   { return (typeof options.done === 'function' ? options.done(e, null) : undefined); }

            var videoURL = uploadRes.url;

            // Stop progress checked
            if (!!progresshwnd)
            {
                clearInterval(progresshwnd);
                progresshwnd = null;
            }

            // Associate newly uploaded video to account
            this.post('/me/videos', _.extend(options.meta, {
                url: videoURL
            }), function(err2, req2, videoCreated) {
                if (typeof options.done !== 'function')
                    return;

                if (!!err)
                    return options.done(err2, null);

                options.done(null, videoCreated);
            });
        });
    });
};

module.exports.client = DailymotionAPI;
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert'),
    Batch = require('batch'),
    getStylesData = require('style-data'),
    getStylesheetList = require('list-stylesheets'),
    getHrefContent = require('href-content');

module.exports = function (html, options, callback) {
    var batch = new Batch();
    var data = getStylesheetList(html, options);
    batch.push(function (callback) {
        getStylesData(data.html, options, callback);
    });
    if (data.hrefs.length) {
        assert.ok(options.url, 'options.url is required');
    }
    data.hrefs.forEach(function (stylesheetHref) {
        batch.push(function (callback) {
            getHrefContent(stylesheetHref, options.url, callback);
        });
    });
    batch.end(function (err, results) {
        if (err) {
            return callback(err);
        }
        var stylesData = results.shift();
        results.forEach(function (content) {
            stylesData.css.push(content);
        });
        var css = stylesData.css.join('\n');
        callback(null, stylesData.html, css);
    });
};
<commit_msg>Fix eslint issues.<commit_after>'use strict';

var assert = require('assert'),
    Batch = require('batch'),
    getStylesData = require('style-data'),
    getStylesheetList = require('list-stylesheets'),
    getHrefContent = require('href-content');

module.exports = function (html, options, callback) {
    var batch = new Batch(),
        data = getStylesheetList(html, options);

    batch.push(function (cb) {
        getStylesData(data.html, options, cb);
    });
    if (data.hrefs.length) {
        assert.ok(options.url, 'options.url is required');
    }
    data.hrefs.forEach(function (stylesheetHref) {
        batch.push(function (cb) {
            getHrefContent(stylesheetHref, options.url, cb);
        });
    });
    batch.end(function (err, results) {
        var stylesData = results.shift(),
            css;

        if (err) {
            return callback(err);
        }
        results.forEach(function (content) {
            stylesData.css.push(content);
        });
        css = stylesData.css.join('\n');
        callback(null, stylesData.html, css);
    });
};
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	parserOptions: {
		ecmaVersion: 2018,
		sourceType: 'module',
		ecmaFeatures: {
			jsx: true
		}
	},
	env: {
		node: true,
		es6: true
	},
	rules: {
		'comma-dangle': ['error', 'never'],
		'for-direction': 'error',
		'getter-return': 'error',
		'no-async-promise-executor': 'error',
		'no-await-in-loop': 'error',
		'no-compare-neg-zero': 'error',
		'no-cond-assign': 'error',
		'no-constant-condition': 'error',
		'no-control-regex': 'error',
		'no-debugger': 'error',
		'no-dupe-args': 'error',
		'no-dupe-keys': 'error',
		'no-duplicate-case': 'error',
		'no-empty-character-class': 'error',
		'no-empty': ['error', {
			allowEmptyCatch: true
		}],
		'no-ex-assign': 'error',
		'no-extra-boolean-cast': 'error',
		// Disabled because of https://github.com/eslint/eslint/issues/6028
		// 'no-extra-parens': [2, 'all', {
		// 	nestedBinaryExpressions: false,
		// 	ignoreJSX: 'multi-line'
		// }],
		'no-extra-semi': 'error',
		'no-func-assign': 'error',
		'no-inner-declarations': 'error',
		'no-invalid-regexp': 'error',
		'no-irregular-whitespace': 'error',
		'no-misleading-character-class': 'error',
		'no-obj-calls': 'error',
		'no-prototype-builtins': 'error',
		'no-regex-spaces': 'error',
		'no-sparse-arrays': 'error',
		'no-template-curly-in-string': 'error',
		'no-unreachable': 'error',
		'no-unsafe-finally': 'error',
		'no-unsafe-negation': 'error',
		'require-atomic-updates': 'error',
		'use-isnan': 'error',
		'valid-typeof': ['error', {requireStringLiterals: false}],
		'no-unexpected-multiline': 'error',
		'accessor-pairs': 'error',
		'array-callback-return': 'error',
		'block-scoped-var': 'error',
		complexity: 'warn',
		curly: 'error',
		'default-case': 'error',
		'dot-notation': 'error',
		'dot-location': ['error', 'property'],
		eqeqeq: 'error',
		'guard-for-in': 'error',
		'no-alert': 'error',
		'no-caller': 'error',
		'no-case-declarations': 'error',
		'no-div-regex': 'error',
		'no-else-return': ['error', {
			allowElseIf: false
		}],
		'no-empty-pattern': 'error',
		'no-eq-null': 'error',
		'no-eval': 'error',
		'no-extend-native': 'error',
		'no-extra-bind': 'error',
		'no-extra-label': 'error',
		'no-fallthrough': 'error',
		'no-floating-decimal': 'error',
		'no-global-assign': 'error',
		'no-implicit-coercion': 'error',
		'no-implicit-globals': 'error',
		'no-implied-eval': 'error',
		'no-iterator': 'error',
		'no-labels': 'error',
		'no-lone-blocks': 'error',
		'no-multi-spaces': 'error',
		'no-multi-str': 'error',
		'no-new-func': 'error',
		'no-new-wrappers': 'error',
		'no-new': 'error',
		'no-octal-escape': 'error',
		'no-octal': 'error',
		'no-proto': 'error',
		'no-redeclare': 'error',
		'no-return-assign': ['error', 'always'],
		'no-return-await': 'error',
		'no-script-url': 'error',
		'no-self-assign': ['error', {props: true}],
		'no-self-compare': 'error',
		'no-sequences': 'error',
		'no-throw-literal': 'error',
		'no-unmodified-loop-condition': 'error',
		'no-unused-expressions': 'error',
		'no-unused-labels': 'error',
		'no-useless-call': 'error',
		'no-useless-concat': 'error',
		'no-useless-escape': 'error',
		'no-useless-return': 'error',
		'no-void': 'error',
		'no-warning-comments': 'warn',
		'no-with': 'error',
		'prefer-promise-reject-errors': ['error', {allowEmptyReject: true}],
		radix: 'error',
		'wrap-iife': ['error', 'inside', {functionPrototypeMethods: true}],
		yoda: 'error',
		'no-delete-var': 'error',
		'no-label-var': 'error',
		'no-restricted-globals': ['error', 'event'],
		'no-shadow-restricted-names': 'error',
		'no-undef-init': 'error',
		'no-undef': ['error', {
			typeof: true
		}],
		'no-unused-vars': ['error', {
			ignoreRestSiblings: true,
			argsIgnorePattern: '^_$'
		}],
		'no-use-before-define': ['error', 'nofunc'],
		// Disabled because of https://github.com/eslint/eslint/issues/3420
		// 'callback-return': ['warn', ['cb', 'callback', 'next', 'done']],
		'handle-callback-err': 'warn',
		'no-buffer-constructor': 'error',
		'no-mixed-requires': ['error', {
			grouping: true,
			allowCall: true
		}],
		'no-new-require': 'error',
		'no-path-concat': 'error',
		'no-restricted-imports': ['error', 'domain', 'freelist', 'smalloc', 'sys', 'colors'],
		'no-restricted-modules': ['error', 'domain', 'freelist', 'smalloc', 'sys', 'colors'],
		'array-bracket-newline': ['error', 'consistent'],
		'array-bracket-spacing': ['error', 'never'],
		'array-element-newline': ['error', 'consistent'],
		'brace-style': ['error', '1tbs', {
			allowSingleLine: false
		}],
		camelcase: ['error', {
			properties: 'always'
		}],
		'capitalized-comments': ['error', 'always', {
			// You can also ignore this rule by wrapping the first word in quotes
			ignorePattern: 'pragma|ignore|prettier-ignore',
			ignoreInlineComments: true,
			ignoreConsecutiveComments: true
		}],
		'comma-spacing': ['error', {
			before: false,
			after: true
		}],
		'comma-style': ['error', 'last'],
		'computed-property-spacing': ['error', 'never'],
		'eol-last': 'error',
		'func-call-spacing': ['error', 'never'],
		'func-name-matching': ['error', {considerPropertyDescriptor: true}],
		'func-names': ['error', 'never'],
		indent: ['error', 'tab', {
			SwitchCase: 1
		}],
		'jsx-quotes': 'error',
		'key-spacing': ['error', {
			beforeColon: false,
			afterColon: true
		}],
		'keyword-spacing': 'error',
		'linebreak-style': [(process.platform === 'win32' ? 'off' : 'error'), 'unix'],
		'lines-between-class-members': ['error', 'always'],
		'max-depth': 'warn',
		'max-nested-callbacks': ['warn', 4],
		'max-params': ['warn', {
			max: 4
		}],
		'max-statements-per-line': 'error',
		'new-cap': ['error', {
			newIsCap: true,
			capIsNew: true
		}],
		'new-parens': 'error',
		'no-array-constructor': 'error',
		'no-lonely-if': 'error',
		'no-mixed-operators': 'error',
		'no-mixed-spaces-and-tabs': 'error',
		'no-multi-assign': 'error',
		'no-multiple-empty-lines': ['error', {
			max: 1
		}],
		'no-negated-condition': 'error',
		'no-new-object': 'error',
		'no-restricted-syntax': ['error', 'WithStatement'],
		'no-whitespace-before-property': 'error',
		'no-trailing-spaces': 'error',
		'no-unneeded-ternary': 'error',
		'object-curly-spacing': ['error', 'never'],
		// Disabled because of https://github.com/xojs/eslint-config-xo/issues/27
		// 'object-property-newline': 'error',
		'one-var': ['error', 'never'],
		'one-var-declaration-per-line': 'error',
		'operator-assignment': ['error', 'always'],
		'operator-linebreak': ['error', 'after'],
		'padded-blocks': ['error', 'never'],
		'quote-props': ['error', 'as-needed'],
		quotes: ['error', 'single', {
			allowTemplateLiterals: true
		}],
		'semi-spacing': ['error', {
			before: false,
			after: true
		}],
		'semi-style': ['error', 'last'],
		semi: ['error', 'always'],
		'space-before-blocks': ['error', 'always'],
		'space-before-function-paren': ['error', {
			anonymous: 'always',
			named: 'never',
			asyncArrow: 'always'
		}],
		'space-in-parens': ['error', 'never'],
		'space-infix-ops': 'error',
		'space-unary-ops': 'error',
		'spaced-comment': ['error', 'always', {
			line: {
				exceptions: ['-', '+', '*'],
				markers: ['!', '/']
			},
			block: {
				exceptions: ['-', '+', '*'],
				markers: ['!', '*'],
				balanced: true
			}
		}],
		'switch-colon-spacing': ['error', {
			after: true,
			before: false
		}],
		'template-tag-spacing': ['error', 'never'],
		'unicode-bom': ['error', 'never'],
		'arrow-parens': ['error', 'as-needed'],
		'arrow-spacing': ['error', {
			before: true,
			after: true
		}],
		'constructor-super': 'error',
		'generator-star-spacing': ['error', 'both'],
		'no-class-assign': 'error',
		'no-const-assign': 'error',
		'no-dupe-class-members': 'error',
		'no-new-symbol': 'error',
		'no-this-before-super': 'error',
		'no-useless-computed-key': 'error',
		'no-useless-constructor': 'error',
		'no-useless-rename': 'error',
		'require-yield': 'error',
		'rest-spread-spacing': ['error', 'never'],
		'symbol-description': 'error',
		'template-curly-spacing': 'error',
		'yield-star-spacing': ['error', 'both'],
		'valid-jsdoc': ['warn', {
			'requireReturn': false,
			'requireParamDescription': true,
			'requireReturnDescription': true
		}]
	}
};
<commit_msg>Add `require-unicode-regexp` rule<commit_after>'use strict';

module.exports = {
	parserOptions: {
		ecmaVersion: 2018,
		sourceType: 'module',
		ecmaFeatures: {
			jsx: true
		}
	},
	env: {
		node: true,
		es6: true
	},
	rules: {
		'comma-dangle': ['error', 'never'],
		'for-direction': 'error',
		'getter-return': 'error',
		'no-async-promise-executor': 'error',
		'no-await-in-loop': 'error',
		'no-compare-neg-zero': 'error',
		'no-cond-assign': 'error',
		'no-constant-condition': 'error',
		'no-control-regex': 'error',
		'no-debugger': 'error',
		'no-dupe-args': 'error',
		'no-dupe-keys': 'error',
		'no-duplicate-case': 'error',
		'no-empty-character-class': 'error',
		'no-empty': ['error', {
			allowEmptyCatch: true
		}],
		'no-ex-assign': 'error',
		'no-extra-boolean-cast': 'error',
		// Disabled because of https://github.com/eslint/eslint/issues/6028
		// 'no-extra-parens': [2, 'all', {
		// 	nestedBinaryExpressions: false,
		// 	ignoreJSX: 'multi-line'
		// }],
		'no-extra-semi': 'error',
		'no-func-assign': 'error',
		'no-inner-declarations': 'error',
		'no-invalid-regexp': 'error',
		'no-irregular-whitespace': 'error',
		'no-misleading-character-class': 'error',
		'no-obj-calls': 'error',
		'no-prototype-builtins': 'error',
		'no-regex-spaces': 'error',
		'no-sparse-arrays': 'error',
		'no-template-curly-in-string': 'error',
		'no-unreachable': 'error',
		'no-unsafe-finally': 'error',
		'no-unsafe-negation': 'error',
		'require-atomic-updates': 'error',
		'use-isnan': 'error',
		'valid-typeof': ['error', {requireStringLiterals: false}],
		'no-unexpected-multiline': 'error',
		'accessor-pairs': 'error',
		'array-callback-return': 'error',
		'block-scoped-var': 'error',
		complexity: 'warn',
		curly: 'error',
		'default-case': 'error',
		'dot-notation': 'error',
		'dot-location': ['error', 'property'],
		eqeqeq: 'error',
		'guard-for-in': 'error',
		'no-alert': 'error',
		'no-caller': 'error',
		'no-case-declarations': 'error',
		'no-div-regex': 'error',
		'no-else-return': ['error', {
			allowElseIf: false
		}],
		'no-empty-pattern': 'error',
		'no-eq-null': 'error',
		'no-eval': 'error',
		'no-extend-native': 'error',
		'no-extra-bind': 'error',
		'no-extra-label': 'error',
		'no-fallthrough': 'error',
		'no-floating-decimal': 'error',
		'no-global-assign': 'error',
		'no-implicit-coercion': 'error',
		'no-implicit-globals': 'error',
		'no-implied-eval': 'error',
		'no-iterator': 'error',
		'no-labels': 'error',
		'no-lone-blocks': 'error',
		'no-multi-spaces': 'error',
		'no-multi-str': 'error',
		'no-new-func': 'error',
		'no-new-wrappers': 'error',
		'no-new': 'error',
		'no-octal-escape': 'error',
		'no-octal': 'error',
		'no-proto': 'error',
		'no-redeclare': 'error',
		'no-return-assign': ['error', 'always'],
		'no-return-await': 'error',
		'no-script-url': 'error',
		'no-self-assign': ['error', {props: true}],
		'no-self-compare': 'error',
		'no-sequences': 'error',
		'no-throw-literal': 'error',
		'no-unmodified-loop-condition': 'error',
		'no-unused-expressions': 'error',
		'no-unused-labels': 'error',
		'no-useless-call': 'error',
		'no-useless-concat': 'error',
		'no-useless-escape': 'error',
		'no-useless-return': 'error',
		'no-void': 'error',
		'no-warning-comments': 'warn',
		'no-with': 'error',
		'prefer-promise-reject-errors': ['error', {allowEmptyReject: true}],
		radix: 'error',
		'require-unicode-regexp': 'error',
		'wrap-iife': ['error', 'inside', {functionPrototypeMethods: true}],
		yoda: 'error',
		'no-delete-var': 'error',
		'no-label-var': 'error',
		'no-restricted-globals': ['error', 'event'],
		'no-shadow-restricted-names': 'error',
		'no-undef-init': 'error',
		'no-undef': ['error', {
			typeof: true
		}],
		'no-unused-vars': ['error', {
			ignoreRestSiblings: true,
			argsIgnorePattern: '^_$'
		}],
		'no-use-before-define': ['error', 'nofunc'],
		// Disabled because of https://github.com/eslint/eslint/issues/3420
		// 'callback-return': ['warn', ['cb', 'callback', 'next', 'done']],
		'handle-callback-err': 'warn',
		'no-buffer-constructor': 'error',
		'no-mixed-requires': ['error', {
			grouping: true,
			allowCall: true
		}],
		'no-new-require': 'error',
		'no-path-concat': 'error',
		'no-restricted-imports': ['error', 'domain', 'freelist', 'smalloc', 'sys', 'colors'],
		'no-restricted-modules': ['error', 'domain', 'freelist', 'smalloc', 'sys', 'colors'],
		'array-bracket-newline': ['error', 'consistent'],
		'array-bracket-spacing': ['error', 'never'],
		'array-element-newline': ['error', 'consistent'],
		'brace-style': ['error', '1tbs', {
			allowSingleLine: false
		}],
		camelcase: ['error', {
			properties: 'always'
		}],
		'capitalized-comments': ['error', 'always', {
			// You can also ignore this rule by wrapping the first word in quotes
			ignorePattern: 'pragma|ignore|prettier-ignore',
			ignoreInlineComments: true,
			ignoreConsecutiveComments: true
		}],
		'comma-spacing': ['error', {
			before: false,
			after: true
		}],
		'comma-style': ['error', 'last'],
		'computed-property-spacing': ['error', 'never'],
		'eol-last': 'error',
		'func-call-spacing': ['error', 'never'],
		'func-name-matching': ['error', {considerPropertyDescriptor: true}],
		'func-names': ['error', 'never'],
		indent: ['error', 'tab', {
			SwitchCase: 1
		}],
		'jsx-quotes': 'error',
		'key-spacing': ['error', {
			beforeColon: false,
			afterColon: true
		}],
		'keyword-spacing': 'error',
		'linebreak-style': [(process.platform === 'win32' ? 'off' : 'error'), 'unix'],
		'lines-between-class-members': ['error', 'always'],
		'max-depth': 'warn',
		'max-nested-callbacks': ['warn', 4],
		'max-params': ['warn', {
			max: 4
		}],
		'max-statements-per-line': 'error',
		'new-cap': ['error', {
			newIsCap: true,
			capIsNew: true
		}],
		'new-parens': 'error',
		'no-array-constructor': 'error',
		'no-lonely-if': 'error',
		'no-mixed-operators': 'error',
		'no-mixed-spaces-and-tabs': 'error',
		'no-multi-assign': 'error',
		'no-multiple-empty-lines': ['error', {
			max: 1
		}],
		'no-negated-condition': 'error',
		'no-new-object': 'error',
		'no-restricted-syntax': ['error', 'WithStatement'],
		'no-whitespace-before-property': 'error',
		'no-trailing-spaces': 'error',
		'no-unneeded-ternary': 'error',
		'object-curly-spacing': ['error', 'never'],
		// Disabled because of https://github.com/xojs/eslint-config-xo/issues/27
		// 'object-property-newline': 'error',
		'one-var': ['error', 'never'],
		'one-var-declaration-per-line': 'error',
		'operator-assignment': ['error', 'always'],
		'operator-linebreak': ['error', 'after'],
		'padded-blocks': ['error', 'never'],
		'quote-props': ['error', 'as-needed'],
		quotes: ['error', 'single', {
			allowTemplateLiterals: true
		}],
		'semi-spacing': ['error', {
			before: false,
			after: true
		}],
		'semi-style': ['error', 'last'],
		semi: ['error', 'always'],
		'space-before-blocks': ['error', 'always'],
		'space-before-function-paren': ['error', {
			anonymous: 'always',
			named: 'never',
			asyncArrow: 'always'
		}],
		'space-in-parens': ['error', 'never'],
		'space-infix-ops': 'error',
		'space-unary-ops': 'error',
		'spaced-comment': ['error', 'always', {
			line: {
				exceptions: ['-', '+', '*'],
				markers: ['!', '/']
			},
			block: {
				exceptions: ['-', '+', '*'],
				markers: ['!', '*'],
				balanced: true
			}
		}],
		'switch-colon-spacing': ['error', {
			after: true,
			before: false
		}],
		'template-tag-spacing': ['error', 'never'],
		'unicode-bom': ['error', 'never'],
		'arrow-parens': ['error', 'as-needed'],
		'arrow-spacing': ['error', {
			before: true,
			after: true
		}],
		'constructor-super': 'error',
		'generator-star-spacing': ['error', 'both'],
		'no-class-assign': 'error',
		'no-const-assign': 'error',
		'no-dupe-class-members': 'error',
		'no-new-symbol': 'error',
		'no-this-before-super': 'error',
		'no-useless-computed-key': 'error',
		'no-useless-constructor': 'error',
		'no-useless-rename': 'error',
		'require-yield': 'error',
		'rest-spread-spacing': ['error', 'never'],
		'symbol-description': 'error',
		'template-curly-spacing': 'error',
		'yield-star-spacing': ['error', 'both'],
		'valid-jsdoc': ['warn', {
			'requireReturn': false,
			'requireParamDescription': true,
			'requireReturnDescription': true
		}]
	}
};
<|endoftext|>


<commit_before>import {isArray} from '@grid/core/utility';

export class Json {
	read(data) {
		const rows = JSON.parse(data);
		if (isArray(rows)) {
			for (let i = 0; i < rows.length; i++) {
				rows[i].rowNum = i;
			}
			return rows;

		}
		return [];
	}
}<commit_msg>get rid of rowNum default column in JSON import<commit_after>import {isArray} from '@grid/core/utility';

export class Json {
	read(data) {
		const rows = JSON.parse(data);
		if (isArray(rows)) {
			return rows;
		}
		return [];
	}
}<|endoftext|>


<commit_before>'use strict'

var Transform = require('stream').Transform
var File = require('vinyl')
var PluginError = require('plugin-error')
var rollup = require('rollup')
var path = require('path')
var applySourceMap = require('vinyl-sourcemaps-apply')
var camelCase = require('lodash.camelcase')

var PLUGIN_NAME = 'gulp-better-rollup'

// map object storing rollup cache objects for each input file
var rollupCache = new Map

function parseBundles(arg) {
	if (typeof arg == 'string')
		return [{format: arg}]
	if (arg instanceof Array)
		return arg
	return [arg]
}

// transformer class
class GulpRollup extends Transform {

	_transform(file, encoding, cb) {
		// cannot handle empty or unavailable files
		if (file.isNull())
			return cb(null, file)

		// cannot handle streams
		if (file.isStream())
			return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported'))

		if (this.arg2) {
			var inputOptions = Object.assign({}, this.arg1)
			var bundleList = parseBundles(this.arg2)
		} else {
			var inputOptions = {}
			var bundleList = parseBundles(this.arg1)
		}

		// user should not specify the input file path, but let him if he insists for some reason
		if (inputOptions.input === undefined)
			// determine input from file filename
			inputOptions.input = path.relative(file.cwd, file.path)
		else
			// rename file if input is given
			file.path = path.join(file.cwd, inputOptions.input)

		// caching is enabled by default because of the nature of gulp and the watching/recompilatin
		// but can be disabled by setting 'cache' to false
		if (inputOptions.cache !== false)
			inputOptions.cache = rollupCache.get(inputOptions.input)

		// enable sourcemap is gulp-sourcemaps plugin is enabled
		var createSourceMap = file.sourceMap !== undefined

		var originalCwd = file.cwd
		var originalPath = file.path
		var moduleName = camelCase(path.basename(file.path, path.extname(file.path)))

		function generateAndApplyBundle(bundle, outputOptions, targetFile) {
			// Sugaring the API by copying convinience objects and properties from inputOptions
			// to outputOptions (if not defined)
			if (outputOptions.file === undefined)
				outputOptions.file = inputOptions.file
			if (outputOptions['exports'] === undefined)
				outputOptions['exports'] = inputOptions['exports']
			if (outputOptions.format ===  undefined)
				outputOptions.format = inputOptions.format
			if (outputOptions.globals ===  undefined)
				outputOptions.globals = inputOptions.globals
			// Rollup won't bundle iife and umd modules without module name.
			// But it won't say anything either, leaving a space for confusion
			if (outputOptions.name === undefined)
				outputOptions.name = inputOptions.name || moduleName
			if (outputOptions.amd === undefined || outputOptions.amd.id === undefined)
				outputOptions.amd = Object.assign({}, outputOptions.amd, {id: outputOptions.name})
			outputOptions.sourcemap = createSourceMap
			// generate bundle according to given or autocompleted options
			return bundle.generate(outputOptions).then(result => {
				// Pass sourcemap content and metadata to gulp-sourcemaps plugin to handle
				// destination (and custom name) was given, possibly multiple output bundles.
				if (createSourceMap) {
					result.map.file = path.relative(originalCwd, originalPath)
					result.map.sources = result.map.sources.map(source => path.relative(originalCwd, source))
				}
				// return bundled file as buffer
				targetFile.contents = new Buffer(result.code)
				// apply sourcemap to output file
				if (createSourceMap)
					applySourceMap(targetFile, result.map)
			})
		}
		var createBundle = (bundle, outputOptions, injectNewFile) => {
			// custom output name might be set
			if (outputOptions.file) {
				// setup filename name from outputOptions.file
				var newFileName = path.basename(outputOptions.file)
				var newFilePath = path.join(file.base, newFileName)
				if (injectNewFile) {
					// create new file and inject it into stream if needed (in case of multiple outputs)
					var newFile = new File({
						cwd: file.cwd,
						base: file.base,
						path: newFilePath,
						stat: {
							isFile: () => true,
							isDirectory: () => false,
							isBlockDevice: () => false,
							isCharacterDevice: () => false,
							isSymbolicLink: () => false,
							isFIFO: () => false,
							isSocket: () => false
						}
					})
					return generateAndApplyBundle(bundle, outputOptions, newFile).then(result => {
						this.push(newFile)
						return result
					})
				} else {
					// rename original file
					file.path = newFilePath
					return generateAndApplyBundle(bundle, outputOptions, file)
				}
			} else {
				// file wasnt renamed nor new one was created,
				// apply data and sourcemaps to the original file
				return generateAndApplyBundle(bundle, outputOptions, file)
			}
		}

		// custom rollup can be provided inside the config object
		rollup = inputOptions.rollup || rollup
		delete inputOptions.rollup
		rollup
			// pass basic options to rollup
			.rollup(inputOptions)
			// after the magic is done, configure the output format
			.then(bundle => {
				// cache rollup object if caching is enabled
				if (inputOptions.cache !== false)
					rollupCache.set(inputOptions.input, bundle)
				// generate ouput according to (each of) given outputOptions
				return Promise.all(bundleList.map((outputOptions, i) => createBundle(bundle, outputOptions, i)))
			})
			// pass file to gulp and end stream
			.then(() => cb(null, file))
			.catch(err => {
				if (inputOptions.cache !== false)
					rollupCache.delete(inputOptions.input)
				process.nextTick(() => {
					this.emit('error', new PluginError(PLUGIN_NAME, err))
					cb(null, file)
				})
			})

	}

}

// first argument (inputOptions) is optional
module.exports = function factory(arg1, arg2) {
	// instantiate the stream class
	var stream = new GulpRollup({objectMode: true})
	// pass in options objects
	stream.arg1 = arg1
	stream.arg2 = arg2
	// return the stream instance
	return stream
}
<commit_msg>better options object desugaring<commit_after>'use strict'

var Transform = require('stream').Transform
var File = require('vinyl')
var PluginError = require('plugin-error')
var rollup = require('rollup')
var path = require('path')
var applySourceMap = require('vinyl-sourcemaps-apply')
var camelCase = require('lodash.camelcase')

var PLUGIN_NAME = 'gulp-better-rollup'

// map object storing rollup cache objects for each input file
var rollupCache = new Map

function parseBundles(arg) {
	if (typeof arg == 'string')
		return [{format: arg}]
	if (arg instanceof Array)
		return arg
	return [arg]
}

function assignCertainProperties(toObject, fromObject, properties = []) {
	for (var key of properties) {
		if (toObject[key] === undefined && fromObject[key] !== undefined)
			toObject[key] = fromObject[key]
	}
}

// transformer class
class GulpRollup extends Transform {

	_transform(file, encoding, cb) {
		// cannot handle empty or unavailable files
		if (file.isNull())
			return cb(null, file)

		// cannot handle streams
		if (file.isStream())
			return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported'))

		if (this.arg2) {
			var inputOptions = Object.assign({}, this.arg1)
			var bundleList = parseBundles(this.arg2)
		} else {
			var inputOptions = {}
			var bundleList = parseBundles(this.arg1)
		}

		// user should not specify the input file path, but let him if he insists for some reason
		if (inputOptions.input === undefined)
			// determine input from file filename
			inputOptions.input = path.relative(file.cwd, file.path)
		else
			// rename file if input is given
			file.path = path.join(file.cwd, inputOptions.input)

		// caching is enabled by default because of the nature of gulp and the watching/recompilatin
		// but can be disabled by setting 'cache' to false
		if (inputOptions.cache !== false)
			inputOptions.cache = rollupCache.get(inputOptions.input)

		// enable sourcemap is gulp-sourcemaps plugin is enabled
		var createSourceMap = file.sourceMap !== undefined

		var originalCwd = file.cwd
		var originalPath = file.path
		var moduleName = camelCase(path.basename(file.path, path.extname(file.path)))

		function generateAndApplyBundle(bundle, outputOptions, targetFile) {
			// Sugaring the API by copying convinience objects and properties from inputOptions
			// to outputOptions (if not defined)
			// Directly copied from https://rollupjs.org/guide/en#outputoptions
			var propsToCopy = [
				// core options
				'format', 'file', 'dir', /*'name'*/, 'globals',
				// advanced options
				'paths', 'banner', 'footer', 'intro', 'outro', 'sourcemap', 'sourcemapFile', 'interop', 'extend',
				// danger zone
				'exports', /*'amd',*/ 'indent', 'strict', 'freeze', 'legacy', 'namespaceToStringTag',
			]
			assignCertainProperties(outputOptions, inputOptions, propsToCopy)
			// Rollup won't bundle iife and umd modules without module name.
			// But it won't say anything either, leaving a space for confusion
			if (outputOptions.name === undefined)
				outputOptions.name = inputOptions.name || moduleName
			if (outputOptions.amd === undefined || outputOptions.amd.id === undefined)
				outputOptions.amd = Object.assign({}, outputOptions.amd, {id: outputOptions.name})
			outputOptions.sourcemap = createSourceMap
			// generate bundle according to given or autocompleted options
			return bundle.generate(outputOptions).then(result => {
				if (result === undefined) return
				// Pass sourcemap content and metadata to gulp-sourcemaps plugin to handle
				// destination (and custom name) was given, possibly multiple output bundles.
				if (createSourceMap) {
					result.map.file = path.relative(originalCwd, originalPath)
					result.map.sources = result.map.sources.map(source => path.relative(originalCwd, source))
				}
				// return bundled file as buffer
				targetFile.contents = Buffer.from(result.code)
				// apply sourcemap to output file
				if (createSourceMap)
					applySourceMap(targetFile, result.map)
			})
		}
		var createBundle = (bundle, outputOptions, injectNewFile) => {
			// custom output name might be set
			if (outputOptions.file) {
				// setup filename name from outputOptions.file
				var newFileName = path.basename(outputOptions.file)
				var newFilePath = path.join(file.base, newFileName)
				if (injectNewFile) {
					// create new file and inject it into stream if needed (in case of multiple outputs)
					var newFile = new File({
						cwd: file.cwd,
						base: file.base,
						path: newFilePath,
						stat: {
							isFile: () => true,
							isDirectory: () => false,
							isBlockDevice: () => false,
							isCharacterDevice: () => false,
							isSymbolicLink: () => false,
							isFIFO: () => false,
							isSocket: () => false
						}
					})
					return generateAndApplyBundle(bundle, outputOptions, newFile).then(result => {
						this.push(newFile)
						return result
					})
				} else {
					// rename original file
					file.path = newFilePath
					return generateAndApplyBundle(bundle, outputOptions, file)
				}
			} else {
				// file wasnt renamed nor new one was created,
				// apply data and sourcemaps to the original file
				return generateAndApplyBundle(bundle, outputOptions, file)
			}
		}

		// custom rollup can be provided inside the config object
		rollup = inputOptions.rollup || rollup
		delete inputOptions.rollup
		rollup
			// pass basic options to rollup
			.rollup(inputOptions)
			// after the magic is done, configure the output format
			.then(bundle => {
				// cache rollup object if caching is enabled
				if (inputOptions.cache !== false)
					rollupCache.set(inputOptions.input, bundle)
				// generate ouput according to (each of) given outputOptions
				return Promise.all(bundleList.map((outputOptions, i) => createBundle(bundle, outputOptions, i)))
			})
			// pass file to gulp and end stream
			.then(() => cb(null, file))
			.catch(err => {
				if (inputOptions.cache !== false)
					rollupCache.delete(inputOptions.input)
				process.nextTick(() => {
					this.emit('error', new PluginError(PLUGIN_NAME, err))
					cb(null, file)
				})
			})

	}

}

// first argument (inputOptions) is optional
module.exports = function factory(arg1, arg2) {
	// instantiate the stream class
	var stream = new GulpRollup({objectMode: true})
	// pass in options objects
	stream.arg1 = arg1
	stream.arg2 = arg2
	// return the stream instance
	return stream
}
<|endoftext|>


<commit_before>"use strict";

console.log('in guzzle');

var browserify = require('gulp-browserify'),
  ecstatic = require('ecstatic'),
  http = require('http'),
  ltld = require('local-tld-lib'),
  fs = require('fs');

module.exports = function(gulp, dir){
  dir = dir || process.cwd();
  var data = fs.readFileSync( + '/package.json', 'utf-8');
  var pkg = JSON.parse(data),
    type = pkg.guzzle || 'gulp plugin';
  pkg.dir = dir;

  return gulps[type](pkg, gulp);
};

// Different types of project templates
var gulps = {
  ui: function(pkg, gulp){
    var name = pkg.name,
      dest = pkg.dir + './.' + name,
      src = pkg.dir + './',
      files = [src + '/{img,fonts,css,json,csv}/*', src + '/*.html'];

    gulp.task('js', function(){
      gulp.src(src + '/*.js')
        .pipe(browserify({debug : false}))
        .pipe(gulp.dest(dest));
    });

    gulp.task('watch', function (){
      gulp.watch(['!' + src + '/node_modules/**', src + '/{*,**/*}.{js}'], ['js']);
      gulp.watch(files, ['cp']);
    });

    gulp.task('cp', function(){
      gulp.src(files).pipe(gulp.dest(dest));
    });

    gulp.task('serve', function(){
      http.createServer(ecstatic({root: dest}))
        .listen(ltld.getPort(name));
      console.log('-> http://' + name + '.dev/');
    });

    gulp.task('build', ['js', 'cp']);
    gulp.task('dev', ['build', 'serve', 'watch']);
  },
  'gulp plugin': function (pkg, gulp){
    gulp.task('default', function(){
      console.log('@todo');
    });
  },
  cli: function(pkg, gulp){
    gulp.task('default', function(){
      console.log('@todo');
    });
  },
  rest: function(pkg, gulp){
    gulp.task('default', function(){
      console.log('@todo');
    });
  }
};
<commit_msg>oh rad.  can take no glob here<commit_after>"use strict";

console.log('in guzzle');

var browserify = require('gulp-browserify'),
  ecstatic = require('ecstatic'),
  http = require('http'),
  ltld = require('local-tld-lib'),
  fs = require('fs');

module.exports = function(gulp, dir){
  dir = dir || process.cwd();
  var data = fs.readFileSync(dir + '/package.json', 'utf-8');
  var pkg = JSON.parse(data),
    type = pkg.guzzle || 'gulp plugin';
  pkg.dir = dir;

  return gulps[type](pkg, gulp);
};

// Different types of project templates
var gulps = {
  ui: function(pkg, gulp){
    var name = pkg.name,
      dest = pkg.dir + '/.' + name,
      src = pkg.dir + '/',
      files = [src + '/{img,fonts,css,json,csv}/*', src + '/*.html'];

    gulp.task('js', function(){
      gulp.src(src + '/index.js')
        .pipe(browserify({debug : false}))
        .pipe(gulp.dest(dest));
    });

    gulp.task('watch', function (){
      gulp.watch(['!' + src + '/node_modules/**', src + '/{*,**/*}.{js}'], ['js']);
      gulp.watch(files, ['cp']);
    });

    gulp.task('cp', function(){
      gulp.src(files).pipe(gulp.dest(dest));
    });

    gulp.task('serve', function(){
      http.createServer(ecstatic({root: dest}))
        .listen(ltld.getPort(name));
      console.log('-> http://' + name + '.dev/', dest, 'port -> ', ltld.getPort(name));
    });

    gulp.task('build', ['js', 'cp']);
    gulp.task('dev', ['build', 'serve', 'watch']);
  },
  'gulp plugin': function (pkg, gulp){
    gulp.task('default', function(){
      console.log('@todo');
    });
  },
  cli: function(pkg, gulp){
    gulp.task('default', function(){
      console.log('@todo');
    });
  },
  rest: function(pkg, gulp){
    gulp.task('default', function(){
      console.log('@todo');
    });
  }
};
<|endoftext|>


<commit_before>var WaterlineDiscovery = require('waterline-discovery-doc-import');
var SailsBackbone = require('sails-backbone');
var Waterline = require('waterline');
var Promise = require('bluebird');
var _ = require('lodash');

/**
 * Generate a Backbone Relational API from a Google Discovery Document
 *
 * @param doc
 * @param [config] - optional waterline config object
 */
exports.generate = function (doc, config) {
  config  = config || { };
  var waterline = new Waterline();
  _.defaults(config, {
      adapters: {
        memory: require('sails-memory')
      },
      connections: {
        sailsDiscovery: {
          adapter: 'memory'
        }
      }
    });
  var collections = WaterlineDiscovery.createCollections(doc);

  return new Promise(function (resolve, reject) {
    _.each(collections, waterline.loadCollection, waterline);
    waterline.initialize(config, function (error, orm) {
      if (error) {
        // resolves issue #2; if connection is already registered, then use that
        // ORM which has already been initialized.
        if (error.name === 'AdapterError' && error.message === 'Connection is already registered') {
          orm = waterline;
        }
        else {
          return reject(error);
        }
      }

      var sails = createSailsObject(doc, orm.collections);
      return resolve(SailsBackbone.generate(sails));
    });
  });
};

/**
 * Manufacture a partially-hydrated sails object for sails-backbone
 */
function createSailsObject (doc, collections) {
  return {
    models: collections,
    config: {
      blueprints: {
        prefix: doc.servicePath
      }
    }
  };
}
<commit_msg>update service path prefix<commit_after>var WaterlineDiscovery = require('waterline-discovery-doc-import');
var SailsBackbone = require('sails-backbone');
var Waterline = require('waterline');
var Promise = require('bluebird');
var _ = require('lodash');

/**
 * Generate a Backbone Relational API from a Google Discovery Document
 *
 * @param doc
 * @param [config] - optional waterline config object
 */
exports.generate = function (doc, config) {
  config  = config || { };
  var waterline = new Waterline();
  _.defaults(config, {
      adapters: {
        memory: require('sails-memory')
      },
      connections: {
        sailsDiscovery: {
          adapter: 'memory'
        }
      }
    });
  var collections = WaterlineDiscovery.createCollections(doc);

  return new Promise(function (resolve, reject) {
    _.each(collections, waterline.loadCollection, waterline);
    waterline.initialize(config, function (error, orm) {
      if (error) {
        // resolves issue #2; if connection is already registered, then use that
        // ORM which has already been initialized.
        if (error.name === 'AdapterError' && error.message === 'Connection is already registered') {
          orm = waterline;
        }
        else {
          return reject(error);
        }
      }

      var sails = createSailsObject(doc, orm.collections);
      return resolve(SailsBackbone.generate(sails));
    });
  });
};

/**
 * Manufacture a partially-hydrated sails object for sails-backbone
 */
function createSailsObject (doc, collections) {
  return {
    models: collections,
    config: {
      blueprints: {
        prefix: doc.servicePath + '/resources'
      }
    }
  };
}
<|endoftext|>


<commit_before>var server = require('http').createServer()
var wr = require('./water_rower.js')({ debug: false} );
var ws = require('ws');
var url = require('url')
var WebSocketServer = ws.Server
var wsServer = new WebSocketServer({ server: server });

var parseArgs = require('minimist');
var argv = parseArgs( process.argv , {
  number: [ 'port' ],
  string: [ 'comport' ],
  boolean: [ 'debug']
});

var port = argv.port || 'NULL';
var debug = argv.debug || false;
var comport = argv.comport;

var rower = new wr.WaterRower({ port: comport });

var express = require('express');
var app = express();
app.get('/', express.static(__dirname+'/public') );

rower.on('readings', function _broadcastReadings( msg ) {
  wsServer.clients.forEach( function(client) {
    client.send( JSON.stringify(msg), function(err) {
      console.log(err.toString());
    });
  });
});

wsServer.on('connection', function connection(sock) {
  var location = url.parse(sock.upgradeReq.url, true);

  sock.on('disconnect', function _accounceDisconnect(){
    console.log("Socket disconnect.");
  });

  console.log("Socket connect.");
});

console.log('Starting water rower.');
server.on('request', app);
server.listen(port, function () {
  console.log('Listening on ' + server.address().port)
});
<commit_msg>Fix dumb case where errors didn't exist in the send callback.<commit_after>var server = require('http').createServer()
var wr = require('./water_rower.js')({ debug: false} );
var ws = require('ws');
var url = require('url')
var WebSocketServer = ws.Server
var wsServer = new WebSocketServer({ server: server });

var parseArgs = require('minimist');
var argv = parseArgs( process.argv , {
  number: [ 'port' ],
  string: [ 'comport' ],
  boolean: [ 'debug']
});

var port = argv.port || 'NULL';
var debug = argv.debug || false;
var comport = argv.comport;

var rower = new wr.WaterRower({ port: comport });

var express = require('express');
var app = express();
app.get('/', express.static(__dirname+'/public') );

rower.on('readings', function _broadcastReadings( msg ) {
  wsServer.clients.forEach( function(client) {
    client.send( JSON.stringify(msg), function(err) {
      if (err) {
        console.log(err.toString());
      }
    });
  });
});

wsServer.on('connection', function connection(sock) {
  var location = url.parse(sock.upgradeReq.url, true);

  sock.on('disconnect', function _accounceDisconnect(){
    console.log("Socket disconnect.");
  });

  console.log("Socket connect.");
});

console.log('Starting water rower.');
server.on('request', app);
server.listen(port, function () {
  console.log('Listening on ' + server.address().port)
});
<|endoftext|>


<commit_before>var optimizer = require("bindings")("swtor_tanking_optimizer.node")
  , classData = {
      'shadow': {
        defenseAdd: 0.06 //in tree
      , defenseBonus: 0.05 //force breach debuff
      , shieldAdd: 0.15 //combat technique
      ,	shieldBonus: 0.20 //kinetic ward w/ 2-piece
      ,	absorbAdd: 0.04 //in tree
      ,	absorbBonus: 0.036 //average value from kinetic ward
      ,	drAddKE: 0.04 //in tree w/ 4-piece
      ,	drAddIE: 0.13 //in tree w/ 4-piece
      ,	drBonus: 0.05 //slow time
      ,	resistPct: 0.02
      }
    , 'guardian': {
        defenseAdd: 0.03 //single saber mastery
      , defenseBonus: 0.10 //5% riposte, 5% dust storm
      , shieldAdd: 0.19 //15% soresu form, 4% in tree
      ,	shieldBonus: 0.0 //correct
      ,	absorbAdd: 0.0 //correct
      ,	absorbBonus: 0.0 //correct
      ,	drAddKE: 0.06 //soresu form
      ,	drAddIE: 0.11 //enure talent and soresu form
      ,	drBonus: 0.03 //guardian slash
      ,	resistPct: 0.00 // really?
      }
    , 'vanguard': {
        defenseAdd: 0.06 //4% in tree, 2% from 4-piece
      , defenseBonus: 0.075 //riot gas debuff
      , shieldAdd: 0.17 //ion cell and 2% in tree
      ,	shieldBonus: 0.0 //none
      ,	absorbAdd: 0.04 //in tree
      ,	absorbBonus: 0.15 //ability proc in tree
      ,	drAddKE: 0.02 //in tree
      ,	drAddIE: 0.02 //in tree
      ,	drBonus: 0.05 //static field
      ,	resistPct: 0.02
      }
    }
  //The following data is from http://www.swtor.com/community/showthread.php?t=616779
  , otherData = {
      dmgKE: 0.790044607 //defendable damage percent
    , dmgIE: 0.209955393 //resistable damage percent
    , shieldLow: 0.364663353 //lower bound on shield as a percent of budget, based on arkanian
    , shieldHigh: 0.658429434 //upper bound on shield as a percent of budget, based on arkanian
    }
  ;

module.exports = {
  optimize: function (klass, statBudget, armor, callback){
    optimizer.optimize(otherData, classData[klass], statBudget, armor, 70, callback);
  }
, optimizer: optimizer
, classData: classData
, otherData: otherData
};
<commit_msg>Fixing some shadow magic numbers<commit_after>var optimizer = require("bindings")("swtor_tanking_optimizer.node")
  , classData = {
      'shadow': {
        defenseAdd: 0.11 // 6% in tree, 5% naturally higher base %
      , defenseBonus: 0.05 //force breach debuff
      , shieldAdd: 0.15 //combat technique
      ,	shieldBonus: 0.20 //kinetic ward w/ 2-piece
      ,	absorbAdd: 0.04 //in tree
      ,	absorbBonus: 0.036 //average value from kinetic ward
      ,	drAddKE: 0.04 //in tree w/ 4-piece
      ,	drAddIE: 0.13 //in tree w/ 4-piece
      ,	drBonus: 0.05 //slow time
      ,	resistPct: 0.02
      }
    , 'guardian': {
        defenseAdd: 0.03 //single saber mastery
      , defenseBonus: 0.10 //5% riposte, 5% dust storm
      , shieldAdd: 0.19 //15% soresu form, 4% in tree
      ,	shieldBonus: 0.0 //correct
      ,	absorbAdd: 0.0 //correct
      ,	absorbBonus: 0.0 //correct
      ,	drAddKE: 0.06 //soresu form
      ,	drAddIE: 0.11 //enure talent and soresu form
      ,	drBonus: 0.03 //guardian slash
      ,	resistPct: 0.00 // really?
      }
    , 'vanguard': {
        defenseAdd: 0.06 //4% in tree, 2% from 4-piece
      , defenseBonus: 0.075 //riot gas debuff
      , shieldAdd: 0.17 //ion cell and 2% in tree
      ,	shieldBonus: 0.0 //none
      ,	absorbAdd: 0.04 //in tree
      ,	absorbBonus: 0.15 //ability proc in tree
      ,	drAddKE: 0.02 //in tree
      ,	drAddIE: 0.02 //in tree
      ,	drBonus: 0.05 //static field
      ,	resistPct: 0.02
      }
    }
  //The following data is from http://www.swtor.com/community/showthread.php?t=616779
  , otherData = {
      dmgKE: 0.790044607 //defendable damage percent
    , dmgIE: 0.209955393 //resistable damage percent
    , shieldLow: 0.364663353 //lower bound on shield as a percent of budget, based on arkanian
    , shieldHigh: 0.658429434 //upper bound on shield as a percent of budget, based on arkanian
    }
  ;

module.exports = {
  optimize: function (klass, statBudget, armor, callback){
    optimizer.optimize(otherData, classData[klass], statBudget, armor, 70, callback);
  }
, optimizer: optimizer
, classData: classData
, otherData: otherData
};
<|endoftext|>


<commit_before>var RecursiveIterator = require('recursive-iterator');

function IncludeDataExtension(env) {
    this.tags = ['includeData'];
    this.keywords = {
        as: 'as',
        clean: 'clean',
        file: 'file',
        data: 'data',
        namespace: 'namespace',
        injectToRoot_as_: '__injectToRoot_as_',
        injectToHere_as_: '__injectToHere_as_'
    };

    this.parse = function(parser, nodes, lexer) {
        var tok = parser.nextToken();
        var args = new nodes.NodeList(tok.lineno, tok.colno);
        var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno);
        var argArray = new nodes.Array(tok.lineno, tok.colno);
        while(1) {
            var nextTok = parser.peekToken();
            if(nextTok.type === lexer.TOKEN_BLOCK_END) {
                if(!argArray.children.length) {
                    parser.fail('parseIncludeData: Expected at least one importData name',
                        tok.lineno,
                        tok.colno);
                }

                parser.nextToken();
                break;
            }
            if(argArray.children.length > 0 && !parser.skip(lexer.TOKEN_COMMA)) {
                parser.fail('parseIncludeData: expected comma',
                    tok.lineno,
                    tok.colno);
            }
            var template = parser.parseExpression();
            var aliasName = (parser.skipSymbol(this.keywords.as)) ? parser.parsePrimary().value : '';
            var clean = parser.skipSymbol(this.keywords.clean);
            var dict = new nodes.Dict(template.lineno, template.colno);
            dict.addChild(new nodes.Pair(template.lineno,
                                          template.colno,
                                          new nodes.Literal(template.lineno, template.colno, this.keywords.clean),
                                          new nodes.Literal(template.lineno, template.colno, clean)));
            dict.addChild(new nodes.Pair(template.lineno,
                                          template.colno,
                                          new nodes.Literal(template.lineno, template.colno, this.keywords.file),
                                          template));
            dict.addChild(new nodes.Pair(template.lineno,
                                          template.colno,
                                          new nodes.Literal(template.lineno, template.colno, this.keywords.namespace),
                                          new nodes.Literal(template.lineno, template.colno, aliasName)));
            argArray.addChild(dict);
        }
        kwargs.addChild(new nodes.Pair(template.lineno,
                                      template.colno,
                                      new nodes.Literal(template.lineno, template.colno, this.keywords.data),
                                      argArray));
        args.addChild(kwargs);
        return new nodes.CallExtension(this, 'run', args);
    };

    this.run = function(context, args) {
        for (var i = 0; i < args.data.length; i++) {
            var data = args.data[i];
            var jsonData = this.readFile(data.file, context.ctx);
            this.addData(context.ctx, jsonData, data.namespace, data.clean);
            console.log(JSON.stringify(jsonData, null, 2));
        }
    };

    this.includeJson = function(root, rootCtx) {
        for(let {parent, node, key, path, deep} of new RecursiveIterator(root)) {
            if (key.startsWith(this.keywords.injectToRoot_as_)) {
                var jsonData = this.readFile(node, rootCtx);
                var namespace = key.substring(this.keywords.injectToRoot_as_.length);
                this.addData(rootCtx, jsonData, namespace, true);
            } else if (key.startsWith(this.keywords.injectToHere_as_)) {
                var jsonData = this.readFile(node, rootCtx);
                var namespace = key.substring(this.keywords.injectToHere_as_.length);
                this.addData(parent, jsonData, namespace, true);
            }
        }
        return root;
    };

    this.readFile = function(fileName, rootCtx) {
        try {
            var fileObj = env.loaders[0].getSource(fileName);
            if (fileObj) {
                var jsonData = JSON.parse(fileObj.src);
                jsonData = this.includeJson(jsonData, rootCtx);
                return jsonData;
            } else {
                console.log("error to load: " + fileName);
            }
        } catch (e) {
            console.log(e);
        }
        return null;
    };

    this.addData = function(ctx, jsonData, namespace, clean) {
        if (jsonData) {
            if (namespace && clean) {
                ctx[namespace] = jsonData;
            } else {
                if (namespace) {
                    if (!ctx[namespace]) {
                        ctx[namespace] = {};
                    }
                    ctx = ctx[namespace];
                }
                for (var key in jsonData) {
                    ctx[key] = jsonData[key];
                }
            }
        }
    };

}

module.exports = IncludeDataExtension;

module.exports.install = function(env) {
    env.addExtension('IncludeDataExtension', new IncludeDataExtension(env));
};
<commit_msg>Remove the __injectToRoot_as_ and __injectToHere_as_ after injected<commit_after>var RecursiveIterator = require('recursive-iterator');

function IncludeDataExtension(env) {
    this.tags = ['includeData'];
    this.keywords = {
        as: 'as',
        clean: 'clean',
        file: 'file',
        data: 'data',
        namespace: 'namespace',
        injectToRoot_as_: '__injectToRoot_as_',
        injectToHere_as_: '__injectToHere_as_'
    };

    this.parse = function(parser, nodes, lexer) {
        var tok = parser.nextToken();
        var args = new nodes.NodeList(tok.lineno, tok.colno);
        var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno);
        var argArray = new nodes.Array(tok.lineno, tok.colno);
        while(1) {
            var nextTok = parser.peekToken();
            if(nextTok.type === lexer.TOKEN_BLOCK_END) {
                if(!argArray.children.length) {
                    parser.fail('parseIncludeData: Expected at least one importData name',
                        tok.lineno,
                        tok.colno);
                }

                parser.nextToken();
                break;
            }
            if(argArray.children.length > 0 && !parser.skip(lexer.TOKEN_COMMA)) {
                parser.fail('parseIncludeData: expected comma',
                    tok.lineno,
                    tok.colno);
            }
            var template = parser.parseExpression();
            var aliasName = (parser.skipSymbol(this.keywords.as)) ? parser.parsePrimary().value : '';
            var clean = parser.skipSymbol(this.keywords.clean);
            var dict = new nodes.Dict(template.lineno, template.colno);
            dict.addChild(new nodes.Pair(template.lineno,
                                          template.colno,
                                          new nodes.Literal(template.lineno, template.colno, this.keywords.clean),
                                          new nodes.Literal(template.lineno, template.colno, clean)));
            dict.addChild(new nodes.Pair(template.lineno,
                                          template.colno,
                                          new nodes.Literal(template.lineno, template.colno, this.keywords.file),
                                          template));
            dict.addChild(new nodes.Pair(template.lineno,
                                          template.colno,
                                          new nodes.Literal(template.lineno, template.colno, this.keywords.namespace),
                                          new nodes.Literal(template.lineno, template.colno, aliasName)));
            argArray.addChild(dict);
        }
        kwargs.addChild(new nodes.Pair(template.lineno,
                                      template.colno,
                                      new nodes.Literal(template.lineno, template.colno, this.keywords.data),
                                      argArray));
        args.addChild(kwargs);
        return new nodes.CallExtension(this, 'run', args);
    };

    this.run = function(context, args) {
        for (var i = 0; i < args.data.length; i++) {
            var data = args.data[i];
            var jsonData = this.readFile(data.file, context.ctx);
            this.addData(context.ctx, jsonData, data.namespace, data.clean);
            console.log(JSON.stringify(jsonData, null, 2));
        }
    };

    this.includeJson = function(root, rootCtx) {
        for(let {parent, node, key, path, deep} of new RecursiveIterator(root)) {
            if (key.startsWith(this.keywords.injectToRoot_as_)) {
                delete parent[key];
                var jsonData = this.readFile(node, rootCtx);
                var namespace = key.substring(this.keywords.injectToRoot_as_.length);
                this.addData(rootCtx, jsonData, namespace, true);
            } else if (key.startsWith(this.keywords.injectToHere_as_)) {
                delete parent[key];
                var jsonData = this.readFile(node, rootCtx);
                var namespace = key.substring(this.keywords.injectToHere_as_.length);
                this.addData(parent, jsonData, namespace, true);
            }
        }
        return root;
    };

    this.readFile = function(fileName, rootCtx) {
        try {
            var fileObj = env.loaders[0].getSource(fileName);
            if (fileObj) {
                var jsonData = JSON.parse(fileObj.src);
                jsonData = this.includeJson(jsonData, rootCtx);
                return jsonData;
            } else {
                console.log("error to load: " + fileName);
            }
        } catch (e) {
            console.log(e);
        }
        return null;
    };

    this.addData = function(ctx, jsonData, namespace, clean) {
        if (jsonData) {
            if (namespace && clean) {
                ctx[namespace] = jsonData;
            } else {
                if (namespace) {
                    if (!ctx[namespace]) {
                        ctx[namespace] = {};
                    }
                    ctx = ctx[namespace];
                }
                for (var key in jsonData) {
                    ctx[key] = jsonData[key];
                }
            }
        }
    };

}

module.exports = IncludeDataExtension;

module.exports.install = function(env) {
    env.addExtension('IncludeDataExtension', new IncludeDataExtension(env));
};
<|endoftext|>


<commit_before>var fs = require('fs');

var _ = require('underscore');
var S = require('string');
var Twit = require('twit');
var dump = require('./parser/dump.js');

var config = fs.existsSync('./local.config.js') ? require('./local.config.js') : require('./config.js');

var Twitter = new Twit(config.API);

var dataFile = __dirname + '/nomenclator.json';
var currentIndex = __dirname + '/current.json';

var places = require(dataFile);

var next = fs.existsSync(currentIndex) ? require(currentIndex) : {
    index: 0
};

var greetings = {
    multi: [
        'Un saúdo para {{place}}, na parroquia {{parish}}, concello {{council}}!'
    ],
    councilparish: [
        'Un saúdo para {{place}}, concello {{council}}'

    ],
    single: [
        'Un saúdo para {{place}}'
    ]
};

var prefixer = function(string) {
    'use strict';

    var s = S(string);

    var prefixes = [{
        pre: 'A ',
        rep: 'da '
    }, {
        pre: 'O ',
        rep: 'do '
    }, {
        pre: 'As ',
        rep: 'das '
    }, {
        pre: 'Os ',
        rep: 'dos '
    }];

    for (var i = 0; i < prefixes.length; i++) {
        var pref = prefixes[i];

        if (s.startsWith(pref.pre)) {
            return pref.rep + s.chompLeft(pref.pre);
        }
    }

    return 'de ' + s.s;
};

var tweet = function() {
    'use strict';

    var place = places[next.index];

    var mode = (place.council === place.parish && place.parish === place.place) ? 'single' : (place.council === place.parish || place.parish === place.place) ? 'councilparish' : 'multi';

    var greeting = _.sample(greetings[mode]);

    place.council = prefixer(place.council);
    place.parish = prefixer(place.parish);

    var tweet = S(greeting).template(place).s;

    Twitter.post('statuses/update', {
        status: tweet
    }, function(error, data, response) {
        if (error) {
            throw new Error(error);
        }

        console.log(next.index + ' | ' + tweet);

        next.index++;

        dump(next, currentIndex, function(error) {
            if (error) {
                console.log('Fatal error!');
                process.exit(1);
            }

        });
    });

};

setInterval(function() {
    'use strict';
    try {
        tweet();
    } catch (e) {
        console.log(e);
    }
}, 1000 * 60 * 15);

tweet();
<commit_msg>string consistency<commit_after>var fs = require('fs');

var _ = require('underscore');
var S = require('string');
var Twit = require('twit');
var dump = require('./parser/dump.js');

var config = fs.existsSync('./local.config.js') ? require('./local.config.js') : require('./config.js');

var Twitter = new Twit(config.API);

var dataFile = __dirname + '/nomenclator.json';
var currentIndex = __dirname + '/current.json';

var places = require(dataFile);

var next = fs.existsSync(currentIndex) ? require(currentIndex) : {
    index: 0
};

var greetings = {
    multi: [
        'Un saúdo para {{place}}, na parroquia {{parish}}, concello {{council}}!'
    ],
    councilparish: [
        'Un saúdo para {{place}}, concello {{council}}!'

    ],
    single: [
        'Un saúdo para {{place}}!'
    ]
};

var prefixer = function(string) {
    'use strict';

    var s = S(string);

    var prefixes = [{
        pre: 'A ',
        rep: 'da '
    }, {
        pre: 'O ',
        rep: 'do '
    }, {
        pre: 'As ',
        rep: 'das '
    }, {
        pre: 'Os ',
        rep: 'dos '
    }];

    for (var i = 0; i < prefixes.length; i++) {
        var pref = prefixes[i];

        if (s.startsWith(pref.pre)) {
            return pref.rep + s.chompLeft(pref.pre);
        }
    }

    return 'de ' + s.s;
};

var tweet = function() {
    'use strict';

    var place = places[next.index];

    var mode = (place.council === place.parish && place.parish === place.place) ? 'single' : (place.council === place.parish || place.parish === place.place) ? 'councilparish' : 'multi';

    var greeting = _.sample(greetings[mode]);

    place.council = prefixer(place.council);
    place.parish = prefixer(place.parish);

    var tweet = S(greeting).template(place).s;

    Twitter.post('statuses/update', {
        status: tweet
    }, function(error, data, response) {
        if (error) {
            throw new Error(error);
        }

        console.log(next.index + ' | ' + tweet);

        next.index++;

        dump(next, currentIndex, function(error) {
            if (error) {
                console.log('Fatal error!');
                process.exit(1);
            }

        });
    });

};

setInterval(function() {
    'use strict';
    try {
        tweet();
    } catch (e) {
        console.log(e);
    }
}, 1000 * 60 * 15);

tweet();
<|endoftext|>


<commit_before>var ss = require('simple-statistics')
var explode = require('turf-explode')
var point = require('turf-point')

module.exports = function(features){
  var vertices = explode(features)
  var averageX,
      averageY,
      xs = [],
      ys = []

  vertices.features.forEach(function(v){
    xs.push(v.geometry.coordinates[0])
    ys.push(v.geometry.coordinates[1])
  })

  averageX = ss.mean(xs)
  averageY = ss.mean(ys)

  return point(averageX, averageY)
}<commit_msg>fixed merge<commit_after>var explode = require('turf-explode')
var point = require('turf-point')

module.exports = function(features){
  var vertices = explode(features).features,
    xSum = 0,
    ySum = 0,
    len = vertices.length

  for (var i = 0; i < len; i++) {
    xSum += vertices[i].geometry.coordinates[0]
    ySum += vertices[i].geometry.coordinates[1]
  }

  return point(xSum / len, ySum / len)
}
<|endoftext|>


<commit_before>function MouseCaptor(canvas, graph) {
  var self = this;
  sigma.classes.EventDispatcher.call(this);

  this.canvas = canvas;
  this.graph = graph;

  // MOUSE
  this.mouseX = 0;
  this.mouseY = 0;
  this.oldMouseX = 0;
  this.oldMouseY = 0;

  this.isMouseDown = false;
  this.triggerDrag = false;

  // SCENE
  this.stageX = 0;
  this.stageY = 0;
  this.ratio = 1;

  this.moveHandler = function(event) {
    self.oldMouseX = event.mouseX;
    self.oldMouseY = event.mouseY;

    self.mouseX = event.offsetX;
    self.mouseY = event.offsetY;

    self.isMouseDown && self.drag(event);
  };

  this.upHandler = function(event) {
    self.isMouseDown = false;

    self.stopDrag();
  };

  this.downHandler = function(event) {
    self.isMouseDown = true;
    self.oldMouseX = event.mouseX;
    self.oldMouseY = event.mouseY;

    self.triggerDrag = false;

    self.startDrag();
  };

  this.canvas.onmousemove = this.moveHandler;
  this.canvas.onmousedown = this.downHandler;
  document.onmouseup = this.upHandler;

  this.startDrag = function(event) {
    // TODO
    self.dispatch('startdrag', event);
  };

  this.stopDrag = function(event) {
    // TODO
    self.dispatch('stopdrag', event);
  };

  this.drag = function(event) {
    // TODO
    self.dispatch('drag', event);
  };
}
<commit_msg>improved mouse events capture<commit_after>function MouseCaptor(canvas, graph) {
  var self = this;
  sigma.classes.EventDispatcher.call(this);

  this.canvas = canvas;
  this.graph = graph;

  // MOUSE
  this.mouseX = 0;
  this.mouseY = 0;
  this.oldMouseX = 0;
  this.oldMouseY = 0;
  this.startX = 0;
  this.startY = 0;

  this.isMouseDown = false;
  this.triggerDrag = false;

  // SCENE
  this.stageX = 0;
  this.stageY = 0;
  this.ratio = 1;

  // CALLBACKS
  function moveHandler(event) {
    self.oldMouseX = self.mouseX;
    self.oldMouseY = self.mouseY;

    self.mouseX = event.offsetX;
    self.mouseY = event.offsetY;

    self.isMouseDown && drag(event);
  };

  function upHandler(event) {
    self.isMouseDown = false;

    stopDrag();
  };

  function downHandler(event) {
    self.isMouseDown = true;
    self.oldMouseX = self.mouseX;
    self.oldMouseY = self.mouseY;

    self.triggerDrag = false;

    startDrag();
  };

  function wheelHandler(event) {
    self.ratio += event.wheelDelta / 10;
  };

  // CUSTOM ACTIONS
  function startDrag(event) {
    self.startX = self.mouseX;
    self.startY = self.mouseY;

    self.dispatch('startdrag', event);
  };

  function stopDrag(event) {
    // TODO
    self.dispatch('stopdrag', event);
  };

  function drag(event) {
    self.dispatch('drag', {
      dx: self.mouseX - self.startX,
      dy: self.mouseY - self.startY,
      x: self.mouseX,
      y: self.mouseY,
      ratio: self.ratio
    });
  };

  // ADD CALLBACKS
  this.canvas.onmousewheel = wheelHandler;
  this.canvas.onmousemove = moveHandler;
  this.canvas.onmousedown = downHandler;
  document.onmouseup = upHandler;
}
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');

// ovt reference
let Ovt;

// Types mappings
const typeMappings = {
  array: ['any'],
  object: 'any',
  alternatives: 'any',
  func: 'any',
  buffer: 'any',
  regexp: 'any'
};

function typeMapper(type) {
  return typeMappings[type] || type || 'any';
}

// ovt Schema extension, transfer nested children into baiji accepted params
function ovtPluginBaiji(ovt) {
  ovt.Schema.prototype.toObject = function() {
    if (this._type !== 'object') return [];

    let params = [];

    for (let name in this._inner.children) {
      let child = this._inner.children[name];

      // Add param item
      params.push({
        name: name,
        type: typeMapper(child._type),
        description: child._description,
        label: child._label,
        notes: child._notes.join(', '),
        tags: child._tags.join(', '),
        http: child._virtuals['http'],
        params: child.toObject()
      });
    }

    params._schema = this;

    return params;
  };

  // Add ovt reference
  Ovt = ovt;
}

ovtPluginBaiji.middleware = function(fn, options) {
  assert(Ovt, 'ovt-plugin-baiji must be required before middleware being called');
  assert(typeof fn === 'function', `${fn} is not a valid function`);

  options = options || {};

  return function ovtMiddleware(ctx, next) {
    let schema = (ctx._method.params || [])._schema;

    if (schema && schema.isOvt) {
      let result = Ovt.validate(ctx.args, schema, options);

      if (result.errors) {
        ctx.ovtErrors = result.errors.flatten() || [];
        ctx.ovtErrors.origin = result.errors;
        fn(ctx, next);
      } else {
        ctx.args = result.value;
        next();
      }
    } else {
      next();
    }
  };
};

module.exports = ovtPluginBaiji;
<commit_msg>add array schema support<commit_after>'use strict';

const assert = require('assert');

// ovt reference
let Ovt;

// Types mappings
const typeMappings = {
  array: ['any'],
  object: 'any',
  alternatives: 'any',
  func: 'any',
  buffer: 'any',
  regexp: 'any'
};

const supportTypes = ['object', 'array'];

function typeMapper(type) {
  return typeMappings[type] || type || 'any';
}

// ovt Schema extension, transfer nested children into baiji accepted params
function ovtPluginBaiji(ovt) {
  ovt.Schema.prototype.toObject = function() {
    if (!~supportTypes.indexOf(this._type)) return [];

    let params = [];
    let inner = this._inner;

    if (this._type === 'array') {
      // Only allow to parse array schema with one object schema item
      let cond = inner.inclusions.length === 1 && inner.requireds.length === 0;
      cond = cond || (inner.inclusions.length === 0 && inner.requireds.length === 1);

      if (!cond) return [];

      let child = inner.inclusions[0] || inner.requireds[0];

      // Only support inner object schema
      if (child._type !== 'object') return [];

      return child.toObject();
    } else {
      for (let name in inner.children) {
        let child = inner.children[name];
        let innerParams = child.toObject();

        // Add param item
        let param = {
          name: name,
          type: typeMapper(child._type),
          description: child._description,
          label: child._label,
          notes: child._notes.join(', '),
          tags: child._tags.join(', '),
          value: child._virtuals['value'],
        };

        // Add inner params
        if (innerParams.length) param.params = innerParams;

        params.push(param);
      }

      // Add schema reference
      params._schema = this;
    }

    return params;
  };

  // Add ovt reference
  Ovt = ovt;
}

ovtPluginBaiji.middleware = function(fn, options) {
  assert(Ovt, 'ovt-plugin-baiji must be required before middleware being called');
  assert(typeof fn === 'function', `${fn} is not a valid function`);

  options = options || {};

  return function ovtMiddleware(ctx, next) {
    let schema = (ctx._method.params || [])._schema;

    if (schema && schema.isOvt) {
      let result = Ovt.validate(ctx.args, schema, options);

      if (result.errors) {
        ctx.ovtErrors = result.errors.flatten() || [];
        ctx.ovtErrors.origin = result.errors;
        fn(ctx, next);
      } else {
        ctx.args = result.value;
        next();
      }
    } else {
      next();
    }
  };
};

module.exports = ovtPluginBaiji;
<|endoftext|>


<commit_before>(function(root) {
  // Shim for detecting performance timer
  var performance = root.performance;
  performance.now = performance.now || (function() {
    var vendors = ['ms', 'moz', 'webkit', 'o'];

    var functionName = '';
    for (var i = 0, j = vendors.length; i < j; i++) {
      functionName = vendors[i] + 'Now';

      if (performance[functionName]) {
        return performance[functionName];
      }
    }
  });
})(this);
<commit_msg>Removed performance.now shim<commit_after><|endoftext|>


<commit_before>'use strict';

var inherits = require('util').inherits;
var Transform = require('stream').Transform;
var PluginError = require('gulp-util').PluginError;

function gulpTransform(transformFn, options) {
  if (isNone(transformFn)) {
    throwPluginError('transformFn must be defined');
  } else if (typeof transformFn !== 'function') {
    throwPluginError('transformFn must be a function');
  } else if (!isNone(options) && !/^(function|object)$/.test(typeof options)) {
    throwPluginError('options must be an object if defined');
  } else {
    return new GulpTransformStream(transformFn, options);
  }
}

function GulpTransformStream(transformFn, options) {
  Transform.call(this, {objectMode: true});
  this.transformFn = transformFn;
  this.options = options || {};
}

inherits(GulpTransformStream, Transform);

GulpTransformStream.prototype._transform = function(file, encoding, next) {
  if (file.isBuffer()) {
    file.contents = transformContents(this.transformFn, file.contents, file, this.options);
  }

  if (file.isStream()) {
    file.contents = file.contents.pipe(new FileStream(this.transformFn, file, this.options));
  }

  next(null, file);
};

function FileStream(transformFn, file, options) {
  Transform.call(this);
  this.transformFn = transformFn;
  this.file = file;
  this.options = options;
  this.data = [];
}

inherits(FileStream, Transform);

FileStream.prototype._transform = function(chunk, encoding, next) {
  this.data.push(chunk);
  next();
};

FileStream.prototype._flush = function(done) {
  var contents = Buffer.concat(this.data);
  this.push(transformContents(this.transformFn, contents, this.file, this.options));
  done();
};

function transformContents(transformFn, contents, file, options) {
  contents = options.encoding ? contents.toString(options.encoding) : contents;
  contents = transformFn.call(options.thisArg, contents, file);

  if (Buffer.isBuffer(contents)) {
    return contents;
  } else if (typeof contents === 'string' || contents instanceof String) {
    return new Buffer(contents);
  } else {
    throwPluginError('transformFn must return a string or a Buffer');
  }
}

function throwPluginError(message) {
  throw new PluginError('gulp-transform', message);
}

function isNone(value) {
  return value === undefined || value === null;
}

module.exports = gulpTransform;
<commit_msg>Fix style<commit_after>'use strict';

var inherits = require('util').inherits;
var Transform = require('stream').Transform;
var PluginError = require('gulp-util').PluginError;

function gulpTransform(transformFn, options) {
  if (isNone(transformFn)) {
    throwPluginError('transformFn must be defined');
  } else if (typeof transformFn !== 'function') {
    throwPluginError('transformFn must be a function');
  } else if (!isNone(options) && !/^(function|object)$/.test(typeof options)) {
    throwPluginError('options must be an object if defined');
  } else {
    return new GulpTransformStream(transformFn, options);
  }
}

function GulpTransformStream(transformFn, options) {
  Transform.call(this, {objectMode: true});
  this.transformFn = transformFn;
  this.options = options || {};
}

inherits(GulpTransformStream, Transform);

GulpTransformStream.prototype._transform = function(file, encoding, next) {
  if (file.isBuffer()) {
    file.contents = transformContents(
      this.transformFn, file.contents, file, this.options);
  }

  if (file.isStream()) {
    file.contents = file.contents.pipe(
      new FileStream(this.transformFn, file, this.options));
  }

  next(null, file);
};

function FileStream(transformFn, file, options) {
  Transform.call(this);
  this.transformFn = transformFn;
  this.file = file;
  this.options = options;
  this.data = [];
}

inherits(FileStream, Transform);

FileStream.prototype._transform = function(chunk, encoding, next) {
  this.data.push(chunk);
  next();
};

FileStream.prototype._flush = function(done) {
  var contents = Buffer.concat(this.data);
  this.push(transformContents(
    this.transformFn, contents, this.file, this.options));
  done();
};

function transformContents(transformFn, contents, file, options) {
  contents = options.encoding ? contents.toString(options.encoding) : contents;
  contents = transformFn.call(options.thisArg, contents, file);

  if (Buffer.isBuffer(contents)) {
    return contents;
  } else if (typeof contents === 'string' || contents instanceof String) {
    return new Buffer(contents);
  } else {
    throwPluginError('transformFn must return a string or a Buffer');
  }
}

function throwPluginError(message) {
  throw new PluginError('gulp-transform', message);
}

function isNone(value) {
  return value === undefined || value === null;
}

module.exports = gulpTransform;
<|endoftext|>