<commit_before>'use strict'
const TestRunner = require('test-runner')
const commandLineArgs = require('../')
const a = require('assert')

const runner = new TestRunner()

runner.test('partial: simple', function () {
  const definitions = [
    { name: 'one', type: Boolean }
  ]
  const argv = [ '--two', 'two', '--one', 'two' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    one: true,
    _unknown: [ '--two', 'two', 'two' ]
  })
})

runner.test('partial: defaultOption', function () {
  const definitions = [
    { name: 'files', type: String, defaultOption: true, multiple: true }
  ]
  const argv = [ '--files', 'file1', '--one', 'file2' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'file2' ],
    _unknown: [ '--one' ]
  })
})

runner.test('partial: defaultOption 2', function () {
  const definitions = [
    { name: 'files', type: String, defaultOption: true, multiple: true },
    { name: 'one', type: Boolean },
    { name: 'two', alias: 't', defaultValue: 2 }
  ]
  const argv = [ 'file1', '--one', 'file2', '-t', '--two=3', 'file3', '-ab' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'file2', 'file3' ],
    two: '3',
    one: true,
    _unknown: [ '-a', '-b' ]
  })
})

runner.test('partial: defaultOption with value equal to defaultValue', function () {
  const definitions = [
    { name: 'file', type: String, defaultOption: true, defaultValue: 'file1' }
  ]
  const argv = [ 'file1', '--two=3', '--four', '5' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    file: 'file1',
    _unknown: [ '--two', '3', '--four', '5' ]
  })
})

runner.test('partial: defaultOption with value equal to defaultValue 2', function () {
  const definitions = [
    { name: 'file', type: String, defaultOption: true, defaultValue: 'file1' }
  ]
  const argv = [ '--file', '--file=file1', '--two=3', '--four', '5' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    file: 'file1',
    _unknown: [ '--two', '3', '--four', '5' ]
  })
})

runner.test('partial: multiple', function () {
  const definitions = [
    { name: 'files', type: String, multiple: true }
  ]
  const argv = [ 'file1', '--files', 'file2', '-t', '--two=3', 'file3', '-ab', '--files=file4' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file2', 'file4' ],
    _unknown: [ 'file1', '-t', '--two=3', 'file3', '-a', '-b' ]
  })
})

runner.test('unknown options: rejected defaultOption values end up in _unknown', function () {
  const definitions = [
    { name: 'foo', type: String },
    { name: 'verbose', alias: 'v', type: Boolean },
    { name: 'libs', type: String, defaultOption: true }
  ]
  const argv = [ '--foo', 'bar', '-v', 'libfn', '--libarg', 'val1', '-r' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    foo: 'bar',
    verbose: true,
    libs: 'libfn',
    _unknown: [ '--libarg', 'val1', '-r' ]
  })
})

runner.test('partial: groups', function () {
  const definitions = [
    { name: 'one', group: 'a' },
    { name: 'two', group: 'a' },
    { name: 'three', group: 'b' }
  ]
  const argv = [ '--one', '1', '--two', '2', '--three', '3', 'ham', '--cheese' ]
  a.deepStrictEqual(commandLineArgs(definitions, { argv, partial: true }), {
    a: {
      one: '1',
      two: '2'
    },
    b: {
      three: '3'
    },
    _all: {
      one: '1',
      two: '2',
      three: '3'
    },
    _unknown: [ 'ham', '--cheese' ]
  })
})

runner.test('partial: multiple groups and _none', function () {
  const definitions = [
    { name: 'one', group: ['a', 'f'] },
    { name: 'two', group: ['a', 'g'] },
    { name: 'three' }
  ]
  const argv = [ '--cheese', '--one', '1', 'ham', '--two', '2', '--three', '3', '-c' ]
  a.deepStrictEqual(commandLineArgs(definitions, { argv, partial: true }), {
    a: {
      one: '1',
      two: '2'
    },
    f: {
      one: '1'
    },
    g: {
      two: '2'
    },
    _none: {
      three: '3'
    },
    _all: {
      one: '1',
      two: '2',
      three: '3'
    },
    _unknown: [ '--cheese', 'ham', '-c' ]
  })
})

runner.test('partial: defaultOption with --option=value notation', function () {
  const definitions = [
    { name: 'files', type: String, multiple: true, defaultOption: true }
  ]
  const argv = [ 'file1', 'file2', '--unknown=something' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'file2' ],
    _unknown: [ '--unknown=something' ]
  })
})

runner.test('partial: defaultOption with --option=value notation 2', function () {
  const definitions = [
    { name: 'files', type: String, multiple: true, defaultOption: true }
  ]
  const argv = [ 'file1', 'file2', '--unknown=something', '--files', 'file3', '--files=file4' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'file2', 'file3', 'file4' ],
    _unknown: [ '--unknown=something' ]
  })
})

runner.test('partial: defaultOption with --option=value notation 3', function () {
  const definitions = [
    { name: 'files', type: String, multiple: true, defaultOption: true }
  ]
  const argv = [ '--unknown', 'file1', '--another', 'something', 'file2', '--unknown=something', '--files', 'file3', '--files=file4' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'something', 'file2', 'file3', 'file4' ],
    _unknown: [ '--unknown', '--another', '--unknown=something' ]
  })
})

runner.test('partial: mulitple unknowns with same name', function () {
  const definitions = [
    { name: 'file' }
  ]
  const argv = [ '--unknown', '--unknown=something', '--file=file1', '--unknown' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    file: 'file1',
    _unknown: [ '--unknown', '--unknown=something', '--unknown' ]
  })
})

runner.test('partial: stopParsingAtFirstUnknown', function () {
  const definitions = [
    { name: 'one', type: Boolean },
    { name: 'two', type: Boolean }
  ]
  const argv = [ '--one', 'a', '--two' ]
  const options = commandLineArgs(definitions, { argv, partial: true, stopParsingAtFirstUnknown: true })
  a.deepStrictEqual(options, {
    one: true,
    _unknown: [ 'a', '--two' ]
  })
})
<commit_msg>added partial test<commit_after>'use strict'
const TestRunner = require('test-runner')
const commandLineArgs = require('../')
const a = require('assert')

const runner = new TestRunner()

runner.test('partial: simple', function () {
  const definitions = [
    { name: 'one', type: Boolean }
  ]
  const argv = [ '--two', 'two', '--one', 'two' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    one: true,
    _unknown: [ '--two', 'two', 'two' ]
  })
})

runner.test('partial: defaultOption', function () {
  const definitions = [
    { name: 'files', type: String, defaultOption: true, multiple: true }
  ]
  const argv = [ '--files', 'file1', '--one', 'file2' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'file2' ],
    _unknown: [ '--one' ]
  })
})

runner.test('partial: defaultOption 2', function () {
  const definitions = [
    { name: 'files', type: String, defaultOption: true, multiple: true },
    { name: 'one', type: Boolean },
    { name: 'two', alias: 't', defaultValue: 2 }
  ]
  const argv = [ 'file1', '--one', 'file2', '-t', '--two=3', 'file3', '-ab' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'file2', 'file3' ],
    two: '3',
    one: true,
    _unknown: [ '-a', '-b' ]
  })
})

runner.test('partial: defaultOption with value equal to defaultValue', function () {
  const definitions = [
    { name: 'file', type: String, defaultOption: true, defaultValue: 'file1' }
  ]
  const argv = [ 'file1', '--two=3', '--four', '5' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    file: 'file1',
    _unknown: [ '--two', '3', '--four', '5' ]
  })
})

runner.test('partial: defaultOption with value equal to defaultValue 2', function () {
  const definitions = [
    { name: 'file', type: String, defaultOption: true, defaultValue: 'file1' }
  ]
  const argv = [ '--file', '--file=file1', '--two=3', '--four', '5' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    file: 'file1',
    _unknown: [ '--two', '3', '--four', '5' ]
  })
})

runner.test('partial: defaultOption with value equal to defaultValue 3', function () {
  const definitions = [
    { name: 'file', type: String, defaultOption: true, defaultValue: 'file1' }
  ]
  const argv = [ 'file1', 'file2', '--two=3', '--four', '5' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    file: 'file1',
    _unknown: [ 'file2', '--two', '3', '--four', '5' ]
  })
})

runner.test('partial: multiple', function () {
  const definitions = [
    { name: 'files', type: String, multiple: true }
  ]
  const argv = [ 'file1', '--files', 'file2', '-t', '--two=3', 'file3', '-ab', '--files=file4' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file2', 'file4' ],
    _unknown: [ 'file1', '-t', '--two=3', 'file3', '-a', '-b' ]
  })
})

runner.test('unknown options: rejected defaultOption values end up in _unknown', function () {
  const definitions = [
    { name: 'foo', type: String },
    { name: 'verbose', alias: 'v', type: Boolean },
    { name: 'libs', type: String, defaultOption: true }
  ]
  const argv = [ '--foo', 'bar', '-v', 'libfn', '--libarg', 'val1', '-r' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    foo: 'bar',
    verbose: true,
    libs: 'libfn',
    _unknown: [ '--libarg', 'val1', '-r' ]
  })
})

runner.test('partial: groups', function () {
  const definitions = [
    { name: 'one', group: 'a' },
    { name: 'two', group: 'a' },
    { name: 'three', group: 'b' }
  ]
  const argv = [ '--one', '1', '--two', '2', '--three', '3', 'ham', '--cheese' ]
  a.deepStrictEqual(commandLineArgs(definitions, { argv, partial: true }), {
    a: {
      one: '1',
      two: '2'
    },
    b: {
      three: '3'
    },
    _all: {
      one: '1',
      two: '2',
      three: '3'
    },
    _unknown: [ 'ham', '--cheese' ]
  })
})

runner.test('partial: multiple groups and _none', function () {
  const definitions = [
    { name: 'one', group: ['a', 'f'] },
    { name: 'two', group: ['a', 'g'] },
    { name: 'three' }
  ]
  const argv = [ '--cheese', '--one', '1', 'ham', '--two', '2', '--three', '3', '-c' ]
  a.deepStrictEqual(commandLineArgs(definitions, { argv, partial: true }), {
    a: {
      one: '1',
      two: '2'
    },
    f: {
      one: '1'
    },
    g: {
      two: '2'
    },
    _none: {
      three: '3'
    },
    _all: {
      one: '1',
      two: '2',
      three: '3'
    },
    _unknown: [ '--cheese', 'ham', '-c' ]
  })
})

runner.test('partial: defaultOption with --option=value notation', function () {
  const definitions = [
    { name: 'files', type: String, multiple: true, defaultOption: true }
  ]
  const argv = [ 'file1', 'file2', '--unknown=something' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'file2' ],
    _unknown: [ '--unknown=something' ]
  })
})

runner.test('partial: defaultOption with --option=value notation 2', function () {
  const definitions = [
    { name: 'files', type: String, multiple: true, defaultOption: true }
  ]
  const argv = [ 'file1', 'file2', '--unknown=something', '--files', 'file3', '--files=file4' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'file2', 'file3', 'file4' ],
    _unknown: [ '--unknown=something' ]
  })
})

runner.test('partial: defaultOption with --option=value notation 3', function () {
  const definitions = [
    { name: 'files', type: String, multiple: true, defaultOption: true }
  ]
  const argv = [ '--unknown', 'file1', '--another', 'something', 'file2', '--unknown=something', '--files', 'file3', '--files=file4' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    files: [ 'file1', 'something', 'file2', 'file3', 'file4' ],
    _unknown: [ '--unknown', '--another', '--unknown=something' ]
  })
})

runner.test('partial: mulitple unknowns with same name', function () {
  const definitions = [
    { name: 'file' }
  ]
  const argv = [ '--unknown', '--unknown=something', '--file=file1', '--unknown' ]
  const options = commandLineArgs(definitions, { argv, partial: true })
  a.deepStrictEqual(options, {
    file: 'file1',
    _unknown: [ '--unknown', '--unknown=something', '--unknown' ]
  })
})

runner.test('partial: stopParsingAtFirstUnknown', function () {
  const definitions = [
    { name: 'one', type: Boolean },
    { name: 'two', type: Boolean }
  ]
  const argv = [ '--one', 'a', '--two' ]
  const options = commandLineArgs(definitions, { argv, partial: true, stopParsingAtFirstUnknown: true })
  a.deepStrictEqual(options, {
    one: true,
    _unknown: [ 'a', '--two' ]
  })
})
<|endoftext|>


<commit_before>"use strict";

import http from 'http';
import { Router } from 'express';
import list from './list';
import post from './post';
import put from './put';
import del from './delete';
import get from './get';

const getRouter = (mongooseModel, { url, hooks, actions, options }) => {
  let resourceListURL = `/${url}`;
  let resourceURL = `${resourceListURL}\\(:id\\)`;

  let routes = [
    {
      method: 'post',
      url: resourceListURL,
      ctrl: post,
      hook: hooks.post,
    },
    {
      method: 'put',
      url: resourceURL,
      ctrl: put,
      hook: hooks.put,
    },
    {
      method: 'delete',
      url: resourceURL,
      ctrl: del,
      hook: hooks.delete,
    },
    {
      method: 'get',
      url: resourceURL,
      ctrl: get,
      hook: hooks.get,
    },
    {
      method: 'get',
      url: resourceListURL,
      ctrl: list,
      hook: hooks.list,
    },
  ];

  let router = Router();
  routes.map((route) => {
    let { method, url, ctrl, hook } = route;
    router[method](url, (req, res, next) => {
      authorizePipe(req, res, hook.auth)
      .then(function() { return beforePipe(req, res, hook.before); })
      .then(function() { return ctrl(req, mongooseModel, options); })
      .then(function(result) { return respondPipe(req, res, result); })
      .then(function(data) { return afterPipe(req, res, hook.after, data); })
      .catch(function(result) { errorPipe(req, res, result); });
    });
  });

  for(let actionUrl in actions) {
    let action = actions[actionUrl];
    ((actionUrl, action) => {
      let fullUrl = `${resourceURL}${actionUrl}`;
      router.post(fullUrl, (req, res, next) => {
        if(checkAuth(action.auth)) {
          action(req, res, next);
        }
        else {
          res.status(401).end();
        }
      });
    })(actionUrl, action);
  }

  return router;
};

const checkAuth = (auth, req) => {
  if (!auth) {
    return true;
  }
  return auth(req);
};

function authorizePipe(req, res, auth) {
  return new Promise((resolve, reject) => {
    if (auth !== undefined) {
      if (!auth(req, res)) {
        return reject({ status: 401 });
      }
    }
    resolve();
  });
}

function beforePipe(req, res, before) {
  return new Promise((resolve, reject) => {
    if (before) {
      before(req.body, req, res);
    }
    resolve();
  });
}

function respondPipe(req, res, result) {
  return new Promise((resolve, reject) => {
    let status = result.status || 200;
    let data = result.entity;
    res.status(status).jsonp(data);
    resolve(data);
  });
}

function afterPipe(req, res, after, data) {
  return new Promise((resolve, reject) => {
    if (after) {
      after(data, req.body, req, res);
    }
    resolve();
  });
}

function errorPipe(req, res, result) {
  return new Promise((resolve, reject) => {
    let status = result.status || 200;
    let text = result.text || http.STATUS_CODES[status];
    res.status(status).send(text);
  });
}

export default { getRouter };
<commit_msg>refacting: use Promise.<commit_after>"use strict";

import http from 'http';
import { Router } from 'express';
import list from './list';
import post from './post';
import put from './put';
import del from './delete';
import get from './get';

const getRouter = (mongooseModel, { url, hooks, actions, options }) => {
  let resourceListURL = `/${url}`;
  let resourceURL = `${resourceListURL}\\(:id\\)`;

  let routes = [
    {
      method: 'post',
      url: resourceListURL,
      ctrl: post,
      hook: hooks.post,
    },
    {
      method: 'put',
      url: resourceURL,
      ctrl: put,
      hook: hooks.put,
    },
    {
      method: 'delete',
      url: resourceURL,
      ctrl: del,
      hook: hooks.delete,
    },
    {
      method: 'get',
      url: resourceURL,
      ctrl: get,
      hook: hooks.get,
    },
    {
      method: 'get',
      url: resourceListURL,
      ctrl: list,
      hook: hooks.list,
    },
  ];

  let router = Router();

  // add REST routes.
  routes.map((route) => {
    let { method, url, ctrl, hook } = route;
    router[method](url, (req, res, next) => {
      authorizePipe(req, res, hook.auth)
      .then(function() { return beforePipe(req, res, hook.before); })
      .then(function() { return ctrl(req, mongooseModel, options); })
      .then(function(result) { return respondPipe(req, res, result); })
      .then(function(data) { return afterPipe(req, res, hook.after, data); })
      .catch(function(result) { errorPipe(req, res, result); });
    });
  });

  // add ACTION routes.
  Object.keys(actions).map(function(url) {
    let action = actions[url];
    router.post(`${resourceURL}${url}`, (req, res, next) => {
      authorizePipe(req, res, action.auth).then(function() {
        action(req, res, next);
      }).catch(function(result) { errorPipe(req, res, result); });
    });
  });

  return router;
};

function authorizePipe(req, res, auth) {
  return new Promise((resolve, reject) => {
    if (auth !== undefined) {
      if (!auth(req, res)) {
        return reject({ status: 401 });
      }
    }
    resolve();
  });
}

function beforePipe(req, res, before) {
  return new Promise((resolve, reject) => {
    if (before) {
      before(req.body, req, res);
    }
    resolve();
  });
}

function respondPipe(req, res, result) {
  return new Promise((resolve, reject) => {
    let status = result.status || 200;
    let data = result.entity;
    res.status(status).jsonp(data);
    resolve(data);
  });
}

function afterPipe(req, res, after, data) {
  return new Promise((resolve, reject) => {
    if (after) {
      after(data, req.body, req, res);
    }
    resolve();
  });
}

function errorPipe(req, res, result) {
  return new Promise((resolve, reject) => {
    let status = result.status || 200;
    let text = result.text || http.STATUS_CODES[status];
    res.status(status).send(text);
  });
}

export default { getRouter };
<|endoftext|>


<commit_before>var Server = require('./../lib/koco-server').Server;

var argv = require('optimist')
    .usage([
            'USAGE: $0 [-p <port>] [<directory>]',
            'simple, rfc 2616 compliant file streaming module for node'
        ]
        .join('\n\n'))
    .option('port', {
        alias: 'p',
        'default': 8080,
        description: 'TCP port at which the files will be served'
    })
    .option('root', {
        alias: 'r',
        'default': '',
        description: 'the root path of the application'
    })
    .option('help', {
        alias: 'h',
        description: 'display this help message'
    })
    .argv;

var dir = argv._[0] || '.';

if (argv.help) {
    require('optimist').showHelp(console.log);
    process.exit(0);
}

var server = new Server({
    dir: dir,
    root: argv.root
});

server.listen(+argv.port, function() {
    console.log('serving "' + dir + '" at ' + server.getUrl());
});
<commit_msg>added #!/usr/bin/env node<commit_after>#!/usr/bin/env node

var Server = require('./../lib/koco-server').Server;

var argv = require('optimist')
    .usage([
            'USAGE: $0 [-p <port>] [<directory>]',
            'simple, rfc 2616 compliant file streaming module for node'
        ]
        .join('\n\n'))
    .option('port', {
        alias: 'p',
        'default': 8080,
        description: 'TCP port at which the files will be served'
    })
    .option('root', {
        alias: 'r',
        'default': '',
        description: 'the root path of the application'
    })
    .option('help', {
        alias: 'h',
        description: 'display this help message'
    })
    .argv;

var dir = argv._[0] || '.';

if (argv.help) {
    require('optimist').showHelp(console.log);
    process.exit(0);
}

var server = new Server({
    dir: dir,
    root: argv.root
});

server.listen(+argv.port, function() {
    console.log('serving "' + dir + '" at ' + server.getUrl());
});
<|endoftext|>


<commit_before>var assert       = require('assert');
var producer     = require('../lib/glossy/produce.js');

assert.ok(producer, 'producer loaded');

var syslogProducer = new producer();
assert.ok(syslogProducer, 'new SyslogProducer object created');

var BSDProducer = new producer('BSD');
assert.ok(BSDProducer, 'new BSDProducer object created');

var msg = syslogProducer.produce({
	facility: 'local4',
	severity: 'error',
	host: 'localhost',
	app_id: 'sudo',
	pid: '123',
	date: new Date(1234567890000),
	message: 'Test Message'
});

assert.equal(msg, "<163>1 2009-01-13T23:31:30.00Z localhost sudo 123 - Test Message",'Valid message returned');

syslogProducer.produce({
	facility: 'audit',
	severity: 'error',
	host: '127.0.0.1',
	app_id: 'sudo',
	pid: '419',
	date: new Date(1234567890000),
	message: 'Test Message'
}, function(cbMsg) {
	assert.equal(cbMsg, '<107>1 2009-01-13T23:31:30.00Z 127.0.0.1 sudo 419 - Test Message', 'Valid message in callback returned');
});

<commit_msg>Adding more producer tests.<commit_after>var assert       = require('assert');
var producer     = require('../lib/glossy/produce.js');

assert.ok(producer, 'producer loaded');

var syslogProducer = new producer();
assert.ok(syslogProducer, 'new SyslogProducer object created');
assert.equal(syslogProducer.messageFormat, 'RFC5424', 'Syslog Producer set correctly');

var BSDProducer = new producer('BSD');
assert.ok(BSDProducer, 'new BSDProducer object created');
assert.equal(BSDProducer.messageFormat, 'RFC3164', 'BSD Producer set correctly');

var msg = syslogProducer.produce({
	facility: 'local4',
	severity: 'error',
	host: 'localhost',
	app_id: 'sudo',
	pid: '123',
	date: new Date(1234567890000),
	message: 'Test Message'
});

assert.equal(msg, "<163>1 2009-01-13T23:31:30.00Z localhost sudo 123 - Test Message",'Valid message returned');

syslogProducer.produce({
	facility: 'audit',
	severity: 'error',
	host: '127.0.0.1',
	app_id: 'sudo',
	pid: '419',
	date: new Date(1234567890000),
	message: 'Test Message'
}, function(cbMsg) {
	assert.equal(cbMsg, '<107>1 2009-01-13T23:31:30.00Z 127.0.0.1 sudo 419 - Test Message', 'Valid message in callback returned');
});

BSDProducer.produce({
	facility: 'audit',
	severity: 'error',
	host: '127.0.0.1',
	app_id: 'sudo',
	pid: '419',
	date: new Date(1234567890000),
	message: 'Test Message'
}, function(cbMsg){
	assert.equal(cbMsg, '<107> Jan 13 23:31:30 127.0.0.1 sudo[419]: - Test Message');
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require( 'fs' );
var parseArgs = require( 'minimist' );
var IndentChecker = require( '../lib/indent-checker' );

var argv = parseArgs( process.argv.slice( 2 ) );
var files = argv._;

if ( argv.version ) {
	var version = require( '../package.json' ).version;
	console.log( 'mixedindentlint version ' + version );
	process.exit( 0 );
}

if ( files.length < 1 ) {
	console.log( 'No files to lint' );
	console.log( 'Usage: mixedindentlint [options] <file1> [<file2>...]' );
	console.log( 'Options:' );
	console.log( '  --version\t\tPrint the current version.' );
	process.exit( 0 );
}

var messages = files.reduce( function( warnings, file ) {
	try {
		var input = fs.readFileSync( file, 'utf8' );
	} catch ( err ) {
		console.error( 'Error trying to read file "' + file + '":', err.message );
		process.exit( 1 );
	}
	var lines = IndentChecker.getLinesWithLessCommonType( input );
	if ( lines.length > 0 ) warnings[ file ] = lines;
	return warnings;
}, {} );

Object.keys( messages ).map( function( file ) {
	messages[ file ].map( function( line ) {
		console.log( 'Line ' + line + ' in "' + file + '" has indentation that differs from the rest of the file.' );
	} );
} );

if ( Object.keys( messages ).length > 0 ) process.exit( 1 );
<commit_msg>Add --spaces and --tabs options to CLI<commit_after>#!/usr/bin/env node

var fs = require( 'fs' );
var parseArgs = require( 'minimist' );
var IndentChecker = require( '../lib/indent-checker' );

var argv = parseArgs( process.argv.slice( 2 ), {
	boolean: [
		'version',
		'spaces',
		'tabs'
	],
	default: {
		version: null,
		spaces: null,
		tabs: null
	}
} );
var files = argv._;

if ( argv.version ) {
	var version = require( '../package.json' ).version;
	console.log( 'mixedindentlint version ' + version );
	process.exit( 0 );
}

if ( files.length < 1 ) {
	console.log( 'No files to lint' );
	console.log( 'Usage: mixedindentlint [options] <file1> [<file2>...]' );
	console.log( 'Options:' );
	console.log( '  --version\t\tPrint the current version.' );
	console.log( '  --spaces\t\tAssume all files should use spaces rather than the most common indentation.' );
	console.log( '  --tabs\t\tAssume all files should use tabs rather than the most common indentation.' );
	process.exit( 0 );
}

var messages = files.reduce( function( warnings, file ) {
	try {
		var input = fs.readFileSync( file, 'utf8' );
	} catch ( err ) {
		console.error( 'Error trying to read file "' + file + '":', err.message );
		process.exit( 1 );
	}
	var lintOptions = {
		indent: null
	};
	if ( argv.spaces ) {
		lintOptions.indent = 'spaces';
	} else if ( argv.tabs ) {
		lintOptions.indent = 'tabs';
	}
	var lines = IndentChecker.lint( input, lintOptions );
	if ( lines.length > 0 ) warnings[ file ] = lines;
	return warnings;
}, {} );

var indentationType = 'the most common type';
if ( argv.spaces ) {
	indentationType = 'spaces';
} else if ( argv.tabs ) {
	indentationType = 'tabs';
}
Object.keys( messages ).map( function( file ) {
	messages[ file ].map( function( line ) {
		console.log( 'Line ' + line + ' in "' + file + '" has indentation that differs from ' + indentationType + '.' );
	} );
} );

if ( Object.keys( messages ).length > 0 ) process.exit( 1 );
<|endoftext|>


<commit_before>'use strict'

const getNode = require('./getNode')
const err = require('./err')

require('setimmediate')

function callNode(db, path, i) {
  let fn = db.updates.fns[path][i]

  if (!fn) {
    return
  }

  let val = getNode(db, path)
  let cacheTest = JSON.stringify(val)

  if (db.updates.cache[path][i] !== cacheTest) {
    db.updates.cache[path][i] = cacheTest

    ;(function () {
      try {
        fn.call(null, JSON.parse(cacheTest))
      } catch (e) {
        err(db, '/err/types/on/2', {
          path: path,
          error: e
        })
      }
    }())

  }
}

function triggerListener(db, path) {

  let fns = db.updates.fns[path]

  if (!fns) {
    return
  }

  let ids = Object.keys(fns)
  let len = ids.length

  for (let i = 0; i < len; i += 1) {

    setImmediate(() => {
      callNode(db, path, ids[i])
    })

  }

}

module.exports = triggerListener
<commit_msg>Stringify errors<commit_after>'use strict'

const getNode = require('./getNode')
const err = require('./err')

require('setimmediate')

function callNode(db, path, i) {
  let fn = db.updates.fns[path][i]

  if (!fn) {
    return
  }

  let val = getNode(db, path)
  let cacheTest = JSON.stringify(val)

  if (db.updates.cache[path][i] !== cacheTest) {
    db.updates.cache[path][i] = cacheTest

    ;(function () {
      try {
        fn.call(null, JSON.parse(cacheTest))
      } catch (e) {
        err(db, '/err/types/on/2', {
          path: path,
          error: e.message + ' ' + e.stack
        })
      }
    }())

  }
}

function triggerListener(db, path) {

  let fns = db.updates.fns[path]

  if (!fns) {
    return
  }

  let ids = Object.keys(fns)
  let len = ids.length

  for (let i = 0; i < len; i += 1) {

    setImmediate(() => {
      callNode(db, path, ids[i])
    })

  }

}

module.exports = triggerListener
<|endoftext|>


<commit_before>var chai = require('chai');
var path = require('path');

var config = require('../src/cli').config
config.set({root: __dirname + '/fixtures'})

var Sql = require('../src/cli').Sql
var Util = require('../src/cli').Util
var fileAttr = require('../src/cli').fileAttr
var Manager = require('../src/cli').Manager;
var fse = require('fs-extra');

describe('Request', function() {
  before( function(done) {
    Manager.instance.init()
      .then(function () {
        this.fixture = {
          tag: fse.readFileSync(__dirname + '/fixtures/templates/article.html', 'utf8'),
          json: fse.readJsonSync(__dirname + '/fixtures/data/article-1.json')
        }
        done()

      }.bind(this))
  });

  /**
   * Sql.getAllAttributes
   *
   */
  it('Util.getAllAttributes()', function(done) {
    var attributes = Util.getAllAttributes(this.fixture.tag, this.fixture.json)
    chai.expect(attributes.sourceString).to.contain('select');
    done();
  });

  /**
   * Sql.executeQuery
   *
   */
  it('Sql.executeQuery()', function(done) {
    try {
      var match = 'select * from ../'
      var jsonPage = {}
      var res = Sql.handleSqlRequest(match, {})

      chai.assert.equal(res.string, 'select ["*"] from ["___abe_dot______abe_dot______abe___"] ', 'select not well formatted')
      done();
    } catch (x) {
      done(x);
    }
  });

  /**
   * Sql.executeFromClause
   *
   */
  it('Sql.executeFromClause()', function() {
    var res = Sql.executeFromClause(['/'], ['/'])
    chai.expect(res).to.have.length(2);
  });

  /**
   * Sql.whereEquals
   *
   */
  it('Sql.executeWhereClause() >', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.priority`>`1`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() >=', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.priority`>=`1`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(2);
  });
  it('Sql.executeWhereClause() <', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.priority`<`1`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(0);
  });
  it('Sql.executeWhereClause() <=', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.priority`<=`1`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() =', function() {
    var request = Sql.handleSqlRequest('select title from ./ where template=`article`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() !=', function() {
    var request = Sql.handleSqlRequest('select title from ./ where template!=`homepage`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() LIKE', function() {
    var request = Sql.handleSqlRequest('select title from ./ where template LIKE `home`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() NOT LIKE', function() {
    var request = Sql.handleSqlRequest('select title from ./ where template NOT LIKE `home`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() AND', function() {
    var request = Sql.handleSqlRequest('select title from ./ where template=`homepage` AND title=`homepage`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() OR', function() {
    var request = Sql.handleSqlRequest('select title from ./ where template=`homepage` OR template=`article`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(2);
  });
  it('Sql.executeWhereClause() IN', function() {
    var request = Sql.handleSqlRequest('select title from ./ where template IN (`homepage`,`test`)', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() NOT IN', function() {
    var request = Sql.handleSqlRequest('select title from ./ where template NOT IN (`homepage`,`test`)', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });

  /**
   * Sql.whereLike
   *
   */
  it('Sql.getSourceType()', function() {
    chai.expect(Sql.getSourceType('http://google.com')).to.equal('url');
    chai.expect(Sql.getSourceType('select * from test')).to.equal('request');
    chai.expect(Sql.getSourceType('{"test":"test"}')).to.equal('value');
    chai.expect(Sql.getSourceType('references.json')).to.equal('file');
    chai.expect(Sql.getSourceType('test')).to.equal('other');
  });

  /**
   * Sql.requestList
   *
   */
  it('Sql.requestList()', function(done) {
    let util = new Util()
    var matches = util.dataRequest(this.fixture.tag)

    chai.expect(matches[0][0]).to.not.be.null

    var attributes = Util.getAllAttributes(matches[0][0], {})
    chai.expect(matches[0][0]).to.not.be.null

    var jsonPage = {}
    Util.requestList(attributes, '', matches[0][0], jsonPage)
      .then(function () {
        chai.expect(jsonPage.abe_source).to.not.be.undefined
        done()
      })
  });
});
<commit_msg>fix UT<commit_after>var chai = require('chai');
var path = require('path');

var config = require('../src/cli').config
config.set({root: __dirname + '/fixtures'})

var Sql = require('../src/cli').Sql
var Util = require('../src/cli').Util
var fileAttr = require('../src/cli').fileAttr
var Manager = require('../src/cli').Manager;
var fse = require('fs-extra');

describe('Request', function() {
  before( function(done) {
    Manager.instance.init()
      .then(function () {
        this.fixture = {
          tag: fse.readFileSync(__dirname + '/fixtures/templates/article.html', 'utf8'),
          json: fse.readJsonSync(__dirname + '/fixtures/data/article-1.json')
        }
        done()

      }.bind(this))
  });

  /**
   * Sql.getAllAttributes
   *
   */
  it('Util.getAllAttributes()', function(done) {
    var attributes = Util.getAllAttributes(this.fixture.tag, this.fixture.json)
    chai.expect(attributes.sourceString).to.contain('select');
    done();
  });

  /**
   * Sql.executeQuery
   *
   */
  it('Sql.executeQuery()', function(done) {
    try {
      var match = 'select * from ../'
      var jsonPage = {}
      var res = Sql.handleSqlRequest(match, {})

      chai.assert.equal(res.string, 'select ["*"] from ["___abe_dot______abe_dot______abe___"] ', 'select not well formatted')
      done();
    } catch (x) {
      done(x);
    }
  });

  /**
   * Sql.executeFromClause
   *
   */
  it('Sql.executeFromClause()', function() {
    var res = Sql.executeFromClause(['/'], ['/'])
    chai.expect(res).to.have.length(2);
  });

  /**
   * Sql.whereEquals
   *
   */
  it('Sql.executeWhereClause() >', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.priority`>`1`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() >=', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.priority`>=`1`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(2);
  });
  it('Sql.executeWhereClause() <', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.priority`<`1`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(0);
  });
  it('Sql.executeWhereClause() <=', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.priority`<=`1`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() =', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.template`=`article`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() !=', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.template`!=`homepage`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() LIKE', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.template` LIKE `home`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() NOT LIKE', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.template` NOT LIKE `home`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() AND', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.template`=`homepage` AND title=`homepage`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() OR', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.template`=`homepage` OR `abe_meta.template`=`article`', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(2);
  });
  it('Sql.executeWhereClause() IN', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.template` IN (`homepage`,`test`)', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });
  it('Sql.executeWhereClause() NOT IN', function() {
    var request = Sql.handleSqlRequest('select title from ./ where `abe_meta.template` NOT IN (`homepage`,`test`)', {})
    var res = Sql.executeWhereClause(Manager.instance.getList(), request.where, request.limit, request.columns, {})
    chai.expect(res).to.have.length(1);
  });

  /**
   * Sql.whereLike
   *
   */
  it('Sql.getSourceType()', function() {
    chai.expect(Sql.getSourceType('http://google.com')).to.equal('url');
    chai.expect(Sql.getSourceType('select * from test')).to.equal('request');
    chai.expect(Sql.getSourceType('{"test":"test"}')).to.equal('value');
    chai.expect(Sql.getSourceType('references.json')).to.equal('file');
    chai.expect(Sql.getSourceType('test')).to.equal('other');
  });

  /**
   * Sql.requestList
   *
   */
  it('Sql.requestList()', function(done) {
    let util = new Util()
    var matches = util.dataRequest(this.fixture.tag)

    chai.expect(matches[0][0]).to.not.be.null

    var attributes = Util.getAllAttributes(matches[0][0], {})
    chai.expect(matches[0][0]).to.not.be.null

    var jsonPage = {}
    Util.requestList(attributes, '', matches[0][0], jsonPage)
      .then(function () {
        chai.expect(jsonPage.abe_source).to.not.be.undefined
        done()
      })
  });
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  refines: 'foam.blob.Buffer',

  javaImports: [
    'java.nio.ByteBuffer'
  ],

  methods: [
    {
      name: 'slice',
      javaReturns: 'foam.blob.Buffer',
      args: [
        {
          name: 'start',
          javaType: 'long'
        },
        {
          name: 'end',
          javaType: 'long'
        }
      ],
      javaCode: 'return new Buffer(end - start, ByteBuffer.wrap(getData().array(), (int) start, (int) (end - start)));'
    }
  ]
});

foam.INTERFACE({
  refines: 'foam.blob.Blob',

  methods: [
    {
      name: 'read',
      javaReturns: 'foam.blob.Buffer',
      args: [
        {
          name: 'buffer',
          javaType: 'foam.blob.Buffer'
        },
        {
          name: 'offset',
          javaType: 'long'
        }
      ]
    },
    {
      name: 'getSize',
      javaReturns: 'long'
    }
  ]
});

foam.INTERFACE({
  refines: 'foam.blob.BlobService',

  methods: [
    {
      name: 'put',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'put_',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'find',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'id',
          javaType: 'Object'
        }
      ]
    },
    {
      name: 'find_',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'id',
          javaType: 'Object'
        }
      ]
    },
    {
      name: 'urlFor',
      javaReturns: 'String',
      args: [
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'urlFor_',
      javaReturns: 'String',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.AbstractBlob',

  methods: [
    {
      name: 'pipe',
      javaCode: 'return;'
    },
    {
      name: 'slice',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'offset',
          javaType: 'long'
        },
        {
          name: 'length',
          javaType: 'long'
        }
      ],
      javaCode: 'return new SubBlob(this, offset, length);'
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.AbstractBlobService',

  methods: [
    {
      name: 'put',
      javaCode: 'return this.put_(getX(), blob);'
    },
    {
      name: 'find',
      javaCode: 'return this.find_(getX(), id);'
    },
    {
      name: 'urlFor',
      javaCode: 'return this.urlFor_(getX(), blob);'
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.SubBlob',

  methods: [
    {
      name: 'read',
      javaCode:
`if ( buffer.getLength() > getSize() - offset ) {
  buffer = buffer.slice(0, getSize() - offset);
}

return getParent().read(buffer, offset + getOffset());`
    },
    {
      name: 'slice',
      javaCode: 'return new SubBlob(getParent(), getOffset() + offset, length);'
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.BlobStore',

  javaImports: [
    'foam.core.X',
    'org.apache.geronimo.mail.util.Hex',
    'java.io.File',
    'java.io.FileOutputStream',
    'java.nio.ByteBuffer',
    'java.security.MessageDigest'
  ],

  constants: [
    {
      name: 'BUFFER_SIZE',
      value: 8192,
      type: 'int'
    }
  ],

  properties: [
    { class: 'String', name: 'tmp', javaFactory: 'return getRoot() + File.separator + "tmp";' },
    { class: 'String', name: 'sha256', javaFactory: 'return getRoot() + File.separator + "sha256";' }
  ],

  methods: [
    {
      name: 'put_',
      javaCode:
`if ( blob instanceof IdentifiedBlob ) {
  return blob;
}

this.setup();

try {
  MessageDigest hash = MessageDigest.getInstance("SHA-256");
  Buffer buffer = new Buffer(BUFFER_SIZE, ByteBuffer.allocate(BUFFER_SIZE));

  long chunk = 0;
  long size = blob.getSize();
  long chunks = (long) Math.ceil((double) size / (double) BUFFER_SIZE);

  File tmp = allocateTmp(1);
  while ( chunk < chunks ) {
    buffer = blob.read(buffer, chunkOffset(chunk));
    byte[] buf = buffer.getData().array();
    hash.update(buf);
    FileOutputStream os = new FileOutputStream(tmp);
    os.write(buf, 0, buf.length);
    os.close();
    buffer.getData().clear();
    chunk++;
  }

  String digest = new String(Hex.encode(hash.digest()));
  File dest = new File(sha256_ + File.separator + digest);
  tmp.renameTo(dest);

  IdentifiedBlob result = new IdentifiedBlob();
  result.setId(digest);
  result.setX(getX());
  return result;
} catch (Throwable t) {
  t.printStackTrace();
  return null;
}`
    },
    {
      name: 'find_',
      javaCode:
`this.setup();
if ( ((String) id).indexOf(File.separatorChar) != -1 ) {
  throw new RuntimeException("Invalid file name");
}

File file = new File(getSha256() + File.separator + id);
if ( ! file.exists() ) {
  throw new RuntimeException("File does not exist");
}

if ( ! file.canRead() ) {
  throw new RuntimeException("Cannot read file");
}

return new FileBlob(file);`
    },
    {
      name: 'urlFor_',
      javaCode: 'throw new UnsupportedOperationException("Unsupported operation: urlFor_");'
    },
    {
      name: 'setup',
      javaReturns: 'void',
      javaCode:
`if ( this.getIsSet() )
  return;
ensureDir(getRoot());
ensureDir(getTmp());
ensureDir(getSha256());
setIsSet(true);`
    },
    {
      name: 'ensureDir',
      javaReturns: 'void',
      args: [
        {
          name: 'path',
          javaType: 'String'
        }
      ],
      javaCode:
`File parsed = new File(path);
if ( parsed.exists() && parsed.isDirectory() ) {
  return;
}

if ( ! parsed.mkdirs() ) {
  throw new RuntimeException("Failed to create: " + path);
}`
    },
    {
      name: 'allocateTmp',
      javaReturns: 'File',
      args: [
        {
          name: 'name',
          javaType: 'long'
        }
      ],
      javaCode:
`String path = this.tmp_ + File.separator + (name++);
File file = new File(path);
if ( file.exists() ) {
  return allocateTmp(name);
}
return file;`
    },
    {
      name: 'chunkOffset',
      javaReturns: 'long',
      args: [
        {
          name: 'i',
          javaType: 'long'
        }
      ],
      javaCode: 'return i * BUFFER_SIZE;'
    }
  ]
});
<commit_msg>Added try catch to find_ function for BlobStore<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  refines: 'foam.blob.Buffer',

  javaImports: [
    'java.nio.ByteBuffer'
  ],

  methods: [
    {
      name: 'slice',
      javaReturns: 'foam.blob.Buffer',
      args: [
        {
          name: 'start',
          javaType: 'long'
        },
        {
          name: 'end',
          javaType: 'long'
        }
      ],
      javaCode: 'return new Buffer(end - start, ByteBuffer.wrap(getData().array(), (int) start, (int) (end - start)));'
    }
  ]
});

foam.INTERFACE({
  refines: 'foam.blob.Blob',

  methods: [
    {
      name: 'read',
      javaReturns: 'foam.blob.Buffer',
      args: [
        {
          name: 'buffer',
          javaType: 'foam.blob.Buffer'
        },
        {
          name: 'offset',
          javaType: 'long'
        }
      ]
    },
    {
      name: 'getSize',
      javaReturns: 'long'
    }
  ]
});

foam.INTERFACE({
  refines: 'foam.blob.BlobService',

  methods: [
    {
      name: 'put',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'put_',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'find',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'id',
          javaType: 'Object'
        }
      ]
    },
    {
      name: 'find_',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'id',
          javaType: 'Object'
        }
      ]
    },
    {
      name: 'urlFor',
      javaReturns: 'String',
      args: [
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    },
    {
      name: 'urlFor_',
      javaReturns: 'String',
      args: [
        {
          name: 'x',
          javaType: 'foam.core.X'
        },
        {
          name: 'blob',
          javaType: 'foam.blob.Blob'
        }
      ]
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.AbstractBlob',

  methods: [
    {
      name: 'pipe',
      javaCode: 'return;'
    },
    {
      name: 'slice',
      javaReturns: 'foam.blob.Blob',
      args: [
        {
          name: 'offset',
          javaType: 'long'
        },
        {
          name: 'length',
          javaType: 'long'
        }
      ],
      javaCode: 'return new SubBlob(this, offset, length);'
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.AbstractBlobService',

  methods: [
    {
      name: 'put',
      javaCode: 'return this.put_(getX(), blob);'
    },
    {
      name: 'find',
      javaCode: 'return this.find_(getX(), id);'
    },
    {
      name: 'urlFor',
      javaCode: 'return this.urlFor_(getX(), blob);'
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.SubBlob',

  methods: [
    {
      name: 'read',
      javaCode:
`if ( buffer.getLength() > getSize() - offset ) {
  buffer = buffer.slice(0, getSize() - offset);
}

return getParent().read(buffer, offset + getOffset());`
    },
    {
      name: 'slice',
      javaCode: 'return new SubBlob(getParent(), getOffset() + offset, length);'
    }
  ]
});

foam.CLASS({
  refines: 'foam.blob.BlobStore',

  javaImports: [
    'foam.core.X',
    'org.apache.geronimo.mail.util.Hex',
    'java.io.File',
    'java.io.FileOutputStream',
    'java.nio.ByteBuffer',
    'java.security.MessageDigest'
  ],

  constants: [
    {
      name: 'BUFFER_SIZE',
      value: 8192,
      type: 'int'
    }
  ],

  properties: [
    { class: 'String', name: 'tmp', javaFactory: 'return getRoot() + File.separator + "tmp";' },
    { class: 'String', name: 'sha256', javaFactory: 'return getRoot() + File.separator + "sha256";' }
  ],

  methods: [
    {
      name: 'put_',
      javaCode:
`if ( blob instanceof IdentifiedBlob ) {
  return blob;
}

this.setup();

try {
  MessageDigest hash = MessageDigest.getInstance("SHA-256");
  Buffer buffer = new Buffer(BUFFER_SIZE, ByteBuffer.allocate(BUFFER_SIZE));

  long chunk = 0;
  long size = blob.getSize();
  long chunks = (long) Math.ceil((double) size / (double) BUFFER_SIZE);

  File tmp = allocateTmp(1);
  while ( chunk < chunks ) {
    buffer = blob.read(buffer, chunkOffset(chunk));
    byte[] buf = buffer.getData().array();
    hash.update(buf);
    FileOutputStream os = new FileOutputStream(tmp);
    os.write(buf, 0, buf.length);
    os.close();
    buffer.getData().clear();
    chunk++;
  }

  String digest = new String(Hex.encode(hash.digest()));
  File dest = new File(sha256_ + File.separator + digest);
  tmp.renameTo(dest);

  IdentifiedBlob result = new IdentifiedBlob();
  result.setId(digest);
  result.setX(getX());
  return result;
} catch (Throwable t) {
  t.printStackTrace();
  return null;
}`
    },
    {
      name: 'find_',
      javaCode:
`try {
  this.setup();
  if ( ((String) id).indexOf(File.separatorChar) != -1 ) {
    throw new RuntimeException("Invalid file name");
  }

  File file = new File(getSha256() + File.separator + id);
  if ( ! file.exists() ) {
    throw new RuntimeException("File does not exist");
  }

  if ( ! file.canRead() ) {
    throw new RuntimeException("Cannot read file");
  }

  return new FileBlob(file);
} catch (Throwable t) {
  throw new RuntimeException(t);
}`
    },
    {
      name: 'urlFor_',
      javaCode: 'throw new UnsupportedOperationException("Unsupported operation: urlFor_");'
    },
    {
      name: 'setup',
      javaReturns: 'void',
      javaCode:
`if ( this.getIsSet() )
  return;
ensureDir(getRoot());
ensureDir(getTmp());
ensureDir(getSha256());
setIsSet(true);`
    },
    {
      name: 'ensureDir',
      javaReturns: 'void',
      args: [
        {
          name: 'path',
          javaType: 'String'
        }
      ],
      javaCode:
`File parsed = new File(path);
if ( parsed.exists() && parsed.isDirectory() ) {
  return;
}

if ( ! parsed.mkdirs() ) {
  throw new RuntimeException("Failed to create: " + path);
}`
    },
    {
      name: 'allocateTmp',
      javaReturns: 'File',
      args: [
        {
          name: 'name',
          javaType: 'long'
        }
      ],
      javaCode:
`String path = this.tmp_ + File.separator + (name++);
File file = new File(path);
if ( file.exists() ) {
  return allocateTmp(name);
}
return file;`
    },
    {
      name: 'chunkOffset',
      javaReturns: 'long',
      args: [
        {
          name: 'i',
          javaType: 'long'
        }
      ],
      javaCode: 'return i * BUFFER_SIZE;'
    }
  ]
});
<|endoftext|>


<commit_before>"use strict";

var jadiTest = require("jaidTest").jadiTest();

jadiTest.declareBeans({
	id : "jadiUtils",
	path : "./jadiTest@SomeTest"
});

jadiTest.run({
	path : "./jadiTest@SomeTest",
	args : ["path:jadi.utils","strs"],
	property : {
		utils : "path:jadi.utils",
		str : "someStr",
		id : "id:jadiUtils"
	},
	init : "initMethod",
	scope : "p",
	test : {
		suite : "Bean definition test suite",
		injectMethods : {
			testJadiTestParameterPassing : ["path:jadi.utils"]
		}
	}
},{
	path : "./jadiTest@This",
	extend:{
		path : "./jadiTest@Super"
	},
	test : {
		suite : "Bean definition test suite"
	}
},{
	beanFactoryAware : true,
	path : "./jadiTestBean@",
	test : {
		suite : "Bean definition test suite",
		injectMethods : {
			testBeanFactoryAwareBeanRetrival : ["id:jadiUtils"]
		}
	}
});<commit_msg>fix test plugin<commit_after>"use strict";
var jadiInstance = require("./../src/nodePlugIn.js").newInstance();
var jadiTest = require("jadiTest").jadiTest(jadiInstance);

jadiTest.declareBeans({
	id : "jadiUtils",
	path : "./jadiTest@SomeTest"
});

jadiTest.run({
	path : "./jadiTest@SomeTest",
	args : [ "path:jadi.utils", "strs" ],
	property : {
		utils : "path:jadi.utils",
		str : "someStr",
		id : "id:jadiUtils"
	},
	init : "initMethod",
	scope : "p",
	test : {
		suite : "Bean definition test suite",
		injectMethods : {
			testJadiTestParameterPassing : [ "path:jadi.utils" ]
		}
	}
}, {
	path : "./jadiTest@This",
	extend : {
		path : "./jadiTest@Super"
	},
	test : {
		suite : "Bean definition test suite"
	}
}, {
	beanFactoryAware : true,
	path : "./jadiTestBean@",
	test : {
		suite : "Bean definition test suite",
		injectMethods : {
			testBeanFactoryAwareBeanRetrival : [ "id:jadiUtils" ]
		}
	}
});<|endoftext|>


<commit_before>foam.CLASS({
  package: 'foam.u2.mcw',
  name: 'Button',
  extends: 'foam.u2.ActionView',

  properties: [
    {
      name: 'ripple_',
      factory: function() { return new mdc.ripple.MDCRipple(this.el()); }
    },
    {
      class: 'Boolean',
      name: 'raised',
      value: true
    },
    {
      class: 'Boolean',
      name: 'primary',
      value: false
    }
  ],

  methods: [
    function initE() {
      this.
        attrs({type: 'button', "data-mdc-auto-init": 'MDCRipple'}).
        SUPER();
    },

    function load() {
      this.SUPER();
      this.ripple_.foundation_.init();
    },

    function initCls() {
      this.cssClass('mdc-button');
      if ( this.raised ) this.cssClass('mdc-button--raised');
      if ( this.primary ) this.cssClass('mdc-button--primary');
    }
  ]
});
<commit_msg>Removed redundant attribute from Button.<commit_after>foam.CLASS({
  package: 'foam.u2.mcw',
  name: 'Button',
  extends: 'foam.u2.ActionView',

  properties: [
    {
      name: 'ripple_',
      factory: function() { return new mdc.ripple.MDCRipple(this.el()); }
    },
    {
      class: 'Boolean',
      name: 'raised',
      value: true
    },
    {
      class: 'Boolean',
      name: 'primary',
      value: false
    }
  ],

  methods: [
    function initE() {
      this.attrs({type: 'button'}).SUPER();
    },

    function load() {
      this.SUPER();
      this.ripple_.foundation_.init();
    },

    function initCls() {
      this.cssClass('mdc-button');
      if ( this.raised  ) this.cssClass('mdc-button--raised');
      if ( this.primary ) this.cssClass('mdc-button--primary');
    }
  ]
});
<|endoftext|>


<commit_before>import '../Forms.vue'

export default {
  props: {
    clearButton: {type: Boolean, default: false},
    cols: {type: Number, default: null},
    disabled: {type: Boolean, default: false},
    help: {type: String, default: null},
    error: {type: String, default: null},
    icon: {type: Boolean, default: false},
    label: {type: String, default: null},
    state: {type: String, default: null},
    name: {type: String, default: null},
    placeholder: {type: String, default: null},
    readonly: {type: Boolean, default: false},
    rows: {type: Number, default: 3},
    type: {type: String, default: 'text'},
    value: {default: null},
    formType: {type: String, default: null},
    horizontalWrapper: {type: String, default: 'col-sm-9'},
    horizontalLabelWrapper: {type: String, default: 'col-sm-3'}
  },
  data () {
    return {
      inState: this.state,
      inFormType: this.formType,
      constants: {
        SUCCESS: {name: 'success', icon: 'check'},
        WARNING: {name: 'warning', icon: 'exclamation'},
        ERROR: {name: 'error', icon: 'times'}
      }
    }
  },
  computed: {
    input () { return this.$refs.input },
    showError () { return this.error },
    showHelp () { return this.help && (!this.showError) },
    title () { return this.error || this.help || '' },
    showState () { return this.inState ? `has-${this.inState}` : '' },
    labelFeedback () { return this.$slots['label'] || this.label },
    showIcon () { return this.inState ? this.constants[this.inState.toUpperCase()].icon : null }
  },
  watch: {
    error: this.setState,
    value (val) {
      this.bindChanges(val)
    }
  },
  methods: {
    setState (val) {
      if (val !== null) {
        this.inState = val ? this.constants.ERROR.name : this.constants.SUCCESS.name
      }
    },
    attr (value) {
      return ~['', null, undefined].indexOf(value) || value instanceof Function ? null : value
    },
    emit (e) {
      this.$emit(e.type, e.type === 'input' ? e.target.value : e)
    },
    bindInput (e) {
      this.bindChanges(e.type === 'input' ? e.target.value : e, e.type)
    },
    bindChanges (value, ev = 'input') {
      this.input.value = value
      this.$emit(ev, value)
    },
    focus () {
      this.input.focus()
    },
    reset () {
      this.bindChanges('')
    },
    wrapperClass () {
      let wClass

      switch (this.inFormType) {
        case 'group':
          wClass = 'input-group'
          break;
        case 'inline':
          wClass = 'relative inline'
          break;
        case 'horizontal':
          wClass = this.horizontalWrapper
          break;
        default:
          wClass = 'relative'
      }

      return wClass
    },
    labelClass () {
      return this.inFormType === "horizontal" ? this.horizontalLabelWrapper : null;
    }
  },
  mounted () {
    const group = typeof this.$slots.before === 'object' || typeof this.$slots.after === 'object'

    this.inFormType = group ? 'group' : this.formType
    this.setState(this.error)
  },
  beforeDestroy () {
    if (this._parent) {
      let index = this._parent.children.indexOf(this)
      this._parent.children.splice(index, 1)
    }
  }
}
<commit_msg>input bug<commit_after>import '../Forms.vue'

export default {
  props: {
    clearButton: {type: Boolean, default: false},
    cols: {type: Number, default: null},
    disabled: {type: Boolean, default: false},
    help: {type: String, default: null},
    error: {type: String, default: null},
    icon: {type: Boolean, default: false},
    label: {type: String, default: null},
    state: {type: String, default: null},
    name: {type: String, default: null},
    placeholder: {type: String, default: null},
    readonly: {type: Boolean, default: false},
    rows: {type: Number, default: 3},
    type: {type: String, default: 'text'},
    value: {default: null},
    formType: {type: String, default: null},
    horizontalWrapper: {type: String, default: 'col-sm-9'},
    horizontalLabelWrapper: {type: String, default: 'col-sm-3'}
  },
  data () {
    return {
      inState: null,
      inFormType: this.formType,
      constants: {
        SUCCESS: {name: 'success', icon: 'check'},
        WARNING: {name: 'warning', icon: 'exclamation'},
        ERROR: {name: 'error', icon: 'times'}
      }
    }
  },
  computed: {
    input () { return this.$refs.input },
    showError () { return this.error },
    showHelp () { return this.help && (!this.showError) },
    title () { return this.error || this.help || '' },
    showState () { return this.inState ? `has-${this.inState}` : '' },
    labelFeedback () { return this.$slots['label'] || this.label },
    showIcon () { return this.inState ? this.constants[this.inState.toUpperCase()].icon : null }
  },
  watch: {
    error (val) {
      this.setState(val)
    },
    value (val) {
      this.bindChanges(val)
    }
  },
  methods: {
    setState (val) {
      this.inState = val ? this.constants.ERROR.name : this.constants.SUCCESS.name
    },
    attr (value) {
      return ~['', null, undefined].indexOf(value) || value instanceof Function ? null : value
    },
    emit (e) {
      this.$emit(e.type, e.type === 'input' ? e.target.value : e)
    },
    bindInput (e) {
      this.bindChanges(e.type === 'input' ? e.target.value : e, e.type)
    },
    bindChanges (value, ev = 'input') {
      this.input.value = value
      this.$emit(ev, value)
    },
    focus () {
      this.input.focus()
    },
    reset () {
      this.bindChanges('')
    },
    wrapperClass () {
      let wClass

      switch (this.inFormType) {
        case 'group':
          wClass = 'input-group'
          break;
        case 'inline':
          wClass = 'relative inline'
          break;
        case 'horizontal':
          wClass = this.horizontalWrapper
          break;
        default:
          wClass = 'relative'
      }

      return wClass
    },
    labelClass () {
      return this.inFormType === "horizontal" ? this.horizontalLabelWrapper : null;
    }
  },
  mounted () {
    const group = typeof this.$slots.before === 'object' || typeof this.$slots.after === 'object'

    this.inFormType = group ? 'group' : this.formType

    if (this.error) {
      this.setState(this.error)
    }
  },
  beforeDestroy () {
    if (this._parent) {
      let index = this._parent.children.indexOf(this)
      this._parent.children.splice(index, 1)
    }
  }
}
<|endoftext|>


<commit_before>/*global pubfood*/
/*eslint no-unused-vars: 0*/

var Rx = pubfood.library.Rx;

function X(x) {
  console.log('This is the callback: ' + x + ' : ' + +new Date());
  return true;
}

var lib = {
  exists: function(name, cb) {
    if (name) {
      cb(name);
    }
    return true;
  }
};

function requestBids(params, timeout, fn) {
  console.log('requestBids: ' + params + ' : ' + timeout + ' : Start: ' + +new Date());
  setTimeout(function() {
    return fn(params);
  }, timeout);
}

function request200(params, fn) {
  setTimeout(function() {
    return fn(params);
  }, 200);
}

function request500(params, fn) {
  setTimeout(function() {
    return fn(params);
  }, 500);
}

function request1000(params, fn) {
  setTimeout(function() {
    return fn(params);
  }, 1000);
}

Rx.config.useNativeEvents = true;

var bidder1 = Rx.Observable.create(function(observer) {
  setTimeout(function() {
    observer.onNext(42);
    observer.onCompleted();
    return function() {
      console.log('disposed');
    };
  }, 100);
});

var scheduler = Rx.Scheduler.default;

var getBids1000 = Rx.Observable.fromCallback(requestBids),
  getBids500 = Rx.Observable.fromCallback(requestBids),
  getBids200 = Rx.Observable.fromCallback(requestBids);

var getBids = Rx.Observable.concat(
  getBids1000('provider=amz&bid=1000', 1000),
  getBids500('provider=crit&bid=500', 500),
  getBids200('provider=yb&bid=200', 200)).toArray().timeout(1200, new Error('Timeout has occurred.'));

var mediator = Rx.Observable.timer;

var observer1 = Rx.Observer.create(
  function(x) {
    console.log('Observer1 Next:');
    console.log('Observer1 This is the callback: ' + x + ' : ' + +new Date());
  },
  function(err) {
    console.log('Observer1 Error: ' + err);
  },
  function() {
    console.log('Observer1 Completed');
  }
);

var observer2 = Rx.Observer.create(
  function(x) {
    console.log('Observer2 Next:');
    console.log('Observer2 This is the callback: ' + x + ' : ' + +new Date());
  },
  function(err) {
    console.log('Observer2 Error: ' + err);
  },
  function() {
    console.log('Observer2 Completed');
  }
);

var observer3 = Rx.Observer.create(
  function(x) {
    console.log('Observer3 Next:');
    console.log('Observer3 This is the callback: ' + x + ' : ' + +new Date());
  },
  function(err) {
    console.log('Observer3 Error: ' + err);
  },
  function() {
    console.log('Observer3 Completed');
  }
);

var sub2 = bidder1.subscribe(
  function(x) {
    console.log('Bidder1 Next: %s', x);
  },
  function(err) {
    console.log('Bidder1 Error: %s', err);
  },
  function() {
    console.log('Bidder1 Completed');
  }
);

var subscription1 = getBids.subscribe(observer1);
var subscription2 = getBids.subscribe(observer2);
var subscription3 = getBids.subscribe(observer3);

var fnObserver = Rx.Observable.create(function() {
  var intervalID = setInterval(function() {
    console.log('doing stuff');
  }, 100);
  setTimeout(function() {
    var done = Rx.Notification.createOnCompleted();
    done.accept(fnSubscription);
    clearInterval(intervalID);
    return true;
  }, 5000);
});

var fnSubscription = fnObserver.subscribe(
  function(x) {
    console.log('Next:');
    console.log('This is the callback: ' + x + ' : ' + +new Date());
  },
  function(err) {
    console.log('Error: ' + err);
  },
  function() {
    console.log('fnObserver Completed');
  });

function IFoo() {
}

IFoo.prototype = {
  hello: function() {

  },
  goodbye: function() {
    console.log('goodbye');
  }
};

var doFoo = new IFoo();

IFoo.prototype.hello = function() {
  console.log('hello bar');

};

IFoo.prototype.goodbye = function() {
  console.log('bar');
};

var doBar = new IFoo();<commit_msg>disable linting on rxtests.js<commit_after>/*global pubfood*/
/*eslint-disable */

var Rx = pubfood.library.Rx;

function X(x) {
  console.log('This is the callback: ' + x + ' : ' + +new Date());
  return true;
}

var lib = {
  exists: function(name, cb) {
    if (name) {
      cb(name);
    }
    return true;
  }
};

function requestBids(params, timeout, fn) {
  console.log('requestBids: ' + params + ' : ' + timeout + ' : Start: ' + +new Date());
  setTimeout(function() {
    return fn(params);
  }, timeout);
}

function request200(params, fn) {
  setTimeout(function() {
    return fn(params);
  }, 200);
}

function request500(params, fn) {
  setTimeout(function() {
    return fn(params);
  }, 500);
}

function request1000(params, fn) {
  setTimeout(function() {
    return fn(params);
  }, 1000);
}

Rx.config.useNativeEvents = true;

var bidder1 = Rx.Observable.create(function(observer) {
  setTimeout(function() {
    observer.onNext(42);
    observer.onCompleted();
    return function() {
      console.log('disposed');
    };
  }, 100);
});

var scheduler = Rx.Scheduler.default;

var getBids1000 = Rx.Observable.fromCallback(requestBids),
  getBids500 = Rx.Observable.fromCallback(requestBids),
  getBids200 = Rx.Observable.fromCallback(requestBids);

var getBids = Rx.Observable.concat(
  getBids1000('provider=amz&bid=1000', 1000),
  getBids500('provider=crit&bid=500', 500),
  getBids200('provider=yb&bid=200', 200)).toArray().timeout(1200, new Error('Timeout has occurred.'));

var mediator = Rx.Observable.timer;

var observer1 = Rx.Observer.create(
  function(x) {
    console.log('Observer1 Next:');
    console.log('Observer1 This is the callback: ' + x + ' : ' + +new Date());
  },
  function(err) {
    console.log('Observer1 Error: ' + err);
  },
  function() {
    console.log('Observer1 Completed');
  }
);

var observer2 = Rx.Observer.create(
  function(x) {
    console.log('Observer2 Next:');
    console.log('Observer2 This is the callback: ' + x + ' : ' + +new Date());
  },
  function(err) {
    console.log('Observer2 Error: ' + err);
  },
  function() {
    console.log('Observer2 Completed');
  }
);

var observer3 = Rx.Observer.create(
  function(x) {
    console.log('Observer3 Next:');
    console.log('Observer3 This is the callback: ' + x + ' : ' + +new Date());
  },
  function(err) {
    console.log('Observer3 Error: ' + err);
  },
  function() {
    console.log('Observer3 Completed');
  }
);

var sub2 = bidder1.subscribe(
  function(x) {
    console.log('Bidder1 Next: %s', x);
  },
  function(err) {
    console.log('Bidder1 Error: %s', err);
  },
  function() {
    console.log('Bidder1 Completed');
  }
);

var subscription1 = getBids.subscribe(observer1);
var subscription2 = getBids.subscribe(observer2);
var subscription3 = getBids.subscribe(observer3);

var fnObserver = Rx.Observable.create(function() {
  var intervalID = setInterval(function() {
    console.log('doing stuff');
  }, 100);
  setTimeout(function() {
    var done = Rx.Notification.createOnCompleted();
    done.accept(fnSubscription);
    clearInterval(intervalID);
    return true;
  }, 5000);
});

var fnSubscription = fnObserver.subscribe(
  function(x) {
    console.log('Next:');
    console.log('This is the callback: ' + x + ' : ' + +new Date());
  },
  function(err) {
    console.log('Error: ' + err);
  },
  function() {
    console.log('fnObserver Completed');
  });

function IFoo() {
}

IFoo.prototype = {
  hello: function() {

  },
  goodbye: function() {
    console.log('goodbye');
  }
};

var doFoo = new IFoo();

IFoo.prototype.hello = function() {
  console.log('hello bar');

};

IFoo.prototype.goodbye = function() {
  console.log('bar');
};

var doBar = new IFoo();<|endoftext|>


<commit_before>import { FontAwesome, MaterialCommunityIcons, MaterialIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { Button, useTheme } from '@ui-kitten/components';
import * as Linking from 'expo-linking';
import * as Location from 'expo-location';
import propTypes from 'prop-types';
import React from 'react';
import { Alert, AppState, Platform, StyleSheet, useWindowDimensions, View } from 'react-native';
import MapView, { PROVIDER_GOOGLE, UrlTile } from 'react-native-maps';
import useAuth from '../auth/context';
import config from '../config';
import RootView from '../RootView';
import { wrapAsyncWithDelay } from '../utilities';

const MapButton = ({ IconComponent, iconName, onPress, style, showAlert }) => {
  const theme = useTheme();
  const iconSize = 30;
  const alertSize = 12;
  const ButtonIcon = () => (
    <View style={{ height: iconSize, width: iconSize, justifyContent: 'center', alignItems: 'center' }}>
      <IconComponent name={iconName} color="white" size={iconSize} />
      {showAlert ? (
        <FontAwesome name="circle" size={alertSize} style={styles.alertIcon} color={theme['color-warning-500']} />
      ) : null}
    </View>
  );

  return <Button accessoryLeft={ButtonIcon} style={style} size="tiny" onPress={onPress} />;
};
MapButton.propTypes = {
  IconComponent: propTypes.func.isRequired,
  iconName: propTypes.string.isRequired,
  onPress: propTypes.func.isRequired,
  style: propTypes.object,
  showAlert: propTypes.bool,
};

const locationToRegion = function (location) {
  return {
    latitude: location.coords.latitude,
    longitude: location.coords.longitude,
    latitudeDelta: 0.1,
    longitudeDelta: 0.05,
  };
};

export default function MainScreen() {
  const navigation = useNavigation();
  const [initialLocation, setInitialLocation] = React.useState(null);
  const appState = React.useRef(AppState.currentState);
  const [showSpinner, setShowSpinner] = React.useState(false);
  const mapView = React.useRef(null);
  const { authInfo } = useAuth();
  const [hasUnsubmittedReports, setHasUnsubmittedReports] = React.useState(false);

  const getLocation = async () => {
    let location;
    try {
      location = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.Low,
      });
    } catch (error) {
      console.log(`getCurrentPositionAsync: ${error}`);

      location = await Location.getLastKnownPositionAsync({
        accuracy: Location.Accuracy.Low,
      });
    }

    return location;
  };

  React.useEffect(() => {
    const initLocation = async () => {
      const result = await Location.requestForegroundPermissionsAsync();
      if (result.status !== 'granted') {
        Alert.alert('Error', 'Location permission are required to submit reports.', [
          { text: 'OK', onPress: () => Linking.openSettings() },
        ]);

        return;
      }

      const location = await getLocation();

      setInitialLocation(location);
    };

    const handleAppStateChange = async (nextAppState) => {
      if (appState.current.match(/inactive|background/) && nextAppState === 'active' && !initialLocation) {
        await wrapAsyncWithDelay(
          initLocation,
          () => setShowSpinner(true),
          () => setShowSpinner(false),
          config.SPINNER_DELAY
        );
      }

      appState.current = nextAppState;
    };

    AppState.addEventListener('change', handleAppStateChange);

    wrapAsyncWithDelay(
      initLocation,
      () => setShowSpinner(true),
      () => setShowSpinner(false),
      config.SPINNER_DELAY
    );

    return () => AppState.removeEventListener('change', handleAppStateChange);
  }, []);

  const zoomToCurrentLocation = async () => {
    const location = await getLocation();

    mapView.current.animateCamera({
      center: {
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
      },
    });
  };
  const showAddReport = () => {
    console.log('showAddReport');
    setHasUnsubmittedReports(!hasUnsubmittedReports);
  };
  const showAddRoute = () => {
    console.log('showAddRoute');
  };

  const { height, width } = useWindowDimensions();
  const ZOOM_FACTOR = 1.3;
  const mapSizeStyle = {
    ...Platform.select({
      ios: {
        height,
        width,
      },
      android: {
        // the cache tiles look super-pixelated on android, this is a hack to help them look better
        height: height * ZOOM_FACTOR,
        width: width * ZOOM_FACTOR,
        marginTop: -(height * ZOOM_FACTOR - height) / 2,
        marginLeft: -(width * ZOOM_FACTOR - width) / 2,
        transform: [{ scale: 1 / ZOOM_FACTOR }],
      },
    }),
  };

  return (
    <RootView showSpinner={showSpinner} spinnerMessage="getting current location" style={styles.root}>
      {initialLocation ? (
        <MapView
          edgePadding={{
            bottom: 20,
            left: 0,
            right: 0,
            top: 20,
          }}
          initialRegion={locationToRegion(initialLocation)}
          mapType="none"
          maxZoomLevel={18}
          minZoomLevel={5}
          pitchEnabled={false}
          provider={PROVIDER_GOOGLE}
          ref={mapView}
          rotateEnabled={false}
          showsMyLocationButton={false}
          showsUserLocation={true}
          style={[styles.map, mapSizeStyle]}
        >
          <UrlTile urlTemplate={config.URLS.LITE} shouldReplaceMapContent={true} minimumZ={3} zIndex={-1} />
        </MapView>
      ) : null}
      <View style={styles.controlContainer}>
        <View>
          <MapButton
            IconComponent={MaterialCommunityIcons}
            iconName="menu"
            onPress={navigation.openDrawer}
            showAlert={hasUnsubmittedReports}
          />
        </View>
        <View>
          <MapButton IconComponent={MaterialIcons} iconName="my-location" onPress={zoomToCurrentLocation} />
        </View>
      </View>
      <View style={styles.controlContainer}>
        <View></View>
        <View style={styles.bottomContainer}>
          {authInfo.user.role === config.USER_TYPES.public ? null : (
            <MapButton
              IconComponent={MaterialIcons}
              iconName="drive-eta"
              onPress={showAddRoute}
              style={styles.topButton}
            />
          )}
          <MapButton IconComponent={MaterialIcons} iconName="add-circle" onPress={showAddReport} />
        </View>
      </View>
    </RootView>
  );
}

MainScreen.propTypes = {
  navigation: propTypes.object,
};

const MAP_PADDING = 20;
const styles = StyleSheet.create({
  root: {
    justifyContent: 'space-between',
  },
  map: {
    position: 'absolute',
    top: 0,
  },
  controlContainer: {
    paddingHorizontal: MAP_PADDING,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  bottomContainer: {
    paddingBottom: Platform.select({ android: MAP_PADDING }),
  },
  topButton: {
    marginBottom: MAP_PADDING / 2,
  },
  alertIcon: {
    position: 'absolute',
    top: 0,
    right: 0,
  },
});
<commit_msg>fix(front): add map padding for ios devices<commit_after>import { FontAwesome, MaterialCommunityIcons, MaterialIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { Button, useTheme } from '@ui-kitten/components';
import * as Linking from 'expo-linking';
import * as Location from 'expo-location';
import propTypes from 'prop-types';
import React from 'react';
import { Alert, AppState, Platform, StyleSheet, useWindowDimensions, View } from 'react-native';
import MapView, { PROVIDER_GOOGLE, UrlTile } from 'react-native-maps';
import useAuth from '../auth/context';
import config from '../config';
import RootView from '../RootView';
import { wrapAsyncWithDelay } from '../utilities';

const MapButton = ({ IconComponent, iconName, onPress, style, showAlert }) => {
  const theme = useTheme();
  const iconSize = 30;
  const alertSize = 12;
  const ButtonIcon = () => (
    <View style={{ height: iconSize, width: iconSize, justifyContent: 'center', alignItems: 'center' }}>
      <IconComponent name={iconName} color="white" size={iconSize} />
      {showAlert ? (
        <FontAwesome name="circle" size={alertSize} style={styles.alertIcon} color={theme['color-warning-500']} />
      ) : null}
    </View>
  );

  return <Button accessoryLeft={ButtonIcon} style={style} size="tiny" onPress={onPress} />;
};
MapButton.propTypes = {
  IconComponent: propTypes.func.isRequired,
  iconName: propTypes.string.isRequired,
  onPress: propTypes.func.isRequired,
  style: propTypes.object,
  showAlert: propTypes.bool,
};

const locationToRegion = function (location) {
  return {
    latitude: location.coords.latitude,
    longitude: location.coords.longitude,
    latitudeDelta: 0.1,
    longitudeDelta: 0.05,
  };
};

export default function MainScreen() {
  const navigation = useNavigation();
  const [initialLocation, setInitialLocation] = React.useState(null);
  const appState = React.useRef(AppState.currentState);
  const [showSpinner, setShowSpinner] = React.useState(false);
  const mapView = React.useRef(null);
  const { authInfo } = useAuth();
  const [hasUnsubmittedReports, setHasUnsubmittedReports] = React.useState(false);

  const getLocation = async () => {
    let location;
    try {
      location = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.Low,
      });
    } catch (error) {
      console.log(`getCurrentPositionAsync: ${error}`);

      location = await Location.getLastKnownPositionAsync({
        accuracy: Location.Accuracy.Low,
      });
    }

    return location;
  };

  React.useEffect(() => {
    const initLocation = async () => {
      const result = await Location.requestForegroundPermissionsAsync();
      if (result.status !== 'granted') {
        Alert.alert('Error', 'Location permission are required to submit reports.', [
          { text: 'OK', onPress: () => Linking.openSettings() },
        ]);

        return;
      }

      const location = await getLocation();

      setInitialLocation(location);
    };

    const handleAppStateChange = async (nextAppState) => {
      if (appState.current.match(/inactive|background/) && nextAppState === 'active' && !initialLocation) {
        await wrapAsyncWithDelay(
          initLocation,
          () => setShowSpinner(true),
          () => setShowSpinner(false),
          config.SPINNER_DELAY
        );
      }

      appState.current = nextAppState;
    };

    AppState.addEventListener('change', handleAppStateChange);

    wrapAsyncWithDelay(
      initLocation,
      () => setShowSpinner(true),
      () => setShowSpinner(false),
      config.SPINNER_DELAY
    );

    return () => AppState.removeEventListener('change', handleAppStateChange);
  }, []);

  const zoomToCurrentLocation = async () => {
    const location = await getLocation();

    mapView.current.animateCamera({
      center: {
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
      },
    });
  };
  const showAddReport = () => {
    console.log('showAddReport');
    setHasUnsubmittedReports(!hasUnsubmittedReports);
  };
  const showAddRoute = () => {
    console.log('showAddRoute');
  };

  const { height, width } = useWindowDimensions();
  const ZOOM_FACTOR = 1.3;
  const mapSizeStyle = {
    ...Platform.select({
      ios: {
        height,
        width,
      },
      android: {
        // the cache tiles look super-pixelated on android, this is a hack to help them look better
        height: height * ZOOM_FACTOR,
        width: width * ZOOM_FACTOR,
        marginTop: -(height * ZOOM_FACTOR - height) / 2,
        marginLeft: -(width * ZOOM_FACTOR - width) / 2,
        transform: [{ scale: 1 / ZOOM_FACTOR }],
      },
    }),
  };

  return (
    <RootView showSpinner={showSpinner} spinnerMessage="getting current location" style={styles.root}>
      {initialLocation ? (
        <MapView
          edgePadding={{
            bottom: 20,
            left: 0,
            right: 0,
            top: 20,
          }}
          initialRegion={locationToRegion(initialLocation)}
          mapType="none"
          maxZoomLevel={18}
          minZoomLevel={5}
          pitchEnabled={false}
          provider={PROVIDER_GOOGLE}
          ref={mapView}
          rotateEnabled={false}
          showsMyLocationButton={false}
          showsUserLocation={true}
          style={[styles.map, mapSizeStyle]}
        >
          <UrlTile urlTemplate={config.URLS.LITE} shouldReplaceMapContent={true} minimumZ={3} zIndex={-1} />
        </MapView>
      ) : null}
      <View style={styles.controlContainer}>
        <View>
          <MapButton
            IconComponent={MaterialCommunityIcons}
            iconName="menu"
            onPress={navigation.openDrawer}
            showAlert={hasUnsubmittedReports}
          />
        </View>
        <View>
          <MapButton IconComponent={MaterialIcons} iconName="my-location" onPress={zoomToCurrentLocation} />
        </View>
      </View>
      <View style={styles.controlContainer}>
        <View></View>
        <View style={styles.bottomContainer}>
          {authInfo.user.role === config.USER_TYPES.public ? null : (
            <MapButton
              IconComponent={MaterialIcons}
              iconName="drive-eta"
              onPress={showAddRoute}
              style={styles.topButton}
            />
          )}
          <MapButton IconComponent={MaterialIcons} iconName="add-circle" onPress={showAddReport} />
        </View>
      </View>
    </RootView>
  );
}

MainScreen.propTypes = {
  navigation: propTypes.object,
};

const MAP_PADDING = 20;
const styles = StyleSheet.create({
  root: {
    justifyContent: 'space-between',
  },
  map: {
    position: 'absolute',
    top: 0,
  },
  controlContainer: {
    paddingHorizontal: MAP_PADDING,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  bottomContainer: {
    paddingBottom: MAP_PADDING,
  },
  topButton: {
    marginBottom: MAP_PADDING / 2,
  },
  alertIcon: {
    position: 'absolute',
    top: 0,
    right: 0,
  },
});
<|endoftext|>