const vscode = require('vscode');

const THEME_CONFIGURATION_ID = 'markdown-preview-github-styles';
const THEME_CONFIGURATION_KEY = 'colorTheme';

const THEME_CONFIGURATION_VALUES = {
    'auto': true,
    'system': true,
    'light': true,
    'dark': true
}
const THEME_CONFIGURATION_AUTO = 'auto';

function getColorTheme() {
    const settings = vscode.workspace.getConfiguration(THEME_CONFIGURATION_ID, null);
    return validThemeConfigurationValue(settings.get(THEME_CONFIGURATION_KEY))
}

function validThemeConfigurationValue(theme) {
    return !THEME_CONFIGURATION_VALUES[theme]
        ? THEME_CONFIGURATION_AUTO
        : theme;
}

exports.activate = function() {
    return {
        extendMarkdownIt(md) {
            return md.use(plugin);
        }
    };
}

function plugin(md) {
    const render = md.renderer.render;
    md.renderer.render = function() {
        return `<div class="markdown-body markdown-${getColorTheme()}">\n${render.apply(md.renderer, arguments)}\n</div>`;
    };
    return md;
}

// @ts-check

const vscode = require('vscode');

const THEME_CONFIGURATION_ID = 'markdown-preview-github-styles';
const THEME_CONFIGURATION_KEY = 'colorTheme';

const THEME_CONFIGURATION_VALUES = {
    'auto': true,
    'system': true,
    'light': true,
    'dark': true
}
const THEME_CONFIGURATION_AUTO = 'auto';

function getColorTheme() {
    const settings = vscode.workspace.getConfiguration(THEME_CONFIGURATION_ID, null);
    return validThemeConfigurationValue(settings.get(THEME_CONFIGURATION_KEY))
}

function validThemeConfigurationValue(theme) {
    return !THEME_CONFIGURATION_VALUES[theme]
        ? THEME_CONFIGURATION_AUTO
        : theme;
}

exports.activate = function(/** @type {vscode.ExtensionContext} */ctx) {
    ctx.subscriptions.push(vscode.workspace.onDidChangeConfiguration(e  => {
        if (e.affectsConfiguration(THEME_CONFIGURATION_ID)) {
            vscode.commands.executeCommand('markdown.preview.refresh');
        }
    }));

    return {
        extendMarkdownIt(md) {
            return md.use(plugin);
        }
    };
}

function plugin(md) {
    const render = md.renderer.render;
    md.renderer.render = function() {
        return `<div class="markdown-body markdown-${getColorTheme()}">\n${render.apply(md.renderer, arguments)}\n</div>`;
    };
    return md;
}

Update preview on setting change


module.exports = function(data, Bot, Config, Helpers) {

  var value = Helpers.getCommandPart(data.message, '2', Config);

  if(Config.admin.indexOf(data.userID) == -1) {

    var message = '';

    message += '@';
    message += data.user;
    message += ' ';

    message += 'Vous n\'avez pas la permission d\'effectuer cette commande'

    Bot.sendMessage({
      'to': data.channelID,
      'message': message
    })

    return;

  }

  if(typeof value !== 'undefined'){

    switch(value){
      case 'all' :

      Bot.getMessages({
        channel: data.channelID,
        limit: 500000
      }, function(messageArr) {

        for(i=0; i = messageArr.length; i++){
          Bot.deleteMessage({
            channel: data.channelID,
            messageID: messageArr[i].id
          });
        }
      });

      break;

      default:

      Bot.getMessages({
        channel: data.channelID,
        limit: parseInt(value)
      }, function(messageArr) {

        for (i = 0; i < messageArr.length; i++) {

          Bot.deleteMessage({
            channel: data.channelID,
            messageID: messageArr[i].id
          });

        }

      });

      break;

    }

  }else{

    Bot.sendMessage({
      'to': data.userID,
      'message': 'merci de spécifier un paramètre'
    });

  }

};

module.exports = function(data, Bot, Config, Helpers) {

  var value = Helpers.getCommandPart(data.message, '2', Config);

  if(Config.admin.indexOf(data.userID) == -1) {

    var message = '';

    message += '@';
    message += data.user;
    message += ' ';

    message += 'Vous n\'avez pas la permission d\'effectuer cette commande'

    Bot.sendMessage({
      'to': data.channelID,
      'message': message
    })

    return;

  }

  if(typeof value !== 'undefined'){

    switch(value){
      case 'all' :

      Bot.getMessages({
        channel: data.channelID,
        limit: 500000
      }, function(messageArr) {

        for(i=0; i < messageArr.length; i++){
          Bot.deleteMessage({
            channel: data.channelID,
            messageID: messageArr[i].id
          });
        }
      });

      break;

      default:

      Bot.getMessages({
        channel: data.channelID,
        limit: parseInt(value)
      }, function(messageArr) {

        for (i = 0; i < messageArr.length; i++) {

          Bot.deleteMessage({
            channel: data.channelID,
            messageID: messageArr[i].id
          });

        }

      });

      break;

    }

  }else{

    Bot.sendMessage({
      'to': data.userID,
      'message': 'merci de spécifier un paramètre'
    });

  }

};

Fix typo on the cleaning loop


module.exports = {
  "extends": "chiton/configurations/default",
  "env": {
    "node": true
  },
  "ecmaFeatures": {
    "arrowFunctions": true
  },
  "rules": {
    "arrow-body-style": [2, "as-needed"],
    "arrow-parens": [2, "as-needed"],
    "arrow-spacing": [2, {"after": true, "before": true}],
    "callback-return": 2,
    "handle-callback-err": 2,
    "no-arrow-condition": 2,
    "no-mixed-requires": 2,
    "no-new-require": 2,
    "no-path-concat": 2
  }
};

module.exports = {
  "extends": "chiton/configurations/default",
  "env": {
    "node": true
  },
  "ecmaFeatures": {
    "arrowFunctions": true
  },
  "rules": {
    "arrow-body-style": [2, "as-needed"],
    "arrow-parens": [2, "always"],
    "arrow-spacing": [2, {"after": true, "before": true}],
    "callback-return": 2,
    "handle-callback-err": 2,
    "no-arrow-condition": 2,
    "no-mixed-requires": 2,
    "no-new-require": 2,
    "no-path-concat": 2
  }
};

Enforce arrow parens style for Node as well


var quill = new Quill('#editor', {
    // modules: {
    //     'toolbar': { container: '#toolbar' },
    //     'link-tooltip': true
    // },
    theme: 'snow'
});
quill.addModule('toolbar', { container: '#toolbar' });

window.connector = new Y.XMPP().join('myprivatequill');
connector.debug = true;
window.y = new Y(connector);

y.observe(function(events){
    for(i in events){
        if(events[i].name === 'editor'){
            y.val('editor').bind('QuillJs', quill);
        }
    }
})

connector.whenSynced(function(){
    if(y.val('editor') == null){
        y.val('editor', new Y.RichText());
    }
})

var quill = new Quill('#editor', {
    modules: {
        'multi-cursor': true,
        'link-tooltip': true
    },
    theme: 'snow'
});
quill.addModule('toolbar', { container: '#toolbar' });
window.connector = new Y.XMPP().join('sqfjqsmdlkjrhguemslkfjmlsdkjf');
/* window.connector = new Y.WebRTC('sqfjqsmdlkjrhguemslkfjmlsdkjf',
    {url: 'http://localhost:8888'}); */
// connector.debug = true;
window.y = new Y(connector);

y.observe (function (events) {
    for (i in events){
        if(events[i].name === 'editor'){
            y.val('editor').bind('QuillJs', quill);
        }
    }
});

connector.whenSynced(function(){
    if(y.val('editor') == null){
        y.val('editor', new Y.RichText());
    }
});

Use multi cursors in quill


/* global window */

/**
 * @module SceneScroller
 */
'use strict';

/**
 * @namespace SceneScroller
 */
var SceneScroller = {}

/**
 * @property {String} version The version of this SceneScroller distribution.
 */
SceneScroller.version = require('../package.json').version

/**
 * @property {Class} EventEmitter
 * @see [EventEmitter](./eventemitter.md)
 */
SceneScroller.EventEmitter = require('./eventemitter')

/**
 * @property {Class} Node
 * @see [Node](./node.md)
 */
SceneScroller.Node = require('./node')

/**
 * @property {Class} Entity
 * @see [Entity](./entity.md)
 */
SceneScroller.Entity = require('./entity')

/**
 * @property {Object} symbols
 * @see [symbols](./symbols.md)
 */
SceneScroller.symbols = require('./symbols')

/**
 * @property {Object} util
 * @see [util](./util.md)
 */
SceneScroller.util = require('./util')

module.exports = SceneScroller

if(window) {
  window.SceneScroller = SceneScroller
}

/* global window */

/**
 * @module SceneScroller
 */
'use strict';

/**
 * @namespace SceneScroller
 */
var SceneScroller = {}

/**
 * @property {String} version The version of this SceneScroller distribution.
 */
SceneScroller.version = require('../package.json').version

/**
 * @property {Class} EventEmitter
 * @see [EventEmitter](./eventemitter.md)
 */
SceneScroller.EventEmitter = require('./eventemitter')

/**
 * @property {Class} Node
 * @see [Node](./node.md)
 */
SceneScroller.Node = require('./node')

/**
 * @property {Class} Entity
 * @see [Entity](./entity.md)
 */
SceneScroller.Entity = require('./entity')

/**
 * @property {Class} Scene
 * @see [Scene](./scene.md)
 */
SceneScroller.Scene= require('./scene')

/**
 * @property {Object} symbols
 * @see [symbols](./symbols.md)
 */
SceneScroller.symbols = require('./symbols')

/**
 * @property {Object} util
 * @see [util](./util.md)
 */
SceneScroller.util = require('./util')

module.exports = SceneScroller

if(window) {
  window.SceneScroller = SceneScroller
}

Add Scene class to SceneScroller object


'use strict';

const { httpStartServer } = require('./http');
const { attachRequire } = require('../utilities');
const { processOptions } = require('./process_options');

/**
 * Start server for each protocol, for the moment only HTTP
 *
 * @param {object} options
 * @param {object} options.idl - IDL definitions
 */
const startServer = async function (options) {
  attachRequire();
  const opts = await processOptions(options);
  const server = await Promise.all([
    httpStartServer(opts),
  ]);
  return server;
};

module.exports = {
  startServer,
};

'use strict';

const { EngineStartupError } = require('../error');
const { attachRequire } = require('../utilities');
const { httpStartServer } = require('./http');
const { processOptions } = require('./process_options');

/**
 * Start server for each protocol, for the moment only HTTP
 *
 * @param {object} options
 * @param {object} options.idl - IDL definitions
 */
const startServer = async function (options) {
  try {
    attachRequire();
    const opts = await processOptions(options);
    const server = await Promise.all([
      httpStartServer(opts),
    ]);
    return server;
  // Make sure all exceptions thrown at startup follow the EngineStartupError signature
  } catch (innererror) {
    if (innererror instanceof EngineStartupError) {
      throw innererror;
    } else {
      throw new EngineStartupError(innererror.message, { reason: 'UNKNOWN', innererror });
    }
  }
};

module.exports = {
  startServer,
};

Make sure all startup errors follow same signature


var eng = require('./node/engine');

module.exports = {
  minimize: function(func, options, callback) {
    eng.runPython('minimize', func, options, callback);
  }
}

var eng = require('./node/engine');

module.exports = {
  minimize: function(func, options, callback) {
    eng.runPython('minimize', func, options, callback);
  },
  nonNegLeastSquares: function(A, b, callback) {
    eng.runPython('nnls', A, b, callback);
  }
}

Add api for non negative least squares


// Hash CSS and JS assets, change filenames and references in markup
module.exports = function(grunt) {
    grunt.config('hashres', {
        options: {
            encoding: 'utf-8',
            fileNameFormat: '${name}-${hash}.${ext}',
            renameFiles: true
        },
        deploy: {
            src: ['dist/styles/master.css',
                  'dist/scripts/master.js'],
            dest: 'dist/*.html'
        }
    });
};

// Hash CSS and JS assets, change filenames and references in markup
module.exports = function(grunt) {
    grunt.config('hashres', {
        options: {
            encoding: 'utf-8',
            fileNameFormat: '${name}-${hash}.${ext}',
            renameFiles: true
        },
        deploy: {
            src: ['dist/styles/master.css',
                  'dist/scripts/master.js'],
            dest: 'dist/**/*.html'
        }
    });
};

Make sure HTML files in subdirs are hasres'd


/**
 * @author Marcelo G.
 */
(function ($) {
    $.viaAjaxLite = {
        sendForm: function(selector, callback) {

            var jqElement = $(selector);
            var self = this;

            $(selector + ' input[type="submit"], ' +
              selector + ' button[type="submit"]' ).bind('click', function(event) {
                event.preventDefault();
                self.send({
                    url: jqElement.attr('action'),
                    type: jqElement.attr('method'),
                    data: jqElement.serialize(),
                    target: jqElement.attr('target') || jqElement.attr('rel')
                },
                callback
                );
            });

        },

        load: function(options, callback) {
            this.send(options, callback);
        },

        send: function(options, callback) {
            // enviar consulta

            options = $.extend({type: 'get', data: {}}, options);

            $.ajax({
                url: options.url,
                type: options.type,
                data: options.data,
                success: function(data, textStatus, jqXHR) {
                    // procesar respuesta
                    $(options.target).html(data);
                    return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]);
                },
                beforeSend: function() {
                    $(options.target).html('

');
                },
                error: function() {
                    return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]);
                }
            });
        }

    };
}(typeof jQuery === 'function' ? jQuery : this));

/**
 * @author Marcelo G.
 */
(function ($) {
    $.viaAjaxLite = {
        sendForm: function(selector, callback) {

            var jqElement = $(selector);
            var self = this;

            $(selector + ' input[type="submit"], ' +
              selector + ' button[type="submit"]' ).bind('click', function(event) {
                event.preventDefault();
                self.send({
                    url: jqElement.attr('action'),
                    type: jqElement.attr('method'),
                    data: jqElement.serialize(),
                    target: jqElement.attr('target') || jqElement.attr('rel')
                },
                callback
                );
            });

        },

        load: function(options, callback) {
            this.send(options, callback);
        },

        send: function(options, callback) {
            // enviar consulta

            options = $.extend({type: 'get', data: {}}, options);

            $.ajax({
                url: options.url,
                type: options.type,
                data: options.data,
                success: function(data, textStatus, jqXHR) {
                    // procesar respuesta
                    $(options.target).html(data);
                    return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]);
                },
                beforeSend: function() {
                    $(options.target).html('

');
                },
                error: function(data, textStatus, jqXHR) {
                    return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]);
                }
            });
        }

    };
}(typeof jQuery === 'function' ? jQuery : this));

Solve data undefined in error event


import { AsyncStorage } from 'react-native';

export { MobileAppSettings } from './MobileAppSettings';

export const SETTINGS_KEYS = {
  APP_VERSION: 'AppVersion',
  CURRENT_LANGUAGE: 'CurrentLanguage',
  MOST_RECENT_USERNAME: 'MostRecentUsername',
  SUPPLYING_STORE_ID: 'SupplyingStoreId',
  SUPPLYING_STORE_NAME_ID: 'SupplyingStoreNameId',
  LAST_POST_PROCESSING_FAILED: 'LastPostProcessingFailed',
  SYNC_IS_INITIALISED: 'SyncIsInitialised',
  SYNC_PRIOR_FAILED: 'SyncPriorFailed',
  SYNC_URL: 'SyncURL',
  SYNC_SITE_ID: 'SyncSiteId',
  SYNC_SERVER_ID: 'SyncServerId',
  SYNC_SITE_NAME: 'SyncSiteName',
  SYNC_SITE_PASSWORD_HASH: 'SyncSitePasswordHash',
  THIS_STORE_ID: 'ThisStoreId',
  THIS_STORE_NAME_ID: 'ThisStoreNameId',
  HARDWARE_UUID: 'Hardware_UUID',
};

export async function getAppVersion() {
  const appVersion = await AsyncStorage.getItem(SETTINGS_KEYS.APP_VERSION);
  return appVersion;
}

import { AsyncStorage } from 'react-native';

export { MobileAppSettings } from './MobileAppSettings';

export const SETTINGS_KEYS = {
  APP_VERSION: 'AppVersion',
  CURRENT_LANGUAGE: 'CurrentLanguage',
  MOST_RECENT_USERNAME: 'MostRecentUsername',
  SUPPLYING_STORE_ID: 'SupplyingStoreId',
  SUPPLYING_STORE_NAME_ID: 'SupplyingStoreNameId',
  LAST_POST_PROCESSING_FAILED: 'LastPostProcessingFailed',
  SYNC_IS_INITIALISED: 'SyncIsInitialised',
  SYNC_PRIOR_FAILED: 'SyncPriorFailed',
  SYNC_URL: 'SyncURL',
  SYNC_SITE_ID: 'SyncSiteId',
  SYNC_SERVER_ID: 'SyncServerId',
  SYNC_SITE_NAME: 'SyncSiteName',
  SYNC_SITE_PASSWORD_HASH: 'SyncSitePasswordHash',
  THIS_STORE_ID: 'ThisStoreId',
  THIS_STORE_NAME_ID: 'ThisStoreNameId',
  HARDWARE_UUID: 'Hardware_UUID',
};

export const getAppVersion = async () => {
  const appVersion = await AsyncStorage.getItem(SETTINGS_KEYS.APP_VERSION);
  return appVersion;
};

Apply prettier, eslint to settings 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-spacing/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-spacing/tachyons-spacing.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)

var srcCSS = fs.readFileSync('./src/_spacing.css', 'utf8')

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

fs.writeFileSync('./docs/layout/spacing/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-spacing/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-spacing/tachyons-spacing.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)

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

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

fs.writeFileSync('./docs/layout/spacing/index.html', html)

Update with reference to global nav partial


$(document).ready( function(){

strip = function(s) { return s.replace(/^\s+/, '').replace(/\s+$/, ''); }
remove_punctuation = function(s) { return s.replace(/[,.;]/g,''); }

$('#ptitle').change(function fillURL(){
    if(! $('#pid').attr('readonly')){
        url = strip(this.value).toLowerCase().replace(/\s+/g, '-');
        url = remove_punctuation(url);
        $('#pid').val(url);
        $('#pid').change(); //is this required?
    }
    return;
});

$('#pid').change( function checkID(){
    $.post('/c/checkID', {pid: strip(this.value)},
         function(available){
            if (available == 'False'){
                msg = 'ID already exists, Choose a different one';
                $('#note_pid').html('' + msg + '');
                $('#pid').focus();
                return false;
            }
            else {
                $('#note_pid').html('');
                return true;
            }
        });
    });
});

$(document).ready( function(){

strip = function(s) { return s.replace(/^\s+/, '').replace(/\s+$/, ''); }
remove_punctuation = function(s) { return s.replace(/[^a-z0-9-]/g,''); }

var ptitle_event = function fillURL(){
    if(! $('#pid').attr('readonly')){
        url = strip(this.value).toLowerCase().replace(/\s+/g, '-');
        url = remove_punctuation(url);
        $('#pid').val(url);
        $('#pid').change(); //is this required?
    }
    return;
}

$('#ptitle').change(ptitle_event);
$('#ptitle').blur(ptitle_event);

$('#pid').change( function checkID(){
    $.post('/c/checkID', {pid: strip(this.value)},
         function(available){
            if (available == 'False'){
                msg = 'ID already exists, Choose a different one';
                $('#note_pid').html('' + msg + '');
                $('#pid').focus();
                return false;
            }
            else {
                $('#note_pid').html('');
                return true;
            }
        });
    });
});

Remove all non-alphanumeric characters when copying title to url. Also copy title on blur event


window.addEventListener("load", function () {
    {lib}
});

window.addEventListener("load", function () {
    var script = document.createElement("script");
    script.innerHTML = "{lib}";
    (document.head || document.documentElement).appendChild(script);
});

Append the code to the page


"use strict";

class  TagManager {
  constructor(topicId) {
    this.topicId = topicId;
  }

  addTag(tagName) {
    API.createTag(tagName, this.topicId);
  }

  removeTag(tagName) {
    API.deleteTag(tagName, this.topicId);
  }
}

Add TagManager class in new class way


/**
 * PluginInstallationController
 *
 * @description :: Server-side logic for managing Plugininstallations
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

module.exports = {

};

var emberUtils = require('../blueprints/_util/actionUtil.js');

/**
 * PluginInstallationController
 *
 * @description :: Server-side logic for managing Plugininstallations
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

var controller = module.exports = {};

/**
 * Overridden from default blueprint.
 *
 * POST /plugininstallations -> PluginInstallationController.create
 */
controller.create = function(req, res) {
  var data = emberUtils.parseValues(req, PluginInstallation);

  sails.async.waterfall([

    function createPluginInst(onCreatePluginInstFinished) {
      PluginInstallation.create(data).exec(function (createErr, pluginInstRecord) {
        if (createErr)
          return onCreatePluginInstFinished(createErr);

        return onCreatePluginInstFinished(null, pluginInstRecord); //next function in waterfall
      });
    },

    function updatePluginInstallCount(pluginInstRecord, onUpdatePluginInstallCountFinished) {
      var pluginId = data.plugin;

      Plugin.findOne(pluginId).exec(function (findErr, pluginRecord) {
        if (findErr)
          return onUpdatePluginInstallCountFinished(findErr);

        var prevCount = pluginRecord.installationCount;

        if (prevCount === undefined)
          prevCount = 0;

        pluginRecord.installationCount = prevCount + 1;

        pluginRecord.save(function (saveErr, pluginRecord) {
          if (saveErr)
            return onUpdatePluginInstallCountFinished(findErr);

          return onUpdatePluginInstallCountFinished(null, pluginInstRecord); // next function in waterfall
        });
      });
    },

    function repopulateRecord(pluginInstRecord, onRepopulateRecordFinished) {
      var Q = PluginInstallation.findOne(pluginInstRecord.id);
      Q = emberUtils.populateEach(Q, req);

      Q.exec(function (findErr, populatedRecord) {
        if (findErr)
          return onRepopulateRecordFinished(findErr);

        return onRepopulateRecordFinished(null, populatedRecord); // finish
      });
    }

  ], function waterfallFinished(err, populatedRecord) {
    if (err)
      return ErrorManager.handleError(err, res);

    return res.emberOk(PluginInstallation, populatedRecord, { status: 201 });
  });
};

Add logic for `installationCount` on Plugin


(function(Monarch) {
  Monarch.Remote.FakeServer = new JS.Singleton('Monarch.Remote.FakeServer', {
    initialize: function() {
      this.reset();
    },

    create: function(record, wireRepresentation) {
      return new Monarch.Remote.FakeCreateRequest(this, record, wireRepresentation);
    },

    update: function(record, wireRepresentation) {
      return new Monarch.Remote.FakeUpdateRequest(this, record, wireRepresentation);
    },

    destroy: function(record) {
      return new Monarch.Remote.FakeDestroyRequest(this, record);
    },

    fetch: function() {
      return new Monarch.Remote.FakeFetchRequest(this, _.toArray(arguments));
    },

    lastCreate: function() {
      return _.last(this.creates);
    },

    lastUpdate: function() {
      return _.last(this.updates);
    },

    lastDestroy: function() {
      return _.last(this.destroys);
    },

    lastFetch: function() {
      return _.last(this.fetches);
    },

    reset: function() {
      this.creates = [];
      this.updates = [];
      this.destroys = [];
      this.fetches = [];
    }
  });

  Monarch.Remote.OriginalServer = Monarch.Remote.OriginalServer;

  Monarch.useFakeServer = function() {
    Monarch.Remote.Server = Monarch.Remote.FakeServer;
    Monarch.Remote.Server.reset();
  };

  Monarch.restoreOriginalServer = function() {
    Monarch.Remote.Server = Monarch.Remote.OriginalServer;
  };
})(Monarch);

(function(Monarch) {
  Monarch.Remote.FakeServer = new JS.Singleton('Monarch.Remote.FakeServer', {
    initialize: function() {
      this.reset();
    },

    create: function(record, wireRepresentation) {
      return new Monarch.Remote.FakeCreateRequest(this, record, wireRepresentation);
    },

    update: function(record, wireRepresentation) {
      return new Monarch.Remote.FakeUpdateRequest(this, record, wireRepresentation);
    },

    destroy: function(record) {
      return new Monarch.Remote.FakeDestroyRequest(this, record);
    },

    fetch: function() {
      return new Monarch.Remote.FakeFetchRequest(this, _.toArray(arguments));
    },

    lastCreate: function() {
      return _.last(this.creates);
    },

    lastUpdate: function() {
      return _.last(this.updates);
    },

    lastDestroy: function() {
      return _.last(this.destroys);
    },

    lastFetch: function() {
      return _.last(this.fetches);
    },

    reset: function() {
      this.creates = [];
      this.updates = [];
      this.destroys = [];
      this.fetches = [];
    }
  });

  Monarch.Remote.OriginalServer = Monarch.Remote.Server;

  Monarch.useFakeServer = function() {
    Monarch.Remote.Server = Monarch.Remote.FakeServer;
    Monarch.Remote.Server.reset();
  };

  Monarch.restoreOriginalServer = function() {
    Monarch.Remote.Server = Monarch.Remote.OriginalServer;
  };
})(Monarch);

Save reference to original server properly.


/* @flow */

var Prefixer = require('../prefixer');

var prefixPlugin = function ({component, style}) {
  var newStyle = Prefixer.getPrefixedStyle(component, style);
  return {style: newStyle};
};

module.exports = prefixPlugin;

/* @flow */

var Prefixer = require('../prefixer');

var prefixPlugin = function ({componentName, style}) {
  var newStyle = Prefixer.getPrefixedStyle(componentName, style);
  return {style: newStyle};
};

module.exports = prefixPlugin;

Fix pulling componentName param in prefixer plugin


'use strict';

var searchResults = [{
  name: 'Edinburgh',
  zoomLevel: 16,
  point: {
    x: 55.953252,
    y: -3.188267
  }
}, {
  name: 'London',
  zoomLevel: 16,
  point: {
    x: 51.5073509,
    y: -0.1277583
  }
}, {
  name: 'Caisteal Dhùn Èideann',
  zoomLevel: 18,
  point: {
    x: 55.953252,
    y: -3.188267
  }
}];

exports.getResults = function(req, res) {
  res.json(searchResults);
};

'use strict';

var gutil = require('gulp-util');

var singleResult = [{
  name: 'EH9 1PR',
  zoomLevel: 16,
  point: {
    x: 55.953252,
    y: -3.188267
  }
}];

var noResults = [];

var multipleResults = [{
  name: 'Edinburgh',
  zoomLevel: 16,
  point: {
    x: 55.953252,
    y: -3.188267
  }
}, {
  name: 'London',
  zoomLevel: 16,
  point: {
    x: 51.5073509,
    y: -0.1277583
  }
}, {
  name: 'Caisteal Dhùn Èideann',
  zoomLevel: 18,
  point: {
    x: 55.953252,
    y: -3.188267
  }
}];

exports.getResults = function(req, res) {
  gutil.log(gutil.colors.green('Search: ', req.query.search));
  if (req.query.search === 'zero') {
    res.json(noResults);
  } else if (req.query.search === 'EH9 1PR') {
    res.json(singleResult);
  } else {
    res.json(multipleResults);
  }
};

Refactor stubbed data to return available results:


'use strict';

const KMSProvider = require('../../providers/kms');

/**
 * Route handler for KMS secrets
 * @param {StorageService} storage
 * @returns {function}
 */
function KMS(storage) {
  return (req, res, next) => {
    // KMS doesn't require a token so we can just pass an empty string
    storage.lookup('', req.body, KMSProvider)
      .then((result) => {
        if (result != null) { // eslint-disable-line eqeqeq
          Object.keys(result).forEach((key) => {
            result[key.toLowerCase()] = result[key];
            if (key.toLowerCase() !== key) {
              delete result[key];
            }
          });
        }
        // Check for both undefined and null. `!= null` handles both cases.
        if (result != null && result.hasOwnProperty('plaintext')) { // eslint-disable-line eqeqeq
          result.plaintext = Buffer.from(result.plaintext, 'base64').toString();
        }

        if (result != null && result.hasOwnProperty('correlation_id')) { // eslint-disable-line eqeqeq
          res.correlationId = result.correlation_id;
          delete result.correlation_id;
        }

        res.json(result);
      })
      .catch(next);
  };
}

module.exports = KMS;

'use strict';

const KMSProvider = require('../../providers/kms');

/**
 * Route handler for KMS secrets
 * @param {StorageService} storage
 * @returns {function}
 */
function KMS(storage) {
  return (req, res, next) => {
    // KMS doesn't require a token so we can just pass an empty string
    storage.lookup('', req.body, KMSProvider)
      .then((result) => {
        if (result) {
          Object.keys(result).forEach((key) => {
            result[key.toLowerCase()] = result[key];
            if (key.toLowerCase() !== key) {
              delete result[key];
            }
          });
        }
        // Check for both undefined and null. `!= null` handles both cases.
        if (result != null && result.hasOwnProperty('plaintext')) { // eslint-disable-line eqeqeq
          result.plaintext = Buffer.from(result.plaintext, 'base64').toString();
        }

        if (result != null && result.hasOwnProperty('correlation_id')) { // eslint-disable-line eqeqeq
          res.correlationId = result.correlation_id;
          delete result.correlation_id;
        }

        res.json(result);
      })
      .catch(next);
  };
}

module.exports = KMS;

Simplify result check to cover null and undefined.


var chalk = require('chalk');

var greetings = "" +
    chalk.yellow("   ..  ..   / o._)                   .---.")      +
    chalk.yellow("  /--'/--\  \-'||        .----.    .'     '.")    +
    chalk.yellow(" /        \_/ / |      .'      '..'         '-.") +
    chalk.yellow(".'\  \__\  __.'.'     .'          ì-._")          +
    chalk.yellow(" )\ |  )\ |      _.'")                            +
    chalk.yellow("// \\ // \\")                                     +
    chalk.yellow("||_  \\|_  \\_")                                  +
    chalk.yellow("'--' '--'' '--'")                                 +

    chalk.gray("\n Yo OCaml! A Yeoman generator that provides a functional boilerplate to easily scaffold OCaml modules. \n");

module.exports = greetings;

'use strict';

var chalk = require('chalk');

var greetings = '\n' +
    chalk.yellow('                     ,,__ \n') +
    chalk.yellow("           ..  ..   / o._)                   .---. \n") +
    chalk.yellow("          /--'/--\  \-'||        .----.    .'     '. \n") +
    chalk.yellow("         /        \_/ / |      .'      '..'         '-. \n") +
    chalk.yellow("       .'\  \__\  __.'.'     .'          '-._ \n") +
    chalk.yellow("         )\ |  )\ |      _.' \n") +
    chalk.yellow('        // \\ // \\ \n') +
    chalk.yellow("       ||_  \\|_  \\_ \n") +
    chalk.yellow("       '--' '--'' '--' \n") +

    chalk.yellow('\n Yo OCaml! ') +
    chalk.gray('A Yeoman generator that provides a functional boilerplate to easily scaffold OCaml modules. \n') +
    chalk.yellow("\n Let's talk about your new module? \n");

module.exports = greetings;

Fix broken camel art and add a better message


/*
  Load Meltdown.js on appropriate fields.
    - Can also be used to specify any custom settings for Meltdown on init.
    - See https://github.com/iphands/Meltdown#options

*/

$(document).ready(function() {
  // By default, only fields marked by the widget.
  $('.grp-meltdown').meltdown()
});

/*
  Load Meltdown.js on appropriate fields.
    - Can also be used to specify any custom settings for Meltdown on init.
    - See https://github.com/iphands/Meltdown#options

*/

$(document).ready(function() {
  // By default, only fields marked by the widget.
  $('.grp-meltdown').meltdown({
    openPreview: true,
  });
});

Make preview default to on


import {OPEN_CARD, CLOSE_CARD} from '../actions/ActionTypes'

export default function cards(state = [], action) {
  switch (action.type) {
    case OPEN_CARD:
      return state.filter(cardName => cardName !== action.cardName).concat(action.cardName)
    case CLOSE_CARD:
      return state.filter(cardName => cardName !== action.cardName)
    default:
      return state
  }
}

import {SET_CURRENT_REGION, OPEN_CARD, CLOSE_CARD} from '../actions/ActionTypes'

export default function cards(state = [], action) {
  switch (action.type) {
    case SET_CURRENT_REGION:
      return []
    case OPEN_CARD:
      return state.filter(cardName => cardName !== action.cardName).concat(action.cardName)
    case CLOSE_CARD:
      return state.filter(cardName => cardName !== action.cardName)
    default:
      return state
  }
}

Clear open cards when region change


import { combineReducers } from 'redux'
import { optimistic } from 'redux-optimistic-ui';
import locationReducer from './location'
import account from 'routes/Account/modules/account'
import library from 'routes/Library/modules/library'
import queue from 'routes/Queue/modules/queue'

export const makeRootReducer = (asyncReducers) => {
  return optimistic(combineReducers({
    location: locationReducer,
    account,
    library,
    queue,
    ...asyncReducers
  }))
}

export const injectReducer = (store, { key, reducer }) => {
  store.asyncReducers[key] = reducer
  store.replaceReducer(makeRootReducer(store.asyncReducers))
}

export default makeRootReducer

import { combineReducers } from 'redux'
import { optimistic } from 'redux-optimistic-ui';
import locationReducer from './location'
import account from 'routes/Account/modules/account'
import library from 'routes/Library/modules/library'
import queue from 'routes/Queue/modules/queue'

export const makeRootReducer = (asyncReducers) => {
  return optimistic(combineReducers({
    location: locationReducer,
    errorMessage,
    account,
    library,
    queue,
    ...asyncReducers
  }))
}

export const injectReducer = (store, { key, reducer }) => {
  store.asyncReducers[key] = reducer
  store.replaceReducer(makeRootReducer(store.asyncReducers))
}

export default makeRootReducer

export const RESET_ERROR_MESSAGE = 'RESET_ERROR_MESSAGE'

function errorMessage(state = null, action) {
  const { type, error } = action

  if (type === RESET_ERROR_MESSAGE) {
    return null
  } else if (error) {
    return action.error
  }

  return state
}

Add global error message reducer


var webpack = require('webpack');
var ejs = require('ejs');
var MIN = process.argv.indexOf('-p') > -1;

function getBanner() {
  var pkg = require('./bower.json');
  var banner = ['/**',
    ' * <%= pkg.name %> - <%= pkg.description %>',
    ' * @version v<%= pkg.version %>',
    ' * @link <%= pkg.homepage %>',
    ' * @license <%= pkg.license %>',
    ' */',
    ''].join('\n');
  return ejs.render(banner, {pkg: pkg});
}

module.exports = {
  entry: __dirname + '/src/angular-bootstrap-confirm.js',
  output: {
    path: __dirname + '/dist',
    filename: MIN ? 'angular-bootstrap-confirm.min.js' : 'angular-bootstrap-confirm.js',
    libraryTarget: 'umd'
  },
  externals: {
    angular: 'angular',
    'angular-sanitize': 'angular-sanitize',
    './ui-bootstrap-position': 'angular-bootstrap'
  },
  devtool: MIN ? 'source-map' : null,
  module: {
    preLoaders: [{
      test: /.*\.js$/,
      loaders: ['eslint'],
      exclude: /node_modules/
    }],
    loaders: [{
      test: /.*\.js$/,
      loaders: ['ng-annotate'],
      exclude: /node_modules/
    }]
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.BannerPlugin(getBanner(), {
      raw: true,
      entryOnly: true
    })
  ]
};

var webpack = require('webpack');
var ejs = require('ejs');
var MIN = process.argv.indexOf('-p') > -1;

function getBanner() {
  var pkg = require('./bower.json');
  var banner = ['/**',
    ' * <%= pkg.name %> - <%= pkg.description %>',
    ' * @version v<%= pkg.version %>',
    ' * @link <%= pkg.homepage %>',
    ' * @license <%= pkg.license %>',
    ' */',
    ''].join('\n');
  return ejs.render(banner, {pkg: pkg});
}

module.exports = {
  entry: __dirname + '/src/angular-bootstrap-confirm.js',
  output: {
    path: __dirname + '/dist',
    filename: MIN ? 'angular-bootstrap-confirm.min.js' : 'angular-bootstrap-confirm.js',
    libraryTarget: 'umd'
  },
  externals: {
    angular: 'angular',
    'angular-sanitize': 'angular-sanitize',
    './ui-bootstrap-position': 'angular-ui-bootstrap'
  },
  devtool: MIN ? 'source-map' : null,
  module: {
    preLoaders: [{
      test: /.*\.js$/,
      loaders: ['eslint'],
      exclude: /node_modules/
    }],
    loaders: [{
      test: /.*\.js$/,
      loaders: ['ng-annotate'],
      exclude: /node_modules/
    }]
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.BannerPlugin(getBanner(), {
      raw: true,
      entryOnly: true
    })
  ]
};

Use proper npm ui-bootstrap dependency


/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Notification from 'GoogleComponents/notifications/notification';

class ErrorHandler extends Component {
	constructor( props ) {
		super( props );

		this.state = {
			error: null,
			info: null,
		};
	}

	componentDidCatch( error, info ) {
		global.console.error( 'Caught an error:', error, info );

		this.setState( { error, info } );
	}

	render() {
		const { children } = this.props;
		const { error, info } = this.state;

		// If there is no caught error, render the children components normally.
		if ( ! error ) {
			return children;
		}

		return (
			<Notification
				id={ 'googlesitekit-error' }
				key={ 'googlesitekit-error' }
				title={ __( 'Site Kit encountered an error', 'google-site-kit' ) }
				description={ { error.message } }
				dismiss={ '' }
				isDismissable={ false }
				format="small"
				type="win-error"
			>

{ info.componentStack }

			</Notification>
		);
	}
}

ErrorHandler.defaultProps = {};

ErrorHandler.propTypes = {
	/** @ignore */
	children: PropTypes.node.isRequired,
};

export default ErrorHandler;

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Notification from 'GoogleComponents/notifications/notification';

class ErrorHandler extends Component {
	constructor( props ) {
		super( props );

		this.state = {
			error: null,
			info: null,
		};
	}

	componentDidCatch( error, info ) {
		global.console.error( 'Caught an error:', error, info );

		this.setState( { error, info } );
	}

	render() {
		const { children } = this.props;
		const { error, info } = this.state;

		// If there is no caught error, render the children components normally.
		if ( ! error ) {
			return children;
		}

		return (
			<Notification
				id="googlesitekit-error"
				title={ __( 'Site Kit encountered an error', 'google-site-kit' ) }
				description={ { error.message } }
				isDismissable={ false }
				format="small"
				type="win-error"
			>

{ info.componentStack }

			</Notification>
		);
	}
}

ErrorHandler.defaultProps = {};

ErrorHandler.propTypes = {
	/** @ignore */
	children: PropTypes.node.isRequired,
};

export default ErrorHandler;

Tidy up strings in ErrorHandler.


Todos.TodoEntryComponent = Ember.Component.extend({
	actions: {

	}

});

Todos.TodoEntryComponent = Ember.Component.extend({
	actions: {
		click: function(){
			this.sendAction('remove');
		}
	}
});

Add action to remove component


require('./lib/js.io/packages/jsio')
jsio.path.shared = './js'
jsio.path.server = './js'

var redis = require('./lib/redis-node-client/lib/redis-client')
var sys = require('sys')

jsio('from shared.javascript import bind')
jsio('import shared.query')

shared.query.init(redis)

process.addListener('exit', shared.query.release)
process.addListener('uncaughtException', function(e) {
	sys.puts("ERROR: uncaught exception", JSON.stringify(e))
	process.exit()
})
process.addListener('SIGINT', process.exit)

require('./lib/js.io/packages/jsio')
jsio.path.shared = './js'
jsio.path.server = './js'

var redis = require('./lib/redis-node-client/lib/redis-client')
var sys = require('sys')

jsio('from shared.javascript import bind')
jsio('import shared.query')

shared.query.init(redis)

process.addListener('exit', shared.query.release)
process.addListener('uncaughtException', function(e) {
	try {
		sys.puts("ERROR: uncaught exception", JSON.stringify(e))
	} catch(e2) {
		sys.puts("ERROR: could not JSON stringify error message", e.message, e2.message)
	}
	process.exit()
})
process.addListener('SIGINT', process.exit)

Add a second layer of try/catch around the error reporting, in case the JSON stringification of the error object fails due to circular references


/* jshint devel: true */
!function() {
	'use strict';

	var navGame = document.getElementById("nav-game");
	var navUpgrade = document.getElementById("nav-upgrade");
	var navAbout = document.getElementById("nav-about");

	var showElement = function(element) {
		document.getElementById(element).className = document
				.getElementById(element).className.replace(
				/(?:^|\s)invisible(?!\S)/g, '');
	};
	var hideElement = function(element) {
		document.getElementById(element).className += " invisible";
	};

	var showGame = function() {
		showElement("game");
		hideElement("upgrades");
		hideElement("about");
	};

	var showUpgrades = function() {
		hideElement("game");
		showElement("upgrades");
		hideElement("about");
	};

	var showAbout = function() {
		hideElement("game");
		hideElement("upgrades");
		showElement("about");
	};

	navGame.addEventListener("click", showGame);
	navUpgrade.addEventListener("click", showUpgrades);
	navAbout.addEventListener("click", showAbout);
}();

/* jshint devel: true */
!function() {
	'use strict';

	var navGame = document.getElementById("nav-game");
	var navUpgrade = document.getElementById("nav-upgrade");
	var navAbout = document.getElementById("nav-about");

	var showElement = function(element) {
		document.getElementById(element).className = document
				.getElementById(element).className.replace(
				/(?:^|\s)invisible(?!\S)/g, '');
	};
	var hideElement = function(element) {
		document.getElementById(element).className += " invisible";
	};
	var setActive = function(element) {
		element.className += " active";
	};
	var setUnactive = function(element) {
		element.className = element.className.replace(/(?:^|\s)active(?!\S)/g,
				'');
	};

	var showGame = function() {
		showElement("game");
		hideElement("upgrades");
		hideElement("about");
		setActive(navGame);
		setUnactive(navUpgrade);
		setUnactive(navAbout);
	};

	var showUpgrades = function() {
		hideElement("game");
		showElement("upgrades");
		hideElement("about");
		setUnactive(navGame);
		setActive(navUpgrade);
		setUnactive(navAbout);
	};

	var showAbout = function() {
		hideElement("game");
		hideElement("upgrades");
		showElement("about");
		setUnactive(navGame);
		setUnactive(navUpgrade);
		setActive(navAbout);
	};

	navGame.addEventListener("click", showGame);
	navUpgrade.addEventListener("click", showUpgrades);
	navAbout.addEventListener("click", showAbout);
}();

Add visual identify which tab is active


import { merge as mergeObs } from 'rxjs/observable'
import { distinctUntilChanged, map as mapObs, debounceTime } from 'rxjs/operators'
import { isEqual, isFunction } from '../util/minilo'
import fromOlEvent from './from-ol-event'

/**
 * Creates Observable from OpenLayers change:* event
 * @param {module:ol/Observable~Observable} target
 * @param {string|string[]} [prop]
 * @param {boolean|function(a, b):boolean|undefined} [distinct] Distinct values by isEqual fn or by custom comparator
 * @param {number|undefined} [debounce] Debounce values by passed amount of ms.
 * @param {function|undefined} [selector] Custom selector
 * @return {Observable<{prop: string, value: *}>}
 */
export default function fromOlChangeEvent (target, prop, distinct, debounce, selector) {
  if (Array.isArray(prop)) {
    return mergeObs(...prop.map(p => fromOlChangeEvent(target, p)))
  }

  selector = selector || ((target, prop) => target.get(prop))
  let event = `change:${prop}`
  let observable = fromOlEvent(target, event, () => selector(target, prop))
  let operations = []

  if (debounce != null) {
    operations.push(debounceTime(debounce))
  }
  if (distinct) {
    isFunction(distinct) || (distinct = isEqual)
    operations.push(distinctUntilChanged(distinct))
  }

  operations.push(mapObs(value => ({ prop, value })))

  return observable.pipe(...operations)
}

import { merge as mergeObs } from 'rxjs/observable'
import { distinctUntilChanged, map as mapObs, debounceTime } from 'rxjs/operators'
import { isEqual, isFunction } from '../util/minilo'
import fromOlEvent from './from-ol-event'

/**
 * Creates Observable from OpenLayers change:* event
 * @param {module:ol/Observable~Observable} target
 * @param {string|string[]} [prop]
 * @param {boolean|function(a, b):boolean|undefined} [distinct] Distinct values by isEqual fn or by custom comparator
 * @param {number|undefined} [debounce] Debounce values by passed amount of ms.
 * @param {function|undefined} [selector] Custom selector
 * @return {Observable<{prop: string, value: *}>}
 */
export default function fromOlChangeEvent (target, prop, distinct, debounce, selector) {
  if (Array.isArray(prop)) {
    return mergeObs(...prop.map(p => fromOlChangeEvent(target, p)))
  }

  selector = selector || ((target, prop) => target.get(prop))
  const event = `change:${prop}`
  const observable = fromOlEvent(target, event, () => selector(target, prop))
  const operations = []

  if (debounce != null) {
    operations.push(debounceTime(debounce))
  }
  if (distinct) {
    isFunction(distinct) || (distinct = isEqual)
    operations.push(distinctUntilChanged(distinct))
  }

  operations.push(mapObs(value => ({ prop, value })))

  return observable.pipe(...operations)
}

Fix lint errors in the `rx-ext` code


/**
 * @fileOverview Project wide enumerations.
 */

var enums = module.exports = {};

/** @enum {string} The CRUD Ops types */
enums.CrudOps = {
  CREATE: 'create',
  READ: 'read',
  READ_ONE: 'readOne',
  PAGINATE: 'paginate',
  UPDATE: 'update',
  DELETE: 'delete',
};

/** @enum {number} HTTP Codes Used by CRUDE */
enums.HttpCode = {
  OK: 200,
  CREATED: 201,
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  INTERNAL_ERROR: 500,
};

/**
 * @fileOverview Project wide enumerations.
 */

var enums = module.exports = {};

/** @enum {string} The CRUD Ops types */
enums.CrudOps = {
  CREATE: 'create',
  READ: 'read',
  READ_ONE: 'readOne',
  PAGINATE: 'paginate',
  UPDATE: 'update',
  DELETE: 'delete',
};

/** @enum {number} HTTP Codes Used by CRUDE */
enums.HttpCode = {
  OK: 200,
  CREATED: 201,
  NO_CONTENT: 204,
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  INTERNAL_ERROR: 500,
};

Add the NO_CONTENT HTTP Code


/**
 * Module dependencies
 */

var fs    = require('fs-extra');
var path  = require('path');
var chalk = require('chalk');

module.exports = function newProject(dir) {
  fs.copy(path.normalize('/usr/local/lib/node_modules/dflt/lib/templates'), dir, function(err) {
    if (err) throw err;
    console.log('Created new project with template \"' + chalk.red('default') + '\" in directory \"' + chalk.blue(dir) + '\".');
  });
};

/**
 * Module dependencies
 */

var fs    = require('fs-extra');
var path  = require('path');
var chalk = require('chalk');

/**
 * Copies the template into a new directory, with the name supplied by the user.
 *
 * @param {String} the name of the directory to copy the template into
 */
module.exports = function newProject(dir) {
  // Use the absolute path for now, this will definitely not work on Windows
  fs.copy(path.normalize('/usr/local/lib/node_modules/dflt/lib/templates'), dir, function(err) {
    if (err) throw err;
    console.log('Created new project with template \"' + chalk.red('default') + '\" in directory \"' + chalk.blue(dir) + '\".');
  });
};

Add proper comments and note about Windows


exports.up = function(knex, Promise) {
	return knex.schema.createTable('entries', function (table) {
		table.increments().primary();
		table.datetime('date').notNull();
		table.string('author').notNull();
		table.string('image_url');
		table.string('text');
		table.string('status').notNull();
		table.text('data');
		table.timestamps();
	})
};

exports.down = function(knex, Promise) {
	return knex.dropTable('entries');
};

exports.up = function(knex, Promise) {
	return knex.schema.createTable('entries', function (table) {
		table.increments().primary();
		table.datetime('date').notNull();
		table.string('author').notNull();
		table.string('image_url');
		table.text('text');
		table.string('status').notNull();
		table.text('data');
		table.timestamps();
	})
};

exports.down = function(knex, Promise) {
	return knex.dropTable('entries');
};

Set 'text' column to text type to avoid length limit


/*
 *  Bookmarkletify at
 *  https://alanhogan.github.io/bookmarkleter/
 */

var version = '1.2';
var name = 'com.alanhogan.bookmarklets.mark-visited.' + version;

var extant = document.querySelector('style[data-via-bookmarklet="'+name+'"]');

if (extant !== null) {
	console.log(`Bookmarklet (${name}): Already ran on page`);
}

var css = `
a:link{
  text-shadow: 0 0.06em 0.3em rgba(100%, 100%, 100%, 1),
    -1px 1px 1px rgba(100%, 100%, 100%, 1),
    1px 1px 1px rgba(104%, 100%, 100%, 1),
    -1px -1px 1px rgba(100%, 100%, 100%, 1),
    1px -1px 1px rgba(100%, 100%, 100%, 1)  !important;
}
a:link,
a:link * {
  color: rgb(5%, 27%, 74%) !important;
}
a:visited,
a:visited * {
  color: rgb(60%, 2%, 53%) !important;
}
`;

var styleElem = document.createElement('style');
styleElem.setAttribute('data-via-bookmarklet', name);
styleElem.innerHTML = css;

document.head.appendChild(styleElem);

Add comment w/ bookmarkleter link


var binding;

try {
	binding = require(__dirname + '/../build/Debug/libxl');
} catch(e) {
	binding = require(__dirname + '/../build/Release/libxl');
}

module.exports = binding;

var os = require('os'),
    path = require('path');

var bindings = null;

var paths = [
    path.join(__dirname, os.platform() + '-' + os.arch(), 'libxl'),
    path.join(__dirname, os.platform(), 'libxl'),
    path.join(__dirname, '..', 'build', 'Debug', 'libxl'),
    path.join(__dirname, '..', 'build', 'Release', 'libxl')
];

for (var i = 0; i < paths.length; i++) {
    try {
        bindings = require(paths[i]);
        break;
    } catch (e) {}
}

if (!bindings) {
    throw new Error('unable to load libxl.node');
}

module.exports = bindings;

Improve binary locator to be more deployment friendly.


const path = require('path')
const merge = require('webpack-merge')
const common = require('./webpack.config.lib.common.js')

const root = path.join(__dirname)

module.exports = merge(common, {
  mode: 'development',
  target: 'node',
  output: {
    path: path.resolve(root + '/dist'),
    filename: '[name]/index.js',
    libraryTarget: 'umd'
  }
})

const path = require('path')
const merge = require('webpack-merge')
const common = require('./webpack.config.lib.common.js')

const root = path.join(__dirname)

module.exports = merge(common, {
  mode: 'development',
  target: 'web',
  output: {
    path: path.resolve(root + '/dist'),
    filename: '[name]/index.js',
    libraryTarget: 'umd'
  }
})

Build with webpack target web


(function() {
       var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
       po.src = 'https://apis.google.com/js/client:plusone.js';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
     })();
function signinCallback(authResult) {
  if (authResult['status']['signed_in']) {
    alert("Sign in Successful");

    $.ajax({
        url: "https://www.googleapis.com/plus/v1/people/me",
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            alert(data);
        },

    });
    // Update the app to reflect a signed in user
    // Hide the sign-in button now that the user is authorized, for example:
    document.getElementById('signinButton').setAttribute('style', 'display: none');
  } else {
    alert("Sign in failed");
    // Update the app to reflect a signed out user
    // Possible error values:
    //   "user_signed_out" - User is signed-out
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatically log in the user
    console.log('Sign-in state: ' + authResult['error']);
  }
}

(function() {
       var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
       po.src = 'https://apis.google.com/js/client:plusone.js';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
     })();
function signinCallback(authResult) {
  if (authResult['status']['signed_in']) {
    alert("Sign in Successful");

       $.ajax({
        url: "https://www.googleapis.com/plus/v1/people/me?access_token="+authResult["access_token"],
        type: 'GET',
        dataType: 'json',

        success: function(data) {
          //do something with the data
        },

    });

    // Update the app to reflect a signed in user
    // Hide the sign-in button now that the user is authorized, for example:
    document.getElementById('signinButton').setAttribute('style', 'display: none');
  } else {
    alert("Sign in failed");
    // Update the app to reflect a signed out user
    // Possible error values:
    //   "user_signed_out" - User is signed-out
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatically log in the user
    console.log('Sign-in state: ' + authResult['error']);
  }
}

ACCESS TOKEN FIX FINALLY :sweat_drops:


import { htmlSafe } from '@ember/template';
import { assert } from '@ember/debug';
import { get } from '@ember/object';

import {
  dottify,
  applyClass
} from 'ember-inline-svg/utils/general';

export function inlineSvg(svgs, path, options) {
  var jsonPath = dottify(path);
  var svg = get(svgs, jsonPath);

  // TODO: Ember.get should return `null`, not `undefined`.
  // if (svg === null && /\.svg$/.test(path))
  if (typeof svg === "undefined" && /\.svg$/.test(path)) {
    svg = get(svgs, jsonPath.slice(0, -4));
  }

  assert("No SVG found for "+path, svg);

  svg = applyClass(svg, options.class);

  return htmlSafe(svg);
}

import { htmlSafe } from '@ember/string';
import { assert } from '@ember/debug';
import { get } from '@ember/object';

import {
  dottify,
  applyClass
} from 'ember-inline-svg/utils/general';

export function inlineSvg(svgs, path, options) {
  var jsonPath = dottify(path);
  var svg = get(svgs, jsonPath);

  // TODO: Ember.get should return `null`, not `undefined`.
  // if (svg === null && /\.svg$/.test(path))
  if (typeof svg === "undefined" && /\.svg$/.test(path)) {
    svg = get(svgs, jsonPath.slice(0, -4));
  }

  assert("No SVG found for "+path, svg);

  svg = applyClass(svg, options.class);

  return htmlSafe(svg);
}

Update htmlSafe call to 'ember/string'


'use strict'

let basic = require('./basic-response-helper')
let executePipelineCommand = require('../../core/pipelines/execute-pipeline-command')

module.exports = {

  /**
   * Sends a list of pipelines
   *
   * @param req
   * @param res
   */
  getList: (req, res) => {
    basic.getList(req, res, 'pipeline_configs')
  },

  /**
   * Get a single pipeline config
   *
   * @param req
   * @param res
   */
  getPipeline: (req, res) => {
    basic.getOne(req, res, 'pipeline_configs')
  },

  /**
   * Create a pipeline
   *
   * @param req
   * @param res
   */
  createPipeline: (req, res) => {
    basic.insertRespond(req, res, 'pipeline_configs')
  },

  /**
   * Start a new pipeline execution
   *
   * @param req
   * @param res
   */
  executePipeline: (req, res) => {
    try {
      executePipelineCommand(req.params.id, req.body, req.user.id, (id) => {

        res.status(200).send({
          data: {
            pipeline_execution_id: id
          }
        })

      })

    } catch (err) {
      res.status(500).send()
    }
  }

}

'use strict'

let basic = require('./basic-response-helper')
let execPipeline = require('../../core/pipelines/execute-pipeline-command')

module.exports = {

  /**
   * Sends a list of pipelines
   *
   * @param req
   * @param res
   */
  getList: (req, res) => {
    basic.getList(req, res, 'pipeline_configs')
  },

  /**
   * Get a single pipeline config
   *
   * @param req
   * @param res
   */
  getPipeline: (req, res) => {
    basic.getOne(req, res, 'pipeline_configs')
  },

  /**
   * Create a pipeline
   *
   * @param req
   * @param res
   */
  createPipeline: (req, res) => {
    basic.insertRespond(req, res, 'pipeline_configs')
  },

  /**
   * Start a new pipeline execution
   *
   * @param req
   * @param res
   */
  executePipeline: (req, res) => {
    try {
      const PIPELINE_ID = req.params.id
      const USER_ID = req.user.id
      const PARAMS = req.body
      const CALLBACK = (id) => {
        res.status(200).send({
          data: {
            pipeline_execution_id: id
          }
        })
      }

      execPipeline(PIPELINE_ID, PARAMS, USER_ID, CALLBACK)

    } catch (err) {
      res.status(500).send()
    }
  }

}

Set func params as constants to give context into their values


(function () {
    'use strict';

    angular
        .module('atlas')
        .controller('MapController', MapController);

    MapController.$inject = ['store', 'crsConverter'];

    function MapController (store, crsConverter) {
        var vm = this;

        store.subscribe(update);

        update();

        function update () {
            var state = store.getState();

            vm.markers = [];

            if (state.search && state.search.location) {
                vm.markers.push({
                    id: 'search',
                    geometry: convertLocationToGeoJSON(state.search.location),
                    useAutoFocus: false
                });
            }

            if (state.detail && state.detail.geometry) {
                vm.markers.push({
                    id: 'detail',
                    geometry: state.detail.geometry,
                    useAutoFocus: true
                });
            }

            if (state.straatbeeld && angular.isArray(state.straatbeeld.location)) {
                vm.markers.push({
                    id: 'straatbeeld_orientation',
                    geometry: convertLocationToGeoJSON(state.straatbeeld.location),
                    orientation: state.straatbeeld.heading,
                    useAutoFocus: false
                });

                vm.markers.push({
                    id: 'straatbeeld_person',
                    geometry: convertLocationToGeoJSON(state.straatbeeld.location),
                    useAutoFocus: false
                });
            }

            vm.mapState = state.map;
            vm.showLayerSelection = state.layerSelection;
        }

        function convertLocationToGeoJSON (location) {
            return {
                type: 'Point',
                coordinates: crsConverter.wgs84ToRd(location)
            };
        }
    }
})();

(function () {
    'use strict';

    angular
        .module('atlas')
        .controller('MapController', MapController);

    MapController.$inject = ['store', 'crsConverter'];

    function MapController (store, crsConverter) {
        var vm = this;

        store.subscribe(update);

        update();

        function update () {
            var state = store.getState();

            vm.markers = [];

            if (state.search && state.search.location) {
                vm.markers.push({
                    id: 'search',
                    geometry: convertLocationToGeoJSON(state.search.location),
                    useAutoFocus: false
                });
            }

            if (state.detail && state.detail.geometry) {
                vm.markers.push({
                    id: 'detail',
                    geometry: state.detail.geometry,
                    useAutoFocus: true
                });
            }

            if (state.straatbeeld) {
                vm.markers.push({
                    id: 'straatbeeld_orientation',
                    geometry: convertLocationToGeoJSON(state.straatbeeld.location),
                    orientation: state.straatbeeld.heading,
                    useAutoFocus: false
                });

                vm.markers.push({
                    id: 'straatbeeld_person',
                    geometry: convertLocationToGeoJSON(state.straatbeeld.location),
                    useAutoFocus: false
                });
            }

            vm.mapState = state.map;
            vm.showLayerSelection = state.layerSelection;
        }

        function convertLocationToGeoJSON (location) {
            return {
                type: 'Point',
                coordinates: crsConverter.wgs84ToRd(location)
            };
        }
    }
})();

Set pano popje when straatbeeld exsts


exports.User = require('./user');
exports.Message = require('./message');
exports.Topic = require('./topic');
exports.Hot = require('./hot');
exports.Reply = require('./reply');

exports.User    = require('./user');
exports.Message = require('./message');
exports.Section = require('./section');
exports.Node    = require('./node');
exports.Topic   = require('./topic');
exports.Append  = require('./append');
exports.Reply   = require('./reply');
exports.Note    = require('./note');
exports.collect = require('./topic_collect');

Add the module to exports.


var docopt = require('docopt');
var fs = require('fs');
var path = require('path');

var meta = require('../package.json');
var usage = fs.readFileSync(path.join(__dirname, 'usage.txt'))
  .toString();

module.exports = function(stdin, stdout, stderr, env, argv, callback) {
  var options;
  try {
    options = docopt.docopt(usage, {
      argv: argv,
      help: false,
      exit: false
    });
  } catch (error) {
    stderr.write(error.message);
    callback(1);
    return;
  }
  if (options['--version'] || options['-v']) {
    stdout.write(meta.name + ' ' + meta.version + '\n');
    callback(0);
  } else if (options['--help'] || options['-h']) {
    stdout.write(usage + '\n');
    callback(0);
  } else {
    throw new Error();
  }
};

var docopt = require('docopt');
var fs = require('fs');
var path = require('path');

var meta = require('../package.json');
var usage = fs.readFileSync(path.join(__dirname, 'usage.txt'))
  .toString();

module.exports = function(stdin, stdout, stderr, env, argv, callback) {
  var options;
  try {
    options = docopt.docopt(usage, {
      argv: argv,
      help: false,
      exit: false
    });
  } catch (error) {
    stderr.write(error.message + '\n');
    callback(1);
    return;
  }
  if (options['--version'] || options['-v']) {
    stdout.write(meta.name + ' ' + meta.version + '\n');
    callback(0);
  } else if (options['--help'] || options['-h']) {
    stdout.write(usage + '\n');
    callback(0);
  } else {
    throw new Error();
  }
};

Add newline to end of usage error messages


/**
 * Executed in the browser.
 *
 * This just ensures that the proxima nova font is loaded, which apparently
 * doesn't happen in the dev pages sometimes.
 */
module.exports = function() {
    var newStyle = document.createElement('style');
    newStyle.appendChild(document.createTextNode(
        "@font-face {" +
        "    font-family: 'Proxima Nova';" +
        "    src: url('https://www.kastatic.org/fonts/ProximaNova-Reg-webfont.woff') format('woff');" +
        "    font-weight: normal;" +
        "    font-style: normal;" +
        "}" +
        "" +
        "@font-face {" +
        "    font-family: 'Proxima Nova';" +
        "    src: url('https://www.kastatic.org/fonts/ProximaNova-Bold-webfont.woff') format('woff');" +
        "    font-weight: bold;" +
        "    font-style: normal;" +
        "}" +
        "" +
        "@font-face {" +
        "    font-family: 'Proxima Nova Bold';" +
        "    src: url('https://www.kastatic.org/fonts/ProximaNova-Bold-webfont.woff') format('woff');" +
        "    font-weight: normal;" +
        "    font-style: normal;" +
        "}" +
        "body {" +
        "   font-family: 'Proxima Nova';" +
        "}"));
    document.head.appendChild(newStyle);
};

/**
 * Executed in the browser.
 *
 * This just ensures that the proxima nova font is loaded, which apparently
 * doesn't happen in the dev pages sometimes.
 */
module.exports = function() {
    var newStyle = document.createElement('style');
    newStyle.appendChild(document.createTextNode(
        "@font-face {" +
        "    font-family: 'Proxima Nova';" +
        "    src: url('https://www.kastatic.org/fonts/Proxima-Nova-Regular.woff') format('woff');" +
        "    font-weight: normal;" +
        "    font-style: normal;" +
        "}" +
        "" +
        "@font-face {" +
        "    font-family: 'Proxima Nova';" +
        "    src: url('https://www.kastatic.org/fonts/Proxima-Nova-Semibold.woff') format('woff');" +
        "    font-weight: bold;" +
        "    font-style: normal;" +
        "}" +
        "" +
        "@font-face {" +
        "    font-family: 'Proxima Nova Bold';" +
        "    src: url('https://www.kastatic.org/fonts/Proxima-Nova-Semibold.woff') format('woff');" +
        "    font-weight: normal;" +
        "    font-style: normal;" +
        "}" +
        "body {" +
        "   font-family: 'Proxima Nova';" +
        "}"));
    document.head.appendChild(newStyle);
};

Update proxima nova font locations.


'use strict';

var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routeBuilder = require('./routes');

var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cookieParser());

app.use('/', routeBuilder(require('./routes/home')));
app.use('/users', routeBuilder(require('./routes/users')));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
    next = next;
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
  next = next;
});

module.exports = app;

'use strict';

var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routeBuilder = require('./routes');

var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cookieParser());

app.use('/', routeBuilder(require('./routes/home')));
app.use('/users', routeBuilder(require('./routes/users')));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: err
    });
    next = next;
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.json({
    message: err.message,
    error: {}
  });
  next = next;
});

module.exports = app;

Return errors as json, instead of throwing an error about view engines.


Package.describe({
  name: "promise",
  version: "0.6.2-beta.16",
  summary: "ECMAScript 2015 Promise polyfill with Fiber support",
  git: "https://github.com/meteor/promise",
  documentation: "README.md"
});

Npm.depends({
  "meteor-promise": "0.6.2"
});

Package.onUse(function(api) {
  api.use("modules");
  api.mainModule("main.js");
  api.export("Promise");
});

Package.onTest(function(api) {
  api.use("tinytest");
  api.use("promise");
  api.addFiles("promise-tests.js");
});

Package.describe({
  name: "promise",
  version: "0.6.2-beta.16",
  summary: "ECMAScript 2015 Promise polyfill with Fiber support",
  git: "https://github.com/meteor/promise",
  documentation: "README.md"
});

Npm.depends({
  "meteor-promise": "0.6.2"
});

Package.onUse(function(api) {
  api.use("modules");
  api.mainModule("main.js");
  api.export("Promise");
});

Package.onTest(function(api) {
  api.use("modules");
  api.use("tinytest");
  api.use("promise");
  api.addFiles("promise-tests.js");
});

Fix meteor-promise tests with api.use("modules").


var fs = require('fs');
var logToTable = require('./util/log-to-table.js');
var logFilePath = 'table.txt';
var commitID = 'abc';
if (process.argv.length >= 4) {
    logFilePath = process.argv[2];
    commitID = process.argv[3];
    console.log(logToTable(fs.readFileSync(logFilePath, 'utf-8'), commitID));
} else {
    console.log('Usage: ' + process.argv.slice(0,2).join(' ') + ' <logFile> <commitID>');
}

var fs = require('fs');
var logToTable = require('./util/log-to-table.js');
var logFilePath = 'table.txt';
var commitID = 'abc';
if (process.argv.length >= 4) {
    logFilePath = process.argv[2];
    commitID = process.argv[3];
    console.log(logToTable(fs.readFileSync(logFilePath, 'utf-8'), commitID) + '\n\n');
} else {
    console.log('Usage: ' + process.argv.slice(0,2).join(' ') + ' <logFile> <commitID>');
}

Append 2 newlines to table for convenience


var self = require("sdk/self");

// create toolbarbutton
var tbb = require("toolbarbutton").ToolbarButton({
  id: "UProxyItem",
  label: "UProxy",
  image: self.data.url("uproxy-19.png"),
  onCommand: function () {
    //tbb.destroy(); // kills the toolbar button
  }
});

tbb.moveTo({
  toolbarID: "nav-bar",
  forceMove: false // only move from palette
});

var self = require("sdk/self");

var initToolbar = function() {
  // create toolbarbutton
  var tbb = require("toolbarbutton").ToolbarButton({
    id: "UProxyItem",
    label: "UProxy",
    image: self.data.url("uproxy-19.png"),
    onCommand: function () {
      //tbb.destroy(); // kills the toolbar button
    }
  });

  tbb.moveTo({
    toolbarID: "nav-bar",
    forceMove: false // only move from palette
  });
};

initToolbar();

Change toolbar initialization in FF.


// <<: timeout
// What will this output?
for (var i=0; i<3; i++) {
  setTimeout(function(){
    console.log(i);
  }, 1000*i);
}
console.log("Howdy!");
// :>>

// <<: new-scope
for (var i=0; i<5; ++i) {
  (function(j) {
    setTimeout(function() {
      console.log(j);
    }, j*1000);
  })(i);
}
// :>>

// <<: bind
for (var i=0; i<5; ++i) {
  setTimeout(function(j) {
    console.log(j);
  }.bind(null, i), i*1000);
}
// :>>

Add another solution to the setTimeout/loop issue


var mongoose = require('mongoose');
// var dbUrl = 'mongodb://username:password@mongodb:port/database';
// var dbUrl = process.env.MONGOHQ_URL || 'mongodb://@localhost:27017/personalblog';
var dbUrl = 'mongodb://localhost/blogmean';
// var dbUrl = process.env.MONGO_DB_URL;

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 = 'mongodb://localhost/personalblog';
// var dbUrl = process.env.MONGO_DB_URL;
var dbUrl = MONGODB_URI;

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');

Update MongoDB URI in server for heroku


jest.dontMock('../heading');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';

const Heading = require('../heading').default;

describe('Heading', () => {

	it('Contains the proper child text', () => {
		var heading = TestUtils.renderIntoDocument(
			<Heading>Test</Heading>
		);

		var headingNode = ReactDOM.findDOMNode(heading);

		expect(headingNode.textContent).toEqual('Test');
	})

})

jest.dontMock('../heading');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';

const Heading = require('../heading').default;

describe('Heading', () => {

	var heading = TestUtils.renderIntoDocument(
		<Heading>Test</Heading>
	);
	var headingNode = ReactDOM.findDOMNode(heading);

	it('Contains the proper child text', () => {
		expect(headingNode.textContent).toEqual('Test');
	});

	it('Is an H1 tag', () => {
		expect(headingNode.tagName).toEqual('H1');
	});

})

Add a second assertion to the test


'use strict';

const Promise = require('bluebird');
const pino = require('pino');
const isPlainObject = require('lodash/isPlainObject');
const wrap = require('lodash/wrap');
const forIn = require('lodash/forIn');
const Big = require('bignumber.js');

// Configure bluebird
// ----------------------------------------------------

// Make bluebird global
global.Promise = Promise;

// Improve debugging by enabling long stack traces.. it has minimal impact in production
Promise.config({ longStackTraces: true, warnings: false });

// Configure BigNumber
// ----------------------------------------------------

// Set BigNumber decimal places for a faster scoring
Big.config({ DECIMAL_PLACES: 16, ERRORS: false });

// Configure global logger (pino)
// ----------------------------------------------------

const logger = global.logger = pino();
const loggerPrototype = Object.getPrototypeOf(logger);

// Make sure that changing the level, affects all children
logger.children = {};
logger.child = (bindings) => {
    const child = loggerPrototype.child.call(logger, bindings);

    if (!bindings.module) {
        throw new Error('Expected logger.child to have a module property');
    }

    logger.children[bindings.module] = child;
    child.child = () => { throw new Error('Unable to use child() on a non-root logger'); };

    return child;
};

Object.defineProperty(logger, 'level', {
    get: loggerPrototype._getLevel,
    set: (level) => {
        loggerPrototype._setLevel.call(logger, level);
        forIn(logger.children, (child) => { child.level = level; });
    },
});

'use strict';

const Promise = require('bluebird');
const pino = require('pino');
const forIn = require('lodash/forIn');
const Big = require('bignumber.js');

// Configure bluebird
// ----------------------------------------------------

// Make bluebird global
global.Promise = Promise;

// Improve debugging by enabling long stack traces.. it has minimal impact in production
Promise.config({ longStackTraces: true, warnings: false });

// Configure BigNumber
// ----------------------------------------------------

// Set BigNumber decimal places for a faster scoring
Big.config({ DECIMAL_PLACES: 16, ERRORS: false });

// Configure global logger (pino)
// ----------------------------------------------------

const logger = global.logger = pino(process.stderr);
const loggerPrototype = Object.getPrototypeOf(logger);

// Make sure that changing the level, affects all children
logger.children = {};
logger.child = (bindings) => {
    const child = loggerPrototype.child.call(logger, bindings);

    if (!bindings.module) {
        throw new Error('Expected logger.child to have a module property');
    }

    logger.children[bindings.module] = child;
    child.child = () => { throw new Error('Unable to use child() on a non-root logger'); };

    return child;
};

Object.defineProperty(logger, 'level', {
    get: loggerPrototype._getLevel,
    set: (level) => {
        loggerPrototype._setLevel.call(logger, level);
        forIn(logger.children, (child) => { child.level = level; });
    },
});

Make pino output to stderr.


const _ = require('lodash');
const gtfs = require('gtfs');
const router = require('express').Router();

const config = require('../config');
const utils = require('../lib/utils');

/*
 * Show all agencies
 */
router.get('/', (req, res, next) => {
  gtfs.agencies((err, agencies) => {
    if (err) return next(err);

    return res.render('agencies', { agencies: _.sortBy(agencies, 'agency_name') });
  });
});

/*
 * Show all timetable pages for an agency
 */
router.get('/timetablepages', (req, res, next) => {
  const agencyKey = req.query.agency_key;

  utils.getTimetablePages(agencyKey).then((timetablePages) => {
    res.render('timetablepages', { agencyKey, timetablePages });
  }, next);
});

/*
 * Show a specific timetable page
 */
router.get('/timetablepage', (req, res, next) => {
  const agencyKey = req.query.agency_key;
  const timetablePageId = req.query.timetable_page_id;

  utils.getTimetablePage(agencyKey, timetablePageId).then((timetablePage) => {
    utils.generateHTML(agencyKey, timetablePage, config, (err, html) => {
      if (err) return next(err);
      res.send(html);
    });
  }, next);
});

module.exports = router;

const _ = require('lodash');
const gtfs = require('gtfs');
const router = require('express').Router();

const config = require('../config');
const utils = require('../lib/utils');

/*
 * Show all agencies
 */
router.get('/', (req, res, next) => {
  gtfs.agencies((err, agencies) => {
    if (err) return next(err);

    return res.render('agencies', { agencies: _.sortBy(agencies, 'agency_name') });
  });
});

/*
 * Show all timetable pages for an agency
 */
router.get('/timetablepages', (req, res, next) => {
  const agencyKey = req.query.agency_key;

  utils.getTimetablePages(agencyKey).then((timetablePages) => {
    const sortedTimetablePages = _.sortBy(timetablePages, 'route_label');
    res.render('timetablepages', { agencyKey, timetablePages: sortedTimetablePages });
  }, next);
});

/*
 * Show a specific timetable page
 */
router.get('/timetablepage', (req, res, next) => {
  const agencyKey = req.query.agency_key;
  const timetablePageId = req.query.timetable_page_id;

  utils.getTimetablePage(agencyKey, timetablePageId).then((timetablePage) => {
    utils.generateHTML(agencyKey, timetablePage, config, (err, html) => {
      if (err) return next(err);
      res.send(html);
    });
  }, next);
});

module.exports = router;

Sort timetable pages in example app


var md = window.markdownit();

function readTextFile(file) {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      if (rawFile.status === 200 || rawFile.status == 0) {
        var allText = rawFile.responseText;
        alert(allText);
      }
    }
  };
  rawFile.send(null);
}

// readTextFile("./README.md");

// fetch("./README.md")
//   .then(response => response.text())
//   .then(text => {
//     document.getElementById("markdown-container").innerHTML = text;
//   });

var md = window.markdownit();

function readTextFile(file) {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4) {
      if (rawFile.status === 200 || rawFile.status == 0) {
        var allText = rawFile.responseText;
        alert(allText);
      }
    }
  };
  rawFile.send(null);
}

// readTextFile("./README.md");

fetch("./README.md")
  .then(response => response.text())
  .then(text => {
    document.getElementById("markdown-container").innerHTML = text;
  });

Test to load README.md in homepage


/*
 * NTwitBot - event.js
 * Copyright (C) 2016 Jordan Sne
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* jshint esversion:6, node: true */

module.exports = class Event {

    constructor(twitterPkg) {
        this.twitterPkg = twitterPkg;
    }

    /*
     * Registers Twitter stream API to handlers.
     */
    registerEvents() {
    }

};

/*
 * NTwitBot - event.js
 * Copyright (C) 2016 Jordan Sne
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* jshint esversion:6, node: true */

module.exports = class Event {

    constructor(twitterPkg, actionHandler, dataHandler) {
        this.twitterPkg = twitterPkg;
        this.actionHandler = actionHandler;
        this.dataHandler = dataHandler;
    }

    /*
     * Registers Twitter stream API to handlers.
     */
    registerEvents() {
    }

};

Add required objects to class


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

function init() {
  var module = {};

  function latestRelease(project, majorVersion, done, cb) {
    var releaseUri = 'https://updates.drupal.org/release-history/';
    request(releaseUri + project + '/' + majorVersion, function (error, response, body) {
      if (!error && response.statusCode == 200 && body.length) {
        xml2js.parseString(body, function (err, result) {
          if (!err && result && result.project && result.project.releases && result.project.releases[0] && result.project.releases[0].release && result.project.releases[0].release[0] && result.project.releases[0].release[0].version) {
            cb(null, result.project.releases[0].release[0].version[0], done);
          }
          else {
            cb('Could not parse latest version of ' + project + ' for Drush makefile. Received:\n', result, done);
          }
        });
      }
      else {
        cb('Could not retrieve latest version of ' + project + ' for Drush makefile.\n', done);
      }
    });
  }

  module.latestRelease = latestRelease;

  return module;
}

module.exports = init();

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

function init() {
  var module = {};

  function latestRelease(project, majorVersion, done, cb) {
    var releaseUri = 'https://updates.drupal.org/release-history/';
    request(releaseUri + project + '/' + majorVersion, function (error, response, body) {
      if (!error && response.statusCode == 200 && body.length) {
        xml2js.parseString(body, function (err, result) {
          if (!err && result && result.project && result.project.releases && result.project.releases[0] && result.project.releases[0].release && result.project.releases[0].release[0] && result.project.releases[0].release[0].version) {
            cb(null, result.project.releases[0].release[0].version[0], done);
          }
          else {
            cb('Could not parse latest version of ' + project + ' for Drush makefile. Received:\n', result, done);
          }
        });
      }
      else {
        cb('Could not retrieve latest version of ' + project + ' for Drush makefile.\n', null, done);
      }
    });
  }

  module.latestRelease = latestRelease;

  return module;
}

module.exports = init();

Fix arguments to pass done through correctly.


define([], function() {
  var util = {};

  util.rateLimit = function(func, rate) {
    var blocked = false;
    return function() {
      if (blocked) {
        return;
      }
      blocked = true;
      setTimeout(function() {
        blocked = false;
      }, rate);
      func.apply(this, arguments);
    };
  };

  util.getClickCoords = function(e, clickElem) {
    /* Get the coordinates for a click on canvas, or null if invalid */
    var offset = {
      x : 0,
      y : 0
    };

    var el = clickElem;
    do {
      console.log(el, el.offsetLeft, el.scrollLeft, el.offsetTop, el.scrollTop);
      offset.x += el.offsetLeft - el.scrollLeft;
      offset.y += el.offsetTop - el.scrollTop;
    } while (el = el.offsetParent)

    // TODO: Verify offset and pageX/pageY in chrome/ff
    //var x = e.clientX - offset.x;
    //var y = e.clientY - offset.y;
    console.log(e);
    var x = e.pageX - offset.x;
    var y = e.pageY - offset.y;

    // Account for the border
    var canvasStyle = getComputedStyle(clickElem);
    x -= canvasStyle.getPropertyValue('border-left-width').replace(/px$/, '');
    y -= canvasStyle.getPropertyValue('border-top-width').replace(/px$/, '');
    // Invalid click handling
    if (y < 0 || y > clickElem.height || x < 0 || x > clickElem.width) {
      return null;
    }
    return { x : x, y : y };
  };

  return util;
});

define([], function() {
  var util = {};

  util.rateLimit = function(func, rate) {
    var blocked = false;
    return function() {
      if (blocked) {
        return;
      }
      blocked = true;
      setTimeout(function() {
        blocked = false;
      }, rate);
      func.apply(this, arguments);
    };
  };

  util.getClickCoords = function(e, clickElem) {
    /* Get the coordinates for a click on canvas, or null if invalid */
    var offset = {
      x : 0,
      y : 0
    };

    var el = clickElem;
    do {
      offset.x += el.offsetLeft - el.scrollLeft;
      offset.y += el.offsetTop - el.scrollTop;
      // Do not do body, because chrome adds scroll to body but FF does not
    } while ((el = el.offsetParent) && (el !== document.body))

    var x = e.pageX - offset.x;
    var y = e.pageY - offset.y;

    // Account for the border
    var canvasStyle = getComputedStyle(clickElem);
    x -= canvasStyle.getPropertyValue('border-left-width').replace(/px$/, '');
    y -= canvasStyle.getPropertyValue('border-top-width').replace(/px$/, '');
    // Invalid click handling
    if (y < 0 || y > clickElem.height || x < 0 || x > clickElem.width) {
      return null;
    }
    return { x : x, y : y };
  };

  return util;
});

Fix click coordinates in FF/Chrome


var $stack = $('.stack'),
    CLASS_LIST = 'contain-0-items contain-1-items contain-2-items contain-3-items contain-4-items';

var getPlatesFrom = function(stack){
  return $(stack).find('.plate').not('.ui-sortable-helper')
}

var updateClass = function(){
  $stack.removeClass(CLASS_LIST).each(function(){
    var count = getPlatesFrom(this).size();
    $(this).addClass('contain-' + count + '-items');
  });
}

$('.plate').mousedown(function(e){
  var $stack = $(this).parent();
  if(! $(this).is($stack.children('.plate:first')) ){
    e.stopImmediatePropagation();
  }
})

var isValidSort = false;
$stack.sortable({
  connectWith: '.stack',
  sort: updateClass,
  stop: function(e, ui){
    updateClass();
    if(!isValidSort){
      $(this).sortable('cancel');
      return;
    }
    isValidSort = false;
  },
  receive: function(e, ui){
    ui.item.prependTo($(this));
    isValidSort = true;
    var size = ui.item.data('size'),
        $platesOnNewStack = getPlatesFrom(this);
    if( $platesOnNewStack.size() > 1 &&
        $platesOnNewStack.eq(1).data('size') < size ){
      ui.sender.sortable('cancel');
    }
  },
  placeholder: 'no-space'
});

$stack.disableSelection();

var $stack = $('.stack'),
    CLASS_LIST = 'contain-0-items contain-1-items contain-2-items contain-3-items contain-4-items';

var getPlatesFrom = function(stack){
  return $(stack).find('.plate').not('.ui-sortable-helper')
}

var updateClass = function(){
  $stack.removeClass(CLASS_LIST).each(function(){
    var count = getPlatesFrom(this).size();
    $(this).addClass('contain-' + count + '-items');
  });
}

$stack.disableSelection();

$('.plate').mousedown(function(e){
  var $stack = $(this).parent();
  if(! $(this).is($stack.children('.plate:first')) ){
    e.stopPropagation();
  }
})

var isValidSort = false;
$stack.sortable({
  connectWith: '.stack',
  sort: updateClass,
  stop: function(e, ui){
    updateClass();
    if(!isValidSort){
      $(this).sortable('cancel');
      return;
    }
    isValidSort = false;
  },
  receive: function(e, ui){
    ui.item.prependTo($(this));
    isValidSort = true;
    var size = ui.item.data('size'),
        $platesOnNewStack = getPlatesFrom(this);
    if( $platesOnNewStack.size() > 1 &&
        $platesOnNewStack.eq(1).data('size') < size ){
      ui.sender.sortable('cancel');
    }
  },
  placeholder: 'no-space'
});

Use stopPropagation instead of stopImmediatePropagation.


/* Copyright 2015 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

'use strict';

var EventEmitter = require('events');
var assert = require('assert');

var ModuleDef = require('server/modules/module_def');

class ModuleLibrary extends EventEmitter {
  constructor() {
    super();

    // Map of name -> ModuleDef
    this.modules = {};
  }
  register(def) {
    assert(!(def.name in this.modules), 'Def ' + def.name + ' already exists!');
    this.modules[def.name] = def;
    // We can safely use 'on' rather than 'once' here, because neither the
    // moduledefs nor this library are ever destroyed.
    def.on('reloaded', () => {
      this.emit('reloaded', def);
    });
  }
}

let library = new ModuleLibrary;

// Engine modules.
library.register(new ModuleDef('_faded_out', 'demo_modules/solid/solid.js', '', '', {
  color: 'black'
}));

module.exports = library;

/* Copyright 2015 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

'use strict';

var EventEmitter = require('events');
var assert = require('assert');

class ModuleLibrary extends EventEmitter {
  constructor() {
    super();

    // Map of name -> ModuleDef
    this.modules = {};
  }
  register(def) {
    assert(!(def.name in this.modules), 'Def ' + def.name + ' already exists!');
    this.modules[def.name] = def;
    // We can safely use 'on' rather than 'once' here, because neither the
    // moduledefs nor this library are ever destroyed.
    def.on('reloaded', () => {
      this.emit('reloaded', def);
    });

    if (def.name == 'solid') {
      this.register(def.extend('_faded_out', '', '', {
        color: 'black'
      }));
    }
  }
}

module.exports = new ModuleLibrary;

Change way we init fading.


//
// Resource Cache
// Caches API resources by ETag
//

import * as bb from 'backbone';

var cache = {};

// Configure jQuery to handle resources that haven't been
// modified since the last request
bb.$.ajaxSetup({
  ifModified: true
});

// Override Backbone.ajax to save & load cached resources
bb.ajax = function(options, ...args) {
  var success = options.success;
  options.success = function(resp, textStatus, jqXHR) {
    var ETag = jqXHR.getResponseHeader('ETag');
    if (textStatus === 'notmodified') {
      resp = cache[jqXHR.getResponseHeader('ETag')];
    } else if (ETag) {
      cache[ETag] = resp;
    }
    if (success) {
      success(resp, textStatus, jqXHR);
    }
  };
  args.unshift(options);
  return bb.$.ajax.apply(bb.$, args);
};

//
// Resource Cache
// Caches API resources by ETag
//

import * as bb from 'backbone';

var cache = {};

// Configure jQuery to handle resources that haven't been
// modified since the last request
bb.$.ajaxSetup({
  ifModified: true
});

// Override Backbone.ajax to save & load cached resources
bb.ajax = function(options, ...args) {
  var success = options.success;
  options.success = function(resp, textStatus, jqXHR) {
    var ETag = jqXHR.getResponseHeader('ETag');
    if (textStatus === 'notmodified') {
      resp = cache[ETag];
    } else if (ETag) {
      cache[ETag] = resp;
    }
    if (success) {
      success(resp, textStatus, jqXHR);
    }
  };
  args.unshift(options);
  return bb.$.ajax.apply(bb.$, args);
};

Remove duplicate fetching of ETag header.


"use strict";

var use = require("alamid-plugin/use.js");

var path = require("path"),
    argv = require("minimist")(process.argv.slice(2));

function dynamicConfig(basePath, fileName) {

    var env = dynamicConfig.getEnv(),
        filePath = dynamicConfig.getFilePath(basePath, env, fileName),
        config;

    if (dynamicConfig.options.log) {
        console.log("Loading configuration '" + fileName + "'  from path '" + filePath + "'");
    }

    config = dynamicConfig.loadConfig(filePath);

    dynamicConfig.last = filePath;

    return config;
}

dynamicConfig.getEnv = function() {
    return argv.env || argv.ENV || process.env.env || dynamicConfig.options.defaultEnv;
};

dynamicConfig.getFilePath = function(basePath, env, fileName) {
    return path.join(basePath, env, fileName);
};

dynamicConfig.loadConfig = function(filePath) {
    var config;

    try {
        config = require(filePath);
    }
    catch (err) {

        //handle only not found errors, throw the rest
        if (err.code === "MODULE_NOT_FOUND") {
            throw new Error("Config not found at '" + filePath + "'");
        }

        throw err;
    }

    return config;
};

dynamicConfig.options = {
    defaultEnv: "develop",
    log: false
};

dynamicConfig.use = use;

module.exports = dynamicConfig;

"use strict";

var use = require("alamid-plugin/use.js");

var path = require("path"),
    argv = require("minimist")(process.argv.slice(2));

function dynamicConfig(basePath, fileName) {

    var env = dynamicConfig.getEnv(),
        filePath = dynamicConfig.getFilePath(basePath, env, fileName),
        config;

    if (dynamicConfig.options.log) {
        console.log("Loading configuration '" + fileName + "'  from path '" + filePath + "'");
    }

    config = dynamicConfig.loadConfig(filePath);

    dynamicConfig.resolvedConfigPath = filePath;

    return config;
}

dynamicConfig.getEnv = function() {
    return argv.env || argv.ENV || process.env.env || dynamicConfig.options.defaultEnv;
};

dynamicConfig.getFilePath = function(basePath, env, fileName) {
    return path.join(basePath, env, fileName);
};

dynamicConfig.loadConfig = function(filePath) {
    var config;

    try {
        config = require(filePath);
    }
    catch (err) {

        //handle only not found errors, throw the rest
        if (err.code === "MODULE_NOT_FOUND") {
            throw new Error("Config not found at '" + filePath + "'");
        }

        throw err;
    }

    return config;
};

dynamicConfig.options = {
    defaultEnv: "develop",
    log: false
};

dynamicConfig.use = use;

module.exports = dynamicConfig;

Rename property from "last" to "resolvedConfigPath"


/*
Example:

widgets.mixins.rejectTokens([ 'comment' ])
*/
var _ = require('lodash');

module.exports = function(types) {
    return {
        filterMatch: function(range, props) {
            var token = this.editor.getTokenAt(range.from);

            if (!token || !token.type) {
                return true;
            }

            return !_.some(token.type.split(' '), function(type){
                return _.contains(types, token.type);
            });
        }
    };
};

/*
Example:

widgets.mixins.rejectTokens([ 'comment' ])
*/
var _ = require('lodash');

module.exports = function(types) {
    return {
        filterMatch: function(range, props) {
            var token = this.editor.getTokenAt({ ch: range.from.ch + 1, line: range.from.line });

            if (!token || !token.type) {
                return true;
            }

            return _.every(token.type.split(' '), function(type){
                return !_.contains(types, type);
            });
        }
    };
};

Improve reliability of rejectTokens mixin