/*jshint node:true, browser:true */

'use strict';

var Output = require('./output');
var output = null;

/**
 * Try to request MIDI access, and select first
 * defined output. Will fail if no output is available or
 * if MIDI is not supported.
 *
 * @return Promise
 */
function connect() {
    return new Promise(function (resolve, reject) {
        if (output !== null) {
            resolve(output);
            return;
        }

        navigator.requestMIDIAccess().then(function (access) {
            var outputs = access.outputs;

            if (outputs.size) {
                output = new Output(outputs.get(0));
                resolve(output);
            } else {
                reject(new Error(
                    'Aucun synthétiseur MIDI n\'est disponible. Sur ' +
                        'certains systèmes d\'exploitation, un ' +
                        'synthétiseur est disponible par défaut. Si ce ' +
                        'n\'est pas votre cas, il faudra utiliser un ' +
                        'logiciel tiers puis relancer l\'application.'
                ));
            }
        }).catch(function () {
            reject(new Error(
                'Impossible d\'obtenir un accès aux contrôleurs ' +
                    'MIDI, il est possible que votre système ne ' +
                    'supporte pas la norme MIDI ou bien que ' +
                    'vous ayez refusé l\'accès à ces périphériques.'
            ));
        });
    });
}

module.exports = connect;

/*jslint node:true, browser:true */

'use strict';

var Output = require('./output');
var promise = require('es6-promise');
var output = null;

/**
 * Try to request MIDI access, and select first
 * defined output. Will fail if no output is available or
 * if MIDI is not supported.
 *
 * @return Promise
 */
function connect() {
    return new promise.Promise(function (resolve, reject) {
        if (output !== null) {
            resolve(output);
            return;
        }

        navigator.requestMIDIAccess().then(function (access) {
            var outputs = access.outputs;

            if (outputs.size) {
                output = new Output(outputs.get(0));
                resolve(output);
            } else {
                reject(new Error('No available MIDI output'));
            }
        }).catch(function () {
            reject(new Error('MIDI access denied'));
        });
    });
}

module.exports = connect;

Use JSLint, shrink Errors descriptions


var express = require('express');
var router = module.exports = express.Router();
var path = require('path');

var appDir = path.join(__dirname, 'app');

router.get('/', function(req, res) {
  res.render('index');
});

router.get('/:page', function(req, res) {
  res.render(req.params.page);
});

router.get('/pages/:page', function(req, res) {
  res.render('pages/' + req.params.page);
});

Add routing for /:page and /pages/:page


/**
 * Translation configuration
 */
function translationConfig($translateProvider) {
  $translateProvider.useStaticFilesLoader({
    prefix: '/locale/locale-',
    suffix: '.json'
  });

  $translateProvider.useSanitizeValueStrategy('escape');

  $translateProvider.determinePreferredLanguage();
}

translationConfig.$inject = ['$translateProvider'];
angular.module('app').config(translationConfig);

/**
 * Translation configuration
 */
function translationConfig($translateProvider) {
  $translateProvider.useStaticFilesLoader({
    prefix: '/locale/locale-',
    suffix: '.json'
  });

  $translateProvider.fallbackLanguage('en_US');

  $translateProvider.useSanitizeValueStrategy('escape');

  $translateProvider.determinePreferredLanguage();
}

translationConfig.$inject = ['$translateProvider'];
angular.module('app').config(translationConfig);

Set fallback language for angular-translate


/**
 * @fileoverview script.js - JS Orrery - A CS323 Assignment
 * @author Ben Brooks (beb12@aber.ac.uk)
 * @version 1.0
 */

var gl;

function init() {
  canvas = document.getElementById('canvas');
  gl = initWebGL(canvas);
  initScene();
}

window.onload = init;

/**
 * @fileoverview script.js - JS Orrery - A CS323 Assignment
 * @author Ben Brooks (beb12@aber.ac.uk)
 * @version 1.0
 */

function init() {
  canvas = document.getElementById('canvas');
  gl = initWebGL(canvas);
  initScene();
}

window.onload = init;

Remove unnessesary var on gl object


// copy card id on click
const input = document.createElement('input');
document.body.appendChild(input);

document.addEventListener('click', (e) => {

	const elem = e.originalTarget;
	const isCardShortId = elem.classList.contains('card-short-id');

	if (isCardShortId) {
		e.stopImmediatePropagation();

		input.value = elem.textContent.replace('Nr. ', '#');
		input.select();
		document.execCommand('Copy');
	}

}, true);

// format card id
(function () {
	const elems = document.querySelectorAll('.card-short-id');
	for (let elem of elems) {
		elem.textContent = elem.textContent.replace('Nr. ', '#');
	}
})()

// copy card id on click
const input = document.createElement('input');
document.body.appendChild(input);

document.addEventListener('click', (e) => {

	const elem = e.originalTarget;
	const isCardShortId = elem.classList.contains('card-short-id');

	if (isCardShortId) {
		e.stopImmediatePropagation();
		e.preventDefault();

		input.value = elem.textContent.replace('Nr. ', '#');
		input.select();
		document.execCommand('Copy');
	}

}, true);

// format card id
(function () {
	const elems = document.querySelectorAll('.card-short-id');
	for (let elem of elems) {
		elem.textContent = elem.textContent.replace('Nr. ', '#');
	}
})()

Stop opening link when clicking on ID


var path = require("path");
var express = require("express");

var app = express();
app.set('port', 8080);
app.use('/data', express.static('data'))
app.use('/dist', express.static('dist'))

app.get("*", function(req, res) {
  res.sendFile(path.join(__dirname, "index.html"));
});

// Listen for requests
var server = app.listen(app.get('port'), function() {
  var port = server.address().port;
  console.log('Listening on port ' + port);
});

var path = require("path");
var express = require("express");

var app = express();
app.set('port', process.env.PORT || 8080);
app.use('/data', express.static('data'))
app.use('/dist', express.static('dist'))

app.get("*", function(req, res) {
  res.sendFile(path.join(__dirname, "index.html"));
});

// Listen for requests
var server = app.listen(app.get('port'), function() {
  var port = server.address().port;
  console.log('Listening on port ' + port);
});

Allow port to be set by heroku


var express = require('express')
var requireAll = require('./lib/require-all')

controllers = requireAll({
  dirname: __dirname + '/app/controllers',
  filter: /(.+)\.js(on)?$/
})

var app = express()

require('./config/initializers/middleware.js').configure(app)
require('./config/routes').configure(app, controllers)

port = process.env.PORT || 4000
app.listen(port)
console.log('Listening on port ', port)

var express = require('express')
var requireAll = require('./lib/require-all')

controllers = requireAll({
  dirname: __dirname + '/app/controllers',
  filter: /(.+)\.js(on)?$/
})

var app = express()

require('./config/initializers/middleware.js').configure(app)
require('./config/routes').configure(app, controllers)

address = process.env.ADDRESS || '127.0.0.1'
port = process.env.PORT || 4000
app.listen(port, address)
console.log('Listening on port ', port)
console.log('Listening on IP address ', address)

Make host address configurable in ENV


/* jshint node: true, asi: true, laxcomma: true, esversion: 6 */
'use strict'

var path = require('path');
var ghost = require('./ghost-middleware.js');

const express = require('express')
const app = express()

//ghost({
  //config: path.join(__dirname, 'config.js')
//}).then(function (ghostServer) {
  //ghostServer.start();
//});

app.post('/ask-rayna', (req, res, next) => {
    if (req.body['domo-arigato-mr-roboto'] !== void 0)
        return res.end()

    return res.end()
})

app.use('/', ghost({
    config: path.join(__dirname, 'config.js')
}))

/* jshint node: true, asi: true, laxcomma: true, esversion: 6 */
'use strict'

var path = require('path');
var ghost = require('./ghost-middleware.js');

const express = require('express')
const app = express()

//ghost({
  //config: path.join(__dirname, 'config.js')
//}).then(function (ghostServer) {
  //ghostServer.start();
//});

app.get('/api/ask-rayna', (req, res, next) => {
    res.json({
        token: 'owo woo woow oo'
    })
})

app.post('/api/ask-rayna', (req, res, next) => {
    if (req.body['domo-arigato-mr-roboto'] !== void 0)
        return res.end()

    return res.end()
})

app.use('/', ghost({
    config: path.join(__dirname, 'config.js')
}))

app.listen(process.env.PORT || 3000, () => {
    console.info('Listening')
})

Set up contact form api endpoint


"use strict";

var util = require('util');
var events = require('events');
var ServiceObject = require('./service_object');

var Service = module.exports = function(bus, serviceName) {
	var self = this;

	self.bus = bus;
	self.serviceName = serviceName;
	self.objects = {};

	self.on('request', function(uniqueName, sender, objectPath, interfaceName, member, message, args) {
		var iface = self.objects[objectPath]['interfaces'][interfaceName];
		if (!iface)
			return;

		iface.call.apply(iface, [ member, message, args ]);
	});
};

util.inherits(Service, events.EventEmitter);

Object.defineProperty(Service.prototype, 'connected', {
	get: function() {
		return this.bus.connected;
	}
});

Service.prototype.createObject = function(objectPath) {
	var self = this;

	if (!self.objects[objectPath])
		self.objects[objectPath] = new ServiceObject(self, objectPath);

	// Register object
	self.bus._dbus.registerObjectPath(self.bus.connection, objectPath);

	return self.objects[objectPath];
};

Service.prototype.removeObject = function(object) {
	var self = this;

	self.bus._dbus.unregisterObjectPath(self.bus.connection, object.path);
};

Service.prototype.disconnect = function() {
	var self = this;

	self.bus.disconnect();
};

"use strict";

var util = require('util');
var events = require('events');
var ServiceObject = require('./service_object');

var Service = module.exports = function(bus, serviceName) {
	var self = this;

	self.bus = bus;
	self.serviceName = serviceName;
	self.objects = {};

	self.on('request', function(uniqueName, sender, objectPath, interfaceName, member, message, args) {
		var iface = self.objects[objectPath]['interfaces'][interfaceName];
		if (!iface)
			return;

		iface.call.apply(iface, [ member, message, args ]);
	});
};

util.inherits(Service, events.EventEmitter);

Object.defineProperty(Service.prototype, 'connected', {
	get: function() {
		return this.bus.connected;
	}
});

Service.prototype.createObject = function(objectPath) {
	var self = this;

	if (!self.objects[objectPath])
		self.objects[objectPath] = new ServiceObject(self, objectPath);

	// Register object
	self.bus._dbus.registerObjectPath(self.bus.connection, objectPath);

	return self.objects[objectPath];
};

Service.prototype.removeObject = function(object) {
	var self = this;

	self.bus._dbus.unregisterObjectPath(self.bus.connection, object.path);

	delete self.objects[object.path];
};

Service.prototype.disconnect = function() {
	var self = this;

	self.bus.disconnect();
};

Remove object from cache when unregistered


const createTab = id => {
    browser.notifications.clear(id)
    browser.tabs.create({
        url: 'https://worldbrain.helprace.com/i34-feature-tagging',
    })
}

const updateNotification = () => {
    browser.notifications.create({
        type: 'basic',
        title: 'NEW FEATURE: Tagging',
        iconUrl: '/img/worldbrain-logo-narrow.png',
        message: 'Click for more Information',
        buttons: [{ title: 'Click for more Information' }],
    })

    browser.notifications.onButtonClicked.addListener((id, index) => {
        createTab(id)
    })

    browser.notifications.onClicked.addListener(id => {
        createTab(id)
    })
}

export default updateNotification

const createTab = id => {
    browser.notifications.clear(id)
    browser.tabs.create({
        url: 'https://worldbrain.helprace.com/i34-feature-tagging',
    })
}

const updateNotification = () => {
    browser.notifications.create({
        type: 'basic',
        title: 'NEW FEATURE: Tagging',
        iconUrl: '/img/worldbrain-logo-narrow.png',
        message: 'Click for more Information',
    })

    browser.notifications.onClicked.addListener(createTab)
}

export default updateNotification

Remove button from update notif


export const getCKEditorDocumentId = (documentId, userId, formType) => {
  if (documentId) return `${documentId}-${userId}-${formType}`
  return `${userId}-${formType}`
}

export function generateTokenRequest(documentId, userId, formType) {
  return () => {
    return new Promise( ( resolve, reject ) => {
        const xhr = new XMLHttpRequest();

        xhr.open( 'GET', '/ckeditor-token' );

        xhr.addEventListener( 'load', () => {
            const statusCode = xhr.status;
            const xhrResponse = xhr.response;

            if ( statusCode < 200 || statusCode > 299 ) {
                return reject( new Error( 'Cannot download a new token!' ) );
            }

            return resolve( xhrResponse );
        } );

        xhr.addEventListener( 'error', () => reject( new Error( 'Network error' ) ) );
        xhr.addEventListener( 'abort', () => reject( new Error( 'Abort' ) ) );

        if (documentId) xhr.setRequestHeader( 'document-id', documentId );
        if (userId) xhr.setRequestHeader( 'user-id', userId );
        if (formType) xhr.setRequestHeader( 'form-type', formType );

        xhr.send();
    } );
  }
}

export const getCKEditorDocumentId = (documentId, userId, formType) => {
  if (documentId) return `${documentId}-${formType}`
  return `${userId}-${formType}`
}

export function generateTokenRequest(documentId, userId, formType) {
  return () => {
    return new Promise( ( resolve, reject ) => {
        const xhr = new XMLHttpRequest();

        xhr.open( 'GET', '/ckeditor-token' );

        xhr.addEventListener( 'load', () => {
            const statusCode = xhr.status;
            const xhrResponse = xhr.response;

            if ( statusCode < 200 || statusCode > 299 ) {
                return reject( new Error( 'Cannot download a new token!' ) );
            }

            return resolve( xhrResponse );
        } );

        xhr.addEventListener( 'error', () => reject( new Error( 'Network error' ) ) );
        xhr.addEventListener( 'abort', () => reject( new Error( 'Abort' ) ) );

        if (documentId) xhr.setRequestHeader( 'document-id', documentId );
        if (userId) xhr.setRequestHeader( 'user-id', userId );
        if (formType) xhr.setRequestHeader( 'form-type', formType );

        xhr.send();
    } );
  }
}

Fix editor document id creation


'use strict';

let requireAsHash   = require('../utils/require-as-hash'),
    Command         = require('../models/command'),
    commands        = requireAsHash('../commands/*.js', Command),
    CLI             = require('./cli');

module.exports = function(options) {
  let cli = new CLI(options);

  let environment = {
    args:       options.args,
    commands:   commands
  };

  cli.run(environment);
}

'use strict';

let requireAsHash   = require('../utils/require-as-hash'),
    Command         = require('../models/command'),
    Project         = require('../models/project'),
    commands        = requireAsHash('../commands/*.js', Command),
    CLI             = require('./cli');

module.exports = function(options) {
  let cli = new CLI(options);

  let environment = {
    args:     options.args,
    commands: commands,
    project:  Project.closest()
  };

  cli.run(environment);
}

Add the project to the environment


/* @flow */

import appendPxIfNeeded from './append-px-if-needed';
import camelCasePropsToDashCase from './camel-case-props-to-dash-case';
import mapObject from './map-object';
import {getPrefixedStyle} from './prefixer';

function createMarkupForStyles(style: Object): string {
  return Object.keys(style).map(property => {
    return property + ': ' + style[property] + ';';
  }).join('\n');
}

export default function cssRuleSetToString(
  selector: string,
  rules: Object,
  userAgent: ?string,
): string {
  if (!rules) {
    return '';
  }

  const prefixedRules = getPrefixedStyle(rules, userAgent);
  const rulesWithPx = mapObject(
    prefixedRules,
    (value, key) => appendPxIfNeeded(key, value)
  );
  const cssPrefixedRules = camelCasePropsToDashCase(rulesWithPx);
  const serializedRules = createMarkupForStyles(cssPrefixedRules);

  return selector + '{' + serializedRules + '}';
}

/* @flow */

import appendPxIfNeeded from './append-px-if-needed';
import camelCasePropsToDashCase from './camel-case-props-to-dash-case';
import mapObject from './map-object';
import {getPrefixedStyle} from './prefixer';

function createMarkupForStyles(style: Object): string {
  return Object.keys(style).map(property => {
    return property + ': ' + style[property] + ';';
  }).join('\n');
}

export default function cssRuleSetToString(
  selector: string,
  rules: Object,
  userAgent: ?string,
): string {
  if (!rules) {
    return '';
  }

  const rulesWithPx = mapObject(
    rules,
    (value, key) => appendPxIfNeeded(key, value)
  );
  const prefixedRules = getPrefixedStyle(rulesWithPx, userAgent);
  const cssPrefixedRules = camelCasePropsToDashCase(prefixedRules);
  const serializedRules = createMarkupForStyles(cssPrefixedRules);

  return selector + '{' + serializedRules + '}';
}

Add px if needed before prefixing


import Ember from 'ember';
import {module, test} from 'qunit';
import startApp from 'unicodeparty/tests/helpers/start-app';

let application;

function getChars() {
  return new Set(Ember.$('.emoji-char').toArray().map(el => el.innerText));
}

module('Acceptance | search', {
  beforeEach() {
    application = startApp();
  },

  afterEach() {
    Ember.run(application, 'destroy');
  },
});

test('search for horse emoji', function (assert) {
  visit('/');

  andThen(() => {
    assert.equal(currentURL(), '/');
  });
  fillIn('input', 'horse');
  andThen(() => {
    let characters = getChars();
    assert.equal(Ember.$('.emoji-tile').length, 4, '4 horse emoji');
    assert.ok(!characters.has('🎈'), 'balloon emoji not found');
    assert.ok(characters.has('🐴'), 'horse emoji found');
  });
});

test('search for flag emoji (HU)', function (assert) {
  visit('/');

  fillIn('input', 'hungary');
  andThen(() => {
    assert.equal(Ember.$('.emoji-name').length, 1, '1 Hungarian flag found');
    assert.equal(Ember.$('.emoji-name').text(), 'Hungary', 'Emoji has correct name')
  });
});

import Ember from 'ember';
import {module, test} from 'qunit';
import startApp from 'unicodeparty/tests/helpers/start-app';

let application;

function getChars() {
  return new Set(Ember.$('.emoji-char').toArray().map(el => el.innerText));
}

module('Acceptance | search', {
  beforeEach() {
    application = startApp();
  },

  afterEach() {
    Ember.run(application, 'destroy');
  },
});

test('search for horse emoji', function (assert) {
  visit('/');

  andThen(() => {
    assert.equal(currentURL(), '/');
  });
  fillIn('input', 'horse');
  andThen(() => {
    let characters = getChars();
    assert.equal(Ember.$('.emoji-tile').length, 4, '4 horse emoji');
    assert.ok(!characters.has('🎈'), 'balloon emoji not found');
    assert.ok(characters.has('🐴'), 'horse emoji found');
  });
});

test('search for flag emoji (HU)', function (assert) {
  visit('/');

  fillIn('input', 'hungary');
  andThen(() => {
    assert.equal(Ember.$('.emoji-name').length, 1, '1 Hungarian flag found');
    assert.equal(Ember.$('.emoji-name').text(), 'Hungary',
      'Emoji has correct name');
  });
});

Fix jshint and missing semicolon


function SwatForm(id)
{
	this.id = id;
	this.form_element = document.getElementById(id);
}

SwatForm.prototype.setDefaultFocus = function(element_id)
{
	// TODO: check if another element in this form is already focused

	var element = document.getElementById(element_id);

	if (element)
		element.focus();
}

function SwatForm(id)
{
	this.id = id;
	this.form_element = document.getElementById(id);
}

SwatForm.prototype.setDefaultFocus = function(element_id)
{
	// TODO: check if another element in this form is already focused

	var element = document.getElementById(element_id);

	if (element && typeof element.focus == 'function')
		element.focus();
}

Make sure we only call focus() on focusable elements.


/* global ga */

var eventTracking = (function() {

  'use strict';

  // http://blog.gospodarets.com/track_javascript_angularjs_and_jquery_errors_with_google_analytics/
  var _sendErrorsToGoogleAnalytics = function () {
    window.addEventListener('error', function (err) {
      var lineAndColumnInfo = err.colno ? ' line:' + err.lineno +', column:'+ err.colno : ' line:' + err.lineno;
      ga(
        'send',
        'event',
        'JavaScript Errors',
        err.message,
        err.filename + lineAndColumnInfo + ' -> ' + navigator.userAgent + navigator.platform + screen.width + screen.height,
        0,
        true
      );
    });
  };

  var init = function () {
    _sendErrorsToGoogleAnalytics();
  };

  return {
    init: init
  };
}());

/* global ga */

var eventTracking = (function() {

  'use strict';

  // http://blog.gospodarets.com/track_javascript_angularjs_and_jquery_errors_with_google_analytics/
  var _sendErrorsToGoogleAnalytics = function () {

    window.addEventListener('error', function (err) {

      var ie = window.event || {};
      var errorMessage = err.message || ie.errorMessage;
      var errorFilename = err.filename || ie.errorUrl;
      var errorLineNumber = ', Line: ' + (err.lineno || ie.errorLine);
      var errorColumnNumber = ', Column: ' + (err.colno || 'undefined'); // print undefined as a string if it doesn’t exist
      var userAgent = ', User Agent: ' + navigator.userAgent;
      var platform = ', Platform: ' + navigator.platform;

      ga('send', 'event', 'JavaScript Errors', errorMessage, errorFilename + errorLineNumber + errorColumnNumber + userAgent + platform, 0, true);
    });
  };

  var init = function () {
    _sendErrorsToGoogleAnalytics();
  };

  return {
    init: init
  };
}());

Update my poor man’s JavaScript error event tracking code.


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

define(["util", "require"], function (util, require) {
  var assert = util.assert;

  function clean(t) {
    // Removes <% /* ... */ %> comments:
    t = t.replace(/[<][%]\s*\/\*[\S\s\r\n]*\*\/\s*[%][>]/, "");
    t = util.trim(t);
    t = t.replace(/http:\/\/localhost:8080/g, TogetherJS.baseUrl);
    t = t.replace(/TOOL_NAME/g, 'TogetherJS')
    return t;
  }

  var lang = TogetherJS.getConfig("lang") || "en-US";
  var moduleName = "./templates-" + lang;
  var templatesLang;
  console.warn("loading lang", lang, "template name", moduleName, TogetherJS.getConfig("lang"));
  require([moduleName], function (mod) {
    templatesLang = mod;
  });

  return function (resourceName) {
    assert(templatesLang, "Templates not yet loaded");
    return clean(templatesLang[resourceName]);
  };

});

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

// FIXME: maybe it would be better to dynamically assemble the first
// argument to define() here to include the localized module:
define(["util", "require"], function (util, require) {
  var assert = util.assert;

  function clean(t) {
    // Removes <% /* ... */ %> comments:
    t = t.replace(/[<][%]\s*\/\*[\S\s\r\n]*\*\/\s*[%][>]/, "");
    t = util.trim(t);
    t = t.replace(/http:\/\/localhost:8080/g, TogetherJS.baseUrl);
    t = t.replace(/TOOL_NAME/g, 'TogetherJS');
    return t;
  }

  var lang = TogetherJS.getConfig("lang") || "en-US";
  var moduleName = "templates-" + lang;
  var templatesLang;
  console.warn("loading lang", lang, "template name", moduleName, TogetherJS.getConfig("lang"));
  require([moduleName], function (mod) {
    templatesLang = mod;
  });

  return function (resourceName) {
    // Sometimes require([moduleName]) doesn't return even after the
    // module has been loaded, but this sync version of require() will
    // pick up the module in that case:
    if (! templatesLang) {
      try {
        templatesLang = require(moduleName);
      } catch (e) {
      }
    }
    assert(templatesLang, "Templates not yet loaded");
    return clean(templatesLang[resourceName]);
  };

});

Handle a load order case


var request = require('request');
module.exports = function(bot){
	bot.addCommand('define', 'Define', '[<keyword>]', USER_LEVEL_NORMAL, false, function(event){
		var keyword = event.params.join('+');
		request('http://api.urbandictionary.com/v0/define?term=' + keyword, function(error, response, body){
			if(body){
				try{
					var parsed = JSON.parse(body).list[0];
					console.log(parsed);
					bot.message(event.target, 'Definition for ' + parsed.word + ': ' + parsed.definition);
				}catch(e){}
			}
		});
	});
}

var request = require('request');
module.exports = function(bot){
	bot.addCommand('define', 'Define', '[<keyword>]', USER_LEVEL_NORMAL, false, function(event){
		var keyword = event.params.join('+');
		request('http://api.urbandictionary.com/v0/define?term=' + keyword, function(error, response, body){
			if(body){
				try{
					var parsed = JSON.parse(body).list[0];
					if(parsed){
						bot.message(event.target, 'Definition for ' + parsed.word + ': ' + parsed.definition);
					}else{
						bot.message(event.target, 'Could not find definition.');
					}
				}catch(e){}
			}
		});
	});
}

Add message if definition not found


// if you don't specify a html file, the sniper will generate a div
var app = require("ProtVista");
new app(
    {
        el: yourDiv, text: 'biojs',
        uniprotacc : 'P05067',
        customDataSource: {
            url: './data/externalFeatures_',
            source: 'myLab',
            useExtension: true
        },
        overwritePredictions: true
    }
);

// if you don't specify a html file, the sniper will generate a div
var app = require("ProtVista");
new app(
    {
        el: yourDiv, text: 'biojs',
        uniprotacc : 'P05067',
        customDataSource: {
            url: './data/externalFeatures_',
            source: 'myLab',
            useExtension: true
        },
        overwritePredictions: true,
        defaultSources: false
    }
);

Create case for only external data.


/* jshint node: true */

'use strict';

var path = require('path');

function getTaskConfig(projectConfig) {
	// Browser Sync options object
	// https://www.browsersync.io/docs/options

	var taskConfig = {
		// Files to watch
		files: path.join(__dirname + '/..', projectConfig.dirs.dest),
		// Server config options
		server: {
			baseDir: path.join(__dirname + '/..', projectConfig.paths.dest.static_html),
			// directory: true, // directory listing
			// index: "index.htm", // specific index filename
		},
		ghostMode: false, // Mirror behaviour on all devices
		online: false, // Speed up startup time (When xip & tunnel aren't being used)
		// notify: false // Turn off UI notifications
		// browser: 'google chrome' //Set what browser to open on start - https://www.browsersync.io/docs/options#option-browser
		// open: false // Stop browser automatically opening
	};

	return taskConfig;
}

module.exports = getTaskConfig;

/* jshint node: true */

'use strict';

var path = require('path');

function getTaskConfig(projectConfig) {
	// Browser Sync options object
	// https://www.browsersync.io/docs/options

	var taskConfig = {
		// Files to watch
		files: path.join(__dirname + '/..', projectConfig.dirs.dest),
		// Server config options
		server: {
			baseDir: path.join(__dirname + '/..', projectConfig.paths.dest.static_html),
			// directory: true, // directory listing
			// index: "index.htm", // specific index filename
		},
		ghostMode: false, // Mirror behaviour on all devices
		online: false, // Speed up startup time (When xip & tunnel aren't being used)
		// notify: false // Turn off UI notifications
		// browser: 'google chrome' //Set what browser to open on start - https://www.browsersync.io/docs/options#option-browser
		// open: false // Stop browser automatically opening
		// Use a specific port (instead of the one auto-detected by Browsersync)
		// port: 8080,
		// Change the UI default port
		// ui: {
		// 	port: 8081
		// }
	};

	return taskConfig;
}

module.exports = getTaskConfig;

Add custom port, UI port (commeted out) to default config


(function() {
	var impl = document.implementation;
	var mother;
	if (impl && impl.createHTMLDocument) {
		if (impl.custom) return;
		mother = impl.createHTMLDocument("");
	} else {
		mother = document.createElement('iframe').contentWindow.document;
	}
	document.implementation.__proto__.createHTMLDocument = function(str) {
		var copy = mother.cloneNode(true);
		if (str != null) copy.title = str;
		return copy;
	};
	document.implementation.__proto__.createHTMLDocument.custom = true;
})();

(function() {
	var impl = document.implementation;
	var mother;
	if (!impl) impl = document.implementation = {};
	if (impl.createHTMLDocument) {
		if (impl.createHTMLDocument.custom) return;
		mother = impl.createHTMLDocument("");
	} else {
		mother = document.createElement('iframe').contentWindow.document;
	}
	function createHTMLDocument(str) {
		var copy = mother.cloneNode(true);
		if (str != null) copy.title = str;
		return copy;
	}
	createHTMLDocument.custom = true;
	impl.__proto__.createHTMLDocument = createHTMLDocument;
})();

Fix a few things because it's sunday


var mongoose = require('mongoose');
// var dbUrl = 'mongodb://username:password@mongodb:port/database';
// var dbUrl = process.env.MONGO_DB_URL; // AWS
// var dbUrl = process.env.MONGODB_URI; // Heroku
var dbUrl = 'mongodb://localhost/personalblog';

mongoose.connect(dbUrl, { safe: true });

process.on('SIGINT', function() {
  mongoose.connection.close(function () {
    console.log('Mongoose default connection disconnected');
    process.exit(0);
  });
});

require('./models/user');
require('./models/post');

var mongoose = require('mongoose');
// var dbUrl = 'mongodb://username:password@mongodb:port/database';
// var dbUrl = process.env.MONGO_DB_URL; // AWS
var dbUrl = process.env.MONGODB_URI; // Heroku
// var dbUrl = 'mongodb://localhost/personalblog';

mongoose.connect(dbUrl, { safe: true });

process.on('SIGINT', function() {
  mongoose.connection.close(function () {
    console.log('Mongoose default connection disconnected');
    process.exit(0);
  });
});

require('./models/user');
require('./models/post');

Fix MongoDB URL for heroku


/** Created by hhj on 1/26/16. */
export default function loadEnv(envFile) {
  let env
  if (process.env.IS_BROWSER !== true) {
    const fs = require('fs')
    const nodeEnv = process.env.NODE_ENV === 'production' ? 'production' : 'development'
    const envJson = JSON.parse(fs.readFileSync(envFile, 'utf8'))[nodeEnv]
    env = { ...envJson, ...process.env }
  } else {
    env = process.env
  }

  return env
}

/** Created by hhj on 1/26/16. */
export default function loadEnv(envFile) {
  let env = {}
  if (process.env.IS_BROWSER !== true) {
    const fs = require('fs')
    const nodeEnv = process.env.NODE_ENV === 'production' ? 'production' : 'development'
    try {
      const envJson = JSON.parse(fs.readFileSync(envFile, 'utf8'))[nodeEnv]
      env = { ...envJson, ...process.env }
    } catch(e) {}
  } else {
    env = process.env
  }

  return env
}

Fix non existing .env.json file


global.__onUncaughtError = function(error){
	if(error.nativeException){
		__log("err.message: " + error.message);
		__log("err.stackTrace: " + error.stackTrace);
		// false == do not continue execution
		return false;
	}

	// true == continue execution
	return true;
}

require('./Infrastructure/timers');

global.__JUnitSaveResults = function (unitTestResults) {
	var pathToSdcard = '/sdcard';
	var unitTestFileName = 'android_unit_test_results.xml';
	try {
        var javaFile = new java.io.File(pathToSdcard, unitTestFileName);
        var stream = new java.io.FileOutputStream(javaFile);
        var actualEncoding = 'UTF-8';
        var writer = new java.io.OutputStreamWriter(stream, actualEncoding);
        writer.write(unitTestResults);
        writer.close();
    }
    catch (exception) {
    	__log('failed writing to files dir: ' + exception);
    }
};

require('./Infrastructure/Jasmine/jasmine-2.0.1/boot'); //runs jasmine, attaches the junitOutputter

require("./mainpage");

global.__onUncaughtError = function(error){
	if(error.nativeException){
		__log("err.message: " + error.message);
		__log("err.stackTrace: " + error.stackTrace);
		// false == do not continue execution
		return false;
	}

	// true == continue execution
	return true;
}

require('./Infrastructure/timers');

global.__JUnitSaveResults = function (unitTestResults) {
	var pathToSdcard = '/sdcard';
	var unitTestFileName = 'android_unit_test_results.xml';
	try {
        var javaFile = new java.io.File(pathToSdcard, unitTestFileName);
        javaFile.mkdirs();
        javaFile.createNewFile();

        var stream = new java.io.FileOutputStream(javaFile);
        var actualEncoding = 'UTF-8';
        var writer = new java.io.OutputStreamWriter(stream, actualEncoding);
        writer.write(unitTestResults);
        writer.close();
    }
    catch (exception) {
    	__log('failed writing to files dir: ' + exception);
    }
};

require('./Infrastructure/Jasmine/jasmine-2.0.1/boot'); //runs jasmine, attaches the junitOutputter

require("./mainpage");

Create tests result file explicitly.


#!/usr/bin/env node
// ---------------------------------------------------------------------------------------------------------------------
// This script is intended to automate the versioning and changelog generation process for a release.
// ---------------------------------------------------------------------------------------------------------------------

const shipit = require('@postman/shipit'),

    // npm run release [true] [beta]
    [pushToOrigin, preReleaseSuffix] = process.argv.splice(2);

// only support `beta` suffix
if (preReleaseSuffix && preReleaseSuffix !== 'beta') {
    throw new Error(`Can't prerelease with \`${preReleaseSuffix}\` suffix.`);
}

// 🚢 Just Ship It!
shipit({
    // don't push to origin unless explicitly set
    pushToOrigin: pushToOrigin === 'true',
    // prerelease suffix, if any
    preReleaseSuffix: preReleaseSuffix,
    // make sure that following dependencies are up to date
    dependencyList: [
        'chai-postman', 'liquid-json', 'lodash3', 'postman-collection',
        'teleport-javascript', 'uniscope', 'uvm'
    ]
}).then((version) => {
    console.info('🚀', version);
}).catch((err) => {
    console.error('🔥', err);
    process.exit(1);
});

#!/usr/bin/env node
// ---------------------------------------------------------------------------------------------------------------------
// This script is intended to automate the versioning and changelog generation process for a release.
// ---------------------------------------------------------------------------------------------------------------------

const shipit = require('@postman/shipit'),

    // npm run release [true] [beta]
    [pushToOrigin, preReleaseSuffix] = process.argv.splice(2);

// only support `beta` suffix
if (preReleaseSuffix && preReleaseSuffix !== 'beta') {
    throw new Error(`Can't prerelease with \`${preReleaseSuffix}\` suffix.`);
}

// 🚢 Just Ship It!
shipit({
    mainBranch: 'main',
    // don't push to origin unless explicitly set
    pushToOrigin: pushToOrigin === 'true',
    // prerelease suffix, if any
    preReleaseSuffix: preReleaseSuffix,
    // make sure that following dependencies are up to date
    dependencyList: [
        'chai-postman', 'liquid-json', 'lodash3', 'postman-collection',
        'teleport-javascript', 'uniscope', 'uvm'
    ]
}).then((version) => {
    console.info('🚀', version);
}).catch((err) => {
    console.error('🔥', err);
    process.exit(1);
});

Update @postman/shipit to version v0.3.0


---
---
window.search_data = {
  {%- assign documents = site.documents | concat: site.pages %}
  {%- for document in documents %}
  {%- unless document.title %}{% continue %}{% endunless %}
  "{{ document.url }}": {
    "title": "{{ document.title | xml_escape }}",
    "category": "{{ document.category | xml_escape }}",
    "content": {{ document.content | newline_to_br | strip_newlines | replace: "<br />", " " | strip_html | jsonify }}
  }
  {%- unless forloop.last -%},{%- endunless -%}
  {%- endfor %}
};

---
---
window.search_data = {
  {%- assign documents = site.documents | concat: site.pages %}
  {%- for document in documents %}
  {%- unless document.title %}{% continue %}{% endunless %}
  "{{ document.url | remove: ".html" }}": {
    "title": "{{ document.title | xml_escape }}",
    "category": "{{ document.category | xml_escape }}",
    "content": {{ document.content | newline_to_br | strip_newlines | replace: "<br />", " " | strip_html | jsonify }}
  }
  {%- unless forloop.last -%},{%- endunless -%}
  {%- endfor %}
};

Make sure pages in search index do not have HTML extension


'use strict';

var moduleSrc = ['module-name.js'];
var specDir = 'spec';
var specs = specDir + '/**/*spec.js';
var gulpTasks = ['gulpfile.js', 'gulp/**/*.js'];
var allSrc = moduleSrc.concat(specs).concat(gulpTasks);

module.exports = {
  lint: {
    src: allSrc
  },
  watch: {
    test: allSrc,
    lint: allSrc
  }
};

'use strict';

var moduleSrc = ['module-name.js'];
var specDir = 'spec';
var specs = specDir + '/**/*spec.js';
var gulpTasks = ['gulpfile.js', 'gulp/**/*.js'];
var src = ['lib/**/*.js', 'conf/*.js'];
var conf = ['conf/*.json'];
var allSrc = moduleSrc.concat(specs).concat(gulpTasks).concat(src);

module.exports = {
  lint: {
    src: allSrc
  },
  watch: {
    test: allSrc.concat(conf),
    lint: allSrc
  }
};

Add lib and conf directories


/* @flow */

const router = require('express').Router();
const SpotifyController = require('./SpotifyController');
const controller = new SpotifyController();

const validParams = ['song', 'artist'];

/**
 * Middleware layer that verifies that both parameter and keyword
 * are present in the command
 */
router.post('/', (req, res, next) => {
  const { body } = req;
  const { text } = body;

  const [param, keyword] = text.split(' ');
  if (validParams.indexOf(param) === -1 || keyword.length <= 0) {
    res.status(200).send('Please enter a valid command!');
    return;
  }

  req.param = param;
  req.keyword = keyword;
  next();
});

/**
 * Main router endpoint.
 * Makes the call to the controller and returns the message
 */
router.post('/', (req, res) => {
  const param: string = req.param;
  const keyword: string = req.keyword;

  controller.search(param, keyword)
    .then(response => {
      res.status(200).send(response);
    });

});

module.exports = router;

/* @flow */

const router = require('express').Router();
const SpotifyController = require('./SpotifyController');
const controller = new SpotifyController();

const validParams = ['song', 'artist'];

/**
 * Middleware layer that verifies that both parameter and keyword
 * are present in the command
 */
router.post('/', (req, res, next) => {
  const { body } = req;
  const { text } = body;

  const tokens: [string] = text.split(' ');
  const param: string = tokens[0];
  const keyword: string = tokens.slice(1).join(' ');

  console.log(param);
  console.log(keyword);

  if (validParams.indexOf(param) === -1 || keyword.length <= 0) {
    res.status(200).send('Please enter a valid command!');
    return;
  }

  req.param = param;
  req.keyword = keyword;
  next();
});

/**
 * Main router endpoint.
 * Makes the call to the controller and returns the message
 */
router.post('/', (req, res) => {
  const param: string = req.param;
  const keyword: string = req.keyword;

  controller.search(param, keyword)
    .then(response => {
      res.status(200).send(response);
    });

});

module.exports = router;

Join the rest of the tokens after slicing the param


import {resolveRoles} from '@sanity/resolver'
import isPlainObject from 'lodash/isPlainObject'
import merge from 'lodash/merge'

let resolving = false
const waiting = []
const roleName = 'variables:@sanity/base/style'

function getStyleVariables(basePath) {
  if (resolving) {
    return new Promise((resolve, reject) => {
      waiting.push({resolve, reject})
    })
  }

  resolving = true
  return resolveRoles({basePath})
    .then(result => {
      const role = result.fulfilled[roleName] || []
      const implementations = role.map(impl => {
        const implementer = require(impl.path)
        const implementation = implementer.__esModule && implementer.default || implementer

        if (!isPlainObject(implementation)) {
          throw new Error(
            `Plugin "${impl.plugin}" implemented "${roleName}", but did not export a plain object`
          )
        }

        return implementation
      })

      const res = merge({}, ...implementations)

      while (waiting.length) {
        waiting.shift().resolve(res)
      }

      resolving = false
      return res
    })
    .catch(err => {
      while (waiting.length) {
        waiting.shift().reject(err)
      }

      resolving = false
    })
}

export default getStyleVariables

import {resolveRoles} from '@sanity/resolver'
import isPlainObject from 'lodash/isPlainObject'
import merge from 'lodash/merge'

let resolving = false
const waiting = []
const roleName = 'variables:@sanity/base/theme'

function getStyleVariables(basePath) {
  if (resolving) {
    return new Promise((resolve, reject) => {
      waiting.push({resolve, reject})
    })
  }

  resolving = true
  return resolveRoles({basePath})
    .then(result => {
      const role = result.fulfilled[roleName] || []
      const implementations = role.map(impl => {
        const implementer = require(impl.path)
        const implementation = implementer.__esModule && implementer.default || implementer

        if (!isPlainObject(implementation)) {
          throw new Error(
            `Plugin "${impl.plugin}" implemented "${roleName}", but did not export a plain object`
          )
        }

        return implementation
      })

      const res = merge({}, ...implementations)

      while (waiting.length) {
        waiting.shift().resolve(res)
      }

      resolving = false
      return res
    })
    .catch(err => {
      while (waiting.length) {
        waiting.shift().reject(err)
      }

      resolving = false
    })
}

export default getStyleVariables

Change style variables role name


'use strict';
const Sequelize = require('sequelize');

// projects-model.js - A sequelize model
//
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.

module.exports = function(sequelize) {
  const Projects = sequelize.define('Projects', {
    name: {
      type: Sequelize.STRING,
      allowNull: false
    },
    description:{
      type: Sequelize.STRING,
      allowNull: false
    },
  }, {

    classMethods: {
      associate() {
        Projects.belongsTo(sequelize.models.Users, {foreignKey: 'userid'});
        Projects.belongsTo(sequelize.models.Submissions, {foreignKey: 'submissionid'});
      }
    }
  });

  // Projects.sync();

  return Projects;
};

'use strict';
const Sequelize = require('sequelize');

// projects-model.js - A sequelize model
//
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.

module.exports = function(sequelize) {
  const Projects = sequelize.define('Projects', {
    name: {
      type: Sequelize.STRING,
      allowNull: false
    },
    description:{
      type: Sequelize.STRING,
      allowNull: false
    },
    bounty: {
      type: Sequelize.INTERGER,
      allowNull: false,
    },
    videoUrl: {
      type: Sequelize.STRING,
      allowNull: true
    },
    image: {
      type: Sequelize.BLOB('long'),
      allowNull: true
    }
  }, {

    classMethods: {
      associate() {
        Projects.belongsTo(sequelize.models.Users, {foreignKey: 'userid'});
        Projects.belongsTo(sequelize.models.Submissions, {foreignKey: 'submissionid'});
      }
    }
  });

  // Projects.sync();

  return Projects;
};

Add missing data to the projects table.


// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  var text = ('Hello, Docker!\n' +
              'This is Node version ' + process.versions.node + '.\n' +
              'Love, The New Tricks.\n');
  response.end(text);
});

var port = process.env.PORT || 3717;
server.listen(port);

// Put a friendly message on the terminal
console.log('Server running at http://127.0.0.1:' + port + '/');

// Load the http module to create an http server.
var http = require('http');
var util = require('util');
var commands = {
  currGitBranch: 'git rev-parse --abbrev-ref HEAD',
  currGitCommitHash: 'git rev-parse --verify HEAD'
};

function getProcessStdout(command, callback) {
  require('child_process').exec(command, function(err, stdout, stderr) {
    if (err) callback(err, null);
    var output = stdout.toString().replace(/^\s+|\s+$/g, '');
    callback(null, output);
  });
}

var branch = '';
var commitHash = '';
getProcessStdout(commands.currGitBranch, function(err, output) {
  branch = output;
});
getProcessStdout(commands.currGitCommitHash, function(err, output) {
  commitHash = output;
});

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  var text = ('Hello, Docker!\n' +
              util.format('Node version: %s\n', process.versions.node) +
              util.format('Git branch: %s\n', branch) +
              util.format('Git commit: %s\n', commitHash) +
              'Love, The New Tricks.\n');
  response.end(text);
});

var port = process.env.PORT || 3717;
server.listen(port);

// Put a friendly message on the terminal
console.log('Server running at http://127.0.0.1:' + port + '/');

Add Git info to server response


#!/usr/bin/env node

var addCommas = require('add-commas')
var columnify = require('columnify')
var minimist  = require('minimist')
var npmme     = require('./')

var argv = minimist(process.argv.slice(2), { boolean: 'p' })
if (!argv._[0]) return console.error([
    'Usage:'
  , '  npm-me <username>'
  , '  npm-me -p <package>'
].join('\n'))

// Individal package download counts
if (argv.p) return npmme.pkg(argv._[0], function(err, count) {
  console.log()
  console.log(argv._[0] + ' ' + addCommas(count))
  console.log()
})

// Username package download counts
npmme(argv._[0], function(err, downloads) {
  if (err) throw err
  downloads = downloads
  .filter(Boolean)
  .map(function(dl) {
    dl.count = Number(dl.count)
    return dl
  })
  .sort(function(a, b) {
    return a.count - b.count
  })
  console.log()
  console.log(columnify(downloads.map(function(dl) {
    return {
      name: dl.name
     , count: addCommas(dl.count)
    }
  }), {config: {count: {align: 'right'}}}))

  var total = downloads.reduce(function(total, dl) {
    return total + dl.count
  }, 0)

  console.log()
  console.log('Total ', addCommas(total))
})

#!/usr/bin/env node

var addCommas = require('add-commas')
var columnify = require('columnify')
var minimist  = require('minimist')
var npmme     = require('./')

var argv = minimist(process.argv.slice(2), { boolean: 'p' })
if (!argv._[0]) return console.error([
    'Usage:'
  , '  npm-me <username>'
  , '  npm-me -p <package>'
].join('\n'))

// Individal package download counts
if (argv.p) return npmme.pkg(argv._[0], function(err, count) {
  console.log()
  console.log(argv._[0] + ' ' + addCommas(count))
  console.log()
})

// Username package download counts
npmme(argv._[0], function(err, downloads) {
  if (err) throw err
  downloads = downloads
  .filter(Boolean)
  .map(function(dl) {
    dl.count = Number(dl.count) || 0
    return dl
  })
  .sort(function(a, b) {
    return a.count - b.count
  })
  console.log()
  console.log(columnify(downloads.map(function(dl) {
    return {
      name: dl.name
     , count: addCommas(dl.count)
    }
  }), {config: {count: {align: 'right'}}}))

  var total = downloads.reduce(function(total, dl) {
    return total + dl.count
  }, 0)

  console.log()
  console.log('Total ', addCommas(total))
})

Handle 0 download counts in CLI


(function() {
  module.exports.register = function(Handlebars, options) {
    var fs = require('fs')
      , path  = require("path")
      , _     = require('lodash')

    /*
     * Usage: {{ include [partial] }}
     */
    Handlebars.registerHelper("include", function(template, datafile) {
      var partial = Handlebars.partials[template]
      if (typeof partial === "string") {
        partial = Handlebars.compile(partial)
        Handlebars.partials[template] = partial
      }
      if (!partial) {
        return new Handlebars.SafeString('Partial **' + template + '** not found.')
      }

      var context = _.extend({}, this, JSON.parse(fs.readFileSync(datafile, 'utf8')))
      return new Handlebars.SafeString(partial(context))
    })
  }
}).call(this)

(function() {
  module.exports.register = function(Handlebars, options) {
    var fs = require('fs')
      , path  = require("path")
      , _     = require('lodash')

    /*
     * Usage: {{ include [partial] }}
     */
    Handlebars.registerHelper("include", function(template, datafile) {
      var partial = Handlebars.partials[template]
      if (typeof partial === "string") {
        partial = Handlebars.compile(partial)
        Handlebars.partials[template] = partial
      }
      if (!partial) {
        if (fs.existsSync(template)) {
          return new Handlebars.SafeString(fs.readFileSync(template))
        }
        return new Handlebars.SafeString('**' + template + '** is not a partial nor a readable file.')
      }

      var context = _.extend({}, this, JSON.parse(fs.readFileSync(datafile, 'utf8')))
      return new Handlebars.SafeString(partial(context))
    })
  }
}).call(this)

Allow {{include}} helper to load not only partials, but also files


var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')

var module = require('tachyons-max-widths/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-max-widths/tachyons-max-widths.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)

var srcCSS = fs.readFileSync('./src/_max-widths.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')

var template = fs.readFileSync('./templates/docs/max-widths/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
  module: module,
  moduleVersion: module.version,
  moduleSize: moduleSize,
  moduleObj: moduleObj,
  srcCSS: srcCSS,
  navDocs: navDocs
})

fs.writeFileSync('./docs/layout/max-widths/index.html', html)

var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')

var module = require('tachyons-max-widths/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-max-widths/tachyons-max-widths.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)

var srcCSS = fs.readFileSync('./src/_max-widths.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')

var template = fs.readFileSync('./templates/docs/max-widths/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
  module: module,
  moduleVersion: module.version,
  moduleSize: moduleSize,
  moduleObj: moduleObj,
  srcCSS: srcCSS,
  navDocs: navDocs,
  siteFooter: siteFooter
})

fs.writeFileSync('./docs/layout/max-widths/index.html', html)

Add site footer to each documentation generator


import Vector2 from 'flockn/types/vector2';

class Rect {
  constructor(x = 0, y = 0, w = 0, h = 0) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
  }

  toString() {
    return JSON.stringify({
      x: this.x,
      y: this.y,
      w: this.w,
      h: this.h
    });
  }

  static fromString(str) {
    var obj = JSON.parse(str);

    return new Rect(obj.x, obj.y, obj.w, obj.h);
  }

  center() {
    return new Vector2(this.w / 2, this.h / 2);
  }

  contains(vector) {
    return (vector.x >= this.x) && (vector.y >= this.y) && (vector.x < this.x + this.w) && (vector.y < this.y + this.h);
  }
}

export default Rect;

import Vector2 from 'flockn/types/vector2';

class Rect {
  constructor(x = 0, y = 0, w = 0, h = 0) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
  }

  clone() {
    return new Rect({x: this.x, y: this.y, w: this.w, h: this.h});
  }

  toJSON() {
    return {x: this.x, y: this.y, w: this.w, h: this.h};
  }

  toString() {
    return JSON.stringify(this.toJSON());
  }

  static fromString(str) {
    var obj = JSON.parse(str);

    return new Rect(obj.x, obj.y, obj.w, obj.h);
  }

  center() {
    return new Vector2(this.w / 2, this.h / 2);
  }

  contains(vector) {
    return (vector.x >= this.x) && (vector.y >= this.y) && (vector.x < this.x + this.w) && (vector.y < this.y + this.h);
  }
}

export default Rect;

Add clone and update serialization


const { promisify } = require("util");

const command = {
  command: "console",
  description:
    "Run a console with contract abstractions and commands available",
  builder: {},
  help: {
    usage: "truffle console [--network <name>] [--verbose-rpc]",
    options: [
      {
        option: "--network <name>",
        description:
          "Specify the network to use. Network name must exist in the configuration."
      },
      {
        option: "--verbose-rpc",
        description:
          "Log communication between Truffle and the Ethereum client."
      }
    ]
  },
  run: async function (options) {
    const Config = require("@truffle/config");
    const Console = require("../console");
    const { Environment } = require("@truffle/environment");

    const config = Config.detect(options);

    // This require a smell?
    const commands = require("./index");
    const excluded = new Set(["console", "init", "watch", "develop"]);

    const consoleCommands = Object.keys(commands).reduce((acc, name) => {
      return !excluded.has(name)
        ? Object.assign(acc, {[name]: commands[name]})
        : acc;
    }, {});

    await Environment.detect(config);
    const c = new Console(consoleCommands, config.with({noAliases: true}));
    return await promisify(c.start).bind(c.start)();
  }
};

module.exports = command;

const command = {
  command: "console",
  description:
    "Run a console with contract abstractions and commands available",
  builder: {},
  help: {
    usage: "truffle console [--network <name>] [--verbose-rpc]",
    options: [
      {
        option: "--network <name>",
        description:
          "Specify the network to use. Network name must exist in the configuration."
      },
      {
        option: "--verbose-rpc",
        description:
          "Log communication between Truffle and the Ethereum client."
      }
    ]
  },
  run: async function (options) {
    const Config = require("@truffle/config");
    const Console = require("../console");
    const { Environment } = require("@truffle/environment");

    const config = Config.detect(options);

    // This require a smell?
    const commands = require("./index");
    const excluded = new Set(["console", "init", "watch", "develop"]);

    const consoleCommands = Object.keys(commands).reduce((acc, name) => {
      return !excluded.has(name)
        ? Object.assign(acc, {[name]: commands[name]})
        : acc;
    }, {});

    await Environment.detect(config);
    const c = new Console(consoleCommands, config.with({noAliases: true}));
    return await c.start();
  }
};

module.exports = command;

Remove unnecessary call to promisify


import React from 'react';
import PropTypes from 'prop-types';

class PagerNumbers extends React.Component {
  constructor(props, context) {
    super(props, context);
  }
  render(){
    const {pagerNum, itemsPerPage, count} = this.props;
    const itemsStart = 1 + (itemsPerPage  * (pagerNum - 1));
    const itemsEnd = itemsPerPage * pagerNum;

    return (
      <span>
        Showing {itemsStart}-{(count < itemsEnd)? count:itemsEnd} of {count}
      </span>
    );
  }

}

PagerNumbers.propTypes = {
  pagerNum: PropTypes.number.isRequired,
  count: PropTypes.number,
  itemsPerPage: PropTypes.number.isRequired,
};
export default PagerNumbers;

import React from 'react';
import PropTypes from 'prop-types';

class PagerNumbers extends React.Component {
  constructor(props, context) {
    super(props, context);
  }
  render(){
    const {pagerNum, itemsPerPage, count} = this.props;
    const itemsStart = (count <= 0)? 0 : 1 + (itemsPerPage  * (pagerNum - 1));
    const itemsEnd = itemsPerPage * pagerNum;

    return (
      <span>
        Showing {itemsStart}-{(count < itemsEnd)? count:itemsEnd} of {count}
      </span>
    );
  }

}

PagerNumbers.propTypes = {
  pagerNum: PropTypes.number.isRequired,
  count: PropTypes.number,
  itemsPerPage: PropTypes.number.isRequired,
};
export default PagerNumbers;

Fix page count for zero items


angular.module('mainApp').controller('mainCtrl', function ($scope, $http) {

    if ($scope.loggedIn) {
        $scope.organizations = $scope.me.organizations.map(function (organization) {
            organization.status = 'not-set';
            $http.get('/api/organizations/' + organization._id).success(function (data) {
                _.assign(organization, data);
            });
            return organization;
        });

        if ($scope.organizations.length === 1) {
            $scope.selectCurrentOrganization($scope.organizations[0]);
        }
    }

});

angular.module('mainApp').controller('mainCtrl', function ($scope, $http) {

    if ($scope.loggedIn) {
        $scope.organizations = $scope.me.organizations.map(function (organization) {
            organization.status = 'not-set';
            $http.get('/api/organizations/' + organization._id).success(function (data) {
                _.assign(organization, data);
            });
            return organization;
        });
    }

});

Fix home when user is member of one organization


const Sequelize = require('sequelize');

module.exports = {
  JSONType: (fieldName, {defaultValue = {}} = {}) => ({
    type: Sequelize.TEXT,
    get: function get() {
      const val = this.getDataValue(fieldName);
      if (!val) { return defaultValue }
      return JSON.parse(val);
    },
    set: function set(val) {
      this.setDataValue(fieldName, JSON.stringify(val));
    },
  }),
  JSONARRAYType: (fieldName, {defaultValue = []} = {}) => ({
    type: Sequelize.TEXT,
    get: function get() {
      const val = this.getDataValue(fieldName);
      if (!val) { return defaultValue }
      return JSON.parse(val);
    },
    set: function set(val) {
      this.setDataValue(fieldName, JSON.stringify(val));
    },
  }),
}

const Sequelize = require('sequelize');

module.exports = {
  JSONType: (fieldName, {defaultValue = {}} = {}) => ({
    type: Sequelize.TEXT,
    get: function get() {
      const val = this.getDataValue(fieldName);
      if (!val) {
        return defaultValue ? Object.assign({}, defaultValue) : null;
      }
      return JSON.parse(val);
    },
    set: function set(val) {
      this.setDataValue(fieldName, JSON.stringify(val));
    },
  }),
  JSONARRAYType: (fieldName) => ({
    type: Sequelize.TEXT,
    get: function get() {
      const val = this.getDataValue(fieldName);
      if (!val) {
        return [];
      }
      return JSON.parse(val);
    },
    set: function set(val) {
      this.setDataValue(fieldName, JSON.stringify(val));
    },
  }),
}

Use defaultValue as a template, fix critical sync issue


var expect = require('chai').expect;
var count = require('count-substring');
var htmlToText = require('html-to-text');

module.exports = function (browser) {
    describe("The tests written in Elm", function () {
        it('should pass', function () {
            return browser
                .url('http://localhost:8080/elm.html')
                .waitUntil(function () {
                    return this.getHTML("#results").then(function (html) {
                        var passedCount = count(html, "All tests passed");
                        var failedCount = count(html, "FAILED");

                        if (passedCount > 0) {
                            return true;
                        }

                        if (failedCount > 0) {
                            console.log("Failed!\n");
                            console.log(htmlToText.fromString(html));

                            throw "Failed tests written in Elm";
                        }

                        return false;
                    });
                }, 3000, 500);
        });
    });
};

var expect = require('chai').expect;
var count = require('count-substring');
var htmlToText = require('html-to-text');

module.exports = function (browser) {
    describe("The tests written in Elm", function () {
        it('should pass', function () {
            return browser
                .url('http://localhost:8080/elm.html')
                .waitUntil(function () {
                    return this.getHTML("#results").then(function (html) {
                        var passedCount = count(html, "All tests passed");
                        var failedCount = count(html, "FAILED");

                        if (passedCount > 0) {
                            return true;
                        }

                        if (failedCount > 0) {
                            console.log("Failed!\n");
                            console.log(htmlToText.fromString(html));

                            throw "Failed tests written in Elm";
                        }

                        return false;
                    });
                }, 10000, 500);
        });
    });
};

Increase timeout for elm tests.


/* eslint-disable no-var */
// NPM 5 now adds optional dependencies, which older versions of npm
// try to install even if it is the wrong architecture.

var fs = require('fs');
var toRemove = ['fsevents'];
var shrinkwrap = JSON.parse(fs.readFileSync('../npm-shrinkwrap.json'));

function cleanRequires(requires) {
  toRemove.forEach(dep => {
    if (dep in requires) {
      console.log('removing requires', dep);
      delete requires[dep];
    }
  });
}

function cleanDependencies(dependencies) {
  Object.keys(dependencies).forEach(dep => {
    if (toRemove.indexOf(dep) > -1) {
      console.log('removing dep', dep);
      delete dependencies[dep];
    } else {
      if (dependencies[dep].dependencies) {
        cleanDependencies(dependencies[dep].dependencies);
      }
      if (dependencies[dep].requires) {
        cleanRequires(dependencies[dep].requires);
      }
    }
  });
}

cleanDependencies(shrinkwrap.dependencies);

fs.writeFileSync('../npm-shrinkwrap.json', `${JSON.stringify(shrinkwrap, null, 2)}\n`);

/* eslint-disable no-var */
// NPM 5 now adds optional dependencies, which older versions of npm
// try to install even if it is the wrong architecture.

var fs = require('fs');
var toRemove = ['fsevents', 'nan'];
var shrinkwrap = JSON.parse(fs.readFileSync('../npm-shrinkwrap.json'));

function cleanRequires(requires) {
  toRemove.forEach(dep => {
    if (dep in requires) {
      console.log('removing requires', dep);
      delete requires[dep];
    }
  });
}

function cleanDependencies(dependencies) {
  Object.keys(dependencies).forEach(dep => {
    if (toRemove.indexOf(dep) > -1) {
      console.log('removing dep', dep);
      delete dependencies[dep];
    } else {
      if (dependencies[dep].dependencies) {
        cleanDependencies(dependencies[dep].dependencies);
      }
      if (dependencies[dep].requires) {
        cleanRequires(dependencies[dep].requires);
      }
    }
  });
}

cleanDependencies(shrinkwrap.dependencies);

fs.writeFileSync('../npm-shrinkwrap.json', `${JSON.stringify(shrinkwrap, null, 2)}\n`);

Add 'nan' to list of packages to remove from shrinkwrap


// Copyright 2014-2015, Renasar Technologies Inc.
/* jshint node: true */

"use strict";

var di = require('di');

module.exports = Runner;

di.annotate(Runner, new di.Provide('Http'));
di.annotate(Runner, new di.Inject(
        'Http.Server',
        'Services.Core',
        'Services.Configuration',
        'Profiles',
        'Templates',
        'common-api-router',
        'fileService',
        'Q',
        'Services.StatsD'
    )
);
function Runner(
    app,
    core,
    configuration,
    profiles,
    templates,
    router,
    fileService,
    Q,
    statsd
) {

    function start() {
        return core.start()
            .then(function() {
                return Q.all([profiles.load(), templates.load()]);
            })
            .then(function() {
                statsd.gauge('hello.world', 1);
console.log('metric sent');
                app.use('/api/common', router);
                app.use('/api/current', router);
                app.use('/api/1.1', router);

                return fileService.start(configuration.get("fileService"));
            })
            .then(function() {
                app.listen();
            });
    }

    function stop() {
        return Q.resolve()
            .then(function() {
                return app.close();
            })
            .then(function() {
                return core.stop();
            });
    }

    return {
        start: start,
        stop: stop
    };
}

// Copyright 2014-2015, Renasar Technologies Inc.
/* jshint node: true */

"use strict";

var di = require('di');

module.exports = Runner;

di.annotate(Runner, new di.Provide('Http'));
di.annotate(Runner, new di.Inject(
        'Http.Server',
        'Services.Core',
        'Services.Configuration',
        'Profiles',
        'Templates',
        'common-api-router',
        'fileService',
        'Promise'
    )
);
function Runner(
    app,
    core,
    configuration,
    profiles,
    templates,
    router,
    fileService,
    Promise
) {

    function start() {
        return core.start()
            .then(function() {
                return Promise.all([profiles.load(), templates.load()]);
            })
            .then(function() {
                app.use('/api/common', router);
                app.use('/api/current', router);
                app.use('/api/1.1', router);

                return fileService.start(configuration.get("fileService"));
            })
            .then(function() {
                app.listen();
            });
    }

    function stop() {
        return Promise.resolve()
            .then(function() {
                return app.close();
            })
            .then(function() {
                return core.stop();
            });
    }

    return {
        start: start,
        stop: stop
    };
}

Swap out Q for Promise and remove superfluous StatsD.


/**
 * Notifications system server front-end.
 *
 * @package randy
 * @author Andrew Sliwinski <andrew@diy.org>
 */

/**
 * Dependencies
 */
var _       = require('underscore'),
    async   = require('async'),
    randy   = require('./lib/index.js');

/**
 * Server
 */
async.auto({

    // Defaults
    // ------------------------------------------
    defaults:   function (callback) {
        _.defaults(process.env, {
            PORT:       80,
            REDIS_HOST: null,
            REDIS_PORT: null,
            REDIS_PASS: null
        });

        callback();
    },

    // Start listening
    // ------------------------------------------
    listen:     ['defaults', function (callback) {
        randy.listen(process.env.PORT, function (err) {
            if (err) {
                callback(err);
            } else {
                console.log('Randy is listening on port', process.env.PORT);
                callback(null);
            }
        });
    }]

}, function (err, obj) {
    if (err) {
        throw new Error(err);
    }
});

/**
 * Process exit handler
 */
process.on('exit', function () {
    randy.destroy(function (err) {
        process.exit();
    });
});

/**
 * Notifications system server front-end.
 *
 * @package randy
 * @author Andrew Sliwinski <andrew@diy.org>
 */

/**
 * Dependencies
 */
var _       = require('underscore'),
    async   = require('async'),
    randy   = require('./lib/index.js');

/**
 * Server
 */
async.auto({

    // Environment defaults
    // ------------------------------------------
    defaults:   function (callback) {
        _.defaults(process.env, {
            PORT:       80,
            REDIS_HOST: null,
            REDIS_PORT: null,
            REDIS_PASS: null
        });

        callback();
    },

    // Start listening
    // ------------------------------------------
    listen:     ['defaults', function (callback) {
        randy.listen(process.env.PORT, {
            host: process.env.REDIS_HOST,
            port: process.env.REDIS_PORT,
            pass: process.env.REDIS_PASS
        }, function (err) {
            if (err) {
                callback(err);
            } else {
                console.log('Randy is listening on port', process.env.PORT);
                callback(null);
            }
        });
    }]

}, function (err, obj) {
    if (err) {
        throw new Error(err);
    }
});

/**
 * Process exit handler
 */
process.on('exit', function () {
    randy.destroy(function (err) {
        process.exit();
    });
});

Use environment variables for Redis connection


import Ember from 'ember';

export default Ember.Mixin.create({

    /**
     * Attribute bindings for mixin's component element
     * @property {array} attributeBindings
     */
    attributeBindings: [ 'title' ],

    /**
     * Enables the tooltip functionality, based on a passed-in `title` attribute
     * @method enableTooltip
     */
    enableTooltip: function () {
        var popoverContent = this.get( 'popover' );
        var title = this.get( 'title' );

        if ( popoverContent ) {
            this.set( 'data-toggle', 'popover' );
            this.$().popover({
                content: popoverContent,
                placement: 'top'
            });
        } else if ( title ) {
            this.set( 'data-toggle', 'tooltip' );
            this.$().tooltip();
        }
    }.observes( 'popover', 'title' ).on( 'didInsertElement' )
});

import Ember from 'ember';

export default Ember.Mixin.create({

    /**
     * Enables the tooltip functionality, based on component's `title` attribute
     * @method enableTooltip
     */
    enableTooltip: function () {
        var popoverContent = this.get( 'popover' );
        var title = this.get( 'title' );

        if ( !popoverContent && !title ) {
            return;
        }

        if ( this.get( 'isPopover' )) {
            this.$().popover( 'destroy' );
            this.set( 'isPopover', false );
        }

        if ( this.get( 'isTooltip' )) {
            this.$().tooltip( 'destroy' );
            this.set( 'isTooltip', false );
        }

        if ( popoverContent ) {
            this.set( 'data-toggle', 'popover' );
            this.$().popover({
                content: popoverContent,
                placement: 'top'
            });
            this.set( 'isPopover', false );
        } else if ( title ) {
            this.set( 'data-toggle', 'tooltip' );
            this.$().tooltip({ title: title });
            this.set( 'isTooltip', true );
        }
    }.observes( 'popover', 'title' ).on( 'didInsertElement' ),

    /**
     * Whether the component has been set up as a popover
     * @property {boolean} isPopover
     * @default false
     */
    isPopover: false,

    /**
     * Whether the component has been set up as a tooltip
     * @property {boolean} isTooltip
     * @default false
     */
    isTooltip: false
});

Enable dynamic update/recreation of sl-tooltip


module.exports = function(grunt) {
    grunt.initConfig({
        concat: {
            options: {
                separator: ''
            },
            app: {
                dest: 'deploy/app.js',
                src: [
                    'src/intro.js.frag',
                    'src/*.js',
                    'src/outro.js.frag'
                ]
            }
        },
        watch: {
            scripts: {
                files: ['src/*.js*'],
                tasks: ['unittests']
            },
            css: {
                files: ['*.css'],
                tasks: ['csslint']
            },
        },
        csslint: {
            src: ['*.css']
        },
        jshint: {
            all: {
                files: {
                    src: ['deploy/app.js']
                }
            }
        },
        jasmine: {
            all: {
                src: ['deploy/app.js'],
                options: {
                    specs: 'unittests/*.spec.js',
                    outfile: 'test-results.html',
                    keepRunner: true,
                    helpers: [
                        'lib/angular.js',
                        'lib/angular-mocks.js'
                    ]
                }
            }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-csslint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-jasmine');

    grunt.registerTask('unittests', ['concat', 'jshint', 'jasmine:all']);
    grunt.registerTask('default', ['csslint', 'unittests']);
    grunt.registerTask('dev', ['default', 'watch']);
};

module.exports = function(grunt) {
    grunt.initConfig({
        concat: {
            options: {
                separator: ''
            },
            app: {
                dest: 'deploy/app.js',
                src: [
                    'src/intro.js.frag',
                    'src/*.js',
                    'src/outro.js.frag'
                ]
            }
        },
        watch: {
            scripts: {
                files: ['src/*.js*', 'unittests/*.spec.js'],
                tasks: ['unittests']
            },
            css: {
                files: ['*.css'],
                tasks: ['csslint']
            },
        },
        csslint: {
            src: ['*.css']
        },
        jshint: {
            all: {
                files: {
                    src: ['deploy/app.js']
                }
            }
        },
        jasmine: {
            all: {
                src: ['deploy/app.js'],
                options: {
                    specs: 'unittests/*.spec.js',
                    outfile: 'test-results.html',
                    keepRunner: true,
                    helpers: [
                        'lib/angular.js',
                        'lib/angular-mocks.js'
                    ]
                }
            }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-csslint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-jasmine');

    grunt.registerTask('unittests', ['concat', 'jshint', 'jasmine:all']);
    grunt.registerTask('default', ['csslint', 'unittests']);
    grunt.registerTask('dev', ['default', 'watch']);
};

Watch unit tests and rerun on change


module.exports = function (grunt) {

  // Project configuration.
  grunt.initConfig({
    release: {},
    simplemocha: {
      options: {
        timeout: 60000,
        reporter: 'spec'
      },
      all: { src: ['test/**/*.js'] }
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      lib: ['lib/**/*.js', 'Gruntfile.js'],
      test: ['test/**/*.js']
    }
  });

  grunt.registerTask('default', 'test');
  grunt.registerTask('test', [ 'jshint', 'simplemocha' ]);

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-release');
  grunt.loadNpmTasks('grunt-simple-mocha');
};

module.exports = function (grunt) {

  // Project configuration.
  grunt.initConfig({
    release: {},
    simplemocha: {
      options: {
        timeout: 600000,
        reporter: 'spec'
      },
      all: { src: ['test/**/*.js'] }
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      lib: ['lib/**/*.js', 'Gruntfile.js'],
      test: ['test/**/*.js']
    }
  });

  grunt.registerTask('default', 'test');
  grunt.registerTask('test', [ 'jshint', 'simplemocha' ]);

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-release');
  grunt.loadNpmTasks('grunt-simple-mocha');
};

Increase timeout a lot because Windows is slow.


import React, { Component } from 'react';
import RepoSearchBar from './components/RepoSearchBar';

export default class SearchScreen extends Component {
  render() {
    return (
      <RepoSearchBar />
    );
  }
}

import React, { Component } from 'react';
import { View } from 'react-native';
import RepoSearchBar from './components/RepoSearchBar';
import RepoSearchButton from './components/RepoSearchButton';

export default class SearchScreen extends Component {
  render() {
    return (
      <View style={{
        flex: 1,
        flexDirection: 'column',
      }}>
        <RepoSearchBar />
        <RepoSearchButton />
      </View>
    );
  }
}

Add button to main layout Encapsulate the page with a view so that the search bar appears at the top, the search button right below and when data is entered the list would be populated


export default {
  entry: 'lib/src/index.js',
  dest: 'lib/apollo.umd.js',
  format: 'umd',
  sourceMap: true,
  moduleName: 'apollo',
  external: [
    'lodash'
  ]
};

function globals(mod) {
  if (mod.indexOf('lodash/') === 0) return '_';
}

export default {
  entry: 'lib/src/index.js',
  dest: 'lib/apollo.umd.js',
  format: 'umd',
  sourceMap: true,
  moduleName: 'apollo',
  external: [
    'lodash'
  ],
  globals
};

Define globals for lodash in rollup


var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var Objectid = mongoose.Schema.Types.ObjectId;
var Organisation = require("./organisation_model");
var SageItem = require("./sageitem_model");
var SageAnalysisCategory = require("./sageanalysiscategory_model");

var LineItemSchema   = new Schema({
	description: String,
	organisation_id: { type: Objectid, ref: 'Organisation' },
	item: { type: Objectid, ref: 'SageItem' },
	amount: { type: Number, validate: function(v) { return (v > 0); }, required: true },
	price: { type: Number, validate: function(v) { return (v >= 0); }, required: true },
	tax_type: String,
	comment: String,
	discount: { type: Number, default: 0 },
	date_created: { type: Date, default: Date.now },
	sage_id: Number,
	is_quote: Boolean,
	analysiscategory: { type: Objectid, ref: 'SageAnalysisCategory' },
	_owner_id: Objectid,
	_deleted: { type: Boolean, default: false, index: true },
});

LineItemSchema.set("_perms", {
	admin: "crud",
	owner: "cr",
	user: "",
	all: ""
});

module.exports = mongoose.model('LineItem', LineItemSchema);

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var Objectid = mongoose.Schema.Types.ObjectId;
var Organisation = require("./organisation_model");
var Sageitem = require("./sageitem_model");
var SageAnalysisCategory = require("./sageanalysiscategory_model");

var LineItemSchema   = new Schema({
	description: String,
	organisation_id: { type: Objectid, ref: 'Organisation' },
	item: { type: Objectid, ref: 'Sageitem' },
	amount: { type: Number, validate: function(v) { return (v > 0); }, required: true },
	price: { type: Number, validate: function(v) { return (v >= 0); }, required: true },
	tax_type: String,
	comment: String,
	discount: { type: Number, default: 0 },
	date_created: { type: Date, default: Date.now },
	sage_id: Number,
	is_quote: Boolean,
	analysiscategory: { type: Objectid, ref: 'Sageanalysiscategory' },
	_owner_id: Objectid,
	_deleted: { type: Boolean, default: false, index: true },
});

LineItemSchema.set("_perms", {
	admin: "crud",
	owner: "cr",
	user: "",
	all: ""
});

module.exports = mongoose.model('LineItem', LineItemSchema);

Fix naming bug that was bombing out lineitem autopopulate


var $ = require('jquery-browserify');
var _ = require('underscore');
var Backbone = require('backbone');
var templates = require('../../dist/templates');
var auth = require('../config');
var cookie = require('../cookie');

// Set scope
auth.scope = cookie.get('scope') || 'repo';

module.exports = Backbone.View.extend({
  id: 'start',

  events: {
    'click a[href="#scopes"]': 'toggleScope',
    'change .toggle-hide select': 'setScope'
  },

  template: templates.start,

  render: function() {
    this.$el.html(_.template(this.template, auth, { variable: 'auth' }));
    return this;
  },

  toggleScope: function(e) {
    e.preventDefault();
    this.$('.toggle-hide').toggleClass('show');
  },

  setScope: function(e) {
    var scope = $(e.currentTarget).val(),
        expire = new Date((new Date()).setYear((new Date()).getFullYear() + 20));
    auth.scope = scope;
    cookie.set('scope', scope, expire);
    this.render();
    router.app.nav.render();
  }
});

var $ = require('jquery-browserify');
var _ = require('underscore');
var Backbone = require('backbone');
var templates = require('../../dist/templates');
var auth = require('../config');
var cookie = require('../cookie');

// Set scope
auth.scope = cookie.get('scope') || 'repo';

module.exports = Backbone.View.extend({
  id: 'start',

  initialize: function () {
    this.persistScope(auth.scope);
  },

  events: {
    'click a[href="#scopes"]': 'toggleScope',
    'change .toggle-hide select': 'setScope'
  },

  template: templates.start,

  render: function() {
    this.$el.html(_.template(this.template, auth, { variable: 'auth' }));
    return this;
  },

  toggleScope: function(e) {
    e.preventDefault();
    this.$('.toggle-hide').toggleClass('show');
  },

  setScope: function(e) {
    var scope = $(e.currentTarget).val();
    this.persistScope(scope);
    this.render();
    router.app.nav.render();
  },

  persistScope: function(scope) {
    var expire = new Date((new Date()).setYear((new Date()).getFullYear() + 20));
    auth.scope = scope;
    cookie.set('scope', scope, expire);
  }
});

Save initial scope cookie if public and private


/**
 * Development environment settings
 * @description :: This section overrides all other config values ONLY in development environment
 */

module.exports = {
    log: {
        level: 'silly'
    },
    models: {
        connection: 'disk'
    }
};

/**
 * Development environment settings
 * @description :: This section overrides all other config values ONLY in development environment
 */

module.exports = {
    port: 3000,
    log: {
        level: 'silly'
    },
    models: {
        connection: 'disk'
    }
};

Add 3000 port to dev config


'use strict'

const Policy = require('trails-policy')

/**
 * @module <%= name %>Policy
 * @description <%= answers.desc %>
 */
module.exports = class <%= name %>Policy extends Policy {

}

'use strict'

/**
 * @module <%= name %>Policy
 * @description <%= answers.desc %>
 */
module.exports = class <%= name %>Policy {

}

Remove extends class for policies


'use strict'

class Pokemon {

   constructor(name) {
       this.name = name;
       this.cp = 100;
   }

   attack() {
       console.log(`Attack ${this.cp} points!`);
   }

   powerUp() {
       this.cp += 100;
       console.log("Power Up completed!")
   }
}

let pikachu = new Pokemon("Pikachu");
console.log(pikachu.name);

pikachu.attack();

pikachu.powerUp();
pikachu.attack();

'use strict'

class Monster {

   constructor(name) {
       this.name = name;
       this.cp = 100;
   }

   attack() {
       console.log(`Attack ${this.cp} points!`);
   }

   powerUp() {
       this.cp += 100;
       console.log("Power Up completed!")
   }
}

let mon = new Monster("My Mon");
console.log(mon.name);

mon.attack();

mon.powerUp();
mon.attack();

Rename class to avoid copyright issue


// User Model
module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    type:     { type: DataTypes.INTEGER, allowNull: false },
    name:     { type: DataTypes.STRING, allowNull: false },
    email:    { type: DataTypes.STRING, allowNull: false },
    password: { type: DataTypes.STRING, allowNull: false },
    salt:     { type: DataTypes.STRING, allowNull: false },
    postal:   { type: DataTypes.STRING, allowNull: false },
    token:    { type: DataTypes.STRING, allowNull: true }
  }, {
    associate: function(models) {
      User.hasOne(models.Profile);
      User.hasMany(models.Message, { as: 'SentMessages', foreignKey: 'SenderId' });
      User.hasMany(models.Message, { as: 'ReceivedMessages', foreignKey: 'ReceiverId' });
    },
    getterMethods: {
      isTutor: function() {
        return this.type === 1;
      }
    },
    instanceMethods: {
      getSimple: function() {
        var obj = {};
        obj.name = this.name;
        obj.email = this.email;
        obj.postal = this.postal;
        obj.profile = this.profile.getSimple();

        return obj;
      }
    }
  });

  return User;
}

// User Model
module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    type:     { type: DataTypes.INTEGER, allowNull: false },
    name:     { type: DataTypes.STRING, allowNull: false },
    email:    { type: DataTypes.STRING, allowNull: false },
    password: { type: DataTypes.STRING, allowNull: false },
    salt:     { type: DataTypes.STRING, allowNull: false },
    postal:   { type: DataTypes.STRING, allowNull: false },
    token:    { type: DataTypes.STRING, allowNull: true }
  }, {
    associate: function(models) {
      User.hasOne(models.Profile);
      User.hasMany(models.Message, { as: 'SentMessages', foreignKey: 'SenderId' });
      User.hasMany(models.Message, { as: 'ReceivedMessages', foreignKey: 'ReceiverId' });
    },
    getterMethods: {
      isTutor: function() {
        return this.type === 1;
      }
    },
    instanceMethods: {
      getSimple: function() {
        var obj = {};
        obj.type = this.type;
        obj.name = this.name;
        obj.email = this.email;
        obj.postal = this.postal;
        obj.profile = this.profile.getSimple();

        return obj;
      }
    }
  });

  return User;
}

Add type to search results


module.exports = function(req, res, next){
    "use strict";
    var Strings = require('../../../strings'),
        Response = require('../../helpers/response'),
        content = require('../../../entities/content'),
        strings = new Strings('en'),
        response = new Response()

    function onGetContent(err, doc){
        if(err){
            response.write(response.STATUS_CODES.SERVER_ERROR, JSON.stringify(err), res);
        }
        else {
            if(doc.node && doc.node._id){
                req.parent = doc.node._id.toString();
            }

            next();
        }
    }

    content.getById(req.params.id, onGetContent);
};

module.exports = function(req, res, next){
    "use strict";
    var Strings = require('../../../strings'),
        Response = require('../../helpers/response'),
        content = require('../../../entities/content'),
        strings = new Strings('en'),
        response = new Response()

    function onGetContent(err, doc){
        if(err){
            response.write(response.STATUS_CODES.NOT_FOUND, JSON.stringify(err), res);
        }
        else {
            if(doc.node && doc.node._id){
                req.parent = doc.node._id.toString();
            }

            next();
        }
    }

    content.getById(req.params.id, onGetContent);
};

Send a 404 if not found.


'use strict';

/* Services */
var SERVER_URL = 'http://localhost:8081';

angular.module('myApp.services', ['ngResource']).factory('Items', function ($resource) {
    return $resource('http://localhost:8081/items', {}, {
        query: {method: 'GET', isArray: true}
    });
}).factory('Import', function ($resource) {
    return $resource(SERVER_URL + '/import/steam', {}, {
        query: {method: 'GET', isArray: true}
  });
});

'use strict';

/* Services */
var SERVER_URL = 'http://localhost:8081';

angular.module('myApp.services', ['ngResource'])
    .factory('Items', function ($resource) {
      return $resource(SERVER_URL + '/items', {}, {
        query: {method: 'GET', isArray: true}
      });
    })
    .factory('Import', function ($resource) {
      return $resource(SERVER_URL + '/import/steam', {}, {
        query: {method: 'GET', isArray: true}
      });
    });

Use server constant in Items-service


var _ = require('lodash')
var courses = require('./db').courses

function splitDeptNum(deptNumString) {
	// "AS/RE 230A" -> ["AS/RE 230A", "AS/RE", "AS", "RE", "230", "A"]
	// -> {depts: ['AS', 'RE'], num: 230, sect: 'A'}
	var combined = deptNumString.toUpperCase()
	var regex = /(([A-Z]+)(?=\/)(?:\/)([A-Z]+)|[A-Z]+) *([0-9]+) *([A-Z]?)/gi
	var matches = regex.exec(combined)

	return {
		dept: _.contains(matches[1], '/') ? [matches[2], matches[3]] : [matches[1]],
		num: parseInt(matches[4], 10),
		sect: matches[5] || undefined
	}
}

function buildDeptNum(course) {
	return course.depts.join('/') + ' ' + course.num + (course.sect || '')
}

module.exports.splitDeptNum = splitDeptNum
module.exports.buildDeptNum = buildDeptNum

var _ = require('lodash')
var courses = require('./db').courses

function splitDeptNum(deptNumString) {
	// "AS/RE 230A" -> ["AS/RE 230A", "AS/RE", "AS", "RE", "230", "A"]
	// -> {depts: ['AS', 'RE'], num: 230}
	var combined = deptNumString.toUpperCase()
	var regex = /(([A-Z]+)(?=\/)(?:\/)([A-Z]+)|[A-Z]+) *([0-9]+) *([A-Z]?)/gi
	var matches = regex.exec(combined)

	return {
		dept: _.contains(matches[1], '/') ? [matches[2], matches[3]] : [matches[1]],
		num: parseInt(matches[4], 10)
	}
}

function buildDeptNum(course) {
	return course.depts.join('/') + ' ' + course.num
}

module.exports.splitDeptNum = splitDeptNum
module.exports.buildDeptNum = buildDeptNum

Remove the section from deptnums, to match with crsid.


var _ = require('underscore');
var SimpleStyleDefaults = require('./simple-style-defaults');
var defaultFormValues = require('../../../data/default-form-styles.json');
var rampList = require('cartocolor');

module.exports = _.defaults({

  _getAggrAttrs: function (geometryType) {
    return {
      aggregation: {
        size: 10,
        value: {
          operator: 'count',
          attribute: ''
        }
      }
    };
  },

  _getStrokeAttrs: function (geometryType) {
    return defaultFormValues.stroke;
  },

  _getFillAttrs: function (geometryType) {
    return {
      fill: {
        'color': {
          attribute: 'agg_value',
          bins: '5',
          quantification: 'quantiles',
          // TODO: flip the ramp when basemap is black
          // range: rampList.ag_GrnYl[5].reverse()
          range: _.clone(rampList.ag_GrnYl[5])
        }
      }
    };
  }

}, SimpleStyleDefaults);

var _ = require('underscore');
var SimpleStyleDefaults = require('./simple-style-defaults');
var defaultFormValues = require('../../../data/default-form-styles.json');
var rampList = require('cartocolor');

module.exports = _.defaults({

  _getAggrAttrs: function (geometryType) {
    return {
      aggregation: {
        size: 10,
        value: {
          operator: 'count',
          attribute: ''
        }
      }
    };
  },

  _getStrokeAttrs: function (geometryType) {
    return {
      stroke: defaultFormValues.stroke
    };
  },

  _getFillAttrs: function (geometryType) {
    return {
      fill: {
        'color': {
          attribute: 'agg_value',
          bins: '5',
          quantification: 'quantiles',
          // TODO: flip the ramp when basemap is black
          // range: rampList.ag_GrnYl[5].reverse()
          range: _.clone(rampList.ag_GrnYl[5])
        }
      }
    };
  }

}, SimpleStyleDefaults);

Set stroke properly for hexabins


const yelp = require('yelp-fusion');
const ApiSecrets = require('./apisecrets.js');

const searchRequest = {
  term: 'restaurant chinese vegetarian',
  location: '94131',
  radius: 8000,
  price: '1,2,3,4',
  limit: 1
};

const ApiCall = function(req, res) {
  const location = req.body.zip ? req.body.zip : 94105;
  const categories = req.body.categories ? req.body.categories : 'italian';
  const client = yelp.client(ApiSecrets.yelpToken);

  client.search({
    location: location,
    categories: categories
  }).then(response => {
    allResults = response.jsonBody.businesses;
    res.send(allResults.slice(0, 3));
  }).catch(e => {
    res.send(e);
  });
};

yelp.accessToken(ApiSecrets.clientId, ApiSecrets.clientSecret).then(response => {
  const client = yelp.client(response.jsonBody.access_token);
  console.log('access_token: ', response.jsonBody.access_token);
  client.search(searchRequest).then(response => {
    const allResults = response.jsonBody.businesses; //this will put all businesses in the location above into allresults
    const prettyJson = JSON.stringify(allResults, null, 4);
    console.log(prettyJson);
  });
}).catch(e => {
  console.log(e);
});

module.exports = ApiCall;

const yelp = require('yelp-fusion');
const ApiSecrets = require('./apisecrets.js');
const token = ApiSecrets.yelpToken;

let getRestaurantsFromYelp = function(userPref, callback) {
  const id = 1; //hardcoding id for 1st user
  const location = userPref[0].location ? userPref[0].location : 94105;
  const preferences = userPref[0].preferences ? userPref[0].preferences : "italian, mexican";
  const client = yelp.client(token);

  client.search({
    location: location,
    term: preferences
  }).then(response => {
    let allResults = response.jsonBody.businesses;
    callback(null, allResults);
  }).catch(e => {
    callback(e, null);
  })
}

module.exports.getRestaurantsFromYelp = getRestaurantsFromYelp;

Add getRestaurantsFromYelp function, Remove ApiCall function and yelp.accessToken function


import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Combatants from 'Parser/Core/Modules/Combatants';

class UnendingThirstTracker extends Analyzer {
  static dependencies = {
    abilityTracker: AbilityTracker,
    combatants: Combatants,
  };

  RecentDSCounter = 0;
  DScost=0;

  on_initialized() {
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.DEATH_STRIKE.id) {
      return;
    }
    if (this.combatants.selected.hasBuff(SPELLS.BLOOD_SHIELD.id, event.timestamp)) {
      this.RecentDSCounter += 1;
      this.DScost=event.classResources[0].cost;
      console.log('DScost is ', this.DScost);
    }
  }

  statistic() {
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.UNENDING_THIRST.id} />}
        value={this.RecentDSCounter}
        label='Empowered Death Strike'
        tooltip='If you\'re looking to increase your dps as the cost of defense try increasing this.'

      />

    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(5);
}

export default UnendingThirstTracker;

import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Combatants from 'Parser/Core/Modules/Combatants';

class UnendingThirstTracker extends Analyzer {
  static dependencies = {
    abilityTracker: AbilityTracker,
    combatants: Combatants,
  };

  RecentDSCounter = 0;
  DScost=0;

  on_initialized() {
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.DEATH_STRIKE.id) {
      return;
    }
    if (this.combatants.selected.hasBuff(SPELLS.BLOOD_SHIELD.id, event.timestamp)) {
      this.RecentDSCounter += 1;
      this.DScost=event.classResources[0].cost;
      console.log('DScost is ', this.DScost);
    }
  }

  statistic() {
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.UNENDING_THIRST.id} />}
        value={this.RecentDSCounter}
        label='Empowered Death Strike'
        tooltip="If you're looking to increase your dps as the cost of defense try increasing this."

      />

    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(5);
}

export default UnendingThirstTracker;

Fix for the blood module for travis


/**
 * Created by Wayne on 16/3/11.
 */
'use strict';

var newTenderService = require('../../../libraries/services/new_tender_payment'),
  fs = require('fs');

exports.examine = function (req, res, next) {
  var tender = req.tender;
  var user = req.user;
  newTenderService.examine(tender, user, function (err, result) {
    return res.send(err || result);
  });
};

exports.payment = function (req, res, next) {
  var tender = req.tender;
  var user = req.user;

  if (!req.body.type) {
    return res.send({err: {type: 'empty_type'}});
  }

  if (req.body.number) {
    return res.send({err: {type: 'empty_number'}});
  }

  if (isNaN(parseInt(req.body.number)) || parseInt(req.body.number) < 0) {
    return res.send({err: {type: 'invalid_number'}});
  }

  newTenderService.payment(tender, user, req.body.type, req.body.number, function (err, result) {
    return res.send(err || result);
  });
};

/**
 * Created by Wayne on 16/3/11.
 */
'use strict';

var newTenderService = require('../../../libraries/services/new_tender_payment'),
  fs = require('fs');

exports.examine = function (req, res, next) {
  var tender = req.tender;
  var user = req.user;
  newTenderService.examine(tender, user, function (err, result) {
    return res.send(err || result);
  });
};

exports.payment = function (req, res, next) {
  var tender = req.tender;
  var user = req.user;

  if (!req.body.type) {
    return res.send({err: {type: 'empty_type'}});
  }

  if (!req.body.number) {
    return res.send({err: {type: 'empty_number'}});
  }

  if (isNaN(parseInt(req.body.number)) || parseInt(req.body.number) < 0) {
    return res.send({err: {type: 'invalid_number'}});
  }

  newTenderService.payment(tender, user, req.body.type, req.body.number, function (err, result) {
    return res.send(err || result);
  });
};

Fix error cause by payment number