'use strict'

var standard = require('standard')
var format = require('util').format
var loaderUtils = require('loader-utils')
var snazzy = require('snazzy')

module.exports = function standardLoader (text) {
  var self = this
  var callback = this.async()

  var config = loaderUtils.getOptions(this)

  this.cacheable()

  standard.lintText(text, config, function (err, result) {
    if (err) return callback(err, text)
    if (result.errorCount === 0) return callback(err, text)

    var warnings = result.results.reduce(function (items, result) {
      return items.concat(result.messages.map(function (message) {
        return format(
          '%s:%d:%d: %s%s',
          result.filePath, message.line || 0, message.column || 0, message.message,
          !config.verbose ? ' (' + message.ruleId + ')' : ''
        )
      }))
    }, [])
    .join('\n')

    if (config.snazzy !== false) {
      snazzy({encoding: 'utf8'})
      .on('data', function (data) {
        if (config.emitErrors) {
          self.emitError(data)
        } else {
          self.emitWarning(data)
        }
      })
      .end(warnings)
    } else {
      if (config.emitErrors) {
        self.emitError(warnings)
      } else {
        self.emitWarning(warnings)
      }
    }
    callback(err, text)
  })
}

'use strict'

var standard = require('standard')
var format = require('util').format
var loaderUtils = require('loader-utils')
var snazzy = require('snazzy')

module.exports = function standardLoader (text) {
  var self = this
  var callback = this.async()

  var config = loaderUtils.getOptions(this)

  config.filename = this.resourcePath
  this.cacheable()

  standard.lintText(text, config, function (err, result) {
    if (err) return callback(err, text)
    if (result.errorCount === 0) return callback(err, text)

    var warnings = result.results.reduce(function (items, result) {
      return items.concat(result.messages.map(function (message) {
        return format(
          '%s:%d:%d: %s%s',
          result.filePath, message.line || 0, message.column || 0, message.message,
          !config.verbose ? ' (' + message.ruleId + ')' : ''
        )
      }))
    }, [])
    .join('\n')

    if (config.snazzy !== false) {
      snazzy({encoding: 'utf8'})
      .on('data', function (data) {
        if (config.emitErrors) {
          self.emitError(data)
        } else {
          self.emitWarning(data)
        }
      })
      .end(warnings)
    } else {
      if (config.emitErrors) {
        self.emitError(warnings)
      } else {
        self.emitWarning(warnings)
      }
    }
    callback(err, text)
  })
}

Include filename in reported output.


'use strict';

const config = require('./config.json');
const fs = require('fs');

const http = require('http');
const https = require('https');

let httpsOptions = {
  key: fs.readFileSync(config.keyPath, 'ascii'),
  cert: fs.readFileSync(config.certPath, 'ascii'),
};

const koa = require('koa');
const enforceHttps = require('koa-sslify');

const app = koa();

// Force HTTPS on all page
app.use(enforceHttps());

app.use(function *() {
  this.body = 'Hello World';
});

// start the server
http.createServer(app.callback()).listen(80);
https.createServer(httpsOptions, app.callback()).listen(443);

'use strict';

const config = require('./config.json');
const fs = require('fs');

const http = require('http');
const https = require('https');

let httpsOptions = {
  key: fs.readFileSync(config.keyPath, 'ascii'),
  cert: fs.readFileSync(config.certPath, 'ascii'),
};

const koa = require('koa');
const enforceHttps = require('koa-sslify');

const app = koa();

// Force HTTPS on all page
app.use(enforceHttps());

app.use(function *() {
  this.body = 'Hello World!';
});

// start the server
http.createServer(app.callback()).listen(80);
https.createServer(httpsOptions, app.callback()).listen(443);

Add an ! to hello world


const {BABEL_ENV, NODE_ENV} = process.env

const defaultOptions = {
  lodash: true,
  modules: BABEL_ENV === 'cjs' || NODE_ENV === 'test' ? 'commonjs' : false,
  targets: {
    browsers: ['IE 11', 'last 2 Edge versions', 'Firefox >= 45', 'last 2 Chrome versions'],
    node: 8,
  },
}

module.exports = (context, userOptions) => {
  const options = Object.assign({}, defaultOptions, userOptions)

  const plugins = [
    // ensure that React is imported if JSX is used
    require('babel-plugin-react-require').default,
  ]

  if (options.lodash) plugins.push(require('babel-plugin-lodash'))

  const presets = [
    [require('@babel/preset-env'), {modules: options.modules, targets: options.targets}],
    [require('@babel/preset-stage-1'), {useBuiltIns: true}],
    [require('@babel/preset-react'), {useBuiltIns: true}],
  ]

  return {plugins, presets}
}

const {BABEL_ENV, NODE_ENV} = process.env

const defaultOptions = {
  lodash: true,
  loose: false,
  modules: BABEL_ENV === 'cjs' || NODE_ENV === 'test' ? 'commonjs' : false,
  targets: {
    browsers: ['IE 11', 'last 2 Edge versions', 'Firefox >= 45', 'last 2 Chrome versions'],
    node: 8,
  },
}

module.exports = (context, userOptions) => {
  const {lodash, loose, modules, targets} = Object.assign({}, defaultOptions, userOptions)

  const plugins = [require('babel-plugin-react-require').default]
  if (lodash) plugins.push(require('babel-plugin-lodash'))

  const presets = [
    [require('@babel/preset-env'), {loose, modules, targets}],
    [require('@babel/preset-stage-1'), {loose, useBuiltIns: true}],
    [require('@babel/preset-react'), {useBuiltIns: true}],
  ]

  return {plugins, presets}
}

Add option to enable loose mode


var server = require('json-server')

var port = process.env.PORT || 3000

function reset() {
  server.low.load('data.json')
}

server.low.autoSave = false
server.low.on('update', reset)
server.low.on('remove', reset)
server.low.on('add', reset)

server.listen(port, function() {
  console.log('JSONPlaceholder listening on http://localhost:' + port)
  reset()
})

var server = require('json-server')

var port = process.env.PORT || 3000

function reset() {
  server.low.load('data.json')
}

server.low.autoSave = false
server.low.on('change', reset)

server.listen(port, function() {
  console.log('JSONPlaceholder listening on http://localhost:' + port)
  reset()
})

Use lowdb on change event


'use strict';
const dargs = require('dargs');
const execa = require('execa');
const gutil = require('gulp-util');
const through = require('through2');

module.exports = opts => {
	opts = Object.assign({
		colors: true,
		suppress: false
	}, opts);

	if (Array.isArray(opts.globals)) {
		// `globals` option should end up as a comma-separated list
		opts.globals = opts.globals.join(',');
	}

	const args = dargs(opts, {
		excludes: ['suppress'],
		ignoreFalse: true
	});

	const files = [];

	function aggregate(file, encoding, done) {
		if (file.isNull()) {
			done(null, file);
			return;
		}

		if (file.isStream()) {
			done(new gutil.PluginError('gulp-mocha', 'Streaming not supported'));
			return;
		}

		files.push(file.path);

		done();
	}

	function flush(done) {
		execa('mocha', files.concat(args))
			.then(result => {
				if (!opts.suppress) {
					process.stdout.write(result.stdout);
				}

				// For testing
				this.emit('_result', result);

				done();
			})
			.catch(err => {
				this.emit('error', new gutil.PluginError('gulp-mocha', err));
				done();
			});
	}

	return through.obj(aggregate, flush);
};

'use strict';
const dargs = require('dargs');
const execa = require('execa');
const gutil = require('gulp-util');
const through = require('through2');

module.exports = opts => {
	opts = Object.assign({
		colors: true,
		suppress: false
	}, opts);

	if (Array.isArray(opts.globals)) {
		// `globals` option should end up as a comma-separated list
		opts.globals = opts.globals.join(',');
	}

	const args = dargs(opts, {
		excludes: ['suppress'],
		ignoreFalse: true
	});

	const files = [];

	function aggregate(file, encoding, done) {
		if (file.isStream()) {
			done(new gutil.PluginError('gulp-mocha', 'Streaming not supported'));
			return;
		}

		files.push(file.path);

		done();
	}

	function flush(done) {
		execa('mocha', files.concat(args))
			.then(result => {
				if (!opts.suppress) {
					process.stdout.write(result.stdout);
				}

				// For testing
				this.emit('_result', result);

				done();
			})
			.catch(err => {
				this.emit('error', new gutil.PluginError('gulp-mocha', err));
				done();
			});
	}

	return through.obj(aggregate, flush);
};

Remove moot empty file check


/* global L */
'use strict';
var gju = require('geojson-utils');

var leafletPip = {
    bassackwards: false,
    pointInLayer: function(p, layer, first) {
        if (p instanceof L.LatLng) p = [p.lng, p.lat];
        else if (leafletPip.bassackwards) p = p.concat().reverse();

        var results = [];

        layer.eachLayer(function(l) {
            if (first && results.length) return;
            if ((l instanceof L.MultiPolygon ||
                 l instanceof L.Polygon) &&
                gju.pointInPolygon({
                    type: 'Point',
                    coordinates: p
                }, l.toGeoJSON().geometry)) {
                results.push(l);
            }
        });
        return results;
    }
};

module.exports = leafletPip;

/* global L */
'use strict';
var gju = require('geojson-utils');

var leafletPip = {
  bassackwards: false,
  pointInLayer: function(p, layer, first) {
    if (p instanceof L.LatLng) p = [p.lng, p.lat];
    else if (leafletPip.bassackwards) p = p.concat().reverse();

    var results = [];

    layer.eachLayer(function(l) {
      if (first && results.length) return;

      if (isPoly(l) &&
        gju.pointInPolygon({
          type:        'Point',
          coordinates: p
        }, l.toGeoJSON().geometry)) {
        results.push(l);
      }
    });
    return results;
  }
};

function isPoly(l) {
  if (L.MultiPolygon) {
    return (l instanceof L.MultiPolygon || l instanceof L.Polygon);
  } else {    //leaftletjs >= 1.0
    return (l.feature && l.feature.geometry && l.feature.geometry.type && -1 != ['Polygon', 'MultiPolygon'].indexOf(l.feature.geometry.type));
  }
}

module.exports = leafletPip;

Support for Leaflet v 1.0


import Ember from 'ember';
import setupMirage from '../helpers/setup-mirage';
import { moduleFor, test } from 'ember-qunit';

const {
  run
} = Ember;

moduleFor('copyable', 'Integration | Copyable | failure', {
  integration: true,

  beforeEach() {
    return setupMirage(this, { async: true });
  },

  afterEach() {
   this.server.shutdown();
 }
});

test('it handles async failures', async function(assert) {
  assert.expect(1);

  this.server.get('/foos/1', { errors: ['There was an error'] }, 500);

  let model;

  await run(async () => {
    model = await this.store.findRecord('bar', 1);
  });

  await run(async () => {
    try {
      await model.copy(true);
    } catch (e) {
      assert.ok(e);
    }
  });
});

test('it handles task cancellation', async function(assert) {
  assert.expect(1);

  let model;

  await run(async () => {
    model = await this.store.findRecord('bar', 1);
  });

  await run(async () => {
    try {
      let taskInstance = model.copy(true);
      taskInstance.cancel();

      await taskInstance;
    } catch (e) {
      assert.ok(e);
    }
  });
});

import Ember from 'ember';
import setupMirage from '../helpers/setup-mirage';
import { moduleFor, test } from 'ember-qunit';

const {
  run
} = Ember;

moduleFor('copyable', 'Integration | Copyable | failure', {
  integration: true,

  beforeEach() {
    return setupMirage(this, { async: true });
  },

  afterEach() {
   this.server.shutdown();
 }
});

test('it handles async failures', async function(assert) {
  assert.expect(2);

  this.server.get('/foos/1', { errors: ['There was an error'] }, 500);

  let model;

  await run(async () => {
    model = await this.store.findRecord('bar', 1);
  });

  await run(async () => {
    try {
      await model.copy(true);
    } catch (e) {
      let models = this.store.peekAll('bar');

      assert.ok(e);
      assert.equal(models.get('length'), 1, 'All created copies were cleaned up');
    }
  });
});

test('it handles task cancellation', async function(assert) {
  assert.expect(2);

  let model;

  await run(async () => {
    model = await this.store.findRecord('bar', 1);
  });

  await run(async () => {
    try {
      let taskInstance = model.copy(true);
      taskInstance.cancel();

      await taskInstance;
    } catch (e) {
      let models = this.store.peekAll('bar');

      assert.ok(e);
      assert.equal(models.get('length'), 1, 'All created copies were cleaned up');
    }
  });
});

Add asserts to check that cleanup did occur


"use strict";
const express = require('express');
const twilio = require('twilio');
const bodyParser = require('body-parser');

const app = express();

// Run server to listen on port 8000.
const server = app.listen(8000, () => {
  console.log('listening on *:8000');
});

const io = require('socket.io')(server);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('static'));

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html');
});

app.post('/sms', (req, res) => {
  let twiml = twilio.TwimlResponse();
  let addOns = JSON.parse(req.body.AddOns);
  let sentimentStatus = addOns.results.ibm_watson_sentiment.status;
  console.log(req.body.From);

  if (sentimentStatus === 'successful') {
    let sentiment = addOns.results.ibm_watson_sentiment.result.docSentiment.type;
    io.emit('sms', { sentiment: sentiment, number: req.body.From });
    console.log(sentiment);
  } else {
    console.log('Sentiment failed');
  }

  twiml.message('Thanks for playing.  Join us tonight at Bash for more fun & games');

  res.send(twiml.toString());
});

"use strict";
const express = require('express');
const twilio = require('twilio');
const bodyParser = require('body-parser');

const app = express();

// Run server to listen on port 8000.
const server = app.listen(8000, () => {
  console.log('listening on *:8000');
});

const io = require('socket.io')(server);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('static'));

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html');
});

app.post('/sms', (req, res) => {
  var twiml = twilio.TwimlResponse();
  var addOns = JSON.parse(req.body.AddOns);
  var sentimentStatus = addOns.results.ibm_watson_sentiment.status;
  console.log(req.body.From);

  if (sentimentStatus === 'successful') {
    var sentiment = addOns.results.ibm_watson_sentiment.result.docSentiment.type;
    io.emit('sms', { sentiment: sentiment, number: req.body.From });
    console.log(sentiment);
  } else {
    console.log('Sentiment failed');
  }

  twiml.message('Thanks for playing.  Join us tonight at Bash for more fun & games');

  res.send(twiml.toString());
});

Change let to var in sms route


'use strict';

var cheerio = require('cheerio');

module.exports = function (html, options) {
    var results = {};
    var $ = cheerio.load(html);

    results.hrefs = [];

    $('link').each(function (index, element) {
        var $el = $(element);
        if ($el.attr('rel').toLowerCase() === 'stylesheet') {
            if (options.applyLinkTags) {
                results.hrefs.push($el.attr('href'));
            }
            if (options.removeLinkTags) {
                $el.remove();
            }
        }
    });

    results.html = $.html();

    return results;
};

'use strict';

var cheerio = require('cheerio');

module.exports = function (html, options) {
    var results = {};
    var $ = cheerio.load(html, {
            decodeEntities: false
        });

    results.hrefs = [];

    $('link').each(function (index, element) {
        var $el = $(element);
        if ($el.attr('rel').toLowerCase() === 'stylesheet') {
            if (options.applyLinkTags) {
                results.hrefs.push($el.attr('href'));
            }
            if (options.removeLinkTags) {
                $el.remove();
            }
        }
    });

    results.html = $.html();

    return results;
};

Set decodeEntities to false for cheerio.


import Ember from 'ember';

const { $ } = Ember;

export default Ember.Route.extend({
  model() {
    return $.getJSON('/telling-stories/acceptance.json');
  },

  setupController(controller, model) {
    this._super(...arguments);

    controller.set('modules', model);
  }
});

import Ember from 'ember';

const { $ } = Ember;

export default Ember.Route.extend({
  model() {
    return $.getJSON('/telling-stories.json');
  },

  setupController(controller, model) {
    this._super(...arguments);

    controller.set('modules', model);
  }
});

Fix route to json file


"use strict"

var rules = {
  "no-yield-in-race": require("./lib/rules/no-yield-in-race"),
  "yield-effects": require("./lib/rules/yield-effects"),
  "no-unhandled-errors": require("./lib/rules/no-unhandled-errors")
}

var allRules = Object.keys(rules).reduce(function(result, name) {
  result["redux-saga/" + name] = 2
  return result
}, {})

module.exports = {
  rules: rules,
  configs: {
    recommended: {
      rules: {
        "redux-saga/no-yield-in-race": 2,
        "redux-saga/yield-effects": 2,
        "redux-saga/no-unhandled-errors": 2
      }
    },
    all: {
      rules: allRules
    }
  }
}

"use strict"

var rules = {
  "no-yield-in-race": require("./lib/rules/no-yield-in-race"),
  "yield-effects": require("./lib/rules/yield-effects"),
  "no-unhandled-errors": require("./lib/rules/no-unhandled-errors")
}

var allRules = Object.keys(rules).reduce(function(result, name) {
  result["redux-saga/" + name] = 2
  return result
}, {})

module.exports = {
  rules: rules,
  configs: {
    recommended: {
      plugins: ['redux-saga'],
      rules: {
        "redux-saga/no-yield-in-race": 2,
        "redux-saga/yield-effects": 2,
        "redux-saga/no-unhandled-errors": 2
      }
    },
    all: {
      plugins: ['redux-saga'],
      rules: allRules
    }
  }
}

Add plugins to included configs


'use strict'
import React, { Children } from 'react'
import classNames from 'classnames'

/* eslint-disable react/prop-types */
export default function Box (props) {
  const c = classNames('box', props.className)

  const contents = []
  const footers = []
  const headers = []

  Children.forEach(props.children, child => {
    if (child.type === Header) {
      return headers.push(child)
    }

    if (child.type === Footer) {
      return footers.push(child)
    }

    contents.push(child)
  })

  return

    {headers}

      {contents}

    {footers}

}

export function Row (props) {
  const c = classNames('row', props.className)
  return
{props.children}

}

export function SingleBox (props) {
  return <Row>
    <Box className={props.className}>
      {props.children}
    </Box>
  </Row>
}

export function Header (props) {
  return
    {props.title ?
{props.title}
 : null}
    {props.children}

}

export function Footer (props) {
  return {props.children}
}

export function Stack (props) {
  const c = classNames('stack', props.className)
  return
{props.children}

}
/* eslint-enable react/prop-types */

'use strict'
import React, { Children } from 'react'
import classNames from 'classnames'

/* eslint-disable react/prop-types */
export default function Box (props) {
  const c = classNames('box', props.className)

  const contents = []
  const footers = []
  const headers = []

  Children.forEach(props.children, child => {
    if (!child) {
      return
    }

    if (child.type === Header) {
      return headers.push(child)
    }

    if (child.type === Footer) {
      return footers.push(child)
    }

    contents.push(child)
  })

  return

    {headers}

      {contents}

    {footers}

}

export function Row (props) {
  const c = classNames('row', props.className)
  return
{props.children}

}

export function SingleBox (props) {
  return <Row>
    <Box className={props.className}>
      {props.children}
    </Box>
  </Row>
}

export function Header (props) {
  return
    {props.title ?
{props.title}
 : null}
    {props.children}

}

export function Footer (props) {
  return {props.children}
}

export function Stack (props) {
  const c = classNames('stack', props.className)
  return
{props.children}

}
/* eslint-enable react/prop-types */

Fix case where child is null


// this proxy will route requests to /api to backend
// and all the other requests to frontend

const backendDevServerPort = 8080;
const frontendDevServerPort = 3000;
const portThatProxyListensOn = 9000;

const http = require("http");
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});

http.createServer((req, res) => {
    const regex = /^\/api/;
    const port = req.url.match(regex) ? backendDevServerPort : frontendDevServerPort;
    proxy.web(req, res, { target: `http://127.0.0.1:${port}` });
}).listen(portThatProxyListensOn);

// this proxy will route requests to /api to backend
// and all the other requests to frontend

const backendDevServerPort = 8080;
const frontendDevServerPort = 3000;
const portThatProxyListensOn = 9000;

const http = require("http");
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});

http.createServer((req, res) => {
    const regex = /^\/(api|_ah)/;
    const port = req.url.match(regex) ? backendDevServerPort : frontendDevServerPort;
    proxy.web(req, res, { target: `http://127.0.0.1:${port}` });
}).listen(portThatProxyListensOn);

Make reverse proxy forward requests to AppEngine console as well


export default function dragZoom(map) {

	const $map = map._container;

	let isDoubleTap = false;
	let isDragging = false;

	let startZoom = 0;
	let startY = 0;

	$map.addEventListener('touchstart', (e) => {

		// Cancel drag zoom with multiple fingers.
		if (e.touches.length > 1) return (isDragging = false);

		// Check for double tap.
		if (!isDoubleTap) {
			isDoubleTap = true;

			setTimeout(() => {
				isDoubleTap = false;
			}, 300);

			return;

		}

		map.dragging.disable();

		startZoom = map.getZoom();
		startY = e.touches[0].pageY;
		isDragging = true;

	});

	$map.addEventListener('touchend', (e) => {
		isDragging = false;
	});

	$map.addEventListener('touchmove', (e) => {
		if (isDragging) map.setZoom(startZoom - (startY - e.touches[0].pageY) / 80);
	});

}

export default function dragZoom(map) {

	const $map = map._container;

	let isDoubleTap = false;
	let isDragging = false;

	let startZoom = 0;
	let startY = 0;

	$map.addEventListener('touchstart', (e) => {

		// Cancel drag zoom with multiple fingers.
		if (e.touches.length > 1) return (isDragging = false);

		// Check for double tap.
		if (!isDoubleTap) {
			isDoubleTap = true;

			setTimeout(() => {
				isDoubleTap = false;
			}, 300);

			return;

		}

		map.dragging.disable();

		startZoom = map.getZoom();
		startY = e.touches[0].pageY;
		isDragging = true;

	});

	$map.addEventListener('touchend', (e) => {
		isDragging = false;
		map.dragging.enable();
	});

	$map.addEventListener('touchmove', (e) => {
		if (isDragging) map.setZoom(startZoom - (startY - e.touches[0].pageY) / 80);
	});

}

Fix not movable map after drag zoom (web)


'use strict';

describe('angularBasicAuthExample.login module', function() {
  var scope;

  // Mock unavailable modules
  angular.module('ngMessages', []);
  angular.module('angularBasicAuthExample.user', []);

  beforeEach(module('angularBasicAuthExample.login'));

  describe('login controller', function() {
    it('should ....', inject(function($rootScope, $controller) {
      scope = $rootScope.$new();
      var user = {login: function() {}};
      var parameters = {
        $scope: scope,
        User: user
      };
      var loginCtrl = $controller('LoginCtrl', parameters);
      expect(loginCtrl).toBeDefined();
    }));

  });
});

'use strict';

describe('angularBasicAuthExample.login module', function() {
  var scope;

  // Mock unavailable modules
  angular.module('ngMessages', []);
  angular.module('ngNotify', []);
  angular.module('angularBasicAuthExample.user', []);

  beforeEach(module('angularBasicAuthExample.login'));

  describe('login controller', function() {
    it('should ....', inject(function($rootScope, $controller) {
      scope = $rootScope.$new();
      var user = {login: function() {}};
      var parameters = {
        $scope: scope,
        ngNotify: null,
        User: user
      };
      var loginCtrl = $controller('LoginCtrl', parameters);
      expect(loginCtrl).toBeDefined();
    }));

  });
});

Fix test to work with ngNotify


/*
 * CSSMIN: Compress CSS files
 */
module.exports = {
    /*
     * TARGET:  Concats and minified library css
     */
    installLibCss: {
        options: {
            compatibility: 'ie8',
            relativeTo: 'css/',
            target: 'css/'
        },
        files: {
            '<%= path.dest.css %>/lib.css': [
                '<%= path.src.lib %>/jquery-ui-1.10.3/jquery-ui.custom.min.css',            // 20 kb
                '<%= path.src.bower %>/magnific-popup/dist/magnific-popup.css',  //  9 kb
                '<%= path.src.lib %>/select2/select2.css',                                  // 19 kb
                '<%= path.src.lib %>/jquery-fileupload/jquery-fileupload-ui.css'            //  2 kb
            ]
        }
    }
};

/*
 * CSSMIN: Compress CSS files
 */
module.exports = {
    /*
     * TARGET:  Concats and minified library css
     */
    installLibCss: {
        options: {
            compatibility: 'ie8',
            rebase: true
        },
        files: {
            '<%= path.dest.css %>/lib.css': [
                '<%= path.src.lib %>/jquery-ui-1.10.3/jquery-ui.custom.min.css',            // 20 kb
                '<%= path.src.bower %>/magnific-popup/dist/magnific-popup.css',  //  9 kb
                '<%= path.src.lib %>/select2/select2.css',                                  // 19 kb
                '<%= path.src.lib %>/jquery-fileupload/jquery-fileupload-ui.css'            //  2 kb
            ]
        }
    }
};

Adjust to new rebasing behavior


'use strict';

var path = require('path');

exports.routes = function() {

    var appPath = path.resolve(__dirname + '/public');

    return {

        'get' : {
            // get routes
            '/<%= _.slugify(appTitle) %>': function(req, res, next){
                res.send('<%= appTitle %>, Another WK ATG App.');
            }
        }

    };
};

'use strict';

var path = require('path');

exports.routes = function() {

    var appPath = path.resolve(__dirname + '/public');

    return {

        'get' : {
            // get routes
            '<%= _.slugify(appTitle) %>': function(req, res, next){
                res.send('<%= appTitle %>, Another EdgePlate App.');
            }
        }

    };
};

Update to default route path and response


var debug       = require( 'debug' )( 'wpcom-vip' );
var Request     = require( './lib/util/request' );

// Modules

function WPCOM_VIP( token ) {
    this.req = new Request( this );

    this.auth = {};
}

WPCOM_VIP.prototype.API_VERSION = '1';
WPCOM_VIP.prototype.API_TIMEOUT = 10000;

WPCOM_VIP.prototype.get = function() {
    return this.req.get.apply( arguments );
};

WPCOM_VIP.prototype.post = function() {
    return this.req.post.apply( arguments );
};

WPCOM_VIP.prototype.put = function() {
    return this.req.get.apply( arguments );
};

WPCOM_VIP.prototype.delete = function() {
    return this.req.delete.apply( arguments );
};

module.exports = WPCOM_VIP;

var debug       = require( 'debug' )( 'wpcom-vip' );
var Request     = require( './lib/util/request' );

// Modules

function WPCOM_VIP( token ) {
    this.req = new Request( this );

    this.auth = {};
}

WPCOM_VIP.prototype.API_VERSION = '1';
WPCOM_VIP.prototype.API_TIMEOUT = 10000;

WPCOM_VIP.prototype.get = function() {
    return this.req.get.apply( this.req, arguments );
};

WPCOM_VIP.prototype.post = function() {
    return this.req.post.apply( this.req, arguments );
};

WPCOM_VIP.prototype.put = function() {
    return this.req.get.apply( this.req, arguments );
};

WPCOM_VIP.prototype.delete = function() {
    return this.req.delete.apply( this.req, arguments );
};

module.exports = WPCOM_VIP;

Fix how Request methods are called (pass them a 'this' arg)


module.exports = (function() {
  var Router = require('router');

  require('lib/config');
  require('lib/helpers');

  window.App = {};

  App.Router = new Router();

  App.User = _.createModel('user');
  App.Cache = _.createModel('app');
  App.Boards = _.createCollection('boards');
  App.Accounts = _.createCollection('accounts');

  App.User.signinFromCache();
  App.Router.start();
})();

module.exports = (function() {
  var Router = require('router');

  require('lib/config');
  require('lib/helpers');

  window.App = {};

  App.Router = new Router();

  App.User = _.createModel('user');
  App.Cache = _.createModel('app');
  App.Boards = _.createCollection('boards');
  App.Accounts = _.createCollection('accounts');

  App.User.signinFromCache();
  App.Router.start({pushState: true});
})();

Use pushState for the Backbone Router.


//handles message function
var SubmitView = Backbone.View.extend({

  events: {
    'submit' : 'handleSubmit',
    'change #lang' : 'changeLanguage',
    'click #roomButton' : 'changeRoom'
  },

  initialize: function(){},

  handleSubmit: function(e){
    e.preventDefault();
    var message = {
      text: $('#chatInput').val(),
      lang: $('#lang').val(),
      username: $('#username').val(),
      room: $('#room').val()
    };
    socket.emit('chat message', message);
    $('#chatInput').val('');
  },

  changeLanguage: function(e){
    e.preventDefault();
    console.log('changing language');
    socket.emit('change language', $('#lang').val());
  },

  changeRoom : function(e){
    e.preventDefault();
    var room = $('#room').val();
    var lang = $('#lang').val();
    socket.emit('join room', {room: room, lang: lang});
  }
});

//handles message function
var SubmitView = Backbone.View.extend({

  events: {
    'submit' : 'handleSubmit',
    'change #lang' : 'changeLanguage',
    'click #roomButton' : 'changeRoom'
  },

  initialize: function(){
    this.currRoom = $("#room").val();
  },

  handleSubmit: function(e){
    e.preventDefault();
    if (this.currRoom === $("#room").val()) {
      this.messageSubmitter();
    } else {
      this.changeRoom(e);
      this.messageSubmitter();
    }
  },

  messageSubmitter: function(){
    var message = {
      text: $('#chatInput').val(),
      lang: $('#lang').val(),
      username: $('#username').val(),
      room: $('#room').val()
    };
    socket.emit('chat message', message);
    $('#chatInput').val('');
  },

  changeLanguage: function(e){
    e.preventDefault();
    console.log('changing language');
    socket.emit('change language', $('#lang').val());
  },

  changeRoom : function(e){
    e.preventDefault();
    this.currRoom = $("#room").val();
    var lang = $('#lang').val();
    socket.emit('join room', {room: this.currRoom, lang: lang});
  }
});

Fix bug so that if the user fails to press change room the app does not break


'use strict';

module.exports = class PivotBuffer {
    constructor(size) {
        this.size = size;
        this.$buffer = new Buffer(size);

        this.$buffer.fill(0);

        this.$curSize = 0;
    }

    append(buffer) {
        if (buffer.length == 0) {
            return;
        }

        if (buffer.length >= this.size) {
            // buffer being appended is longer than buffer size
            buffer.copy(this.$buffer, 0, buffer.length - this.size);
        } else {
            // rotate current buffer
            var leftover = this.size - buffer.length;
            this.$buffer.copy(this.$buffer, 0, this.size - leftover);

            // copy the new buffer to the current one
            buffer.copy(this.$buffer, leftover);
        }

        this.$curSize = Math.min(this.size, this.$curSize + buffer.length);
    }

    get value() {
        return this.$curSize != this.size
            ? this.$buffer.slice(this.size - this.$curSize) // truncate the buffer if it was not yet filled up
            : this.$buffer;
    }

    get length() {
        return this.$curSize;
    }
};

'use strict';

module.exports = class PivotBuffer {
    constructor(size) {
        this.size = size;
        this.$buffer = new Buffer(size);

        this.$buffer.fill(0);

        this.$curSize = 0;
    }

    append(buffer) {
        if (buffer.length === 0) {
            return;
        }

        if (buffer.length >= this.size) {
            // buffer being appended is longer than buffer size
            buffer.copy(this.$buffer, 0, buffer.length - this.size);
        } else {
            // rotate current buffer
            var leftover = this.size - buffer.length;
            this.$buffer.copy(this.$buffer, 0, this.size - leftover);

            // copy the new buffer to the current one
            buffer.copy(this.$buffer, leftover);
        }

        this.$curSize = Math.min(this.size, this.$curSize + buffer.length);
    }

    get value() {
        return this.$curSize != this.size
            ? this.$buffer.slice(this.size - this.$curSize) // truncate the buffer if it was not yet filled up
            : this.$buffer;
    }

    get length() {
        return this.$curSize;
    }
};

Use === instead of ==


var express = require('express');
var app = express();

var request = require('request');
var cheerio = require('cheerio');

app.get('/', function(req, res) {
  res.sendFile('./consume.html', {"root": __dirname})
});

var port = process.env.PORT || 3000
app.listen(port, function () {
  console.log('Testing 123, we are live!');
});

var lookupHash = {
	"SJC11":{"code":4021,"menu":12183,"label":"Artisan"},
	"SJCJ":{"code":4017,"menu":12738,"label":"Eat at Bridges"},
	"SJC03":{"code":4020,"menu":12471,"label":"Eat at Lakeview"},
	"SJCQ":{"code":4015,"menu":13324,"label":"Green Bar"},
	"SJCD":{"code":4018,"menu":12744,"label":"Market 170"},
	"MR2":{"code":4011,"menu":12180,"label":"Milpa 3 Fresh"},
	"SJC30":{"code":4013,"menu":12189,"label":"Social Roast"},
	"SJC17":{"code":4014,"menu":13076,"label":"The Food Foundry"},
	"SJC21":{"code":4012,"menu":12163,"label":"The Quarter"}
};

app.get('/cafes', function(req, res){
	res.send(Object.keys(lookupHash))
});

Implement main lookup hash from vendor site


exports = module.exports = function(IoC, store, logger) {
  var flowstate = require('flowstate');

  var dispatcher = new flowstate.Manager(store);

  return Promise.resolve(dispatcher)
    .then(function(dispatcher) {
      // TODO: If any of these prompts have @requires that aren't satisfied, its an error.
      //       should it be a warning?

      console.log('CREATE PROMPTS!');
      //return dispatcher;

      var components = IoC.components('http://i.bixbyjs.org/http/ceremony/Prompt2');

      return Promise.all(components.map(function(comp) { return comp.create(); } ))
        .then(function(prompts) {
          prompts.forEach(function(prompt, i) {
            var name = components[i].a['@name'];
            logger.info('Loaded HTTP ceremony prompt: ' + name);
            dispatcher.use(name, prompt);
          });
        })
        .then(function() {
          return dispatcher;
        });
    })
    .then(function(dispatcher) {
      console.log('CREATE YIELDS!');
      //return dispatcher;

      var components = IoC.components('http://i.bixbyjs.org/http/ceremony/Yield2');

      return Promise.all(components.map(function(comp) { return comp.create(); } ))
        .then(function(yielders) {
          yielders.forEach(function(yielder, i) {
            var to = components[i].a['@state']
              , from = components[i].a['@result']
            logger.info("Loaded HTTP ceremony yield from '" + from + "' to '" + to +  "'");
            dispatcher.yield(to, from, yielder);
          });
        })
        .then(function() {
          return dispatcher;
        });
    })
    .then(function(dispatcher) {
      return dispatcher;
    });
};

exports['@singleton'] = true;
exports['@require'] = [
  '!container',
  'http://i.bixbyjs.org/http/state/Store',
  'http://i.bixbyjs.org/Logger'
];

exports = module.exports = function(IoC, store, logger) {
  var flowstate = require('flowstate');

  var dispatcher = new flowstate.Manager(store);

  return Promise.resolve(dispatcher)
    .then(function(dispatcher) {
      // TODO: If any of these prompts have @requires that aren't satisfied, its an error.
      //       should it be a warning?

      console.log('CREATE PROMPTS!');
      return dispatcher;

      // TODO: Remove .use from flowstate
    })
    .then(function(dispatcher) {
      console.log('CREATE YIELDS!');
      return dispatcher;

      var components = IoC.components('http://i.bixbyjs.org/http/ceremony/Yield2');

      // TODO: remove .yield from flowstate
    })
    .then(function(dispatcher) {
      return dispatcher;
    });
};

exports['@singleton'] = true;
exports['@require'] = [
  '!container',
  'http://i.bixbyjs.org/http/state/Store',
  'http://i.bixbyjs.org/Logger'
];

Remove flowstate .use and .yield.


'use strict';

var getYouTubeID = require('get-youtube-id');

module.exports = function(url){
  var id = getYouTubeID(url);

  return {
    default: {
      url: 'http://img.youtube.com/vi/' + id + '/default.jpg',
      width: 120,
      height: 90
    },
    medium: {
      url: 'http://img.youtube.com/vi/' + id + '/mqdefault.jpg',
      width: 320,
      height: 180
    },
    high: {
      url: 'http://img.youtube.com/vi/' + id + '/hqdefault.jpg',
      width: 480,
      height: 360
    },
  }
};

'use strict';

var getYouTubeID = require('get-youtube-id');

module.exports = function(url){
  var id = getYouTubeID(url);

  if(!id && url.length === 11){
    id = url
  }

  return {
    default: {
      url: 'http://img.youtube.com/vi/' + id + '/default.jpg',
      width: 120,
      height: 90
    },
    medium: {
      url: 'http://img.youtube.com/vi/' + id + '/mqdefault.jpg',
      width: 320,
      height: 180
    },
    high: {
      url: 'http://img.youtube.com/vi/' + id + '/hqdefault.jpg',
      width: 480,
      height: 360
    },
  }
};

Handle clean YouTube ids instead of the full URL


var
	Spotlight = require('./src/spotlight');

Spotlight.version = '2.6.0-pre.17';

module.exports = Spotlight;

var
	Spotlight = require('./src/spotlight');

Spotlight.version = '2.6.0-pre.17.1';

module.exports = Spotlight;

Update version string to 2.6.0-pre.17.1


var async = require('async'),
	boom = require('boom'),
	defaultData = {'success' : true};

function Series(arr) {
	this.arr = arr;
}

function Validate(arr) {
	var len = arr.length;
	while(len--) {
		if(typeof arr[len] !== 'function') {
			throw new Error('')
		}
	}
}

Series.prototype.execute = function(request,reply) {

	if(!request) {
		throw new Error('Request can\'t be empty.');
		return;
	}

	if(!reply) {
		throw new Error('Reply can\'t be empty.');
		return;
	}

	var arr = this.arr;

	async.series(arr.map(function(func) {
		return function(cb) {

			func.call({},request,reply,function(err) {

				if(err) {
					return cb(err);
				}

				cb();
			});

		}
	}),function(err,results) {

		if(err) {
			reply(boom.badData(err));
		}

		reply.data = reply.data || defaultData;
		reply(reply.data);
	});
};

module.exports = Series;

var async = require('async'),
	boom = require('boom'),
	defaultData = {'success' : true};

function Series(arr) {
	this.arr = arr;
	Validate(arr);
}

function Validate(arr) {
	var len = arr.length;
	while(len--) {
		if(typeof arr[len] !== 'function') {
			throw new Error('Arguments passed in hapi-next must be functions');
		}
	}
}

Series.prototype.execute = function(request,reply) {

	if(!request) {
		throw new Error('Request can\'t be empty.');
		return;
	}

	if(!reply) {
		throw new Error('Reply can\'t be empty.');
		return;
	}

	var arr = this.arr;

	async.series(arr.map(function(func) {
		return function(cb) {

			func.call({},request,reply,function(err) {

				if(err) {
					return cb(err);
				}

				cb();
			});

		}
	}),function(err,results) {

		if(err) {
			reply(boom.badData(err));
		}

		reply.data = reply.data || defaultData;
		reply(reply.data);
	});
};

module.exports = Series;

Update error handling and provide better error message


/*global require, module*/
/*!
 * missing-keys <https://github.com/tobiasoberrauch/missing-keys>
 *
 * Copyright (c) 2015, Tobias Oberrauch.
 * Licensed under the MIT License.
 */

'use strict';

(function (factory) {
  if (typeof module === "object" && typeof module.exports === "object") {
    module.exports = factory();
  }
  else if (typeof window === "object") {
    window.missingKeys = factory();
  }
}(function () {
  /**
   *
   * @param {object} object
   * @param {string|object} expectedKeys
   * @returns {Array.<T>|*}
   */
  function missingKeys(object, expectedKeys) {
    expectedKeys = Object.prototype.toString.call(expectedKeys) === '[object Array]' ? expectedKeys : [expectedKeys];
    var actualKeys = Object.keys(object);
    return expectedKeys.filter(function (expectedKey) {
      return actualKeys.indexOf(expectedKey) === -1;
    });
  }

  /**
   * @type {missingKeys}
   */
  missingKeys.get = missingKeys;

  /**
   *
   * @param {object} object
   * @param {string|object} expectedKeys
   * @returns {boolean}
   */
  missingKeys.has = function (object, expectedKeys) {
    return missingKeys(object, expectedKeys).length > 0;
  };

  return missingKeys;
}));

/*global require, module*/
/*!
 * missing-keys <https://github.com/tobiasoberrauch/missing-keys>
 *
 * Copyright (c) 2015, Tobias Oberrauch.
 * Licensed under the MIT License.
 */

'use strict';

(function (factory) {
  if (typeof module === "object" && typeof module.exports === "object") {
    module.exports = factory();
  }
  else if (typeof window === "object") {
    // poly-fill when array.filter doesn't exists
    [].filter || (Array.prototype.filter = function (a, b, c, d, e) {
      c = this;
      d = [];
      for (e in c)~~e + '' == e && e >= 0 && a.call(b, c[e], +e, c) && d.push(c[e]);
      return d
    });
    window.missingKeys = factory();
  }
}(function () {
  /**
   *
   * @param {object} object
   * @param {string|object} expectedKeys
   * @returns {Array.<T>|*}
   */
  function missingKeys(object, expectedKeys) {
    expectedKeys = Object.prototype.toString.call(expectedKeys) === '[object Array]' ? expectedKeys : [expectedKeys];
    var actualKeys = Object.keys(object);
    return expectedKeys.filter(function (expectedKey) {
      return actualKeys.indexOf(expectedKey) === -1;
    });
  }

  /**
   * @type {missingKeys}
   */
  missingKeys.get = missingKeys;

  /**
   *
   * @param {object} object
   * @param {string|object} expectedKeys
   * @returns {boolean}
   */
  missingKeys.has = function (object, expectedKeys) {
    return missingKeys(object, expectedKeys).length > 0;
  };

  return missingKeys;
}));

Add poly-fill when array.filter doesn't exists


'use strict';

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

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

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

        var stylesData = results.shift(),
            css;

        results.forEach(function (content) {
            stylesData.css.push(content);
        });
        css = stylesData.css.join('\n');
        callback(null, stylesData.html, css);
    });
};

'use strict';

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

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

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

        if (err) {
            return callback(err);
        }

        stylesData = results.shift();

        results.forEach(function (content) {
            stylesData.css.push(content);
        });
        css = stylesData.css.join('\n');
        callback(null, stylesData.html, css);
    });
};

Move var declarations to the top.


var inputContext = input.RegisterInputContextRaw("fpsMouseLook", 150);
inputContext.SetTakeMouseEventsOverQt(true);
inputContext.MouseEventReceived.connect(MouseEvent);

function MouseEvent(event)
{
    // Press RMB
    if (event.GetEventType() == 3 && event.GetMouseButton() == 2)
    {
        if (input.IsMouseCursorVisible())
            input.SetMouseCursorVisible(false);
    }
    // Release RMB
    if (event.GetEventType() == 4 && event.GetMouseButton() == 2)
    {
        if (!input.IsMouseCursorVisible())
            input.SetMouseCursorVisible(true);
    }
}

var inputContext = input.RegisterInputContextRaw("fpsMouseLook", 150);
inputContext.SetTakeMouseEventsOverQt(true);
inputContext.MouseEventReceived.connect(MouseEvent);

// Returns user's avatar entity if connected.
function FindUserAvatar()
{
    var scene = framework.Scene().MainCameraScene();
    if (scene && client.IsConnected())
        return scene.GetEntityByName("Avatar" + client.GetConnectionID());
    else
        return null;
}

// Hides and shows mourse cursor when RMB is pressed and released
function MouseEvent(event)
{
    // Never show mouse cursor, if avatar camera is active and in first-person mode.
    var avatarCameraActiveInFps = false;
    var userAvatar = FindUserAvatar();
    var scene = framework.Scene().MainCameraScene();
    if (userAvatar && scene)
    {
        var avatarCamera = scene.GetEntityByName("AvatarCamera");
        if (avatarCamera && avatarCamera.camera)
            avatarCameraActiveInFps = avatarCamera.camera.IsActive() && userAvatar.dynamiccomponent.GetAttribute("cameraDistance") < 0;
    }

    // RMB pressed
    if (event.GetEventType() == 3 && event.GetMouseButton() == 2 && input.IsMouseCursorVisible())
        input.SetMouseCursorVisible(false);
    // RMB released
    else if (event.GetEventType() == 4 && event.GetMouseButton() == 2 && !input.IsMouseCursorVisible())
        if (!avatarCameraActiveInFps)
            input.SetMouseCursorVisible(true);
}

Fix bug which caused camera to rotate when avatar camera was in FPS mode and RMB was pressed/released. Also fixes bug (which was part of the aforementioned bug) which caused mouse cursor to become visible right after entering avatar FPS mode and pressing RMB.


var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var cli = new CLIEngine({});
var format = '';

module.exports = function (paths, options) {
  if (options && options.formatter) {
    format = options.formatter;
  }
  describe('eslint', function () {
    paths.forEach(function (p) {
      it(`should have no errors in ${p}`, function () {
        try {
          var report = cli.executeOnFiles([p]);
          var formatter = cli.getFormatter(format);
        } catch (err) {
          throw new Error(err);
        }
        if (
          report &&
          report.errorCount > 0
        ) {
          throw new Error(
            `${chalk.red('Code did not pass lint rules')}
            ${formatter(report.results)}`
          );
        }
      });
    });
  });
};

var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var cli = new CLIEngine({});
var format = '';

module.exports = function (paths, options) {
  if (options && options.formatter) {
    format = options.formatter;
  }
  describe('eslint', function () {
    paths.forEach(function (p) {
      it('should have no errors in ' + p, function () {
        try {
          var report = cli.executeOnFiles([p]);
          var formatter = cli.getFormatter(format);
        } catch (err) {
          throw new Error(err);
        }
        if (
          report &&
          report.errorCount > 0
        ) {
          throw new Error(
            `${chalk.red('Code did not pass lint rules')}
            ${formatter(report.results)}`
          );
        }
      });
    });
  });
};

Remove template strings for node compatibility


Template.postsList.helpers({
  posts: function() {
    return Posts.find();
  }
});

Template.postsList.helpers({
  posts: function() {
    return Posts.find({}, {sort: {submitted: -1}});
  }
});

Order posts by submitted time.


'use strict';

const fs = require('fs');

const WebClient = require('@slack/client').WebClient;

const token = require('./config.js').apiToken;

const message = process.argv[2];

const web = new WebClient(token);
web.chat.postMessage('deployment', message, {as_user: true}, function (err, res) {
  if (err) {
    const fd = fs.openSync('slack-bot-errors.log', 'a');
    fs.writeSync(fd, new Date().toString() + ": " + err.toString() + "\n");
    fs.closeSync(fd);
    process.exit(1);
  }
});

'use strict';

const fs = require('fs');

const WebClient = require('@slack/client').WebClient;

const token = require('./config.js').apiToken;

let message, channel;
if (process.argv.length === 3) {
  // Only a message was passed so we use default channel
  channel = "deployment"
  message = process.argv[2];
} else if (process.argv.length === 4) {
  channel = process.argv[2];
  message = process.argv[3];
} else {
  console.error("Usage: node index.js 'message to send'\nOR\nnode index.js <channel_to_send_to> 'message to send'");
  process.exit(1);
}

const web = new WebClient(token);
web.chat.postMessage(channel, message, {as_user: true}, function (err, res) {
  if (err) {
    const fd = fs.openSync('slack-bot-errors.log', 'a');
    fs.writeSync(fd, new Date().toString() + ": " + err.toString() + "\n");
    fs.closeSync(fd);
    process.exit(1);
  }
});

Add functionality to post to custom channels


/* Main app file for CEL project
 * Mostly stolen from requirejs examples: http://requirejs.org/docs/api.html
 */

'use strict';

requirejs.config({
    //except, if the module ID starts with 'app',
    //load it from the js/app directory. paths
    //config is relative to the baseUrl, and
    //never includes a '.js' extension since
    //the paths config could be for a directory.
    paths: {
        cel: '../cel',
        jquery: 'jquery-1.10.2.min'
    }
});

require(['jquery'], function($) {
    console.debug('main.js loaded!');
    if (typeof $ !== 'undefined') {
        console.debug('jquery loaded!');
    }
});

/* Main app file for CEL project
 * Mostly stolen from requirejs examples: http://requirejs.org/docs/api.html
 */

'use strict';

requirejs.config({
    //except, if the module ID starts with 'app',
    //load it from the js/app directory. paths
    //config is relative to the baseUrl, and
    //never includes a '.js' extension since
    //the paths config could be for a directory.
    paths: {
        cel: '../cel',
        jquery: 'jquery-1.10.2.min'
    }
});

require(['jquery'], function($) {
    // This is the main entry point.  In order to add modules that get loaded, make a new file in
    // ../cel, and load it by adding it to the args above (both in the array and function)
    // for example, to define module foo:
    //
    // Add the file ../cel/foo.js
    //
    // Put this in it:
    // define(['dep1', 'dep2'], function(dep1, dep2) {
    //     // foo body
    //     return something;
    // });
    //
    // Then load it above by modifying the line above:
    // require(['jquery', 'foo'], function($, foo) {
    //
    // parameter foo gets assigned the return value of the function in define()
    //
    // See http://requirejs.org/docs/api.html for details
    console.debug('main.js loaded!');
    if (typeof $ !== 'undefined') {
        console.debug('jquery loaded!');
    }
});

Add quick intro to modules


/*
 * Initialize Bolt module
 */
var Bolt = {};

/*
 * Initialize the Bolt module
 *
 * @type {Object}
 * @module Bolt
 * @mixes BoltApp
 * @mixes BoltConf
 * @mixes BoltData
 */
var Bolt = {};

Improve Bolt module doc block


var Twitter = require('twode'),
    _ = require('underscore'),
    CronJob = require('cron').CronJob;
    config = require('./lib/config'),
    fs = require("fs"),
    readFile = fs.readFileSync("./data/FY2016Q1.json", "UTF-8"),
    q1 = JSON.parse(readFile),
    counter = 0,
    twit = new Twitter({
        consumer_key: config.TWITTER_CONSUMER_KEY,
        consumer_secret: config.TWITTER_CONSUMER_SECRET,
        access_token_key: config.TWITTER_ACCESS_TOKEN_KEY,
        access_token_secret: config.TWITTER_ACCESS_TOKEN_SECRET
    });

// Define Function to Tweet
function tweetAboutContract (contract) {
    if (contract.Total_Transactions && contract.Contract_Description) {
        twit.updateStatus('The City spent $' + contract.Total_Transactions.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + ' on ' +  contract.Contract_Description,
          function (err, data) {
            if (err) {
              console.log(err);
            }
          }
        );
    }
}

// Set up Cron Job. Runs at 11:30 and 6:30 PM daily
new CronJob('00 11,18 * * *', function() {
  tweetAboutContract(q1[counter]);
  counter++;
}, null, true, 'America/New_York');

// Hack to get it to run on Heroku
require('net').createServer().listen();

var Twitter = require('twode'),
    _ = require('underscore'),
    CronJob = require('cron').CronJob;
    config = require('./lib/config'),
    fs = require("fs"),
    readFile = fs.readFileSync("./data/FY2016Q1.json", "UTF-8"),
    q1 = JSON.parse(readFile),
    counter = 0,
    twit = new Twitter({
        consumer_key: config.TWITTER_CONSUMER_KEY,
        consumer_secret: config.TWITTER_CONSUMER_SECRET,
        access_token_key: config.TWITTER_ACCESS_TOKEN_KEY,
        access_token_secret: config.TWITTER_ACCESS_TOKEN_SECRET
    });

// Define Function to Tweet
function tweetAboutContract (contract) {
    if (contract.Total_Transactions && contract.Contract_Description) {
        twit.updateStatus('The City spent $' + contract.Total_Transactions.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + ' on ' +  contract.Contract_Description,
          function (err, data) {
            if (err) {
              console.log(err);
            }
          }
        );
    }
}

// Set up Cron Job. Runs at 11:00 AM and 6:00 PM daily
new CronJob('00 11,18 * * *', function() {
  tweetAboutContract(q1[counter]);
  counter++;
}, null, true, 'America/New_York');

Remove heroku hack, fix comments


module.exports = {
	Model: require('./src/model'),
	Document: require('./src/document'),
	Query: require('./src/query'),
	MemStore: require('./src/mem-store'),
	MemSource: require('./src/mem-source')
}

module.exports = {
	Model: require('./src/model'),
	Document: require('./src/document'),
	Query: require('./src/query').Query,
	QueryResult: require('./src/query').QueryResult,
	MemStore: require('./src/mem-store'),
	MemSource: require('./src/mem-source')
}

Add QueryResult to default export


'use strict';
const pMap = require('p-map');

const filter = filterer => (x, i) => Promise.resolve(filterer(x, i)).then(val => {
	if (!val) {
		const err = new Error();
		err.code = 'EISFALSE';
		throw err;
	}

	return val;
});

module.exports = (iterable, filterer, opts) => pMap(iterable, filter(filterer), opts)
	.then(() => true)
	.catch(err => {
		if (err.code === 'EISFALSE') {
			return false;
		}

		throw err;
	});

'use strict';
const pMap = require('p-map');

class EndError extends Error {} // eslint-disable-line unicorn/custom-error-definition

const filter = filterer => (x, i) => Promise.resolve(filterer(x, i)).then(val => {
	if (!val) {
		throw new EndError();
	}

	return val;
});

module.exports = (iterable, filterer, opts) => pMap(iterable, filter(filterer), opts)
	.then(() => true)
	.catch(err => {
		if (err instanceof EndError) {
			return false;
		}

		throw err;
	});

Use custom error instance instead of checking the error code


var React = require('react/addons');

var Notfication = React.createClass({

  /**
   * @function hide
   * @description Focus on the element.
   */
  open: function () {
    this.setState({
      active: true
    });
  },

  /**
   * @function hide
   * @description Focus on the element.
   */
  hide: function () {
    this.setState({
      active: false
    });
  },

  propTypes: {
    message: React.PropTypes.string.isRequired,
    action: React.PropTypes.string,
    onClick: React.PropTypes.func
  },

  getInitialState: function () {
    return {
      active: false
    };
  },

  getDefaultProps: function () {
    return {
      message: '',
      action: 'Dismiss',
      onClick: function () {
        this.hide();
      }
    };
  },

  render: function () {
    return (

          {this.props.message}
          {this.props.action}

    )
  }

});

module.exports = Notfication;

var React = require('react/addons');

var Notfication = React.createClass({

  /**
   * @function hide
   * @description Focus on the element.
   */
  open: function () {
    this.setState({
      active: true
    });
  },

  /**
   * @function hide
   * @description Focus on the element.
   */
  hide: function () {
    this.setState({
      active: false
    });
  },

  propTypes: {
    message: React.PropTypes.string.isRequired,
    action: React.PropTypes.string,
    onClick: React.PropTypes.func
  },

  getInitialState: function () {
    return {
      active: false
    };
  },

  getDefaultProps: function () {
    return {
      action: 'Dismiss',
      onClick: function () {
        this.hide();
      }
    };
  },

  render: function () {
    return (

          {this.props.message}
          {this.props.action}

    )
  }

});

module.exports = Notfication;

Remove "message" from default props


module.exports = function parse(value){
  if(isTemplateString(value)){
    var parameter = Parameter(value);

    var template = function (context){
      if(typeof context === "undefined"){
        context = {};
      }
      return context[parameter.key] || parameter.defaultValue;
    };
    template.parameters = [parameter];
    return template;

  } else {
    var template = function (context){
      return value;
    };
    template.parameters = [];
    return template;
  }
};

// Checks whether a given string fits the form {{xyz}}.
function isTemplateString(str){
  return (
      (str.length > 5)
    &&
      (str.substr(0, 2) === "{{")
    &&
      (str.substr(str.length - 2, 2) === "}}")
  );
}

// Constructs a parameter object from the given template string.
// e.g. "{{xyz}}" --> { key: "xyz" }
// e.g. "{{xyz:foo}}" --> { key: "xyz", defaultValue: "foo" }
function Parameter(str){

  // Extract the key.
  var parameter = {
    key: str.substring(2, str.length - 2)
  };

  // Handle default values.
  var colonIndex = parameter.key.indexOf(":");
  if(colonIndex !== -1){
    parameter.defaultValue = parameter.key.substr(colonIndex + 1);
    parameter.key = parameter.key.substr(0, colonIndex);
  }

  return parameter;
}

module.exports = function parse(value){
  if(isTemplateString(value)){
    var parameter = Parameter(value);

    return Template(function (context){
      if(typeof context === "undefined"){
        context = {};
      }
      return context[parameter.key] || parameter.defaultValue;
    }, [parameter]);

  } else {

    return Template(function (){
      return value;
    }, []);

  }
};

// Checks whether a given string fits the form {{xyz}}.
function isTemplateString(str){
  return (
      (str.length > 5)
    &&
      (str.substr(0, 2) === "{{")
    &&
      (str.substr(str.length - 2, 2) === "}}")
  );
}

// Constructs a parameter object from the given template string.
// e.g. "{{xyz}}" --> { key: "xyz" }
// e.g. "{{xyz:foo}}" --> { key: "xyz", defaultValue: "foo" }
function Parameter(str){

  // Extract the key.
  var parameter = {
    key: str.substring(2, str.length - 2)
  };

  // Handle default values.
  var colonIndex = parameter.key.indexOf(":");
  if(colonIndex !== -1){
    parameter.defaultValue = parameter.key.substr(colonIndex + 1);
    parameter.key = parameter.key.substr(0, colonIndex);
  }

  return parameter;
}

// Constructs a template function with `parameters` property.
function Template(fn, parameters){
  fn.parameters = parameters;
  return fn;
}

Add simple Template constructor to simplify code


module.exports = compressible

compressible.specs =
compressible.specifications = require('./specifications.json')

compressible.regex
compressible.regexp = /json|text|javascript|dart|ecmascript|xml|x-font-ttf|ms-opentype|ms-fontobject/

function compressible(type) {
  return compressible.regexp.test(type)
}

module.exports = compressible

compressible.specs =
compressible.specifications = require('./specifications.json')

compressible.regex
compressible.regexp = /json|text|javascript|dart|ecmascript|xml|x-font-ttf|ms-opentype|ms-fontobject/

function compressible(type) {
  var spec = compressible.specs[type]
  return spec ? spec.compressible : false
}

Use object-key lookup to check for compressibility.


/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-g-map'
};

/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-g-map',

  contentFor: function(type, config) {
    var content = '';

    if (type === 'head') {
      var src = "//maps.googleapis.com/maps/api/js";
      var gMapConfig = config['g-map'] || {};
      var params = [];

      var key = gMapConfig.key;
      if (key) {
        params.push('key=' + encodeURIComponent(key));
      }

      var libraries = gMapConfig.libraries;
      if (libraries && libraries.length) {
        params.push('libraries=' + encodeURIComponent(libraries.join(',')));
      }

      src += '?' + params.join('&');
      content = '<script type="text/javascript" src="' + src + '"></script>';
    }

    return content;
  }
};

Load google-map lib on page load


/* @flow */

import React, { Component } from 'react';
import { NativeModules } from 'react-native';

export default class KeepAwake extends Component {

  static isActive = false;

  static activate() {
      if (!KeepAwake.isActive) {
          NativeModules.KCKeepAwake.activate();
          KeepAwake.isActive = true;
      }
  }

  static deactivate() {
      if (KeepAwake.isActive) {
          NativeModules.KCKeepAwake.deactivate();
          KeepAwake.isActive = false;
      }
  }

  componentWillMount() {
    KeepAwake.activate();
  }

  componentWillUnmount() {
    KeepAwake.deactivate();
  }

  render() {
    return this.props.children || null;
  }
}

/* @flow */

import React, { Component } from 'react';
import { NativeModules } from 'react-native';

export default class KeepAwake extends Component {
  static activate() {
    NativeModules.KCKeepAwake.activate();
  }

  static deactivate() {
    NativeModules.KCKeepAwake.deactivate();
  }

  componentWillMount() {
    KeepAwake.activate();
  }

  componentWillUnmount() {
    KeepAwake.deactivate();
  }

  render() {
    return this.props.children || null;
  }
}

Remove active state from JS Native method can be called even though sleep preventing flag are set. There are no drawbacks to this


'use strict';

var fs = require('fs');
var pictureTube = require('picture-tube');
var webshot = require('webshot');

function hitThat (url, options) {
  var name = Date.now() + '_that.png';
  var o = options || {};
  if (o.width === void 0) { o.width = 1024; }
  if (o.height === void 0) { o.height = 768; }
  if (o.cols === void 0) { o.cols = 80; }
  if (o.dest === void 0) { o.dest = process.stdout; }

  var tube = pictureTube({ cols: o.cols });

  tube.pipe(o.dest);
  webshot(url, { windowSize: { width: o.width, height: o.height } }, ready);

  function ready (err, reader) {
    if (err) {
      throw err;
    }
    var file = fs.createWriteStream(name, {
      encoding: 'binary'
    });

    reader.on('data', read);
    reader.on('end', write);

    function read (data) {
      file.write(data.toString('binary'), 'binary');
    }
    function write () {
      fs.createReadStream(name).pipe(tube).on('end', remove);
    }
    function remove () {
     fs.unlink(name);
    }
  }
}

module.exports = hitThat;

'use strict';

var fs = require('fs');
var pictureTube = require('picture-tube');
var webshot = require('webshot');

function hitThat (url, options) {
  var name = Date.now() + '_that.png';
  var o = options || {};
  if (o.width === void 0) { o.width = 1024; }
  if (o.height === void 0) { o.height = 768; }
  if (o.cols === void 0) { o.cols = 80; }
  if (o.dest === void 0) { o.dest = process.stdout; }

  var tube = pictureTube({ cols: o.cols });

  tube.pipe(o.dest);
  webshot(url, { windowSize: { width: o.width, height: o.height } }, ready);

  function ready (err, reader) {
    if (err) {
      throw err;
    }
    var file = fs.createWriteStream(name, {
      encoding: 'binary'
    });

    reader.on('data', read);
    reader.on('end', write);

    function read (data) {
      file.write(data.toString('binary'), 'binary');
    }
    function write () {
      fs.createReadStream(name).pipe(tube).on('end', remove);
    }
    function remove () {
     fs.unlinkSync(name);
    }
  }
}

module.exports = hitThat;

Fix deprecation warning on unlink()


/* jshint node: true */
'use strict';

var fs = require('fs');
var path = require('path');
var merge = require('lodash-node/modern/object/merge');
var template = require('lodash-node/modern/string/template');

module.exports = {
  name: 'ember-cli-rollbar',
  contentFor: function(type, config) {
    var environment = this.app.env;
    config = config.rollbar || {};
    var includeScript = environment !== 'development' || config.enabled;
    if (type === 'head' && includeScript) {
      var rollbarConfig = merge({
        enabled: environment !== 'development',
        captureUncaught: true,
        payload: {
          environment: environment
        }
      }, config);
      var snippetPath = path.join(__dirname, 'addon', 'rollbar-snippet.html');
      var snippetContent = fs.readFileSync(snippetPath, 'utf-8');
      return template(snippetContent)({ rollbarConfig: JSON.stringify(rollbarConfig) });
    }
  }
};

/* jshint node: true */
'use strict';

var fs = require('fs');
var path = require('path');
var merge = require('lodash-node/modern/object/merge');
var template = require('lodash-node/modern/string/template');

module.exports = {
  name: 'ember-cli-rollbar',
  contentFor: function(type, config) {
    var environment = this.app.env;
    config = config.rollbar || {};
    var isProductionEnv = ['development', 'test'].indexOf(environment) === -1;
    var includeScript = isProductionEnv || config.enabled;
    if (type === 'head' && includeScript) {
      var rollbarConfig = merge({
        enabled: isProductionEnv,
        captureUncaught: true,
        payload: {
          environment: environment
        }
      }, config);
      var snippetPath = path.join(__dirname, 'addon', 'rollbar-snippet.html');
      var snippetContent = fs.readFileSync(snippetPath, 'utf-8');
      return template(snippetContent)({ rollbarConfig: JSON.stringify(rollbarConfig) });
    }
  }
};

Disable rollbar for test env


const isBoolean = require('is-boolean')
const isFunction = require('is-function')

const doWheil = (d0, wh1le) => {
  if (!isFunction(d0)) { throw new TypeError('d0 is no function!, D0 MUST BE A FUNCTION') }
  if (!isBoolean(wh1le) && !isFunction(wh1le)) {
    throw new TypeError('wh1le is no boolean or boolyfunc!, WH1LE MUST BE A BOOLEAN OR A BOOLYFUNC')
  }
  do {
    d0()
  } while(isFunction(wh1le) ? wh1le() : wh1le)
}

module.exports = doWheil

const isBoolean = require('is-boolean')
const isFunction = require('is-function')

const doWheil = (d0, wh1le) => {
  if (!isFunction(d0)) { throw new TypeError('d0 is no function!, D0 MUST BE A FUNCTION') }
  const wh1leIsFunction = isFunction(wh1le)
  if (!isBoolean(wh1le) && !wh1leIsFunction) {
    throw new TypeError('wh1le is no boolean or boolyfunc!, WH1LE MUST BE A BOOLEAN OR A BOOLYFUNC')
  }
  do {
    d0()
  } while(wh1leIsFunction ? wh1le() : wh1le)
}

module.exports = doWheil

Reduce the number of calls to isFunction


'use strict'

/**
 * @module ember-refined-faker
 */

 /**
 * @class config
 */

module.exports = {
  name: 'ember-refined-faker',

  options: {
    nodeAssets: {
      faker() {
        return {
          srcDir: 'build/build/',
          import: [
            { path: 'faker.js', using: [{ transformation: 'amd', as: 'faker' }] }
          ],
          enabled: this.__defaults.enabled
        }
      }
    }
  },

  isDevelopingAddon() {
    return !this.app.isProduction
  },

  /**
   * Default configurations.
   * Users can overwrite this in Ember Application's config/environment.js.
   *
   * @property defaults
   * @type Object
   * @param defaults.defaultLocale { String } 缺省使用的语言，默认值：'en_US'
   * @param defaults.imageService { String } 占位图片使用的服务名称，默认值：'default'，使用 faker 内置的占位图片服务
   * @param defaults.enabled { Boolean } 是否开启 ember-refined-faker，默认会在 production 下禁止
   */
 config(env, config) {
    this.__defaults = {
      defaultLocale: 'en_US',
      imageService: 'default',
      enabled: 'production' !== env
    }

    return {
      faker: Object.assign(this.__defaults, config.faker || {})
    }
  }
}

'use strict'

/**
 * @module ember-refined-faker
 */

/**
 * @class config
 */
module.exports = {
  name: 'ember-refined-faker',

  options: {
    nodeAssets: {
      faker() {
        return {
          srcDir: 'build/build/',
          import: [
            { path: 'faker.js', using: [{ transformation: 'amd', as: 'faker' }] }
          ],
          enabled: !this.app.isProduction
        }
      }
    }
  },

  isDevelopingAddon() {
    return !this.app.isProduction
  },

  /**
   * Default configurations.
   * Users can overwrite this in Ember Application's config/environment.js.
   *
   * @property defaults
   * @type Object
   * @param defaults.defaultLocale { String } 缺省使用的语言，默认值：'en_US'
   * @param defaults.imageService { String } 占位图片使用的服务名称，默认值：'default'，使用 faker 内置的占位图片服务
   */
  config(env, config) {
    this.__defaults = {
      defaultLocale: 'en_US',
      imageService: 'default',
    }

    return {
      faker: Object.assign(this.__defaults, config.faker || {})
    }
  }
}

Fix test: can't rely on environment config for ember-cli-node-assets


'use strict';

var React = require('react'),
    withSideEffect = require('react-side-effect');

function reducePropsToState(propsList) {
  var innermostProps = propsList[propsList.length - 1];
  if (innermostProps) {
    var result = {};
    var patt = /^body(.+)$/i;

    for (var key in innermostProps) {
      var m = patt.exec(key);
      if (innermostProps.hasOwnProperty(key) && (m != null)) {
        result[m[1]] = innermostProps[key];
      }
    }

    return result;
  }
}

function handleStateChangeOnClient(props) {
  for (var key in props) {
    if (props.hasOwnProperty(key)) {
      if (key == 'Class' || key == 'class') {
        var currentClasses = document.body.getAttribute(key);
        document.body.setAttribute(key, currentClasses + ' ' + props[key]);
      } else {
        document.body.setAttribute(key, props[key]);
      }
    }
  }
}

var BodyAttribute = React.createClass({
  displayName: 'BodyAttribute',

  render: function render() {
    if (this.props.children) {
      return React.Children.only(this.props.children);
    } else {
      return null;
    }
  }
});

module.exports = withSideEffect(
  reducePropsToState,
  handleStateChangeOnClient
)(BodyAttribute);

'use strict';

var React = require('react'),
    withSideEffect = require('react-side-effect');

function reducePropsToState(propsList) {
  var innermostProps = propsList[propsList.length - 1];
  if (innermostProps) {
    var result = {};
    var patt = /^body(.+)$/i;

    for (var key in innermostProps) {
      var m = patt.exec(key);
      if (innermostProps.hasOwnProperty(key) && (m != null)) {
        result[m[1]] = innermostProps[key];
      }
    }

    return result;
  }
}

function handleStateChangeOnClient(props) {
  for (var key in props) {
    if (props.hasOwnProperty(key)) {
      if (key == 'Class' || key == 'class') {
        var currentClasses = document.body.getAttribute(key);
        if (!currentClasses) {
            document.body.setAttribute(key, props[key]);
        } else if (currentClasses.indexOf(props[key]) === -1)
            // Simple dedupe to prevent handleStateChangeOnClient() called multiple time
            document.body.setAttribute(key, currentClasses + ' ' + props[key]);
      } else {
        document.body.setAttribute(key, props[key]);
      }
    }
  }
}

var BodyAttribute = React.createClass({
  displayName: 'BodyAttribute',

  render: function render() {
    if (this.props.children) {
      return React.Children.only(this.props.children);
    } else {
      return null;
    }
  }
});

module.exports = withSideEffect(
  reducePropsToState,
  handleStateChangeOnClient
)(BodyAttribute);

Fix null and duplicated class name


'use strict';

var through = require('through2');
var glob = require('glob');
var _ = require('lodash');

module.exports = function() {

    var transform = function(file, env, cb) {

        // find all instances matching
        var contents = file.contents.toString('utf-8');

        var reg = /@import\s+\"([^\"]*\*[^\"]*)\";/;
        var result;

        while((result = reg.exec(contents)) !== null) {

            var index = result.index;
            var sub = result[0];
            var globName = result[1];

            var files = glob.sync(file.base + globName);
            var replaceString = '';

            _.each(files, function(filename) {
                replaceString += '@import "' + filename + '";\n';
            });

            contents = contents.replace(sub, replaceString);

        }

        file.contents = new Buffer(contents);
        cb(null, file);
    };

    return through.obj(transform);
};

'use strict';

var through = require('through2');
var glob = require('glob');

module.exports = function() {

    var transform = function(file, env, cb) {

        // find all instances matching
        var contents = file.contents.toString('utf-8');

        var reg = /@import\s+\"([^\"]*\*[^\"]*)\";/;
        var result;

        while((result = reg.exec(contents)) !== null) {

            var index = result.index;
            var sub = result[0];
            var globName = result[1];

            var files = glob.sync(file.base + globName);
            var replaceString = '';

            files.forEach(function(filename){
                replaceString += '@import "' + filename + '";\n';
            });

            contents = contents.replace(sub, replaceString);

        }

        file.contents = new Buffer(contents);
        cb(null, file);
    };

    return through.obj(transform);
};

Replace lodash each() with standard forEach()


#!/usr/bin/env node

var http = require('http')
var opn = require('opn')
var rc = module.require('rc')
var argv = require('optimist').argv
var config = rc('hcat', {}, argv)

if (argv.usage) {
	console.log(require('./usage.js'))
	process.exit(0)
}

function handler(request, response) {
  // Only accept one request
  server.close();

	var contentType = 'text/html'

	var stream = process.stdin

	response.setHeader('Content-Type', contentType)

	stream.pipe(response)
}

var server = http.createServer(handler)

server.on('listening', function() {
  opn('http://localhost:' + server.address().port)
})

server.listen(config.port || 0, 'localhost')

#!/usr/bin/env node

var http = require('http')
var opn = require('opn')
var rc = module.require('rc')
var argv = require('optimist').argv
var config = rc('hcat', {}, argv)

if (argv.usage) {
	console.log(require('./usage.js'))
	process.exit(1)
}

function handler(request, response) {
  // Only accept one request
  server.close();

	var contentType = 'text/html'

	var stream = process.stdin

	response.setHeader('Content-Type', contentType)

	stream.pipe(response)
}

var server = http.createServer(handler)

server.on('listening', function() {
  opn('http://localhost:' + server.address().port)
})

server.listen(config.port || 0, 'localhost')

Use non-zero exit code for usage


module.exports = function fnStringify (fn) {
  return /\*([^*]*)\*/.exec(fn.toString())[1].trim()
}

module.exports = function fnStringify (fn) {
  var comment = /\*([^*]*)\*/.exec(fn.toString())[1]
  var indent = /([^\n]\s+)/.exec(comment)[1].length
  return comment.split('\n').map(function (line) {
    return line.slice(indent)
  }).join('\n').trim()
}

Fix example and basic test


var express = require('express');
var Connection = require('./lib/droonga-protocol/connection').Connection;
var httpAdapter = require('./lib/adapter/http');
var socketIoAdapter = require('./lib/adapter/socket.io');
var dashboardUI = require('./lib/ui/dashboard');

function droonga(application, params) {
  params = params || {};

  params.connection = params.connection || new Connection(params);
  var connection = params.connection;

  params.prefix = params.prefix || '';
  params.prefix = params.prefix.replace(/\/$/, '');

  httpAdapter.register(application, params);

  if (params.server) {
    socketIoAdapter.register(application, params.server, params);
    params.server.on('close', function() {
      // The connection can be mocked/stubbed. We don't need to close
      // such a fake connection.
      if (typeof connection.close == 'function')
        connection.close();
    });
  }

  dashboardUI.register(application, params);

  application.connection = connection;
  application.emitMessage = connection.emitMessage.bind(connection); // shorthand
}

exports.initialize = droonga;
express.application.droonga = function(params) {
  droonga(this, params);
};

require('./lib/adapter/api').exportTo(exports);

exports.command = require('./lib/adapter/command');
exports.cache = require('./lib/cache');
exports.middleware = {
  cacheStatistics: require('./lib/middleware/cache-statistics'),
  cache: require('./lib/middleware/cache')
};

var express = require('express');
var Connection = require('./lib/droonga-protocol/connection').Connection;
var httpAdapter = require('./lib/adapter/http');
var socketIoAdapter = require('./lib/adapter/socket.io');
var dashboardUI = require('./lib/ui/dashboard');

function droonga(application, params) {
  params = params || {};

  params.connection = params.connection || new Connection(params);
  var connection = params.connection;

  params.prefix = params.prefix || '';
  params.prefix = params.prefix.replace(/\/$/, '');

  httpAdapter.register(application, params);

  if (params.server) {
    socketIoAdapter.register(application, params.server, params);
    params.server.on('close', function() {
      // The connection can be mocked/stubbed. We don't need to close
      // such a fake connection.
      if (typeof connection.close == 'function')
        connection.close();
    });
  }

  dashboardUI.register(application, params);

  application.connection = connection;
  application.emitMessage = connection.emitMessage.bind(connection); // shorthand
}

exports.initialize = droonga;
express.application.droonga = function(params) {
  droonga(this, params);
};

require('./lib/adapter/api').exportTo(exports);

exports.command = require('./lib/adapter/command');
exports.Cache = require('./lib/cache');
exports.middleware = {
  cacheStatistics: require('./lib/middleware/cache-statistics'),
  cache: require('./lib/middleware/cache')
};

Use Capital case for class


module.exports = function (Model) {

  Model.on('initialize', function (model) {

    Object.keys(Model.attrs).forEach(function (key) {
      var options = Model.attrs[key]

      if (Object.hasOwnProperty.call(options, 'value')) {
        return Object.defineProperty(model.attrs, key, {
          value: options.value,
          enumerable: true
        })
      }

      if (typeof options.get === 'function') {
        var descriptor = {}
        descriptor.get = options.get.bind(model)

        if (typeof options.set === 'function') {
          descriptor.set = options.set.bind(model)
        }
        return Object.defineProperty(model.attrs, key, descriptor)
      }
    })

  })

}

module.exports = function (Model) {

  Model.on('initialize', function (model) {

    Object.keys(Model.attrs).forEach(function (key) {
      var options = Model.attrs[key]

      // enumerable defaults to false
      var enumerable = !!options.enumerable || false

      if (Object.hasOwnProperty.call(options, 'value')) {
        return Object.defineProperty(model.attrs, key, {
          value: options.value,
          enumerable: enumerable
        })
      }

      if (typeof options.get === 'function') {
        var descriptor = {}
        descriptor.enumerable = enumerable
        descriptor.get = options.get.bind(model)

        if (typeof options.set === 'function') {
          descriptor.set = options.set.bind(model)
        }
        return Object.defineProperty(model.attrs, key, descriptor)
      }
    })

  })

}

Allow enumerable to be specified


// @import parallel2

function conicEquidistant(φ0, φ1) {
  var cosφ0 = Math.cos(φ0),
      n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0),
      G = cosφ0 / n + φ0;

  if (!n) return d3.geo.equirectangular.raw;

  function forward(λ, φ) {
    var ρ = G - φ;
    return [
      ρ * Math.sin(n * λ),
      G - ρ * Math.cos(n * λ)
    ];
  }

  forward.invert = function(x, y) {
    var ρ0_y = G - y;
    return [
      Math.atan2(x, ρ0_y) / n,
      G - sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y)
    ];
  };

  return forward;
}

(d3.geo.conicEquidistant = function() { return parallel2Projection(conicEquidistant); }).raw = conicEquidistant;

// @import parallel2

function conicEquidistant(φ0, φ1) {
  var cosφ0 = Math.cos(φ0),
      n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0),
      G = cosφ0 / n + φ0;

  if (Math.abs(n) < ε) return d3.geo.equirectangular.raw;

  function forward(λ, φ) {
    var ρ = G - φ;
    return [
      ρ * Math.sin(n * λ),
      G - ρ * Math.cos(n * λ)
    ];
  }

  forward.invert = function(x, y) {
    var ρ0_y = G - y;
    return [
      Math.atan2(x, ρ0_y) / n,
      G - sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y)
    ];
  };

  return forward;
}

(d3.geo.conicEquidistant = function() { return parallel2Projection(conicEquidistant); }).raw = conicEquidistant;

Use ε when detecting equirectangular case.


var postcss = require('postcss');

module.exports = postcss.plugin('postcss-messages', function (opts) {
    if ( opts && opts.disabled === true ) {
        return function () { };
    }

    return function (css, result) {
        css.append({ selector: 'body:before' });
        css.last.append({ prop: 'display', value: 'block' });
        css.last.append({ prop: 'padding', value: '20px 30px' });
        css.last.append({ prop: 'background', value: 'red' });
        css.last.append({ prop: 'font-size', value: '16px' });
        css.last.append({ prop: 'color', value: 'white' });
        css.last.append({ prop: 'white-space', value: 'pre' });

        var content = result.warnings().map(function (message) {
            return message.toString().replace(/"/g, '\\"');
        }).join('\\00000a');

        css.last.append({ prop: 'content', value: '"' + content + '"' });
    };
});

var postcss = require('postcss');

module.exports = postcss.plugin('postcss-messages', function (opts) {
    if ( opts && opts.disabled === true ) {
        return function () { };
    };

    var styleKeys = ['display', 'padding', 'background', 'font-size', 'color', 'white-space'];

    var defaultStyles = {
      'display': 'block',
      'padding': '20px 30px',
      'background': 'red',
      'font-size': '16px',
      'color': 'white',
      'white-space': 'pre'
    };
    if ( opts && opts.styles ) {
      for ( var attrname in opts.styles ) {
        if ( opts.styles.hasOwnProperty(attrname) ) {
          defaultStyles[attrname] = opts.styles[attrname];
        };
      };
    };

    return function (css, result) {
        css.append({ selector: (opts && opts.selector) ? opts.selector : 'body:before' });
        for ( var style in defaultStyles ) {
          if ( defaultStyles.hasOwnProperty(style) ) {
            css.last.append({ prop: style, value: defaultStyles[style] });
          }
        };

        var content = result.warnings().map(function (message) {
            return message.toString().replace(/"/g, '\\"');
        }).join('\\00000a');

        css.last.append({ prop: 'content', value: '"' + content + '"' });
    };
});

Add styles from options logic


var Prism = require('prismjs');
var cheerio = require('cheerio');
var path = require('path');

var prismCSS = require.resolve('prismjs/themes/prism.css');

module.exports = {
  book: {
    assets: path.dirname(prismCSS),
    css: [path.basename(prismCSS)]
  },
  hooks: {
    page: function (page) {
      page.sections.forEach(function (section) {
        var $ = cheerio.load(section.content);

        $('code').each(function() {
          var text = $(this).text();
          var highlighted = Prism.highlight(text, Prism.languages.javascript);
          $(this).html(highlighted);
        });

        section.content = $.html();
      });
      return page;
    }
  }
};

var Prism = require('prismjs');
var path = require('path');

var prismCSS = require.resolve('prismjs/themes/prism.css');

var DEFAULT_LANGUAGE = 'javascript';
var MAP_LANGUAGES = {
  'py': 'python',
  'js': 'javascript',
  'json': 'javascript',
  'rb': 'ruby',
  'csharp': 'cs',
};

var assets = {
  assets: path.dirname(prismCSS),
  css: [path.basename(prismCSS)]
};

module.exports = {
  book: assets,
  ebook: assets,
  blocks: {
    code: function(block) {
      // Normalize language id
      var lang = block.kwargs.language || DEFAULT_LANGUAGE;
      lang = MAP_LANGUAGES[lang] || lang;

      // Get languages from prism
      lang = Prism.languages[lang] || Prism.languages[DEFAULT_LANGUAGE];

      return Prism.highlight(block.body, lang);
    }
  }
};

Define block "code" for highlighting


(function(Backbone) {

  var superDelegateEvents = Backbone.View.prototype.delegateEvents;

  _.extend(Backbone.View.prototype, {

    // Hook up `listen` processing in `delegateEvents`.
    delegateEvents: function(events) {
      superDelegateEvents.call(this, events);
      this._setupListening();
    },

    // Take a the value of the `listen` property and process them into
    // `listenTo` calls. `listen` should have the following form:
    //
    // `{object: {"event": "functionNameOrDeclaration"}`
    //
    // `object` should have `Backbone.Events` mixed in and should be
    // available on `this` after `initialize` e.g. you can initialize
    // it in `initialize` or have somewhere on the prototype chain.
    _setupListening: function() {
      var listen;
      if (!(listen = _.result(this, 'listen'))) return;
      this.stopListening();
      for (var prop in listen) {
        var object = this[prop];
        if (!object) throw new Error('Property "' + prop + '" does not exist');
        var events = listen[prop];
        for (var event in events) {
          var method = events[event];
          if (!_.isFunction(method)) method = this[events[event]];
          if (!method) throw new Error('Method "' + events[event] + '" does not exist');
          this.listenTo(object, event, method);
        }
      }
    }

  });

}).call(this, Backbone);

(function(Backbone) {

  var superDelegateEvents = Backbone.View.prototype.delegateEvents;

  _.extend(Backbone.View.prototype, {

    // Hook up `listen` processing in `delegateEvents`.
    delegateEvents: function(events) {
      superDelegateEvents.call(this, events);
      this._setupListening();
    },

    // Take the value of the `listen` property and process it into
    // `listenTo` calls. `listen` should have the following form:
    //
    // `{object: {"event": "functionNameOrDeclaration"}}`
    //
    // `object` should have `Backbone.Events` mixed in and should be
    // available on `this` after `initialize` e.g. it can be created
    // in `initialize` or somewhere down the prototype chain.
    _setupListening: function() {
      var listen;
      if (!(listen = _.result(this, 'listen'))) return;
      this.stopListening();
      for (var prop in listen) {
        var object = this[prop];
        if (!object) throw new Error('Property "' + prop + '" does not exist');
        var events = listen[prop];
        for (var event in events) {
          var method = events[event];
          if (!_.isFunction(method)) method = this[events[event]];
          if (!method) throw new Error('Method "' + events[event] + '" does not exist');
          this.listenTo(object, event, method);
        }
      }
    }

  });

}).call(this, Backbone);

Fix up grammar errors in the comments


'use strict'

const expandGlobPaths = require('./expand-glob-paths')
const standard = require('standard')
const path = require('path')

const CONFIG = require('../config')

module.exports = function () {
  const globPathsToLint = [
    path.join(CONFIG.repositoryRootPath, 'exports', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'packages', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'script', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'src', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'static', '*.js')
  ]
  return expandGlobPaths(globPathsToLint).then((paths) => {
    return new Promise((resolve, reject) => {
      standard.lintFiles(paths, (error, lintOutput) => {
        if (error) {
          reject(error)
        } else {
          const errors = []
          for (let result of lintOutput.results) {
            for (let message of result.messages) {
              errors.push({path: result.filePath, lineNumber: message.line, message: message.message, rule: message.ruleId})
            }
          }
          resolve(errors)
        }
      })
    })
  })
}

'use strict'

const expandGlobPaths = require('./expand-glob-paths')
const standard = require('standard')
const path = require('path')

const CONFIG = require('../config')

module.exports = async function () {
  const globPathsToLint = [
    path.join(CONFIG.repositoryRootPath, 'exports', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'packages', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'script', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'spec', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'src', '**', '*.js'),
    path.join(CONFIG.repositoryRootPath, 'static', '*.js')
  ]
  const globPathsToIgnore = [
    path.join(CONFIG.repositoryRootPath, 'spec', 'fixtures', '**', '*.js')
  ]

  const [includePaths, excludePaths] = await Promise.all([
    expandGlobPaths(globPathsToLint),
    expandGlobPaths(globPathsToIgnore)
  ])

  const paths = includePaths.filter(
    myPath => excludePaths.indexOf(myPath) === -1
  )

  return new Promise((resolve, reject) => {
    standard.lintFiles(paths, (error, lintOutput) => {
      if (error) {
        reject(error)
      } else {
        const errors = []
        for (let result of lintOutput.results) {
          for (let message of result.messages) {
            errors.push({
              path: result.filePath,
              lineNumber: message.line,
              message: message.message,
              rule: message.ruleId
            })
          }
        }
        resolve(errors)
      }
    })
  })
}

Enable linter on spec/ folder


module.exports = function(remote, url) {
    var repoPattern = /github.com(?:[:\/])([^\/]+)\/(.+?)\.git$/;
    var result = repoPattern.exec(url);
    if (!result) {
        throw new Error("the remote '" + remote+ "' is not configured to a github repository");
    }
    return {
        owner: result[1],
        project: result[2]
    };
};

module.exports = function(remote, url) {
    var repoPattern = /github.com(?:[:\/])([^\/]+)\/(.+?)(?:\.git)?$/;
    var result = repoPattern.exec(url);
    if (!result) {
        throw new Error("the remote '" + remote+ "' is not configured to a github repository");
    }
    return {
        owner: result[1],
        project: result[2]
    };
};

Allow plain URLs, without .git at the end


var GatewayProcessManager = require(__dirname+'/../process_manager.js');

/**\
 * @requires GatewayProcessManager
 * @function listProcesses
 *
 * @description Looks into the process manager and lists process that are `online`
 *
 * @param opts
 * @param fn
 */

function listProcesses(opts, fn) {
  processManager = new GatewayProcessManager();
  processManager.listProcesses(opts, fn);
}

module.exports = listProcesses;

var GatewayProcessManager = require(__dirname+'/../process_manager.js');

/**\
 * @requires GatewayProcessManager
 * @function listProcesses
 *
 * @description Looks into the process manager and lists process that are `online`
 * The node.js pm2 module is a daemon that runs and can restart failed processes
 * when they crash. By default several processes are started that represent
 * workers moving transactions through the gateway and their various states.
 *
 * - The `deposits` process takes newly recorded deposits and creates corresponding
 * ripple transactions
 * - The `withdrawals` processes takes newly recorded incoming ripple transactions
 * and creates corresponding external withrawal transactions.
 * - The `outgoing` process takes newly created outgoing ripple transaction
 * records in the gateway and attempts to send them to Ripple, recording the
 * resulting status and transaction hash.
 * - The `incoming` process polls Ripple REST for new transactions made to the
 * gateway's cold wallet address and records them in the ripple transactions table
 *
 * @param opts
 * @param fn
 */

function listProcesses(opts, fn) {
  processManager = new GatewayProcessManager();
  processManager.listProcesses(opts, fn);
}

module.exports = listProcesses;

Add verobse description of listProcesses.


exports.analyze = function(stats) {
  var len = stats.length;
  var ret = {};

  stats.forEach(function(stat) {
    stat.result().forEach(function(item) {
      ret[item.key] = ret[item.key] || { total: 0 };
      ret[item.key].total += item.total;
    });
  });

  Object.keys(ret).forEach(function(key) {
    ret[key].average = +(ret[key].total / len).toFixed(2);
  });

  if (len > 0) {
    ret.files = { total: len };
  }

  return ret;
};

exports.analyze = function(stats) {
  var len = stats.length;
  var ret = {};
  var files = [];
  var total = {};

  stats.forEach(function(stat) {
    var result = stat.result();

    files.push({ filename: stat.file, result: result });

    result.forEach(function(item) {
      total[item.key] = total[item.key] || { total: 0 };
      total[item.key].total += item.total;
    });
  });

  Object.keys(total).forEach(function(key) {
    total[key].average = +(total[key].total / len).toFixed(2);
  });

  return {
    files: files,
    total: { files: len, result: total }
  };
};

Return richer structure for the formatters


/* eslint-disable */
// See: https://jestjs.io/docs/en/configuration.html

module.exports = {
  // Indicates whether the coverage information should be collected while executing the test
  collectCoverage: true,

  // An object that configures minimum threshold enforcement for coverage results
  coverageThreshold: {
    global: { lines: 95 },
  },

  // A preset that is used as a base for Jest's configuration.
  preset: "ts-jest",

  testMatch: ["**/__tests__/**/*.test.ts", "**/?(*.)+(spec|test).ts"],
};

/* eslint-disable */
// See: https://jestjs.io/docs/en/configuration.html

module.exports = {
  // Indicates whether the coverage information should be collected while executing the test
  collectCoverage: true,

  // An object that configures minimum threshold enforcement for coverage results
  coverageThreshold: {
    global: { lines: 98 },
  },

  // A preset that is used as a base for Jest's configuration.
  preset: "ts-jest",

  testMatch: ["**/__tests__/**/*.test.ts", "**/?(*.)+(spec|test).ts"],
};

Update coverage threshold to 98%


'use strict';

const D3 = require('D3');

exports.parser = function(rows) {

    var overviewResponse = rows;

    var overview = D3.nest()
        .key(function(d) {
            return d.region_code;
        })
        .rollup(function(v) {
            console.log(v)
            return {
                'region_code': v[0].region_code,
                'region_name': v[0].region_name,
                'current_total': v[0].current_total,
                'delayed_total': v[0].delayed_total,
                'days_to_payment': v[0].days_to_payment
            }
        })
        .entries(overviewResponse)
        .map(function(d) {
            return d.value;
        });

    var data = {
        'overview': overview
    };

    return data;

};

'use strict';

const D3 = require('D3');

exports.parser = function(rows) {

    var overviewResponse = rows;

    var overview = D3.nest()
        .key(function(d) {
            return d.region_code;
        })
        .rollup(function(v) {
            return {
                'region_code': v[0].region_code,
                'region_name': v[0].region_name,
                'current_total': v[0].current_total,
                'delayed_total': v[0].delayed_total,
                'days_to_payment': v[0].days_to_payment
            }
        })
        .entries(overviewResponse)
        .map(function(d) {
            return d.value;
        });

    var data = {
        'overview': overview
    };

    return data;

};

Remove logging in overview data parser