<commit_before>module.exports = {
  'plugins': [
    'react'
  ],
  'ecmaFeatures': {
    'jsx': true
  },
  // View link below for react rules documentation
  // https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules
  'rules': {
    // Prevent missing displayName in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
    'react/display-name': 0,
    // Forbid certain propTypes (any, array, object)
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
    'react/forbid-prop-types': [0, {'forbid': ['any', 'array', 'object']}],
    // Enforce boolean attributes notation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
    'react/jsx-boolean-value': [2, 'never'],
    // Validate closing bracket location in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md
    'react/jsx-closing-bracket-location': [2, 'line-aligned'],
    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    'react/jsx-curly-spacing': 0,
    // Enforce event handler naming conventions in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md
    'react/jsx-handler-names': [0, {
      'eventHandlerPrefix': 'handle',
      'eventHandlerPropPrefix': 'on',
    }],
    // Validate props indentation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md
    'react/jsx-indent-props': [2, 2],
    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    'react/jsx-key': 0,
    // Limit maximum of props on a single line in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md
    'react/jsx-max-props-per-line': [0, {'maximum': 1}],
    // Prevent usage of .bind() and arrow functions in JSX props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
    'react/jsx-no-bind': 2,
    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    'react/jsx-no-duplicate-props': 0,
    // Prevent usage of unwrapped JSX strings
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md
    'react/jsx-no-literals': 0,
    // Disallow undeclared variables in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md
    'react/jsx-no-undef': 2,
    // Enforce PascalCase for user-defined JSX components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md
    'react/jsx-pascal-case': 0,
    // Enforce propTypes declarations alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-prop-types.md
    'react/jsx-sort-prop-types': 0,
    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    'react/jsx-sort-props': 0,
    // Prevent React to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
    'react/jsx-uses-react': 2,
    // Prevent variables used in JSX to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md
    'react/jsx-uses-vars': 2,
    // Prevent usage of dangerous JSX properties
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
    'react/no-danger': 0,
    // Prevent usage of deprecated methods
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md
    'react/no-deprecated': [1, {"react": "0.14.0"}],
    // Prevent usage of setState in componentDidMount
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
    'react/no-did-mount-set-state': [2, 'allow-in-func'],
    // Prevent usage of setState in componentDidUpdate
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md
    'react/no-did-update-set-state': [2, 'allow-in-func'],
    // Prevent direct mutation of this.state
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
    'react/no-direct-mutation-state': 0,
    // Prevent usage of isMounted
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md
    'react/no-is-mounted': 2,
    // Prevent multiple component definition per file
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md
    'react/no-multi-comp': 2,
    // Prevent usage of setState
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md
    'react/no-set-state': 0,
    // Prevent using string references
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md
    'react/no-string-refs': 0,
    // Prevent usage of unknown DOM property
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md
    'react/no-unknown-property': 2,
    // Require ES6 class declarations over React.createClass
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md
    'react/prefer-es6-class': [2, 'always'],
    // Prevent missing props validation in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md
    'react/prop-types': 2,
    // Prevent missing React when using JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md
    'react/react-in-jsx-scope': 2,
    // Restrict file extensions that may be required
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-extension.md
    'react/require-extension': 0,
    // Prevent extra closing tags for components without children
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md
    'react/self-closing-comp': 2,
    // Enforce component methods order
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md
    'react/sort-comp': [2, {
      'order': [
        'lifecycle',
        '/^on.+$/',
        '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/',
        'everything-else',
        '/^render.+$/',
        'render'
      ]
    }],
    // Prevent missing parentheses around multilines JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/wrap-multilines.md
    'react/wrap-multilines': [2, {
      declaration: true,
      assignment: true,
      return: true
    }],
  }
};
<commit_msg>add default config to all rules which take a config<commit_after>module.exports = {
  'plugins': [
    'react'
  ],
  'ecmaFeatures': {
    'jsx': true
  },
  // View link below for react rules documentation
  // https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules
  'rules': {
    // Prevent missing displayName in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
    'react/display-name': [0, {'acceptTranspilerName', false}],
    // Forbid certain propTypes (any, array, object)
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
    'react/forbid-prop-types': [0, {'forbid': ['any', 'array', 'object']}],
    // Enforce boolean attributes notation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
    'react/jsx-boolean-value': [2, 'never'],
    // Validate closing bracket location in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md
    'react/jsx-closing-bracket-location': [2, 'line-aligned'],
    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    'react/jsx-curly-spacing': [0, 'never', {'allowMultiline': true}],
    // Enforce event handler naming conventions in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md
    'react/jsx-handler-names': [0, {
      'eventHandlerPrefix': 'handle',
      'eventHandlerPropPrefix': 'on',
    }],
    // Validate props indentation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md
    'react/jsx-indent-props': [2, 2],
    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    'react/jsx-key': 0,
    // Limit maximum of props on a single line in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md
    'react/jsx-max-props-per-line': [0, {'maximum': 1}],
    // Prevent usage of .bind() and arrow functions in JSX props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
    'react/jsx-no-bind': 2,
    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    'react/jsx-no-duplicate-props': [0, {'ignoreCase': false}],
    // Prevent usage of unwrapped JSX strings
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md
    'react/jsx-no-literals': 0,
    // Disallow undeclared variables in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md
    'react/jsx-no-undef': 2,
    // Enforce PascalCase for user-defined JSX components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md
    'react/jsx-pascal-case': 0,
    // Enforce propTypes declarations alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-prop-types.md
    'react/jsx-sort-prop-types': [0, {
      'ignoreCase': false,
      'callbacksLast': false,
    }],
    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    'react/jsx-sort-props': [0, {
      'ignoreCase': false,
      'callbacksLast': false,
    }],
    // Prevent React to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
    'react/jsx-uses-react': [2, {'pragma': 'React'}],
    // Prevent variables used in JSX to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md
    'react/jsx-uses-vars': 2,
    // Prevent usage of dangerous JSX properties
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
    'react/no-danger': 0,
    // Prevent usage of deprecated methods
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md
    'react/no-deprecated': [1, {"react": "0.14.0"}],
    // Prevent usage of setState in componentDidMount
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
    'react/no-did-mount-set-state': [2, 'allow-in-func'],
    // Prevent usage of setState in componentDidUpdate
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md
    'react/no-did-update-set-state': [2, 'allow-in-func'],
    // Prevent direct mutation of this.state
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
    'react/no-direct-mutation-state': 0,
    // Prevent usage of isMounted
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md
    'react/no-is-mounted': 2,
    // Prevent multiple component definition per file
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md
    'react/no-multi-comp': [2, {'ignoreStateless': false}],
    // Prevent usage of setState
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md
    'react/no-set-state': 0,
    // Prevent using string references
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md
    'react/no-string-refs': 0,
    // Prevent usage of unknown DOM property
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md
    'react/no-unknown-property': 2,
    // Require ES6 class declarations over React.createClass
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md
    'react/prefer-es6-class': [2, 'always'],
    // Prevent missing props validation in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md
    'react/prop-types': [2, {'ignore': [], customValidators: []}],
    // Prevent missing React when using JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md
    'react/react-in-jsx-scope': 2,
    // Restrict file extensions that may be required
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-extension.md
    'react/require-extension': [0, {'extensions': ['.jsx']}],
    // Prevent extra closing tags for components without children
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md
    'react/self-closing-comp': 2,
    // Enforce component methods order
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md
    'react/sort-comp': [2, {
      'order': [
        'lifecycle',
        '/^on.+$/',
        '/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/',
        'everything-else',
        '/^render.+$/',
        'render'
      ]
    }],
    // Prevent missing parentheses around multilines JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/wrap-multilines.md
    'react/wrap-multilines': [2, {
      declaration: true,
      assignment: true,
      return: true
    }],
  }
};
<|endoftext|>


<commit_before>var request = require('request')

// With username parsed from request, check that the user has submitted a
// PR to jlord/Patchwork.
// Because PRs are merged so fast by @RR, we loop through each of the closed
// issues to find the user's PR.
// called by: checkPR(username, function(err, pr){ prStatus(res, err, pr) })
// callback includes a function which sends the pr boolean on as a response

module.exports = function (username, callback) {
  var options = {
    url: 'https://api.github.com/repos/jlord/patchwork/issues?state=closed',
    json: true,
    headers: {
      'User-Agent': 'request',
      'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
    }
  }

  request(options, getIssues)

  function getIssues (error, response, body) {
    if (error) return callback(error, null)

    var issues = body
    var pr = false

    for (var i = 0; i < issues.length; i++) {
      var issue = issues[i]
      var user = issue.user.login.toLowerCase()
      // what is the max number of issues that it returns?
      var prStatus = issue.pull_request.html_url
      if (user.match(username.toLowerCase()) && prStatus != null) {
        pr = true
        return callback(null, pr)
      }
    }
    // TODO why this here, shouldn't it fail early?
    // Check for non 200 responses
    callback(error, pr)
  }
}
<commit_msg>Return if PR doesn't exist<commit_after>var request = require('request')

// With username parsed from request, check that the user has submitted a
// PR to jlord/Patchwork.
// Because PRs are merged so fast by @RR, we loop through each of the closed
// issues to find the user's PR.
// called by: checkPR(username, function(err, pr){ prStatus(res, err, pr) })
// callback includes a function which sends the pr boolean on as a response

module.exports = function (username, callback) {
  var options = {
    url: 'https://api.github.com/repos/jlord/patchwork/issues?state=closed',
    json: true,
    headers: {
      'User-Agent': 'request',
      'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
    }
  }

  request(options, getIssues)

  function getIssues (error, response, body) {
    if (error) return callback(error, null)
    var issues = body
    var pr = false

    for (var i = 0; i < issues.length; i++) {
      var issue = issues[i]
      var user = issue.user.login.toLowerCase()
      // what is the max number of issues that it returns?
      if (!issue.pull_request) return callback(null, pr)
      if (user.match(username.toLowerCase())) {
        pr = true
        return callback(null, pr)
      }
    }
  }
}
<|endoftext|>


<commit_before>var say = require('../../utils/say');
var global = require('../../global');

module.exports = function (unitPaymentCorrection) {

    var items = unitPaymentCorrection.items.map((item) => {
        return {
            quantity: item.quantity,
            uom: item.uom,
            product: item.product,
            pricePerUnit: item.pricePerUnit,
            priceTotal: item.priceTotal,
            prNo: item.purchaseOrder.purchaseRequest.no
        };
    });

    items = [].concat.apply([], items);
    var iso = "FM-PB-00-06-015";
    var currency = unitPaymentCorrection.items.find(r => true).currency.code;
    var urDates = unitPaymentCorrection.unitPaymentOrder.items.map(unitPaymentOrderItem => {
        return new Date(unitPaymentOrderItem.unitReceiptNote.date)
    })
    var sjDate = Math.max.apply(null, urDates);

    var locale = global.config.locale;

    var moment = require('moment');
    moment.locale(locale.name);

    var numberLocaleOptions = {
        style: 'decimal',
        maximumFractionDigits: 4

    };
    var header = [
        {
            columns: [
                {
                    width: '40%',
                    text: 'PT DAN LIRIS',
                    style: ['size15', 'bold', 'left']
                }, {
                    width: '60%',
                    text: 'NOTA DEBET',
                    style: ['size15', 'bold', 'left']

                }]
        }, {
            columns: [
                {
                    width: '70%',
                    text: 'BANARAN, GROGOL, SUKOHARJO',
                    style: ['size08']
                }, {
                    width: '30%',
                    stack: [
                        {
                            text: iso,
                            style: ['size09', 'bold']
                        },
                        `SUKOHARJO, ${moment(unitPaymentCorrection.date).format(locale.date.format)}`,
                        `(${unitPaymentCorrection.unitPaymentOrder.supplier.code}) ${unitPaymentCorrection.unitPaymentOrder.supplier.name}`,
                        `${unitPaymentCorrection.unitPaymentOrder.supplier.address}`],
                    alignment: 'left',
                    style: ['size08']

                }]
        }, '\n', {
            columns: [
                {
                    stack: [{
                        columns: [{
                            width: '35%',
                            text: "Retur/Potongan"
                        }, {
                                width: '5%',
                                text: ":"
                            }, {
                                width: '*',
                                text: unitPaymentCorrection.unitPaymentOrder.category.name
                            }],
                        style: ['size08']
                    }, {
                            columns: [{
                                width: '35%',
                                text: "Untuk"
                            }, {
                                    width: '5%',
                                    text: ":"
                                }, {
                                    width: '*',
                                    text: unitPaymentCorrection.unitPaymentOrder.division.name
                                }],
                            style: ['size08']
                        }
                    ]
                }, {
                    width: '20%',
                    text: ''
                }, {
                    width: '30%',
                    text: `Nomor ${unitPaymentCorrection.no}`,
                    style: ['size09', 'left', 'bold']
                }]
        }, '\n'
    ];

    var thead = [
        {
            text: 'No.',
            style: 'tableHeader'
        }, {
            text: 'Nama Barang',
            style: 'tableHeader'
        }, {
            text: 'Jumlah',
            style: 'tableHeader'
        }, {
            text: 'Harga Satuan',
            style: 'tableHeader'
        }, {
            text: 'Harga Total',
            style: 'tableHeader'
        }, {
            text: 'Nomor Order',
            style: 'tableHeader'
        }
    ];

    var tbody = items.map(function (item, index) {
        return [{
            text: (index + 1).toString() || '',
            style: ['size08', 'center']
        }, {
                text: item.product.name,
                style: ['size08', 'left']
            }, {
                text: `${item.quantity} ${item.uom.unit}`,
                style: ['size08', 'right']
            }, {
                columns: [{
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                        width: '*',
                        text: parseFloat(item.pricePerUnit).toLocaleString(locale, locale.currency),
                        style: ['size08', 'right']
                    }]
            }, {
                columns: [{
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                        width: '*',
                        text: parseFloat(item.priceTotal).toLocaleString(locale, locale.currency),
                        style: ['size08', 'right']
                    }]
            }, {
                text: item.prNo,
                style: ['size08', 'left']
            }];
    });

    tbody = tbody.length > 0 ? tbody : [
        [{
            text: "tidak ada barang",
            style: ['size08', 'center'],
            colSpan: 6
        }, "", "", "", "", ""]
    ];

    var table = [{
        table: {
            widths: ['5%', '35%', '15%', '15%', '15%', '15%'],
            headerRows: 1,
            body: [].concat([thead], tbody)
        }
    }];

    var initialValue = {
        priceTotal: 0
    };

    var sum = (items.length > 0 ? items : [initialValue])
        .map(item => item.priceTotal)
        .reduce(function (prev, curr, index, arr) {
            return prev + curr;
        }, 0);

    var useIncomeTax = unitPaymentCorrection.unitPaymentOrder.incomeTaxNo.length > 0 ? sum * 0.1 : 0;

    var totalKoreksiJumlah = ['\n',
        {
            columns: [{
                width: '30%',
                text: 'Jumlah',
                style: ['size08']
            }, {
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                    width: '65%',
                    text: parseFloat(sum).toLocaleString(locale, locale.currency),
                    style: ['size08', 'right']
                }],
            margin: [350, 0, 0, 0]
        }, {
            columns: [{
                width: '30%',
                text: 'PPN',
                style: ['size08']
            }, {
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                    width: '65%',
                    text: parseFloat(useIncomeTax).toLocaleString(locale, locale.currency),
                    style: ['size08', 'right']
                }],
            margin: [350, 0, 0, 0]
        }, {
            columns: [{
                width: '30%',
                text: 'Total',
                style: ['size08']
            }, {
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                    width: '65%',
                    text: parseFloat(sum + useIncomeTax).toLocaleString(locale, locale.currency),
                    style: ['size08', 'right', 'bold']
                }],
            margin: [350, 0, 0, 0]
        },
        '\n'];

    var totalKoreksiHarga = ['\n',
        {
            columns: [{
                width: '30%',
                text: 'Jumlah',
                style: ['size08']
            }, {
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                    width: '65%',
                    text: parseFloat(sum).toLocaleString(locale, locale.currency),
                    style: ['size08', 'right']
                }],
            margin: [350, 0, 0, 0]
        }, '\n'];

    var total = unitPaymentCorrection.correctionType === "Jumlah" ? totalKoreksiJumlah : totalKoreksiHarga;

    var terbilang = unitPaymentCorrection.correctionType === "Jumlah" ? {
        text: `Terbilang : ${say(sum + useIncomeTax, unitPaymentCorrection.items.find(r => true).currency.description)}`,
        style: ['size09', 'bold']
    } : {
            text: `Terbilang : ${say(sum, unitPaymentCorrection.items.find(r => true).currency.description)}`,
            style: ['size09', 'bold']
        };

    var footer = ['\n',
        {
            columns: [
                {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: 'Perjanjian Pembayaran',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: ':',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: moment(unitPaymentCorrection.unitPaymentOrder.dueDate).format(locale.date.format),
                            style: ['size08']
                        }]
                }, {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: '',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: '',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: "",
                            style: ['size08']
                        }]
                }]
        }, {
            columns: [
                {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: 'Nota',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: ':',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: `${unitPaymentCorrection.unitPaymentOrder.no}`,
                            style: ['size08']
                        }]
                }, {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: 'Barang Datang',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: ':',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: `${moment(sjDate).format(locale.date.format)} `,
                            style: ['size08']
                        }]
                }]
        }, {
            columns: [{
                width: '50%',
                columns: [{
                    width: '35%',
                    text: 'Keterangan',
                    style: ['size08']
                }, {
                        width: '3%',
                        text: ':',
                        style: ['size08']
                    }, {
                        width: '*',
                        text: unitPaymentCorrection.remark,
                        style: ['size08']
                    }]
            }, {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: 'Nomor Nota Retur',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: ':',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: unitPaymentCorrection.returNoteNo,
                            style: ['size08']
                        }]
                }]
        }, '\n'];

    var signature = [{
        columns: [{
            width: '25%',
            stack: ['Diperiksa,', 'Verifikasi', '\n\n\n\n', '(                               )'],
            style: ['center']
        }, {
                width: '25%',
                stack: ['Mengetahui,', 'Pimpinan Bagian', '\n\n\n\n', '(                               )'],
                style: ['center']
            }, {
                width: '25%',
                stack: ['Tanda Terima,', 'Bagian Pembelian', '\n\n\n\n', '(                               )'],
                style: ['center']
            }, {
                width: '25%',
                stack: ['Dibuat Oleh,', ' ', '\n\n\n\n', `(  ${unitPaymentCorrection._createdBy}  )`],
                style: ['center']
            }],
        style: ['size08']
    }, '\n', {
            text: `Dicetak Oleh ${unitPaymentCorrection._createdBy}`,
            style: ['size08']
        }];

    var dd = {
        pageSize: 'A5',
        pageOrientation: 'landscape',
        pageMargins: 20,
        content: [].concat(header, table, total, terbilang, footer, signature),
        styles: {
            size06: {
                fontSize: 6
            },
            size07: {
                fontSize: 7
            },
            size08: {
                fontSize: 8
            },
            size09: {
                fontSize: 9
            },
            size10: {
                fontSize: 10
            },
            size15: {
                fontSize: 15
            },
            bold: {
                bold: true
            },
            center: {
                alignment: 'center'
            },
            left: {
                alignment: 'left'
            },
            right: {
                alignment: 'right'
            },
            justify: {
                alignment: 'justify'
            },
            tableHeader: {
                bold: true,
                fontSize: 8,
                color: 'black',
                alignment: 'center'
            }
        }
    }

    return dd;
}<commit_msg>update file pdf unit payment correction<commit_after>var say = require('../../utils/say');
var global = require('../../global');

module.exports = function (unitPaymentCorrection) {

    var items = unitPaymentCorrection.items.map((item) => {
        return {
            quantity: item.quantity,
            uom: item.uom,
            product: item.product,
            pricePerUnit: item.pricePerUnit,
            priceTotal: item.priceTotal,
            prNo: item.purchaseOrder.purchaseRequest.no
        };
    });

    items = [].concat.apply([], items);
    var iso = "FM-PB-00-06-015";
    var currency = unitPaymentCorrection.items.find(r => true).currency.code;
    var urDates = unitPaymentCorrection.unitPaymentOrder.items.map(unitPaymentOrderItem => {
        return new Date(unitPaymentOrderItem.unitReceiptNote.date)
    })
    var sjDate = Math.max.apply(null, urDates);

    var locale = global.config.locale;

    var moment = require('moment');
    moment.locale(locale.name);

    var numberLocaleOptions = {
        style: 'decimal',
        maximumFractionDigits: 4

    };
    var header = [
        {
            columns: [
                {
                    width: '40%',
                    text: 'PT DAN LIRIS',
                    style: ['size15', 'bold', 'left']
                }, {
                    width: '60%',
                    text: 'NOTA DEBET',
                    style: ['size15', 'bold', 'left']

                }]
        }, {
            columns: [
                {
                    width: '70%',
                    text: 'BANARAN, GROGOL, SUKOHARJO',
                    style: ['size08']
                }, {
                    width: '30%',
                    stack: [
                        {
                            text: iso,
                            style: ['size09', 'bold']
                        },
                        `SUKOHARJO, ${moment(unitPaymentCorrection.date).format(locale.date.format)}`,
                        `(${unitPaymentCorrection.unitPaymentOrder.supplier.code}) ${unitPaymentCorrection.unitPaymentOrder.supplier.name}`,
                        `${unitPaymentCorrection.unitPaymentOrder.supplier.address}`],
                    alignment: 'left',
                    style: ['size08']

                }]
        }, '\n', {
            columns: [
                {
                    stack: [{
                        columns: [{
                            width: '35%',
                            text: "Retur/Potongan"
                        }, {
                                width: '5%',
                                text: ":"
                            }, {
                                width: '*',
                                text: unitPaymentCorrection.unitPaymentOrder.category.name
                            }],
                        style: ['size08']
                    }, {
                            columns: [{
                                width: '35%',
                                text: "Untuk"
                            }, {
                                    width: '5%',
                                    text: ":"
                                }, {
                                    width: '*',
                                    text: unitPaymentCorrection.unitPaymentOrder.division.name
                                }],
                            style: ['size08']
                        }
                    ]
                }, {
                    width: '20%',
                    text: ''
                }, {
                    width: '30%',
                    text: `Nomor ${unitPaymentCorrection.no}`,
                    style: ['size09', 'left', 'bold']
                }]
        }, '\n'
    ];

    var thead = [
        {
            text: 'No.',
            style: 'tableHeader'
        }, {
            text: 'Nama Barang',
            style: 'tableHeader'
        }, {
            text: 'Jumlah',
            style: 'tableHeader'
        }, {
            text: 'Harga Satuan',
            style: 'tableHeader'
        }, {
            text: 'Harga Total',
            style: 'tableHeader'
        }, {
            text: 'Nomor Order',
            style: 'tableHeader'
        }
    ];

    var tbody = items.map(function (item, index) {
        return [{
            text: (index + 1).toString() || '',
            style: ['size08', 'center']
        }, {
                text: item.product.name,
                style: ['size08', 'left']
            }, {
                text: `${item.quantity} ${item.uom.unit}`,
                style: ['size08', 'right']
            }, {
                columns: [{
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                        width: '*',
                        text: parseFloat(item.pricePerUnit).toLocaleString(locale, locale.currency),
                        style: ['size08', 'right']
                    }]
            }, {
                columns: [{
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                        width: '*',
                        text: parseFloat(item.priceTotal).toLocaleString(locale, locale.currency),
                        style: ['size08', 'right']
                    }]
            }, {
                text: item.prNo,
                style: ['size08', 'left']
            }];
    });

    tbody = tbody.length > 0 ? tbody : [
        [{
            text: "tidak ada barang",
            style: ['size08', 'center'],
            colSpan: 6
        }, "", "", "", "", ""]
    ];

    var table = [{
        table: {
            widths: ['5%', '35%', '15%', '15%', '15%', '15%'],
            headerRows: 1,
            body: [].concat([thead], tbody)
        }
    }];

    var initialValue = {
        priceTotal: 0
    };

    var sum = (items.length > 0 ? items : [initialValue])
        .map(item => item.priceTotal)
        .reduce(function (prev, curr, index, arr) {
            return prev + curr;
        }, 0);

    var totalIncomeTax = unitPaymentCorrection.unitPaymentOrder.incomeTaxNo.length > 0 ? sum * 0.1 : 0;

    var totalKoreksiDenganPPN = ['\n',
        {
            columns: [{
                width: '30%',
                text: 'Jumlah',
                style: ['size08']
            }, {
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                    width: '65%',
                    text: parseFloat(sum).toLocaleString(locale, locale.currency),
                    style: ['size08', 'right']
                }],
            margin: [350, 0, 0, 0]
        }, {
            columns: [{
                width: '30%',
                text: 'PPN',
                style: ['size08']
            }, {
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                    width: '65%',
                    text: parseFloat(totalIncomeTax).toLocaleString(locale, locale.currency),
                    style: ['size08', 'right']
                }],
            margin: [350, 0, 0, 0]
        }, {
            columns: [{
                width: '30%',
                text: 'Total',
                style: ['size08']
            }, {
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                    width: '65%',
                    text: parseFloat(sum + totalIncomeTax).toLocaleString(locale, locale.currency),
                    style: ['size08', 'right', 'bold']
                }],
            margin: [350, 0, 0, 0]
        },
        '\n'];

    var totalKoreksiTanpaPPN = ['\n',
        {
            columns: [{
                width: '30%',
                text: 'Jumlah',
                style: ['size08']
            }, {
                    width: '5%',
                    text: currency,
                    style: ['size08']
                }, {
                    width: '65%',
                    text: parseFloat(sum).toLocaleString(locale, locale.currency),
                    style: ['size08', 'right']
                }],
            margin: [350, 0, 0, 0]
        }, '\n'];

    var total =  unitPaymentCorrection.unitPaymentOrder.useIncomeTax ? totalKoreksiDenganPPN : totalKoreksiTanpaPPN;

    var terbilang = unitPaymentCorrection.unitPaymentOrder.useIncomeTax ? {
        text: `Terbilang : ${say(sum + totalIncomeTax, unitPaymentCorrection.items.find(r => true).currency.description)}`,
        style: ['size09', 'bold']
    } : {
            text: `Terbilang : ${say(sum, unitPaymentCorrection.items.find(r => true).currency.description)}`,
            style: ['size09', 'bold']
        };

    var footer = ['\n',
        {
            columns: [
                {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: 'Perjanjian Pembayaran',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: ':',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: moment(unitPaymentCorrection.unitPaymentOrder.dueDate).format(locale.date.format),
                            style: ['size08']
                        }]
                }, {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: '',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: '',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: "",
                            style: ['size08']
                        }]
                }]
        }, {
            columns: [
                {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: 'Nota',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: ':',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: `${unitPaymentCorrection.unitPaymentOrder.no}`,
                            style: ['size08']
                        }]
                }, {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: 'Barang Datang',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: ':',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: `${moment(sjDate).format(locale.date.format)} `,
                            style: ['size08']
                        }]
                }]
        }, {
            columns: [{
                width: '50%',
                columns: [{
                    width: '35%',
                    text: 'Keterangan',
                    style: ['size08']
                }, {
                        width: '3%',
                        text: ':',
                        style: ['size08']
                    }, {
                        width: '*',
                        text: unitPaymentCorrection.remark,
                        style: ['size08']
                    }]
            }, {
                    width: '50%',
                    columns: [{
                        width: '35%',
                        text: 'Nomor Nota Retur',
                        style: ['size08']
                    }, {
                            width: '3%',
                            text: ':',
                            style: ['size08']
                        }, {
                            width: '*',
                            text: unitPaymentCorrection.returNoteNo,
                            style: ['size08']
                        }]
                }]
        }, '\n'];

    var signature = [{
        columns: [{
            width: '25%',
            stack: ['Diperiksa,', 'Verifikasi', '\n\n\n\n', '(                               )'],
            style: ['center']
        }, {
                width: '25%',
                stack: ['Mengetahui,', 'Pimpinan Bagian', '\n\n\n\n', '(                               )'],
                style: ['center']
            }, {
                width: '25%',
                stack: ['Tanda Terima,', 'Bagian Pembelian', '\n\n\n\n', '(                               )'],
                style: ['center']
            }, {
                width: '25%',
                stack: ['Dibuat Oleh,', ' ', '\n\n\n\n', `(  ${unitPaymentCorrection._createdBy}  )`],
                style: ['center']
            }],
        style: ['size08']
    }, '\n', {
            text: `Dicetak Oleh ${unitPaymentCorrection._createdBy}`,
            style: ['size08']
        }];

    var dd = {
        pageSize: 'A5',
        pageOrientation: 'landscape',
        pageMargins: 20,
        content: [].concat(header, table, total, terbilang, footer, signature),
        styles: {
            size06: {
                fontSize: 6
            },
            size07: {
                fontSize: 7
            },
            size08: {
                fontSize: 8
            },
            size09: {
                fontSize: 9
            },
            size10: {
                fontSize: 10
            },
            size15: {
                fontSize: 15
            },
            bold: {
                bold: true
            },
            center: {
                alignment: 'center'
            },
            left: {
                alignment: 'left'
            },
            right: {
                alignment: 'right'
            },
            justify: {
                alignment: 'justify'
            },
            tableHeader: {
                bold: true,
                fontSize: 8,
                color: 'black',
                alignment: 'center'
            }
        }
    }

    return dd;
}<|endoftext|>


<commit_before>module.exports = function(browser) {
    var login = browser.globals.pages.login;

    return {
        mobileVisit: function() {
            return browser
                .verifyLoginMobile(login.username,function(result){
                    console.log("Login verification ");
                })
                .verify.elementNotPresent(login.emailTextBox)
                .verify.visible('a.mobile-nav-btn[href="/statement-mobile"]')
                .click('a.mobile-nav-btn[href="/statement-mobile"]')
                .keys(['\uE015', '\uE006'])
                .pause(1000)
                .waitForElementVisible('body', 3000)
                .url(function(response){
                    this.assert.urlContains(response.value, 'statement-mobile')
                })
                .verify.elementPresent('a.sidebar-btn')
                .assert.cssClassPresent('a.mobile-nav-btn[href="/statement-mobile"]','active')
                .verify.elementPresent('[role=tablist]')
                .verify.containsText('[role=tablist]','TODAY')
                .verify.elementPresent('div[role="tab"][title="Today"][aria-selected="true"]')
                .verify.elementPresent('div[role="tab"][title="Yesterday"][aria-selected="false"]')
                .click('div[role="tab"][title="Yesterday"]')
                .keys(['\uE015', '\uE006'])
                .pause(1000)
                .waitForElementVisible('body', 3000)
                .verify.elementPresent('div[role="tab"][title="Today"][aria-selected="false"]')
                .verify.elementPresent('div[role="tab"][title="Yesterday"][aria-selected="true"]')

        },
        desktopVisit: function() {
            return browser
                .verifyLogin(login.username,function(result){
                        console.log("Login verification ");
                })
                .verify.elementNotPresent(login.emailTextBox)
                .waitForElementVisible('.workspace-panel', 1000)
                .verify.elementPresent('div[role="tab"][title="Statement"]')
                .click('div[role="tab"][title="Statement"]')
                .keys(['\uE015', '\uE006'])
                .pause(1000)
                .verify.elementPresent('div[role="tab"][title="Statement"][aria-selected="true"]')

        }
    };

}<commit_msg>Fix statement route<commit_after>module.exports = function(browser) {
    var login = browser.globals.pages.login;

    return {
        mobileVisit: function() {
            return browser
                .verifyLoginMobile(login.username,function(result){
                    console.log("Login verification ");
                })
                .verify.elementNotPresent(login.emailTextBox)
                .click('a.mobile-nav-btn[href="/statement"]')
                .keys(['\uE015', '\uE006'])
                .pause(1000)
                .waitForElementVisible('body', 3000)
                .url(function(response){
                    this.assert.urlContains(response.value, 'statement')
                })
                .verify.elementPresent('a.sidebar-btn')
                .assert.cssClassPresent('a.mobile-nav-btn[href="/statement"]','active')
                .verify.elementPresent('[role=tablist]')
                .verify.containsText('[role=tablist]','TODAY')
                .verify.elementPresent('div[role="tab"][title="Today"][aria-selected="true"]')
                .verify.elementPresent('div[role="tab"][title="Yesterday"][aria-selected="false"]')
                .click('div[role="tab"][title="Yesterday"]')
                .keys(['\uE015', '\uE006'])
                .pause(1000)
                .waitForElementVisible('body', 3000)
                .verify.elementPresent('div[role="tab"][title="Today"][aria-selected="false"]')
                .verify.elementPresent('div[role="tab"][title="Yesterday"][aria-selected="true"]')

        },
        desktopVisit: function() {
            return browser
                .verifyLogin(login.username,function(result){
                        console.log("Login verification ");
                })
                .verify.elementNotPresent(login.emailTextBox)
                .waitForElementVisible('.workspace-panel', 1000)
                .verify.elementPresent('div[role="tab"][title="Statement"]')
                .click('div[role="tab"][title="Statement"]')
                .keys(['\uE015', '\uE006'])
                .pause(1000)
                .verify.elementPresent('div[role="tab"][title="Statement"][aria-selected="true"]')

        }
    };

}<|endoftext|>


<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2017 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

const ModalShortcuts = React.createClass({
  displayName: 'ModalShortcuts',

  propTypes: {
    closeModal: React.PropTypes.func.isRequired,
    guiVersion: React.PropTypes.string.isRequired,
    keybindings: React.PropTypes.object.isRequired
  },

  /**

  @return {Array} An array of the bindings to create ul.
  */
  _generateBindings: function() {
    let bindings = [];
    Object.keys(this.props.keybindings).forEach(key => {
      const binding = this.props.keybindings[key];
      if (binding.help && (binding.condition === undefined ||
        binding.condition.call(this) === true)) {
        bindings.push({
          key: key,
          label: binding.label || key,
          help: binding.help
        });
      }
    });

    return bindings;
  },

  /**
    Generate list of keybindings for help modal

    @return {Array} An array of React li elements.
  */
  _generateList: function() {
    const bindings = this._generateBindings();
    const components = bindings.map(binding => {
      return(

            {binding.label}

            {binding.help}

);
    });
    return components;
  },

  render: function() {
    return (

Keyboard Shortcuts

            <juju.components.SvgIcon name="close_16"
              size="16" />

            {this._generateList()}

            Juju GUI version {this.props.guiVersion}

    );
  }
});

YUI.add('modal-shortcuts', function() {
  juju.components.ModalShortcuts = ModalShortcuts;
}, '0.1.0', { requires: [
  'svg-icon'
]});
<commit_msg>Update ModalShortcuts to use es6 class.<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2017 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

class ModalShortcuts extends React.Component {
  /**
  @return {Array} An array of the bindings to create ul.
  */
  _generateBindings() {
    let bindings = [];
    Object.keys(this.props.keybindings).forEach(key => {
      const binding = this.props.keybindings[key];
      if (binding.help && (binding.condition === undefined ||
        binding.condition.call(this) === true)) {
        bindings.push({
          key: key,
          label: binding.label || key,
          help: binding.help
        });
      }
    });

    return bindings;
  }

  /**
    Generate list of keybindings for help modal

    @return {Array} An array of React li elements.
  */
  _generateList() {
    const bindings = this._generateBindings();
    const components = bindings.map(binding => {
      return(

            {binding.label}

            {binding.help}

);
    });
    return components;
  }

  render() {
    return (

Keyboard Shortcuts

            <juju.components.SvgIcon name="close_16"
              size="16" />

            {this._generateList()}

            Juju GUI version {this.props.guiVersion}

    );
  }
};

ModalShortcuts.propTypes = {
  closeModal: React.PropTypes.func.isRequired,
  guiVersion: React.PropTypes.string.isRequired,
  keybindings: React.PropTypes.object.isRequired
};

YUI.add('modal-shortcuts', function() {
  juju.components.ModalShortcuts = ModalShortcuts;
}, '0.1.0', { requires: [
  'svg-icon'
]});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
var fs = require('fs')
  , program = require('commander')
  , chalk = require('chalk')
  , moment = require('moment')
  , liner = require('./liner');

/**
 * displayError
 * Display error messages in red
 * @param message
 */
function displayError(message) {
  console.log(chalk.red.bold(message));
}

/**
 * processLine
 * @param line
 */
function processLine(line) {
  var jsObj, text, output;
  try {
    text = '';
    jsObj = JSON.parse(line);
    if (program.timestamp) {
      text = jsObj.time + ' | ';
    } else if (program.prettydate) {
      text = moment(jsObj.time).format("MMMM Do YYYY, hh:mm:ss a") + ' | ';
    }
    if (program.expression) {
      try {
        var result = eval('jsObj.' + program.expression);
        if (result) {
          if (program.source) {
            output = JSON.stringify(jsObj, undefined, 2);
          } else {
            if (typeof result === 'boolean') {
              var subExps = program.expression.split(' ');
              text += eval('jsObj.' + subExps[0]);
            } else if (typeof result === 'string' || typeof result === 'number') {
              text += result;
            } else if (typeof result === 'object') {
              text += JSON.stringify(result);
            }
            output = text;
          }
        }
      } catch (e) {
      }
    } else {
      output = text + JSON.stringify(jsObj, undefined, 2);
    }
  } catch (e) {
    displayError(e);
    process.exit(-1);
  }
  return output;
}

/**
 * main
 */
function main() {
  program
    .version('0.0.1')
    .usage('[options] bunyan.log')
    .option('-a, --array', 'Output results in array format')
    .option('-e, --expression [expression]', 'Filter using expression predicate')
    .option('-s, --source', 'Extract source (JSON) object')
    .option('-t, --timestamp', 'Show timestamp in results')
    .option('-p, --prettydate', 'Show pretty timestamp in results')
    .parse(process.argv);

  if (!program.args.length) {
    program.help();
  } else {
    var arrayOutput = (program['array'] && program.source)
      , source = fs.createReadStream(program.args[0]);

    if (arrayOutput) {
      console.log('[');
    }

    source.pipe(liner);
    source.on('error', function(err) {
      if (err.errno === 34) {
        displayError('Can\'t open ' + err.path);
      } else {
        displayError(err);
      }
      process.exit(-1);
    });
    liner.on('readable', function() {
      var lineIn, lineOut;
      while (lineIn = liner.read()) {
        lineOut = processLine(lineIn);
        console.log(lineOut + ((arrayOutput) ? ',' : ''));
      }
    });
    process.on('exit', function() {
      if (arrayOutput) {
        console.log(']');
      }
    });
  }
}

main();
<commit_msg>Handle source option only in boolean expressions for now.<commit_after>#!/usr/bin/env node
'use strict';
var fs = require('fs')
  , program = require('commander')
  , chalk = require('chalk')
  , moment = require('moment')
  , liner = require('./liner');

/**
 * displayError
 * Display error messages in red
 * @param message
 */
function displayError(message) {
  console.log(chalk.red.bold(message));
}

/**
 * processLine
 * @param line
 */
function processLine(line) {
  var jsObj, text, output;
  try {
    text = '';
    jsObj = JSON.parse(line);
    if (program.timestamp) {
      text = jsObj.time + ' | ';
    } else if (program.prettydate) {
      text = moment(jsObj.time).format("MMMM Do YYYY, hh:mm:ss a") + ' | ';
    }
    if (program.expression) {
      try {
        var result = eval('jsObj.' + program.expression);
        if (result) {
          if (typeof result === 'boolean') {
            var subExps = program.expression.split(' ');
            text += eval('jsObj.' + subExps[0]);
            if (program.source) {
              text = JSON.stringify(jsObj, undefined, 2);
            }
          } else if (typeof result === 'string' || typeof result === 'number') {
            text += result;
          } else if (typeof result === 'object') {
            text += JSON.stringify(result);
          }
          output = text;
        }
      } catch (e) {
        output = '';
      }
    } else {
      output = text + JSON.stringify(jsObj, undefined, 2);
    }
  } catch (e) {
    displayError(e);
    process.exit(-1);
  }
  return output;
}

/**
 * main
 */
function main() {
  program
    .version('0.0.1')
    .usage('[options] bunyan.log')
    .option('-a, --array', 'Output results in array format')
    .option('-e, --expression [expression]', 'Filter using expression predicate')
    .option('-s, --source', 'Extract source (JSON) object')
    .option('-t, --timestamp', 'Show timestamp in results')
    .option('-p, --prettydate', 'Show pretty timestamp in results')
    .parse(process.argv);

  if (!program.args.length) {
    program.help();
  } else {
    var arrayOutput = (program['array'] && program.source)
      , source = fs.createReadStream(program.args[0]);

    if (arrayOutput) {
      console.log('[');
    }

    source.pipe(liner);
    source.on('error', function(err) {
      if (err.errno === 34) {
        displayError('Can\'t open ' + err.path);
      } else {
        displayError(err);
      }
      process.exit(-1);
    });
    liner.on('readable', function() {
      var lineIn, lineOut;
      while (lineIn = liner.read()) {
        lineOut = processLine(lineIn);
        console.log(lineOut + ((arrayOutput) ? ',' : ''));
      }
    });
    process.on('exit', function() {
      if (arrayOutput) {
        console.log(']');
      }
    });
  }
}

main();
<|endoftext|>


<commit_before>'use strict';
/*
 * BLECAST_BL (BLE with Illuminance Sensor) node
 * BLECAST_TM (BLE with Temeprature Sensor) node
 */

import * as ble from './ble';
import * as blecast from './blecast';
import * as blecastBl from './blecast_bl';
import * as blecastTm from './blecast_tm';

export default function(RED) {
  let p = ble.start(RED).then(() => {
    ble.registerDiscoverHandler(blecast.acceptFunc, blecast.discoverFunc);
    class BlecastBlNode {
      constructor(n) {
        RED.nodes.createNode(this, n);
        this.address = n.address;
        this.uuid = n.uuid;
      }
    }
    RED.nodes.registerType('', 'BLECAST_BL', BlecastBlNode);

    class BlecastBlInNode {
      constructor(n) {
        RED.nodes.createNode(this, n);
        this.useString = n.useString;
        this.blecastBlNodeId = n.blecastBl;
        this.blecastBlNode = RED.nodes.getNode(this.blecastBlNodeId);
        if (this.blecastBlNode) {
          blecast.registerIn(this, 'BLECAST_BL', this.blecastBlNode.address, this.blecastBlNode.uuid,
            blecastBl.parse, this.useString, RED);
        }
        this.name = n.name;

        this.on('close', () => {
          if (this.blecastBlNode) {
            blecast.removeIn(this, 'BLECAST_BL', this.blecastBlNode.address, this.blecastBlNode.uuid, RED);
          }
        });
        blecast.clear(RED);
      }
    }
    RED.nodes.registerType('', 'BLECAST_BL in', BlecastBlInNode);

    class BlecastTmNode {
      constructor(n) {
        RED.nodes.createNode(this, n);
        this.address = n.address;
        this.uuid = n.uuid;
      }
    }
    RED.nodes.registerType('', 'BLECAST_TM', BlecastTmNode);

    class BlecastTmInNode {
      constructor(n) {
        RED.nodes.createNode(this, n);
        this.useString = n.useString;
        this.blecastTmNodeId = n.blecastTm;
        this.blecastTmNode = RED.nodes.getNode(this.blecastTmNodeId);
        if (this.blecastTmNode) {
          blecast.registerIn(this, 'BLECAST_TM', this.blecastTmNode.address, this.blecastTmNode.uuid,
            blecastTm.parse, this.useString, RED);
        }
        this.name = n.name;

        this.on('close', () => {
          if (this.blecastTmNode) {
            blecast.removeIn(this, 'BLECAST_TM', this.blecastTmNode.address, this.blecastTmNode.uuid, RED);
          }
        });
        blecast.clear(RED);
      }
    }
    RED.nodes.registerType('BLECAST_TM in', BlecastTmInNode);
  });

  if (RED.debug) {
    // Should not return anything except for test
    // since Node-RED tries to manipulate the return value unless it's null/undefined
    // and TypeError will be raised in the end.
    return p;
  } else {
    p.catch(e => {
      RED.log.error(RED._('blecast_bl.errors.unknown', { error: e }));
    });
  }
}
<commit_msg>Add separator comment<commit_after>'use strict';
/*
 * BLECAST_BL (BLE with Illuminance Sensor) node
 * BLECAST_TM (BLE with Temeprature Sensor) node
 */

import * as ble from './ble';
import * as blecast from './blecast';
import * as blecastBl from './blecast_bl';
import * as blecastTm from './blecast_tm';

export default function(RED) {
  let p = ble.start(RED).then(() => {

    // BLECAST
    ble.registerDiscoverHandler(blecast.acceptFunc, blecast.discoverFunc);
    class BlecastBlNode {
      constructor(n) {
        RED.nodes.createNode(this, n);
        this.address = n.address;
        this.uuid = n.uuid;
      }
    }
    RED.nodes.registerType('', 'BLECAST_BL', BlecastBlNode);

    class BlecastBlInNode {
      constructor(n) {
        RED.nodes.createNode(this, n);
        this.useString = n.useString;
        this.blecastBlNodeId = n.blecastBl;
        this.blecastBlNode = RED.nodes.getNode(this.blecastBlNodeId);
        if (this.blecastBlNode) {
          blecast.registerIn(this, 'BLECAST_BL', this.blecastBlNode.address, this.blecastBlNode.uuid,
            blecastBl.parse, this.useString, RED);
        }
        this.name = n.name;

        this.on('close', () => {
          if (this.blecastBlNode) {
            blecast.removeIn(this, 'BLECAST_BL', this.blecastBlNode.address, this.blecastBlNode.uuid, RED);
          }
        });
        blecast.clear(RED);
      }
    }
    RED.nodes.registerType('', 'BLECAST_BL in', BlecastBlInNode);

    class BlecastTmNode {
      constructor(n) {
        RED.nodes.createNode(this, n);
        this.address = n.address;
        this.uuid = n.uuid;
      }
    }
    RED.nodes.registerType('', 'BLECAST_TM', BlecastTmNode);

    class BlecastTmInNode {
      constructor(n) {
        RED.nodes.createNode(this, n);
        this.useString = n.useString;
        this.blecastTmNodeId = n.blecastTm;
        this.blecastTmNode = RED.nodes.getNode(this.blecastTmNodeId);
        if (this.blecastTmNode) {
          blecast.registerIn(this, 'BLECAST_TM', this.blecastTmNode.address, this.blecastTmNode.uuid,
            blecastTm.parse, this.useString, RED);
        }
        this.name = n.name;

        this.on('close', () => {
          if (this.blecastTmNode) {
            blecast.removeIn(this, 'BLECAST_TM', this.blecastTmNode.address, this.blecastTmNode.uuid, RED);
          }
        });
        blecast.clear(RED);
      }
    }
    RED.nodes.registerType('BLECAST_TM in', BlecastTmInNode);
  });

  // DEBUG
  if (RED.debug) {
    // Should not return anything except for test
    // since Node-RED tries to manipulate the return value unless it's null/undefined
    // and TypeError will be raised in the end.
    return p;
  } else {
    p.catch(e => {
      RED.log.error(RED._('blecast_bl.errors.unknown', { error: e }));
    });
  }
}
<|endoftext|>


<commit_before>/**
 * Express configuration
 */

'use strict';

var express         = require('express');
var favicon         = require('static-favicon');
var morgan          = require('morgan');
var compression     = require('compression');
var bodyParser      = require('body-parser');
var methodOverride  = require('method-override');
var cookieParser    = require('cookie-parser');
var errorHandler    = require('errorhandler');
var path            = require('path');
var config          = require('./environment');
var uuid            = require('node-uuid');

module.exports = function(app) {
  var env = app.get('env');
  app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
   });

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser('superEmprendimiento2014'));

  app.use(function(req, res, next){
    console.log("cookie");
    if (!req.cookies.JSESSIONID || req.cookies.JSESSIONID == "undefined") {
      console.log("dont have cookie");
      var theUuid = uuid.v4();
      console.log("there is not, asigning cookie " + theUuid);
      // Guardo en las sesions con el nombre uuid con el value de un numero aleatorio y expira en una semana
      console.log("created: " + theUuid);
      res.cookie('JSESSIONID', theUuid, {maxAge: 604800000});
    }
    //console.log("there is a cookie, " + req.cookies.uuid);
    next();
  });

  if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    app.set('appPath', 'client');
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }
};<commit_msg>5.01 de la mañana, estoy quemadisimo<commit_after>/**
 * Express configuration
 */

'use strict';

var express         = require('express');
var favicon         = require('static-favicon');
var morgan          = require('morgan');
var compression     = require('compression');
var bodyParser      = require('body-parser');
var methodOverride  = require('method-override');
var cookieParser    = require('cookie-parser');
var errorHandler    = require('errorhandler');
var path            = require('path');
var config          = require('./environment');
var uuid            = require('node-uuid');

module.exports = function(app) {
  var env = app.get('env');
  app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
   });

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser('superEmprendimiento2014'));

  app.use(function(req, res, next){
    console.log("cookie");
    console.log(req.cookies);
    console.log(req.cookies.JSESSIONID);
    if (!req.cookies.JSESSIONID || req.cookies.JSESSIONID == "undefined" || req.cookies.JSESSIONID.length == 9) {
      console.log("dont have cookie");
      var theUuid = uuid.v4();
      console.log("there is not, asigning cookie " + theUuid);
      // Guardo en las sesions con el nombre uuid con el value de un numero aleatorio y expira en una semana
      console.log("created: " + theUuid);
      res.cookie('JSESSIONID', theUuid, {maxAge: 604800000});
    }
    //console.log("there is a cookie, " + req.cookies.uuid);
    next();
  });

  if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    app.set('appPath', 'client');
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }
};<|endoftext|>


<commit_before>var User = require('../models/user');
var jwt = require('jwt-simple');
var moment = require('moment');
var app = require("../../app");
var jwtTokenSecret = "YOUR_SECRET_STRING";

// ********************** local application methods ************************//

// cheking whether user logged in or not
exports.loggedin = function(req, res, next) {
    res.send(req.isAuthenticated() ? req.user : '0');
}

// logout function
exports.logout = function(req, res, next) {
    req.logout();
    res.status(200).send("");
}

// return the logged in user
exports.me = function(req, res) {
    res.json(req.user || null);
};

// user creation function
exports.create = function(req, res, next) {
    console.log('came to the create request');
    var user = new User(req.body);
    user.provider = 'local';

    // because we set our user.provider to local our models/user.js validation will always be true
    req.assert('name', 'You must enter a name').notEmpty();
    req.assert('email', 'You must enter a valid email address').isEmail();
    req.assert('password', 'Password must be between 8-20 characters long').len(8, 20);
    req.assert('username', 'Username cannot be more than 20 characters').len(1, 20);
    req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();
    if (errors) {
        return res.status(400).send(errors);
    }
    console.log(2);

    // Hard coded for now. Will address this with the user permissions system in v0.3.5
    user.roles = ['authenticated'];
    user.save(function(err) {
        if (err) {
            switch (err.code) {
                case 11000:
                    res.status(400).send([{
                        msg: 'Email already taken',
                        param: 'email'
                    }]);
                    break;
                case 11001:
                    res.status(400).send([{
                        msg: 'Username already taken',
                        param: 'username'
                    }]);
                    break;
                default:
                    var modelErrors = [];

                    if (err.errors) {

                        for (var x in err.errors) {
                            modelErrors.push({
                                param: x,
                                msg: err.errors[x].message,
                                value: err.errors[x].value
                            });
                        }

                        res.status(400).send(modelErrors);
                    }
            }

            return res.status(400);
        }
        // log in the user
        req.logIn(user, function(err) {
            if (err) return next(err);
            if (req.body.thirdparty) {
                var token = generateToken(user);
                res.send({
                    user: user,
                    token: token
                });
            } else {
                return res.redirect('/');
            }
        });
        res.status(200);
    });
}

// login the user externally
exports.doLogin = function(req, res) {
    if (req.body.thirdparty) {
        var token = generateToken(req.user);
        res.send({
            user: req.user,
            token: token
        });
    } else {
        res.send({
            user: req.user,
        });
    }
}

// ******************************** third party application methods *******************//

// function to generate token for _id of given user document
var generateToken = function(user) {
    var expires = moment().add(7, 'days').valueOf();
    var sec = Date.now().valueOf()
    var token = jwt.encode({
        iss: user._id,
        exp: expires
    }, jwtTokenSecret);

    return token;
};

// clear the token
var clearToken = function(req, done) {
    User.update({
        _id: req.body.id
    }, {
        token: {
            jwt: '',
            createdAt: ''
        }
    })
        .exec(function(err, user) {
            if (err) console.log(err);
            else {
                done(null, user);
            };

        });
};

// validate the user using jwt token
exports.requiresToken = function(req, res, next) {
    var decoded = jwt.decode(req.query.token, jwtTokenSecret);

    // time limit validation
    if (decoded.exp <= Date.now()) {
        res.end('Access token has expired', 400);
    }

    // user _id validation
    if (decoded.iss) {

        User
            .findById(
                 decoded.iss
            )
            .exec(function(err, user) {
                console.log( "token" + user);
                if (err) return res.send(401, 'User is not authorized');

                if (!user)
                      return res.status(401).send('User not found');
                req.user = user;
                next();
            });

    } else return res.send(401, 'User is not authorized');

};

// function for log in function

exports.socialLogin = function(req, res) {
    User.findOne({
        email: req.body.email
    }).exec(function(err, user) {
        if (user) {
            User.update({ _id : user._id } , req.body , function(){
               var token = generateToken(user);
               res.send({
                   user: user,
                   token: token
               });
            });

        } else {
            console.log('came to no user');
            var user = new User(req.body);
            // Hard coded for now. Will address this with the user permissions system in v0.3.5
            user.roles = ['authenticated'];
            if(user.provider !== "twitter"){
              if(!user.email)
               res.status(400).send([{
                                msg: 'You must enter a valid email address',
                                param: 'email'
                            }]);
            }

            user.save(function(err) {
                if (err) {
                    console.log(err);
                    switch (err.code) {
                        case 11000:
                            res.status(400).send([{
                                msg: 'Email already taken',
                                param: 'email'
                            }]);
                            break;
                        case 11001:
                            res.status(400).send([{
                                msg: 'Username already taken',
                                param: 'username'
                            }]);
                            break;
                        default:
                            var modelErrors = [];

                            if (err.errors) {

                                for (var x in err.errors) {
                                    modelErrors.push({
                                        param: x,
                                        msg: err.errors[x].message,
                                        value: err.errors[x].value
                                    });
                                }

                                res.status(400).send(modelErrors);
                            }
                    }

                    return res.status(400);
                }
                console.log(user);
                var token = generateToken(user);
                res.send({
                    user: user,
                    token: token
                });

            });
            res.status(200);

        }
    });

}

// logout for third party app
exports.signoutapp = function(req, res) {
    clearToken(req, function(err, user) {
        if (err) res.status(400).send(err);
        else {
            res.send({
                message: 'success'
            });
        }
    });
};
<commit_msg>return added<commit_after>var User = require('../models/user');
var jwt = require('jwt-simple');
var moment = require('moment');
var app = require("../../app");
var jwtTokenSecret = "YOUR_SECRET_STRING";

// ********************** local application methods ************************//

// cheking whether user logged in or not
exports.loggedin = function(req, res, next) {
    res.send(req.isAuthenticated() ? req.user : '0');
}

// logout function
exports.logout = function(req, res, next) {
    req.logout();
    res.status(200).send("");
}

// return the logged in user
exports.me = function(req, res) {
    res.json(req.user || null);
};

// user creation function
exports.create = function(req, res, next) {
    console.log('came to the create request');
    var user = new User(req.body);
    user.provider = 'local';

    // because we set our user.provider to local our models/user.js validation will always be true
    req.assert('name', 'You must enter a name').notEmpty();
    req.assert('email', 'You must enter a valid email address').isEmail();
    req.assert('password', 'Password must be between 8-20 characters long').len(8, 20);
    req.assert('username', 'Username cannot be more than 20 characters').len(1, 20);
    req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();
    if (errors) {
        return res.status(400).send(errors);
    }
    console.log(2);

    // Hard coded for now. Will address this with the user permissions system in v0.3.5
    user.roles = ['authenticated'];
    user.save(function(err) {
        if (err) {
            switch (err.code) {
                case 11000:
                    res.status(400).send([{
                        msg: 'Email already taken',
                        param: 'email'
                    }]);
                    break;
                case 11001:
                    res.status(400).send([{
                        msg: 'Username already taken',
                        param: 'username'
                    }]);
                    break;
                default:
                    var modelErrors = [];

                    if (err.errors) {

                        for (var x in err.errors) {
                            modelErrors.push({
                                param: x,
                                msg: err.errors[x].message,
                                value: err.errors[x].value
                            });
                        }

                        res.status(400).send(modelErrors);
                    }
            }

            return res.status(400);
        }
        // log in the user
        req.logIn(user, function(err) {
            if (err) return next(err);
            if (req.body.thirdparty) {
                var token = generateToken(user);
                res.send({
                    user: user,
                    token: token
                });
            } else {
                return res.redirect('/');
            }
        });
        res.status(200);
    });
}

// login the user externally
exports.doLogin = function(req, res) {
    if (req.body.thirdparty) {
        var token = generateToken(req.user);
        res.send({
            user: req.user,
            token: token
        });
    } else {
        res.send({
            user: req.user,
        });
    }
}

// ******************************** third party application methods *******************//

// function to generate token for _id of given user document
var generateToken = function(user) {
    var expires = moment().add(7, 'days').valueOf();
    var sec = Date.now().valueOf()
    var token = jwt.encode({
        iss: user._id,
        exp: expires
    }, jwtTokenSecret);

    return token;
};

// clear the token
var clearToken = function(req, done) {
    User.update({
        _id: req.body.id
    }, {
        token: {
            jwt: '',
            createdAt: ''
        }
    })
        .exec(function(err, user) {
            if (err) console.log(err);
            else {
                done(null, user);
            };

        });
};

// validate the user using jwt token
exports.requiresToken = function(req, res, next) {
    var decoded = jwt.decode(req.query.token, jwtTokenSecret);

    // time limit validation
    if (decoded.exp <= Date.now()) {
        res.end('Access token has expired', 400);
    }

    // user _id validation
    if (decoded.iss) {

        User
            .findById(
                 decoded.iss
            )
            .exec(function(err, user) {
                console.log( "token" + user);
                if (err) return res.send(401, 'User is not authorized');

                if (!user)
                      return res.status(401).send('User not found');
                req.user = user;
                next();
            });

    } else return res.send(401, 'User is not authorized');

};

// function for log in function

exports.socialLogin = function(req, res) {
    User.findOne({
        email: req.body.email
    }).exec(function(err, user) {
        if (user) {
            User.update({ _id : user._id } , req.body , function(){
               var token = generateToken(user);
               res.send({
                   user: user,
                   token: token
               });
            });

        } else {
            console.log('came to no user');
            var user = new User(req.body);
            // Hard coded for now. Will address this with the user permissions system in v0.3.5
            user.roles = ['authenticated'];
            if(user.provider !== "twitter"){
              if(!user.email)
               return res.status(400).send([{
                                msg: 'You must enter a valid email address',
                                param: 'email'
                            }]);
            }

            user.save(function(err) {
                if (err) {
                    console.log(err);
                    switch (err.code) {
                        case 11000:
                            res.status(400).send([{
                                msg: 'Email already taken',
                                param: 'email'
                            }]);
                            break;
                        case 11001:
                            res.status(400).send([{
                                msg: 'Username already taken',
                                param: 'username'
                            }]);
                            break;
                        default:
                            var modelErrors = [];

                            if (err.errors) {

                                for (var x in err.errors) {
                                    modelErrors.push({
                                        param: x,
                                        msg: err.errors[x].message,
                                        value: err.errors[x].value
                                    });
                                }

                                res.status(400).send(modelErrors);
                            }
                    }

                    return res.status(400);
                }
                console.log(user);
                var token = generateToken(user);
                res.send({
                    user: user,
                    token: token
                });

            });
            res.status(200);

        }
    });

}

// logout for third party app
exports.signoutapp = function(req, res) {
    clearToken(req, function(err, user) {
        if (err) res.status(400).send(err);
        else {
            res.send({
                message: 'success'
            });
        }
    });
};
<|endoftext|>


<commit_before>/*
 * L.DomUtil contains various utility functions for working with DOM.
 */

L.DomUtil = {
	get: function (id) {
		return (typeof id === 'string' ? document.getElementById(id) : id);
	},

	getStyle: function (el, style) {

		var value = el.style[style];

		if (!value && el.currentStyle) {
			value = el.currentStyle[style];
		}

		if (!value || value === 'auto') {
			var css = document.defaultView.getComputedStyle(el, null);
			value = css ? css[style] : null;
		}

		return value === 'auto' ? null : value;
	},

	getViewportOffset: function (element) {

		var top = 0,
			left = 0,
			el = element,
			docBody = document.body,
			pos;

		do {
			top  += el.offsetTop  || 0;
			left += el.offsetLeft || 0;
			pos = L.DomUtil.getStyle(el, 'position');

			if (el.offsetParent === docBody && pos === 'absolute') { break; }

			if (pos === 'fixed') {
				top  += docBody.scrollTop  || 0;
				left += docBody.scrollLeft || 0;
				break;
			}
			el = el.offsetParent;

		} while (el);

		el = element;

		do {
			if (el === docBody) { break; }

			top  -= el.scrollTop  || 0;
			left -= el.scrollLeft || 0;

			//Webkit handles RTL scrollLeft different to everyone else
			// https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
			if (!L.DomUtil.documentIsLtr() && L.Browser.webkit) {
				left += el.scrollWidth - el.clientWidth;
			}

			el = el.parentNode;
		} while (el);

		return new L.Point(left, top);
	},

	documentIsLtr: function () {
		if (!L.DomUtil._docIsLtrCached) {
			L.DomUtil._docIsLtrCached = true;
			L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') == "ltr";
		}
		return L.DomUtil._docIsLtr;
	},

	create: function (tagName, className, container) {

		var el = document.createElement(tagName);
		el.className = className;

		if (container) {
			container.appendChild(el);
		}

		return el;
	},

	disableTextSelection: function () {
		if (document.selection && document.selection.empty) {
			document.selection.empty();
		}
		if (!this._onselectstart) {
			this._onselectstart = document.onselectstart;
			document.onselectstart = L.Util.falseFn;
		}
	},

	enableTextSelection: function () {
		if (document.onselectstart === L.Util.falseFn) {
			document.onselectstart = this._onselectstart;
			this._onselectstart = null;
		}
	},

	hasClass: function (el, name) {
		return (el.className.length > 0) &&
				new RegExp("(^|\\s)" + name + "(\\s|$)").test(el.className);
	},

	addClass: function (el, name) {
		if (!L.DomUtil.hasClass(el, name)) {
			el.className += (el.className ? ' ' : '') + name;
		}
	},

	removeClass: function (el, name) {

		function replaceFn(w, match) {
			if (match === name) { return ''; }
			return w;
		}

		el.className = el.className
				.replace(/(\S+)\s*/g, replaceFn)
				.replace(/(^\s+|\s+$)/, '');
	},

	setOpacity: function (el, value) {

		if ('opacity' in el.style) {
			el.style.opacity = value;

		} else if ('filter' in el.style) {

			var filter = false,
				filterName = 'DXImageTransform.Microsoft.Alpha';

			// filters collection throws an error if we try to retrieve a filter that doesn't exist
			try { filter = el.filters.item(filterName); } catch (e) {}

			value = Math.round(value * 100);

			if (filter) {
				filter.Enabled = (value !== 100);
				filter.Opacity = value;
			} else {
				el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
			}
		}
	},

	testProp: function (props) {

		var style = document.documentElement.style;

		for (var i = 0; i < props.length; i++) {
			if (props[i] in style) {
				return props[i];
			}
		}
		return false;
	},

	getTranslateString: function (point) {
		// on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
		// makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
		// (same speed either way), Opera 12 doesn't support translate3d

		var is3d = L.Browser.webkit3d,
			open = 'translate' + (is3d ? '3d' : '') + '(',
			close = (is3d ? ',0' : '') + ')';

		return open + point.x + 'px,' + point.y + 'px' + close;
	},

	getScaleString: function (scale, origin) {

		var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
		    scaleStr = ' scale(' + scale + ') ';

		return preTranslateStr + scaleStr;
	},

	setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])

		el._leaflet_pos = point;

		if (!disable3D && L.Browser.any3d) {
			el.style[L.DomUtil.TRANSFORM] =  L.DomUtil.getTranslateString(point);

			// workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
			if (L.Browser.mobileWebkit3d) {
				el.style.WebkitBackfaceVisibility = 'hidden';
			}
		} else {
			el.style.left = point.x + 'px';
			el.style.top = point.y + 'px';
		}
	},

	getPosition: function (el) {
		// this method is only used for elements previously positioned using setPosition,
		// so it's safe to cache the position for performance
		return el._leaflet_pos;
	}
};

// prefix style property names

L.DomUtil.TRANSFORM = L.DomUtil.testProp(
		['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);

L.DomUtil.TRANSITION = L.DomUtil.testProp(
		['transition', 'webkitTransition', 'OTransition', 'MozTransition', 'msTransition']);

L.DomUtil.TRANSITION_END =
		L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
		L.DomUtil.TRANSITION + 'End' : 'transitionend';
<commit_msg>Make getStyle work for ie < 9. Make IE<=7 support RTL too.<commit_after>/*
 * L.DomUtil contains various utility functions for working with DOM.
 */

L.DomUtil = {
	get: function (id) {
		return (typeof id === 'string' ? document.getElementById(id) : id);
	},

	getStyle: function (el, style) {

		var value = el.style[style];

		if (!value && el.currentStyle) {
			value = el.currentStyle[style];
		}

		if ((!value || value === 'auto') && document.defaultView) {
			var css = document.defaultView.getComputedStyle(el, null);
			value = css ? css[style] : null;
		}

		return value === 'auto' ? null : value;
	},

	getViewportOffset: function (element) {

		var top = 0,
			left = 0,
			el = element,
			docBody = document.body,
			pos,
			ie7 = L.Browser.ie7;

		do {
			top  += el.offsetTop  || 0;
			left += el.offsetLeft || 0;
			pos = L.DomUtil.getStyle(el, 'position');

			if (el.offsetParent === docBody && pos === 'absolute') { break; }

			if (pos === 'fixed') {
				top  += docBody.scrollTop  || 0;
				left += docBody.scrollLeft || 0;
				break;
			}
			el = el.offsetParent;

		} while (el);

		el = element;

		do {
			if (el === docBody) { break; }

			top  -= el.scrollTop  || 0;
			left -= el.scrollLeft || 0;

			//Webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
			// https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/style/bidi.js
			if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
				left += el.scrollWidth - el.clientWidth;

				//ie7 shows the scrollbar by default and provides clientWidth counting it, so we need to add it back in if it is visible
				// Scrollbar is on the left as we are RTL
				if (ie7 && L.DomUtil.getStyle(el, 'overflow-y') != 'hidden' && L.DomUtil.getStyle(el, 'overflow') != 'hidden') {
					left += 17;
				}
			}

			el = el.parentNode;
		} while (el);

		return new L.Point(left, top);
	},

	documentIsLtr: function () {
		if (!L.DomUtil._docIsLtrCached) {
			L.DomUtil._docIsLtrCached = true;
			L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') == "ltr";
		}
		return L.DomUtil._docIsLtr;
	},

	create: function (tagName, className, container) {

		var el = document.createElement(tagName);
		el.className = className;

		if (container) {
			container.appendChild(el);
		}

		return el;
	},

	disableTextSelection: function () {
		if (document.selection && document.selection.empty) {
			document.selection.empty();
		}
		if (!this._onselectstart) {
			this._onselectstart = document.onselectstart;
			document.onselectstart = L.Util.falseFn;
		}
	},

	enableTextSelection: function () {
		if (document.onselectstart === L.Util.falseFn) {
			document.onselectstart = this._onselectstart;
			this._onselectstart = null;
		}
	},

	hasClass: function (el, name) {
		return (el.className.length > 0) &&
				new RegExp("(^|\\s)" + name + "(\\s|$)").test(el.className);
	},

	addClass: function (el, name) {
		if (!L.DomUtil.hasClass(el, name)) {
			el.className += (el.className ? ' ' : '') + name;
		}
	},

	removeClass: function (el, name) {

		function replaceFn(w, match) {
			if (match === name) { return ''; }
			return w;
		}

		el.className = el.className
				.replace(/(\S+)\s*/g, replaceFn)
				.replace(/(^\s+|\s+$)/, '');
	},

	setOpacity: function (el, value) {

		if ('opacity' in el.style) {
			el.style.opacity = value;

		} else if ('filter' in el.style) {

			var filter = false,
				filterName = 'DXImageTransform.Microsoft.Alpha';

			// filters collection throws an error if we try to retrieve a filter that doesn't exist
			try { filter = el.filters.item(filterName); } catch (e) {}

			value = Math.round(value * 100);

			if (filter) {
				filter.Enabled = (value !== 100);
				filter.Opacity = value;
			} else {
				el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
			}
		}
	},

	testProp: function (props) {

		var style = document.documentElement.style;

		for (var i = 0; i < props.length; i++) {
			if (props[i] in style) {
				return props[i];
			}
		}
		return false;
	},

	getTranslateString: function (point) {
		// on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
		// makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
		// (same speed either way), Opera 12 doesn't support translate3d

		var is3d = L.Browser.webkit3d,
			open = 'translate' + (is3d ? '3d' : '') + '(',
			close = (is3d ? ',0' : '') + ')';

		return open + point.x + 'px,' + point.y + 'px' + close;
	},

	getScaleString: function (scale, origin) {

		var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
		    scaleStr = ' scale(' + scale + ') ';

		return preTranslateStr + scaleStr;
	},

	setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])

		el._leaflet_pos = point;

		if (!disable3D && L.Browser.any3d) {
			el.style[L.DomUtil.TRANSFORM] =  L.DomUtil.getTranslateString(point);

			// workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
			if (L.Browser.mobileWebkit3d) {
				el.style.WebkitBackfaceVisibility = 'hidden';
			}
		} else {
			el.style.left = point.x + 'px';
			el.style.top = point.y + 'px';
		}
	},

	getPosition: function (el) {
		// this method is only used for elements previously positioned using setPosition,
		// so it's safe to cache the position for performance
		return el._leaflet_pos;
	}
};

// prefix style property names

L.DomUtil.TRANSFORM = L.DomUtil.testProp(
		['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);

L.DomUtil.TRANSITION = L.DomUtil.testProp(
		['transition', 'webkitTransition', 'OTransition', 'MozTransition', 'msTransition']);

L.DomUtil.TRANSITION_END =
		L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
		L.DomUtil.TRANSITION + 'End' : 'transitionend';
<|endoftext|>