/**
 * Has Vowels
 *
 * hasVowel tests if the String calling the function has a vowels
 *
 * @param {void}
 * @return {Boolean} returns true or false indicating if the string
 * has a vowel or not
 */
String.prototype.hasVowels = function() {
    var inputString = this;
    return /[aeiou]/gi.test(inputString);
};

/**
 * To Upper
 *
 * toUpper converts its calling string to all uppercase characters
 *
 * @param {void}
 * @return {String} returns an upperCase version of the calling string
 */
String.prototype.toUpper = function() {
    // the 'this' keyword represents the string calling the function
    return this.replace(/[a-z]/g, function(item, position, string) {
        return String.fromCharCode(string.charCodeAt(position)-32);
    });
};

String.prototype.toLower = function() {
    return "";
};

/**
 * Has Vowels
 *
 * hasVowel tests if the String calling the function has a vowels
 *
 * @param {void}
 * @return {Boolean} returns true or false indicating if the string
 * has a vowel or not
 */
String.prototype.hasVowels = function() {
    var inputString = this;
    return /[aeiou]/gi.test(inputString);
};

/**
 * To Upper
 *
 * toUpper converts its calling string to all uppercase characters
 *
 * @param {void}
 * @return {String} returns an upperCase version of the calling string
 */
String.prototype.toUpper = function() {
    // the 'this' keyword represents the string calling the function
    return this.replace(/[a-z]/g, function(item, position, string) {
        return String.fromCharCode(string.charCodeAt(position)-32);
    });
};

String.prototype.toLower = function() {
    // the 'this' keyword represents the string calling the function
    return this.replace(/[A-Z]/g, function(item, position, string) {
        return String.fromCharCode(string.charCodeAt(position)+32);
    });
};

Modify toLower() to pass returned result test


const { Spinner } = require('cli-spinner');
const inquirer = require('inquirer');
const log = require('../lib/log');

Spinner.setDefaultSpinnerString(Spinner.spinners[7]);

module.exports.prompt = async (question) => {
	if (!global.isInteractive){
		throw new Error('Prompts are not allowed in non-interactive mode');
	}
	return inquirer.prompt(question);
};

module.exports.spin = async (promise, str) => {
	let spinner;

	if (!global.isInteractive){
		return promise;
	}

	if (global.verboseLevel > 1){
		log.debug(str);
		return promise;
	}

	try {
		spinner = new Spinner(str);
		spinner.start();
		return promise;
	} finally {
		spinner.stop(true);
	}
};

const { Spinner } = require('cli-spinner');
const inquirer = require('inquirer');
const log = require('../lib/log');

Spinner.setDefaultSpinnerString(Spinner.spinners[7]);

module.exports.prompt = async (question) => {
	if (!global.isInteractive){
		throw new Error('Prompts are not allowed in non-interactive mode');
	}
	return inquirer.prompt(question);
};

module.exports.spin = async (promise, str) => {
	let spinner;

	if (!global.isInteractive){
		return promise;
	}

	if (global.verboseLevel > 1){
		log.debug(str);
		return promise;
	}

	spinner = new Spinner(str);
	spinner.start();
	return promise.finally(() => spinner.stop(true));
};

Fix UI spinner stopping immediately

Fix UI spinner stopping immediately


angular.module('progressButtonDemo', ['progressButton'])
	.controller('ProgressButtonsCtrl', function($scope) {
		$scope.generate = function(button) {
			button.progressTimed(3, function() {
				$scope.generate = function() {
					alert('Showing how a callback works!');
				}
			})
		}
	})
	.controller('ProgressControlCtrl', function($scope) {
		$scope.controlButton = {}

		$scope.increment = function(value) {
			$scope.controlButton.progressIncrement(value)
		}

		$scope.setTo = function(value) {
			$scope.controlButton.progressSet(value)
		}

		$scope.finish = function() {
			$scope.controlButton.progressFinish()
		}
	})

angular.module('progressButtonDemo', ['progressButton'])
	.controller('ProgressButtonsCtrl', function($scope) {
		$scope.generate = function(button) {
			button.progressTimed(3, function() {
				$scope.generate = function() {
					alert('Showing how a callback works!');
				}
			})
		}
	})
	.controller('ProgressControlCtrl', function($scope, $timeout) {
		$scope.controlButton = {}

		$timeout(function() {
			$scope.increment = function(value) {
				$scope.controlButton.progressIncrement(value)
			}

			$scope.setTo = function(value) {
				$scope.controlButton.progressSet(value)
			}

			$scope.finish = function() {
				$scope.controlButton.progressFinish()
			}
		})
	})

Use $timeout as explained in readme for the progress control button


//jshint esversion:6
const api = require('./api/api');
const cod = "";

api.getInfo(cod)
  .then(function (res) {
    console.log(res);
  }).catch(function (err) {
    console.error(err);
  });

//jshint esversion:6
const fs = require('fs'),
  csv = require('fast-csv');

const api = require('./api/api');
let codes = [];
let stream = fs.createReadStream("clienti.csv");

let csvStream = csv
  .parse()
  .on("data", function (data) {
    codes.push(data.pop());
  }).on("end", function () {
    codes.shift();
    getLocations(codes);
  });
stream.pipe(csvStream);

const getLocations = function (codes) {
  const locations = codes.map(function (cod) {
    return api.getInfo(cod)
      .then(function (res) {
        return res;
      }).catch(function (err) {
        console.error(err);
      });
  });

  Promise.all(locations).then(function (values) {
    console.log(values);
  });
};

Add in some basic csv parsing and info retrieval


const assign = require('object-assign')
const validate = require('../validators')

function DatasetsClient(client) {
  this.request = client.request.bind(client)
}

assign(DatasetsClient.prototype, {
  create(name, options) {
    return this._modify('PUT', name, options)
  },

  delete(name) {
    return this._modify('DELETE', name)
  },

  list() {
    return this.request({uri: '/datasets'})
  },

  _modify(method, name, body) {
    validate.dataset(name)
    return this.request({method, uri: `/datasets/${name}`, body})
  }
})

module.exports = DatasetsClient

const assign = require('object-assign')
const validate = require('../validators')

function DatasetsClient(client) {
  this.request = client.request.bind(client)
}

assign(DatasetsClient.prototype, {
  create(name, options) {
    return this._modify('PUT', name, options)
  },

  edit(name, options) {
    return this._modify('PATCH', name, options)
  },

  delete(name) {
    return this._modify('DELETE', name)
  },

  list() {
    return this.request({uri: '/datasets'})
  },

  _modify(method, name, body) {
    validate.dataset(name)
    return this.request({method, uri: `/datasets/${name}`, body})
  }
})

module.exports = DatasetsClient

Add method to alter dataset properties

[client] Add method to alter dataset properties


const winston = require('winston');

let logger;

winston.level = process.env.NVIM_NODE_LOG_LEVEL || 'debug';

if (process.env.NVIM_NODE_LOG_FILE) {
  logger = new winston.Logger({
    transports: [
      new winston.transports.File({
        filename: process.env.NVIM_NODE_LOG_FILE,
        level: winston.level,
        json: false,
      }),
    ],
  });
} else {
  // Remove Console transport
  winston.remove(winston.transports.Console);
  logger = winston;
}

module.exports = logger;
module.exports.default = module.exports;

const winston = require('winston');

let logger;

winston.level = process.env.NVIM_NODE_LOG_LEVEL || 'debug';

if (process.env.NVIM_NODE_LOG_FILE) {
  logger = new winston.Logger({
    transports: [
      new winston.transports.File({
        filename: process.env.NVIM_NODE_LOG_FILE,
        level: winston.level,
        json: false,
      }),
    ],
  });
} else {
  if (!process.env.ALLOW_CONSOLE) {
    // Remove Console transport
    winston.remove(winston.transports.Console);
  }
  logger = winston;
}

module.exports = logger;
module.exports.default = module.exports;

Add env var to allow printing to console


Hummingbird.QuickUpdateItemController = Ember.ObjectController.extend({
  loading: false,
  isComplete: Hummingbird.computed.propertyEqual('episodesWatched', "anime.episodeCount"),

  percentComplete: function() {
    var episodesWatched = this.get('episodesWatched'),
        episodeCount = this.get('anime.episodeCount');

    if (episodeCount) {
      return Math.ceil(100 * episodesWatched / episodeCount);
    } else {
      return "?";
    }
  }.property('episodesWatched', 'anime.episodeCount'),

  nextEpisodeNumber: function() {
    return this.get('episodesWatched') + 1;
  }.property('episodesWatched'),

  actions: {
    markViewed: function() {
      var libraryEntry = this.get('model'),
          self = this;
      libraryEntry.set('episodesWatched', this.get('nextEpisodeNumber'));
      if (this.get('isComplete')) {
        libraryEntry.set('status', "Completed");
      } else {
        libraryEntry.set('status', "Plan to Watch");
      }
      this.set('loading', true);
      libraryEntry.save().then(function() {
        self.set('loading', false);
      });
    }
  }
});

Hummingbird.QuickUpdateItemController = Ember.ObjectController.extend({
  loading: false,
  isComplete: Hummingbird.computed.propertyEqual('episodesWatched', "anime.episodeCount"),

  percentComplete: function() {
    var episodesWatched = this.get('episodesWatched'),
        episodeCount = this.get('anime.episodeCount');

    if (episodeCount) {
      return Math.ceil(100 * episodesWatched / episodeCount);
    } else {
      return "?";
    }
  }.property('episodesWatched', 'anime.episodeCount'),

  nextEpisodeNumber: function() {
    return this.get('episodesWatched') + 1;
  }.property('episodesWatched'),

  actions: {
    markViewed: function() {
      var libraryEntry = this.get('model'),
          self = this;
      libraryEntry.set('episodesWatched', this.get('nextEpisodeNumber'));
      if (this.get('isComplete')) {
        libraryEntry.set('status', "Completed");
      } else {
        libraryEntry.set('status', "Currently Watching");
      }
      this.set('loading', true);
      libraryEntry.save().then(function() {
        self.set('loading', false);
      });
    }
  }
});

Fix status bug with the new quick update.


var chai   = require('chai'),
    sinon  = require('sinon'),
    rewire = require('rewire');

require('sinon-as-promised');

var expect = chai.expect;
var assert = chai.assert;

describe("Scan", function() {
    var detector,
        loggerMock,
        sonumiLoggerMock,
        networkAdapterMock;
    var deviceDetector = rewire("../lib/detector");

    beforeEach(function() {
        loggerMock = sinon.stub();
        loggerMock.log = sinon.stub();
        loggerMock.addLogFile = sinon.stub();
        sonumiLoggerMock = sinon.stub();
        sonumiLoggerMock.init = sinon.stub().returns(loggerMock);
        networkAdapterMock = sinon.stub();
        networkAdapterMock.scan = sinon.spy();

        configMock = {
            "logging": {
                "logDir": "/tmp/"
            }
        };

        deviceDetector.__set__({
            config: configMock,
            logger: loggerMock,
            sonumiLogger: sonumiLoggerMock
        });

        detector = new deviceDetector({ network: networkAdapterMock });
    });

    it('should retrieve a list of connected devices from the network adapter', function() {
        detector.scan();

        assert(networkAdapterMock.scan.calledOnce);
    });
});

describe("LAN adapter", function() {
    // test that the lan adapter scans the network
});

var chai   = require('chai'),
    sinon  = require('sinon'),
    rewire = require('rewire');

var expect = chai.expect;
var assert = chai.assert;

describe("It scans for devices", function() {
    var detector,
        loggerMock,
        sonumiLoggerMock,
        networkAdapterMock;
    var deviceDetector = rewire("../lib/detector");

    beforeEach(function() {
        loggerMock = sinon.stub();
        loggerMock.log = sinon.stub();
        loggerMock.addLogFile = sinon.stub();
        sonumiLoggerMock = sinon.stub();
        sonumiLoggerMock.init = sinon.stub().returns(loggerMock);
        networkAdapterMock = sinon.stub();
        networkAdapterMock.scan = sinon.spy();

        configMock = {
            "logging": {
                "logDir": "/tmp/"
            }
        };

        deviceDetector.__set__({
            config: configMock,
            logger: loggerMock,
            sonumiLogger: sonumiLoggerMock
        });

        detector = new deviceDetector({ network: networkAdapterMock });
    });

    it('should retrieve a list of connected devices from the network adapter', function() {
        detector.scan();

        assert(networkAdapterMock.scan.calledOnce);
    });
});

Clean up unused packages in tests

Clean up unused packages in tests


const { NSEventMonitor, NSEventMask } = require('../');
const assert = require('assert');
const app = require('./support/App');
const mouse = require('./support/Mouse');

describe('NSEventMonitor', () => {
  let monitor;

  beforeEach(() => {
    monitor = new NSEventMonitor();
  });

  afterEach(() => {
    monitor.stop();
  })

  it('should receive click', (done) => {
    monitor.start((NSEventMask.leftMouseDown | NSEventMask.rightMouseDown), () => done());
    mouse.clickAt(0, 20000);
  });

  it('should throw exception when wrong arguments passed', () => {
    assert.throws(() => monitor.start());
    assert.throws(() => monitor.start("hello", "world"));
  });

});

const addon = require('../');
const NSEventMonitor = addon.NSEventMonitor;
const NSEventMask = addon.NSEventMask;
const assert = require('assert');
const app = require('./support/App');
const mouse = require('./support/Mouse');

describe('NSEventMonitor', () => {
  let monitor;

  beforeEach(() => {
    monitor = new NSEventMonitor();
  });

  afterEach(() => {
    monitor.stop();
  })

  it('should receive click', (done) => {
    monitor.start((NSEventMask.leftMouseDown | NSEventMask.rightMouseDown), () => done());
    mouse.clickAt(0, 20000);
  });

  it('should throw exception when wrong arguments passed', () => {
    assert.throws(() => monitor.start());
    assert.throws(() => monitor.start("hello", "world"));
  });

});

Fix tests to run on node.js 5

Fix tests to run on node.js 5


colette.iframeResizer = (function() {
    'use strict';

    var pub = {},
        cfg = {
            selector: '#iframeContent',
            el: null,
            delay: 0,
            resizeInternal: false
        };

    pub.init = function(args)
    {
        cfg.delay = args.delay || cfg.delay;
        cfg.el = document.querySelector(args.selector || cfg.selector);

        window.addEventListener('message', function(e) {
            // resizeComplete
            if ('resizeComplete' === e.data) {
                iframeResizeComplete();
            }
        });

        window.addEventListener('load', function(e) {
            height();
        });

        window.addEventListener('resize', function(e) {
            height();
        });

    };

    var iframeResizeComplete = function()
    {
        setTimeout(function() {
            cfg.resizeInternal = false;
        }, 500);
    };

    var height = function()
    {
        if (!cfg.resizeInternal) {
            setTimeout(function() {
                sendHeight();
            }, cfg.delay);
        }
    };

    var sendHeight = function()
    {
        window.top.postMessage({type: 'doResize', height: cfg.el.offsetHeight}, '*');
        cfg.resizeInternal = true;
    };

    return pub;
})();

colette.iframeResizer = (function() {
    'use strict';

    var pub = {},
        cfg = {
            selector: '#iframeContent',
            el: null,
            delay: 0,
            resizeInternal: false,
            iframeId: 'iframeId'
        };

    pub.init = function(args)
    {
        cfg.delay = args.delay || cfg.delay;
        cfg.iframeId = args.iframeId || cfg.iframeId;
        cfg.el = document.querySelector(args.selector || cfg.selector);

        window.addEventListener('message', function(e) {
            // resizeComplete
            if ('resizeComplete' === e.data) {
                iframeResizeComplete();
            }
        });

        window.addEventListener('load', function(e) {
            height();
        });

        window.addEventListener('resize', function(e) {
            height();
        });

    };

    var iframeResizeComplete = function()
    {
        setTimeout(function() {
            cfg.resizeInternal = false;
        }, 500);
    };

    var height = function()
    {
        if (!cfg.resizeInternal) {
            setTimeout(function() {
                sendHeight();
            }, cfg.delay);
        }
    };

    var sendHeight = function()
    {
        window.top.postMessage({type: 'doResize', height: cfg.el.offsetHeight, iframeId: cfg.iframeId}, '*');
        cfg.resizeInternal = true;
    };

    return pub;
})();

Fix resizer for election's embeds

Fix resizer for election's embeds


var keystone = require('keystone'),
	Types = keystone.Field.Types;

// Create model. Additional options allow menu name to be used what auto-generating URLs
var RecommendedFamilyConstellation = new keystone.List('Recommended Family Constellations', {
	autokey: { path: 'key', from: 'constellationType', unique: true },
	map: { name: 'constellationType' }
});

// Create fields
RecommendedFamilyConstellation.add({
	constellationType: { type: String, label: 'Constellation Type', required: true, index: true, initial: true }
});

// Define default columns in the admin interface and register the model
RecommendedFamilyConstellation.defaultColumns = 'constellationType';
RecommendedFamilyConstellation.register();

var keystone = require('keystone'),
	Types = keystone.Field.Types;

// Create model. Additional options allow menu name to be used what auto-generating URLs
var RecommendedFamilyConstellation = new keystone.List('Recommended Family Constellation', {
	autokey: { path: 'key', from: 'familyConstellation', unique: true },
	map: { name: 'familyConstellation' }
});

// Create fields
RecommendedFamilyConstellation.add({
	familyConstellation: { type: String, label: 'Family Constellation', required: true, index: true, initial: true }
});

// Define default columns in the admin interface and register the model
RecommendedFamilyConstellation.defaultColumns = 'familyConstellation';
RecommendedFamilyConstellation.register();

Add Reference list model for Recommended Family Constellations.


var juice = require('juice');

var WebsiteGenerator = require('../website');
var JSONUtils = require('../../json');
var Templating = require('../../templating');
var Promise = require('../../utils/promise');

/**
    Generate PDF header/footer templates

    @param {Output} output
    @param {String} type
    @return {String}
*/
function getPDFTemplate(output, type) {
    var filePath = 'pdf_' + type + '.html';
    var outputRoot = output.getRoot();
    var engine = WebsiteGenerator.createTemplateEngine(output, filePath);

    // Generate context
    var context = JSONUtils.encodeOutput(output);
    context.page = {
        num: '_PAGENUM_',
        title: '_TITLE_',
        section: '_SECTION_'
    };

    // Render the theme
    return Templating.renderFile(engine, 'ebook/' + filePath, context)

    // Inline css and assets
    .then(function(tplOut) {
        return Promise.nfcall(juice.juiceResources, tplOut.getContent(), {
            webResources: {
                relativeTo: outputRoot
            }
        });
    });
}

module.exports = getPDFTemplate;

var juice = require('juice');

var WebsiteGenerator = require('../website');
var JSONUtils = require('../../json');
var Templating = require('../../templating');
var Promise = require('../../utils/promise');

/**
    Generate PDF header/footer templates

    @param {Output} output
    @param {String} type
    @return {String}
*/
function getPDFTemplate(output, type) {
    var filePath = 'pdf_' + type + '.html';
    var outputRoot = output.getRoot();
    var engine = WebsiteGenerator.createTemplateEngine(output, filePath);

    // Generate context
    var context = JSONUtils.encodeOutput(output);
    context.page = {
        num: '_PAGENUM_',
        title: '_SECTION_'
    };

    // Render the theme
    return Templating.renderFile(engine, 'ebook/' + filePath, context)

    // Inline css and assets
    .then(function(tplOut) {
        return Promise.nfcall(juice.juiceResources, tplOut.getContent(), {
            webResources: {
                relativeTo: outputRoot
            }
        });
    });
}

module.exports = getPDFTemplate;

Fix page's title in pdf header/footer

Fix page's title in pdf header/footer


(function(app) {
  'use strict';

  var GeoNamesLocations = function() {};

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = GeoNamesLocations;
  } else {
    app.GeoNamesLocations = GeoNamesLocations;
  }
})(this.app || (this.app = {}));

(function(app) {
  'use strict';

  var Events = app.Events || require('../base/events.js');

  var GeoNamesLocations = function() {
    this._events = new Events();
  };

  GeoNamesLocations.prototype.on = function() {
    return Events.prototype.on.apply(this._events, arguments);
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = GeoNamesLocations;
  } else {
    app.GeoNamesLocations = GeoNamesLocations;
  }
})(this.app || (this.app = {}));

Use event module for model object of GeoNames locations


(function () {

    if ($('body#home-page').length === 0) return; // Check if it is home page

    var Flickity = require('flickity');

    var fkt = new Flickity('#home-carousel', {
        wrapAround: true,
        autoPlay: true,
    });

})();

(function () {

    if ($('body#home-page').length === 0) return; // Check if it is home page

    var Flickity = require('flickity');

    var fkt = new Flickity('#home-carousel', {
        wrapAround: true,
        autoPlay: 10000,
    });

})();

Increase some slider auto play delay time


angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead'])

    .directive('entityPicker', function() {

        var tpl =
            '<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingLocations" class="form-control">' +
            '<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>';

        return {
            restrict: 'E',
            transclude: true,
            scope: {
                url: '=',
                subject: '='
            },
            template: tpl,
            controller: function($scope, $http, $attrs) {

                // Get the object by search term
                $scope.getObject = function(term) {
                    return $http.get($scope.url, {
                        params: {
                            term: term
                        }
                    }).then(function(response){
                        return response.data.map(function(item){
                            return item;
                        });
                    });
                };

                // Select the object
                $scope.onSelect = function(item, model, label) {
                    if (angular.isUndefined($scope.subject.right.value)) {
                        $scope.subject.right.value = [];
                    }

                    var item = {id:item.id, name:item.name};

                    if ($scope.subject.right.value.indexOf(item) == -1) {
                        $scope.subject.right.value.push(item);
                    }

                    $scope.search = null;
                };
            }
        };
    })
;

angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead'])

    .directive('entityPicker', function() {

        var tpl =
            '<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingLocations" class="form-control">' +
            '<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>';

        return {
            restrict: 'E',
            transclude: true,
            scope: {
                subject: '=',
                configuration: '='
            },
            template: tpl,
            controller: function($scope, $http, $attrs) {

                // Get the object by search term
                $scope.getObject = function(term) {
                    return $http.get(Routing.generate($scope.configuration.searchRoute(), [], true), {
                        params: {
                            term: term
                        }
                    }).then(function(response){
                        return response.data.map(function(item){
                            return item;
                        });
                    });
                };

                // Select the object
                $scope.onSelect = function(item, model, label) {
                    if (angular.isUndefined($scope.subject.right.value)) {
                        $scope.subject.right.value = [];
                    }

                    if ($scope.subject.right.value.indexOf(item.id) == -1) {
                        $scope.subject.right.value.push(item.id);
                        $scope.configuration.add(item);
                    }

                    $scope.search = null;
                };
            }
        };
    })
;

Use the new RulesEngine configuration service for vars


/*global require*/
// require in the complete Cesium object and reassign it globally.
// This is meant for use with the Almond loader.
require(['Cesium'], function(Cesium) {
    "use strict";
    /*global self*/

    Cesium.defaultValue(window, self).Cesium = Cesium;
}, undefined, true);

/*global require*/
// require in the complete Cesium object and reassign it globally.
// This is meant for use with the Almond loader.
require(['Cesium'], function(Cesium) {
    "use strict";
    /*global self*/
    var scope = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {};

    scope.Cesium = Cesium;
}, undefined, true);

Fix logic for assigning to self if window doesn't exist.


const templateUrl = require('~components/layout/side-nav.partial.html');

function atSideNavLink (scope, element, attrs, ctrl) {
    scope.layoutVm = ctrl;

    document.on('click', (e) => {
        if ($(e.target).parents('.at-Layout-side').length === 0) {
            scope.$emit('clickOutsideSideNav');
        }
    });
}

function AtSideNavController ($scope, $window) {
    let vm = this || {};
    const breakpoint = 700;

    vm.isExpanded = false;

    vm.toggleExpansion = () => {
        vm.isExpanded = !vm.isExpanded;
    };

    $scope.$watch('layoutVm.currentState', () => {
        if ($window.innerWidth <= breakpoint) {
            vm.isExpanded = false;
        }
    });

    $scope.$on('clickOutsideSideNav', () => {
        if ($window.innerWidth <= breakpoint) {
            vm.isExpanded = false;
        }
    });
}

AtSideNavController.$inject = ['$scope', '$window'];

function atSideNav () {
    return {
        restrict: 'E',
        replace: true,
        require: '^^atLayout',
        controller: AtSideNavController,
        controllerAs: 'vm',
        link: atSideNavLink,
        transclude: true,
        templateUrl,
        scope: {
        }
    };
}

export default atSideNav;

const templateUrl = require('~components/layout/side-nav.partial.html');

function atSideNavLink (scope, element, attrs, ctrl) {
    scope.layoutVm = ctrl;

    document.on('click', (e) => {
        if ($(e.target).parents('.at-Layout-side').length === 0) {
            scope.$emit('clickOutsideSideNav');
        }
    });
}

function AtSideNavController ($scope, $window) {
    const vm = this || {};
    const breakpoint = 700;

    vm.isExpanded = false;

    vm.toggleExpansion = () => {
        vm.isExpanded = !vm.isExpanded;
    };

    $scope.$watch('layoutVm.currentState', () => {
        if ($window.innerWidth <= breakpoint) {
            vm.isExpanded = false;
        }
    });

    $scope.$on('clickOutsideSideNav', () => {
        if ($window.innerWidth <= breakpoint) {
            vm.isExpanded = false;
        }
    });
}

AtSideNavController.$inject = ['$scope', '$window'];

function atSideNav () {
    return {
        restrict: 'E',
        replace: true,
        require: '^^atLayout',
        controller: AtSideNavController,
        controllerAs: 'vm',
        link: atSideNavLink,
        transclude: true,
        templateUrl,
        scope: {
        }
    };
}

export default atSideNav;

Use const instead of let on never reassigned var

Signed-off-by: Julen Landa Alustiza <9f547bdd49d2612aea2f3e70f57e0c5f51269763@zokormazo.info>


function square(x) {
  return x * x;
}

function toggleRed() {
  $('#second-div').toggleClass('red');
}

function onGotData(data) {
  var table = $('#my-table-body');
  data.rows.forEach(function(number) {
    table.append("
" + number + "	" + square(number) + "
")
  })
}

$.getJSON('https://robbie-c.github.io/cfg-ic-6/ajax/data.json', onGotData);

loadDataAndPopulateTable();

console.log('You opened the console! Try writing "2 + 2" and hitting enter!');

function square(x) {
  return x * x;
}

function toggleRed() {
  $('#second-div').toggleClass('red');
}

function onGotData(data) {
  var table = $('#my-table-body');
  data.rows.forEach(function(number) {
    table.append("
" + number + "	" + square(number) + "
")
  })
}

$.getJSON('https://robbie-c.github.io/cfg-ic-6/ajax/data.json', onGotData);

console.log('You opened the console! Try writing "2 + 2" and hitting enter!');

Remove call to non-existent function

Remove call to non-existent function


(function(i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function() {
        (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();
    a = s.createElement(o),
        m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-74822546-3', 'auto');
ga('send', 'pageview');

var userId = $('div.hidden-user-information').data('user-id');
if (userId) {
  ga('set', 'userId', userId);
}

Add user ID tracking to Google Analytics


import React from 'react'
import Layout from '@theme/Layout'
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'
import 'url-search-params-polyfill';
import styles from './styles.module.css'
import errorCodes from '../../../errors.json'

function Errors() {
  const context = useDocusaurusContext()
  const { siteConfig = {} } = context
  const errorCode = new URLSearchParams(window.location.search).get("code");
  const error = errorCodes[errorCode];

  return (
    <Layout
      title={`${siteConfig.title} - A predictable state container for JavaScript apps.`}
      description="A predictable state container for JavaScript apps."
    >

Production Error Codes

          When Redux is built and running in production, error text is replaced
          by indexed error codes to save on bundle size. These errors will provide a link to this page with more information about the error below.

        {error &&
        <React.Fragment>

The full text of the error you just encountered is:

            {error}

        </React.Fragment>
        }

    </Layout>
  )
}

export default Errors

import React from 'react'
import Layout from '@theme/Layout'
import {useLocation} from '@docusaurus/router';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext'
import styles from './styles.module.css'
import errorCodes from '../../../errors.json'
import 'url-search-params-polyfill';

function Errors() {
  const location = useLocation();
  const context = useDocusaurusContext()
  const { siteConfig = {} } = context
  const errorCode = new URLSearchParams(location.search).get("code");
  const error = errorCodes[errorCode];

  return (
    <Layout
      title={`${siteConfig.title} - A predictable state container for JavaScript apps.`}
      description="A predictable state container for JavaScript apps."
    >

Production Error Codes

          When Redux is built and running in production, error text is replaced
          by indexed error codes to save on bundle size. These errors will provide a link to this page with more information about the error below.

        {error &&
        <React.Fragment>

The full text of the error you just encountered is:

            {error}

        </React.Fragment>
        }

    </Layout>
  )
}

export default Errors

Fix: Resolve build issue caused by using window object server side.


var num;
var result;

var getIntegerDecimalPart = function(num) {
   var integer = Math.floor(num);
   var decimal = (num - integer).toFixed(5); // temporarily, 5 digits to appear after the decimal point
   var str_decimal = ('0.00000' != decimal) ? decimal.slice(1) : '';
   return {integer: integer.toString(), decimal: str_decimal};
};

var getCommaDelimitedIntegerPart = function(str_integer) {
  var out = '';
  while (str_integer.length > 0) {
    var three_digits = str_integer.slice(-3); // get 3 digits
    out = three_digits + out;

    str_integer = str_integer.slice(0, -3);	// remove 3 digits
    if (str_integer.length >= 1) {
      out = ',' + out;
    }
  }
  return out;
}

// check args
if (process.argv.length < 3) { // sample value
  num = Math.floor(Math.random() * 1000000000) + 1;
} else {
  num = process.argv[2];
}
console.log('input: ' + num);

var obj_num = getIntegerDecimalPart(Number(num));
result = obj_num.decimal;
result = getCommaDelimitedIntegerPart(obj_num.integer) + result;

console.log(result);

var num;
var result;

var getIntegerDecimalPart = function(num) {
  var re = /(\d+)(\.\d+)?/;
  var found = num.match(re);
  var decimal = found[2] ? found[2] : '';
  return {integer: found[1], decimal: decimal};
};

var getCommaDelimitedIntegerPart = function(str_integer) {
  var out = '';
  while (str_integer.length > 0) {
    var three_digits = str_integer.slice(-3); // get 3 digits
    out = three_digits + out;

    str_integer = str_integer.slice(0, -3);	// remove 3 digits
    if (str_integer.length >= 1) {
      out = ',' + out;
    }
  }
  return out;
}

// check args
if (process.argv.length < 3) { // sample value
  num = Math.floor(Math.random() * 1000000000) + 1;
  num = num.toString();
} else {
  num = process.argv[2];
}
console.log('input: ' + num);

var obj_num = getIntegerDecimalPart(num);
result = obj_num.decimal;
result = getCommaDelimitedIntegerPart(obj_num.integer) + result;

console.log(result);

Fix the decimal places limitation (at a758918).


app.controller('SearchController', ['$http', '$mdDialog', 'BioFactory', function($http, $mdDialog, BioFactory) {
  console.log('SearchController running');
  var self = this;

  self.mentors = BioFactory.mentors;

  self.newSearch = {
    first_name: null,
    last_name: null,
    email: null,
    company: null,
    job_title: null,
    zip: null,
    race: null,
    gender: null,
    orientation: null,
    birthday: null,
    school: null,
    degree: null,
    major: null,
    language: null
  };

  self.test = function() {
    console.log(self.newSearch);
  };

  self.getMentor = function(mentorId){
    console.log(mentorId);
    BioFactory.setMentorId(mentorId);
  }

  self.getMentors = function() {
    console.log("SEARCH controller new.Search:", self.newSearch)
    BioFactory.getMentors(self.newSearch);
  };

  self.createMessage = function(ev) {
    $mdDialog.show({
      controller: 'MessageController as message',
      templateUrl: '../../views/message-modal.html',
      targetEvent: ev,
      clickOutsideToClose: true
    });
  };

}]);

/**
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be foundin the LICENSE file at http://material.angularjs.org/HEAD/license.
**/

app.controller('SearchController', ['$http', '$mdDialog', 'BioFactory', function($http, $mdDialog, BioFactory) {
  console.log('SearchController running');
  var self = this;

  self.mentors = BioFactory.mentors;

  self.newSearch = {
    first_name: null,
    last_name: null,
    email: null,
    company: null,
    job_title: null,
    zip: null,
    race: null,
    gender: null,
    orientation: null,
    birthday: null,
    school: null,
    degree: null,
    major: null,
    language: null
  };

  self.test = function() {
    console.log(self.newSearch);
  };

  self.setMentor = function(mentor){
    console.log(mentor);
    BioFactory.setMentor(mentor);
  }

  self.getMentors = function() {
    console.log("SEARCH controller new.Search:", self.newSearch)
    BioFactory.getMentors(self.newSearch);
  };

  self.createMessage = function(ev) {
    $mdDialog.show({
      controller: 'MessageController as message',
      templateUrl: '../../views/message-modal.html',
      targetEvent: ev,
      clickOutsideToClose: true
    });
  };

}]);

/**
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be foundin the LICENSE file at http://material.angularjs.org/HEAD/license.
**/

Modify setMentor. Remove unnessary test function


var telegramBot = require('node-telegram-bot-api');
var log4js = require('log4js');

var nconf = require('nconf');
nconf.file('config', __dirname + '/config.json')
     .file('response', __dirname + '/response.json');

var appLogPath = nconf.get('log').app_log_path;

log4js.clearAppenders();
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(appLogPath), 'APP_LOG');

var token = nconf.get('bot').token;
var bot = new telegramBot(token, {polling: true});

bot.onText(/\/start/, function (msg) {
    var fromId = msg.from.id;
    var resp = nconf.get('response').start;
    bot.sendMessage(fromId, resp);
});

bot.on('/\/rule/', function (msg) {
    var fromId = msg.from.id;
    var resp = nconf.get('response').rule;
    bot.sendMessage(fromId, resp);
});

var telegramBot = require('node-telegram-bot-api');
var log4js = require('log4js');

var nconf = require('nconf');
nconf.file('config', __dirname + '/config.json')
     .file('response', __dirname + '/response.json');

var appLogPath = nconf.get('log').app_log_path;

log4js.clearAppenders();
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(appLogPath), 'APP_LOG');

var token = nconf.get('bot').token;
var bot = new telegramBot(token, {polling: true});

//Setting response of the telegram bot when detected keyword
bot.onText(/\/start/, function (msg) {
    var fromId = msg.from.id;
    var resp = nconf.get('response').start;
    bot.sendMessage(fromId, resp);
});

bot.onText(/\/rule/, function (msg) {
    var fromId = msg.from.id;
    var resp = nconf.get('response').rule;
    bot.sendMessage(fromId, resp);
});

bot.onText(/\/new/, function (msg) {
    var fromId = msg.from.id;
    var resp = nconf.get('response').new_content;
    bot.sendMessage(fromId, resp);
});

Fix the mistake on detect keyword, add the response of /new command


/* global THREE */
/*
exported
remove
round
createVertexHelper
updateGeometry
createTextLabel
*/
function remove( object ) {
  if ( object && object.parent ) {
    object.parent.remove( object );
  }
}

function round( precision ) {
  return function( number ) {
    return Number( number.toFixed( precision ) )
  };
}

function createVertexHelper( vertex, size ) {
  var vertexHelper = new THREE.Mesh(
    new THREE.BoxBufferGeometry( size, size, size ),
    new THREE.MeshBasicMaterial()
  );

  vertexHelper.position.copy( vertex );
  return vertexHelper;
}

function updateGeometry( geometry ) {
  geometry.computeFaceNormals();
  geometry.computeVertexNormals();

  geometry.normalsNeedUpdate = true;
  geometry.verticesNeedUpdate = true;
}

function createTextLabel( text, size ) {
  size = size || 512;

  var canvas = document.createElement( 'canvas' );
  var ctx = canvas.getContext( '2d' );

  canvas.width = size;
  canvas.height = size;

  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';

  ctx.fillStyle = '#fff';
  ctx.font = canvas.width + 'px Menlo, Monaco, monospace';
  ctx.fillText( text, canvas.width / 2, canvas.height / 2 );

  var texture = new THREE.Texture( canvas );
  texture.needsUpdate = true;

  return new THREE.Sprite(
    new THREE.SpriteMaterial({ map: texture, transparent: true })
  );
}

/* global THREE */
/*
exported
remove
round
createVertexHelper
updateGeometry
createTextLabel
*/
function remove( object ) {
  if ( object && object.parent ) {
    object.parent.remove( object );
  }
}

function round( precision ) {
  return function( number ) {
    return Number( number.toFixed( precision ) )
  };
}

function createVertexHelper( vertex, size ) {
  var vertexHelper = new THREE.Mesh(
    new THREE.BoxBufferGeometry( size, size, size ),
    new THREE.MeshBasicMaterial()
  );

  vertexHelper.position.copy( vertex );
  return vertexHelper;
}

function updateGeometry( geometry ) {
  geometry.computeFaceNormals();
  geometry.computeVertexNormals();

  geometry.normalsNeedUpdate = true;
  geometry.verticesNeedUpdate = true;

  geometry.computeBoundingBox();
  geometry.computeBoundingSphere();
}

function createTextLabel( text, size ) {
  size = size || 512;

  var canvas = document.createElement( 'canvas' );
  var ctx = canvas.getContext( '2d' );

  canvas.width = size;
  canvas.height = size;

  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';

  ctx.fillStyle = '#fff';
  ctx.font = canvas.width + 'px Menlo, Monaco, monospace';
  ctx.fillText( text, canvas.width / 2, canvas.height / 2 );

  var texture = new THREE.Texture( canvas );
  texture.needsUpdate = true;

  return new THREE.Sprite(
    new THREE.SpriteMaterial({ map: texture, transparent: true })
  );
}

lathe[cuboid]: Fix incorrect bounding primitives for mesh intersections.


/* eslint no-console: 0 */
var DBWrkrMongoDb = require('dbwrkr-mongodb');
var dbWrkrTests = require('dbwrkr').tests;

var testOptions = {
  storage: new DBWrkrMongoDb({
    dbName: 'dbwrkr_tests'
  })
};

dbWrkrTests(testOptions, function (err) {
  if (err) throw err;
});

/* eslint no-console: 0 */
var DBWrkrMongoDb = require('dbwrkr-mongodb');
var dbWrkrTests = require('../index').tests;

var testOptions = {
  storage: new DBWrkrMongoDb({
    dbName: 'dbwrkr_tests'
  })
};

dbWrkrTests(testOptions, function (err) {
  if (err) throw err;
});

Fix tests (using local module)

Fix tests (using local module)


'use strict';

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

var sortVersions = require('../lib/sort_versions');

module.exports = function(output, target, scrape) {
    return function(cb) {
        console.log('Starting to update ' + target + ' data');

        scrape(function(err, libraries) {
            if(err) {
                console.error('Failed to update ' + target + ' data!', err);

                return cb(err);
            }

            var p = path.join(output, target + '.json');

            libraries = libraries.map(function(library) {
                library.versions = sortVersions(library.versions);
                library.lastversion = library.versions[0];

                return library;
            });

            fs.writeFile(
                p,
                JSON.stringify(libraries),
                function(err) {
                    if(err) {
                        console.error('Failed to write', p);

                        return cb(err);
                    }

                    console.log('Updated', target, 'data');

                    cb();
                }
            );
        });
    };
};

'use strict';

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

var sortVersions = require('../lib/sort_versions');

module.exports = function(output, target, scrape) {
    return function(cb) {
        console.log('Starting to update ' + target + ' data');

        scrape(function(err, libraries) {
            if(err) {
                console.error('Failed to update ' + target + ' data!', err);

                return cb(err);
            }

            var p = path.join(output, target + '.json');

            libraries = libraries.map(function(library) {
                library.versions = sortVersions(library.versions);

                // skip if library is missing versions for some reason
                if(!library.versions) {
                    console.warn('Failed to find versions for', library);

                    return;
                }

                library.lastversion = library.versions[0];

                return library;
            }).filter(id);

            fs.writeFile(
                p,
                JSON.stringify(libraries),
                function(err) {
                    if(err) {
                        console.error('Failed to write', p);

                        return cb(err);
                    }

                    console.log('Updated', target, 'data');

                    cb();
                }
            );
        });
    };
};

function id(a) {
    return a;
}

Add check against missing library versions

@tomByrer, Please check your PR. Now it outputs just bootstrap library
for Bootstrap CDN.


// not sure how far to take this
// could make every mode extend methods like go, hide, show
    // not a fan, not enough modes to bother yet
    // naming is consistent enough to do this the dumb way
osmly.mode = (function() {
    var mode = {now: false, last:false};

    mode.set = function(theMode) {
        if (mode.now == theMode) return false;
        if (mode.now) osmly[mode.now].stop();
        osmly[theMode].go();
        change(theMode);
    };

    function change(changeTo) {
        mode.last = mode.now;
        mode.now = changeTo;
    }

    mode.import = function() { mode.set('import'); };
    mode.qa = function() { mode.set('qa'); };
    mode.overview = function() { mode.set('overview'); };
    mode.toLast = function() {
        if (mode.last) {
            mode.set(mode.last);
        } else {
            osmly[mode.now].stop();
        }
    };
    // convenience

    return mode;
}());

// not sure how far to take this
// could make every mode extend methods like go, hide, show
    // not a fan, not enough modes to bother yet
    // naming is consistent enough to do this the dumb way
osmly.mode = (function() {
    var mode = {now: false, last:false};

    mode.set = function(theMode) {
        if (mode.now == theMode) return false;
        if (mode.now) osmly[mode.now].stop();
        osmly[theMode].go();
        change(theMode);
    };

    function change(changeTo) {
        mode.last = mode.now;
        mode.now = changeTo;
    }

    mode.import = function() { mode.set('import'); };
    mode.qa = function() { mode.set('qa'); };
    mode.overview = function() { mode.set('overview'); };
    mode.toLast = function() {
        if (mode.last) {
            mode.set(mode.last);
        } else {
            osmly[mode.now].stop();
            mode.now = false;
        }
    };
    // convenience

    return mode;
}());

Fix for pre-logged in Overview

Fix for pre-logged in Overview


'use strict';

var program = require('commander');
var packageInfo = require('../package.json');
var jokes = require('./jokes.js');
var advice = require('./advice.js');
var resume = require('./resume.js');

module.exports = function (argv) {
  program
    .version(packageInfo.version)
    .option('-r, --resume', 'Open my resume')
    .option('-j, --joke',   'tell a joke!')
    .option('-a, --advice', 'Ask for advice.')
    .parse(argv);

  // Tell some sweet jokes
  if (program.joke) {
    jokes();
  }

  // Give a little advice
  if (program.advice) {
    advice();
  }

  // Open my resume
  if (program.resume) {
    resume();
  }
};

'use strict';

var program = require('commander');
var packageInfo = require('../package.json');
var jokes = require('./jokes.js');
var advice = require('./advice.js');
var resume = require('./resume.js');

module.exports = function (argv) {
  program
    .version(packageInfo.version)
    .option('-r, resume', 'Open my resume')
    .option('-j, joke',   'tell a joke!')
    .option('-a, advice', 'Ask for advice')
    .parse(argv);

  // Tell some sweet jokes
  if (program.joke) {
    jokes();
  }

  // Give a little advice
  if (program.advice) {
    advice();
  }

  // Open my resume
  if (program.resume) {
    resume();
  }
};

Change CLI such that long form doesn't use -- before the argument


var stripAnsi = require('strip-ansi')
var wcwidth = require('wcwidth')

var stepSize = 10000
module.exports = function(str) {
  // step through data in increments as the stripAnsi
  // regex is sensitive to large strings.
  var width = 0
  for (var i = 0; i < str.length; i += stepSize + 1) {
    width += wcwidth(stripAnsi(
      str.slice(i, i + stepSize)
    ))
  }
  return width
}

var stripAnsi = require('strip-ansi')
var wcwidth = require('wcwidth')

module.exports = function(str) {
  return wcwidth(stripAnsi(str))
}

Revert "Chunk calls to stripAnsi to avoid blowing max string length on regex."

Not necessary now that splitLongWords won't blow stack.

This reverts commit fd6a0c9f04fa0e247b82a86b85ee99d4054690b3.


chrome.storage.local.get(['pattern', 'color', 'opacity'], function(items) {
  var pattern, color, opacity;

  pattern = items.pattern;
  if (!pattern) {
    pattern = 'WIP';
  }
  pattern = new RegExp(pattern, 'i');

  color   = items.color   || 'lightgray';
  opacity = items.opacity || 0.7;

  var unhighlighter = function(element, pattern, color, opacity) {
    if (element.querySelector('.list-group-item-name').innerText.match(pattern)) {
      element.style.backgroundColor = color;
      element.style.opacity = opacity;
    }
  };

  var target = document.querySelector('body');
  var config = {
    childList: true,
    subtree: true
  };

  var observer = new MutationObserver(function(mutations, self) {
    mutations.forEach(function(mutation) {
      if (mutation.type === 'childList') {
        var elements = document.querySelectorAll('.pulls-list-group li.list-group-item');

        Array.prototype.forEach.call(elements, function(element) {
          unhighlighter(element, pattern, color, opacity);
        });
      }
    });
  });

  observer.observe(target, config);
});

chrome.storage.local.get(['pattern', 'case_insensitive', 'color', 'opacity'], function(items) {
  var pattern, case_insensitive, color, opacity;
  var re, flags;

  pattern = items.pattern;
  if (!pattern) {
    pattern = 'WIP';
  }

  case_insensitive = !!items.case_insensitive;
  if (case_insensitive) {
    flags = 'i';
  } else {
    flags = '';
  }

  re = new RegExp(pattern, flags);

  color   = items.color   || 'lightgray';
  opacity = items.opacity || 0.7;

  var unhighlighter = function(element, re, color, opacity) {
    if (element.querySelector('.list-group-item-name').innerText.match(re)) {
      element.style.backgroundColor = color;
      element.style.opacity = opacity;
    }
  };

  var target = document.querySelector('body');
  var config = {
    childList: true,
    subtree: true
  };

  var observer = new MutationObserver(function(mutations, self) {
    mutations.forEach(function(mutation) {
      if (mutation.type === 'childList') {
        var elements = document.querySelectorAll('.pulls-list-group li.list-group-item');

        Array.prototype.forEach.call(elements, function(element) {
          unhighlighter(element, re, color, opacity);
        });
      }
    });
  });

  observer.observe(target, config);
});

Add case insensitive matching feature

Add case insensitive matching feature


(function () {
    "use strict";

    var Frame = function (elem) {
        if (typeof elem === 'string') {
            elem = document.getElementById(elem);
        }

        var height = elem.scrollHeight;
        var width = elem.scrollWidth;

        var viewAngle = 45;
        var aspect = width / (1.0 * height);
        var near = 0.1;
        var far = 10000;

        this.scene = new THREE.Scene();

        this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
        this.camera.position.z = 10;
        this.scene.add(this.camera);

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setSize(width, height);

        elem.appendChild(this.renderer.domElement);
    };
    window.Frame = Frame;

    Frame.prototype.addNode = function (x, y, z) {
        var geometry = new THREE.SphereGeometry(1);
        geometry.position = {x: x, y: y, z: z};
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});
        var cube = new THREE.Mesh(geometry, material);
        this.scene.add(cube);
    };

    Frame.prototype.render = function () {
        this.renderer.render(this.scene, this.camera);
    };
}());

(function () {
    "use strict";

    var Frame = function (elem) {
        if (typeof elem === 'string') {
            elem = document.getElementById(elem);
        }

        var height = elem.scrollHeight;
        var width = elem.scrollWidth;

        var viewAngle = 45;
        var aspect = width / (1.0 * height);
        var near = 0.1;
        var far = 10000;

        this.scene = new THREE.Scene();

        this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
        this.camera.position.z = 10;
        this.scene.add(this.camera);

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setSize(width, height);

        elem.appendChild(this.renderer.domElement);
    };
    window.Frame = Frame;

    Frame.prototype.addNode = function (x, y, z) {
        var geometry = new THREE.SphereGeometry(1);
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});
        var cube = new THREE.Mesh(geometry, material);
        cube.position = {x: x, y: y, z: z};
        this.scene.add(cube);
    };

    Frame.prototype.render = function () {
        this.renderer.render(this.scene, this.camera);
    };
}());

Apply position on mesh, not geometry

Apply position on mesh, not geometry


/**
 * Analyze number of requests and sizes of differet assets types
 */
exports.version = '0.1';

exports.module = function(phantomas) {
	['html', 'css', 'js', 'image', 'base64', 'other'].forEach(function(key) {
		phantomas.setMetric(key + 'Count');
		phantomas.setMetric(key + 'Size');
	});

	phantomas.on('recv', function(entry, res) {
		phantomas.incrMetric(entry.type + 'Count');
		phantomas.incrMetric(entry.type + 'Size', entry.bodySize);
	});

	phantomas.on('base64recv', function(entry, res) {
		phantomas.incrMetric('base64Count');
		phantomas.incrMetric('base64Size', entry.bodySize);
	});
};

/**
 * Analyze number of requests and sizes of differet assets types
 */
exports.version = '0.1';

exports.module = function(phantomas) {
	['html', 'css', 'js', 'image', 'webfont', 'base64', 'other'].forEach(function(key) {
		phantomas.setMetric(key + 'Count');
		phantomas.setMetric(key + 'Size');
	});

	phantomas.on('recv', function(entry, res) {
		phantomas.incrMetric(entry.type + 'Count');
		phantomas.incrMetric(entry.type + 'Size', entry.bodySize);
	});

	phantomas.on('base64recv', function(entry, res) {
		phantomas.incrMetric('base64Count');
		phantomas.incrMetric('base64Size', entry.bodySize);
	});
};

Add new metric: web font requests

Add new metric: web font requests

* webfontCount
* webfontSize

Issue #24


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

app.set('port', (process.env.PORT || 8080));

//Public files
app.use(express.static('public'));
//node_modules
app.use(express.static('node_modules'));
//node_modules
app.use(express.static('bower_components'));

app.get('/', function (req, res) {
	if(req.headers.host.match('javicaballero-web.herokuapp.com')){
		res.redirect(301, 'http://javicaballero.com' + req.path);
	}
  res.sendFile('index.html');
});

app.listen(app.get('port'));

console.log('Servidor iniciado');

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

app.set('port', (process.env.PORT || 8080));

//Public files
app.use(express.static('public'));
//node_modules
app.use(express.static('node_modules'));
//node_modules
app.use(express.static('bower_components'));

app.get('/', function (req, res) {
  res.sendFile('index.html');
});

app.listen(app.get('port'));

console.log('Servidor iniciado');

Revert "Added redirect to javicaballero.com"

This reverts commit 1b613fcc1ef745bea91dfd0431633f5261329b03.


var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
var path = require('path');
var m = require('mori');
var game = require('./game.js');

var app = express();
var server = http.Server(app);
var io = socketIO(server);

app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');

app.use(express.static('public'));

var gameState = game.getInitialState();

app.get('/', function(req, res) {
  var dealt = m.toJs(m.get(gameState, 'dealt'));
  res.render('index', {'dealt': dealt});
});

io.on('connection', function(socket){
  console.log('CONNECT', socket.id);
  socket.on('log on', function(name){
    console.log('LOG ON', name);
    socket.broadcast.emit('log on', name);
  })
  socket.on('log off', function(name) {
    console.log('LOG OFF', name);
    socket.broadcast.emit('log off', name);
  })
  socket.on('disconnect', function(){
    console.log('DISCONNECT', socket.id);
  });
  socket.on('card click', function(click){
    console.log('CARD CLICK', click.user, click.card);
    io.emit('card click', click);
  });
});

server.listen(3000, function() {
  console.log("listening on port 3000");
});

var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
var path = require('path');
var m = require('mori');
var game = require('./game.js');

var app = express();
var server = http.Server(app);
var io = socketIO(server);

app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');

app.use(express.static('public'));

var gameState = game.getInitialState();

app.get('/', function(req, res) {
  var stateObject = m.toJs(gameState);
  res.render('index', stateObject);
});

io.on('connection', function(socket){
  console.log('CONNECT', socket.id);
  socket.on('log on', function(name){
    console.log('LOG ON', name);
    socket.broadcast.emit('log on', name);
  })
  socket.on('log off', function(name) {
    console.log('LOG OFF', name);
    socket.broadcast.emit('log off', name);
  })
  socket.on('disconnect', function(){
    console.log('DISCONNECT', socket.id);
  });
  socket.on('card click', function(click){
    console.log('CARD CLICK', click.user, click.card);
    io.emit('card click', click);
  });
});

server.listen(3000, function() {
  console.log("listening on port 3000");
});

Convert gameState to JS object and pass to template


'use strict'

const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
  plugins: [
    new CopyPlugin([
      { from: 'vendor/assets', ignore: ['.gitkeep'] }
    ])
  ]
}

'use strict'

const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
  plugins: [
    new CopyPlugin([
      { from: 'vendor/assets', ignore: ['.gitkeep'] },
      { from: 'manifest.webapp' }
    ])
  ]
}

[fix] Copy the manifest.webapp file to the build dir


'use strict';

module.exports = {
  env: {
    es6: true,
    node: true,
    browser: true,
  },
  extends: 'eslint:recommended',
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 8,
  },
  rules: {
    indent:             [ 'error', 2 , {SwitchCase: 1}],
    'linebreak-style':  [ 'error', 'unix' ],
    quotes:             [ 'error', 'single', {avoidEscape: true} ],
    semi:               [ 'error', 'always' ],
    'no-console':       'off',
    'no-unused-vars':   'warn',
  }
};

'use strict';

module.exports = {
  env: {
    es6: true,
    node: true,
    browser: true,
  },
  extends: 'eslint:recommended',
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 8,
  },
  rules: {
    indent:             [ 'error', 2 , {SwitchCase: 1}],
    'linebreak-style':  [ 'error', 'unix' ],
    quotes:             [ 'error', 'single', {
      avoidEscape: true,
      allowTemplateLiterals: true
    } ],
    semi:               [ 'error', 'always' ],
    'no-console':       'off',
    'no-unused-vars':   'warn',
  }
};

Allow template literal for quote rule

[eslint] Allow template literal for quote rule


/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import classnames from 'classnames';
import ErrorIcon from '../../../svg/error.svg';

const { useSelect } = Data;

/**
 * A single module. Keeps track of its own active state and settings.
 */
/*
class ModuleSettingsWarning extends Component {
	render() {
		return null;
	}
}

export default withFilters( 'googlesitekit.ModuleSettingsWarning' )( ModuleSettingsWarning );
*/

export default function ModuleSettingsWarning( {
	slug,
	// context,
} ) {
	// @TODO: Resolver only runs once per set of args, so we are working around
	// this to rerun after modules are loaded.
	// Once #1769 is resolved, we can remove the call to getModules,
	// and remove the !! modules cache busting param.
	const modules = useSelect( ( select ) => select( CORE_MODULES ).getModules() );
	const requirementsStatus = useSelect( ( select ) => select( CORE_MODULES ).getCheckRequirementsStatus( slug, !! modules ) );

	if ( requirementsStatus === null ) {
		return null;
	}

	return (
		<div
			className={ classnames( 'googlesitekit-settings-module-warning', 'googlesitekit-settings-module-warning--modules-list' ) } >
			<ErrorIcon height="20" width="23" /> { requirementsStatus }
		</div>
	);
}

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
import classnames from 'classnames';
import ErrorIcon from '../../../svg/error.svg';

const { useSelect } = Data;

/*
 * A single module. Keeps track of its own active state and settings.
 */
export default function ModuleSettingsWarning( {
	slug,
	// context,
} ) {
	// @TODO: Resolver only runs once per set of args, so we are working around
	// this to rerun after modules are loaded.
	// Once #1769 is resolved, we can remove the call to getModules,
	// and remove the !! modules cache busting param.
	const modules = useSelect( ( select ) => select( CORE_MODULES )?.getModules() );
	const requirementsStatus = useSelect( ( select ) => select( CORE_MODULES )?.getCheckRequirementsStatus( slug, !! modules ) );

	if ( requirementsStatus === null ) {
		return null;
	}

	return (
		<div
			className={ classnames( 'googlesitekit-settings-module-warning', 'googlesitekit-settings-module-warning--modules-list' ) } >
			<ErrorIcon height="20" width="23" /> { requirementsStatus }
		</div>
	);
}

Remove old class declaration and ensure store exists.


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

/**
 * @function startGateway
 * @requires GatewayProcessManager
 * @description Starts gateway processes.
 * @param opts
 */

function startGateway(opts, fn) {
  processManager = new GatewayProcessManager();
  processManager.start(opts, function(err, processes){
    if(err){
      fn(err, null);
    } else {
      fn(null, processes);
    }
  });

}

module.exports = startGateway;

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

/**
 * @function startGateway
 * @requires GatewayProcessManager
 * @description Starts gateway processes.
 * @param opts
 */

function startGateway(opts, fn) {
  processManager = new GatewayProcessManager();
  processManager.start(opts, function(err, processes){
    fn(null, processes);
  });

}

module.exports = startGateway;

Revert "[CHORE] fire callback with error or processes"

This reverts commit 9a5fc4935bb6e755c4a242259bc416fa4acdad37.


(function () {
    function CreateNotifyController(
        $scope,
        contentResource,
        navigationService,
        angularHelper) {
        var vm = this;
        var currentForm;
        vm.notifyOptions = [];
        vm.save = save;
        vm.cancel = cancel;
        vm.message = {
            name: $scope.currentNode.name
        };;
        function onInit() {
            vm.loading = true;
            contentResource.getNotifySettingsById($scope.currentNode.id).then(function (options) {
                currentForm = angularHelper.getCurrentForm($scope);
                vm.loading = false;
                vm.notifyOptions = options;
            });
        }
        function cancel() {
            navigationService.hideMenu();
        };
        function save(notifyOptions) {
            vm.saveState = "busy";
            vm.saveError = false;
            vm.saveSuccces = false;
            var selectedString = [];
            angular.forEach(notifyOptions,
                function(option) {
                    if (option.checked === true && option.notifyCode) {
                        selectedString.push(option.notifyCode);
                    }
            console.log('selectedString', selectedString);

            contentResource.setNotifySettingsById($scope.currentNode.id, selectedString).then(function () {
                vm.saveState = "success";
                vm.saveSuccces = true;
            }, function (error) {
                vm.saveState = "error";
                vm.saveError = error;
            });
        }
        onInit();
    }
    angular.module("umbraco").controller("Umbraco.Editors.Content.CreateNotifyController", CreateNotifyController);
}());

(function () {
    function CreateNotifyController(
        $scope,
        contentResource,
        navigationService,
        angularHelper) {
        var vm = this;
        var currentForm;
        vm.notifyOptions = [];
        vm.save = save;
        vm.cancel = cancel;
        vm.message = {
            name: $scope.currentNode.name
        };;
        function onInit() {
            vm.loading = true;
            contentResource.getNotifySettingsById($scope.currentNode.id).then(function (options) {
                currentForm = angularHelper.getCurrentForm($scope);
                vm.loading = false;
                vm.notifyOptions = options;
            });
        }
        function cancel() {
            navigationService.hideMenu();
        };
        function save(notifyOptions) {
            vm.saveState = "busy";
            vm.saveError = false;
            vm.saveSuccces = false;
            var selectedString = [];
            angular.forEach(notifyOptions, function (option) {
                    if (option.checked === true && option.notifyCode) {
                        selectedString.push(option.notifyCode);
                    }
            })

            contentResource.setNotifySettingsById($scope.currentNode.id, selectedString).then(function () {
                vm.saveState = "success";
                vm.saveSuccces = true;
            }, function (error) {
                vm.saveState = "error";
                vm.saveError = error;
            });
        }
        onInit();
    }
    angular.module("umbraco").controller("Umbraco.Editors.Content.CreateNotifyController", CreateNotifyController);
}());

Fix up syntax error in JS from my merge/port upto V8 - oops :(


define([], function () {
  return function () {
    var container = document.createElement("ul")
    container.classList.add("filters")
    var div = document.createElement("div")

    function render(el) {
      el.appendChild(div)
    }

    function filtersChanged(filters) {
      while (container.firstChild)
        container.removeChild(container.firstChild)

      filters.forEach( function (d) {
        var li = document.createElement("li")
        var div = document.createElement("div")
        container.appendChild(li)
        li.appendChild(div)
        d.render(div)

        var button = document.createElement("button")
        button.textContent = ""
        button.onclick = function () {
          d.clear()
        }
        // Prevent blur events from stealing the click event
        button.onmousedown = function (ev) {
          ev.preventDefault()
        }
        li.appendChild(button)
      })

      if (container.parentNode === div && filters.length === 0)
        div.removeChild(container)
      else if (filters.length > 0)
        div.appendChild(container)
    }

    return { render: render,
             filtersChanged: filtersChanged
           }
  }
})

define([], function () {
  return function (filterManager) {
    var container = document.createElement("ul")
    container.classList.add("filters")
    var div = document.createElement("div")

    function render(el) {
      el.appendChild(div)
    }

    function filtersChanged(filters) {
      while (container.firstChild)
        container.removeChild(container.firstChild)

      filters.forEach( function (d) {
        var li = document.createElement("li")
        var div = document.createElement("div")
        container.appendChild(li)
        li.appendChild(div)
        d.render(div)

        var button = document.createElement("button")
        button.textContent = ""
        button.onclick = function () {
          if (typeof d.clear !== "undefined")
            d.clear()
          else
            filterManager.removeFilter(d)
        }
        // Prevent blur events from stealing the click event
        button.onmousedown = function (ev) {
          ev.preventDefault()
        }
        li.appendChild(button)
      })

      if (container.parentNode === div && filters.length === 0)
        div.removeChild(container)
      else if (filters.length > 0)
        div.appendChild(container)
    }

    return { render: render,
             filtersChanged: filtersChanged
           }
  }
})

Fix removing filter for hostname filters


import express from 'express';
import compression from 'compression';
import expressEnforcesSSL from 'express-enforces-ssl';
import helmet from 'helmet';
import http from 'http';
import path from 'path';

// Express server

let app = express();
let server = http.Server(app);

// Force HTTPS on production
if (process.env.NODE_ENV === 'production') {
  app.enable('trust proxy');
  app.use(expressEnforcesSSL());
  app.use(helmet());
}

// Serve assets using gzip compression
app.use(compression());

// Routes

app.get('/room/:roomCode', (req, res) => {
  res.sendFile(path.join(path.dirname(__dirname), 'index.html'));
});
app.get('/room', (req, res) => {
  res.sendFile(path.join(path.dirname(__dirname), 'index.html'));
});
app.use(express.static(path.dirname(__dirname)));

// Warning: app.listen(8080) will not work here; see
// <https://github.com/socketio/socket.io/issues/2075>
server.listen(process.env.PORT || 8080, () => {
  console.log(`Server started. Listening on port ${server.address().port}`);
});

export default server;

import express from 'express';
import compression from 'compression';
import expressEnforcesSSL from 'express-enforces-ssl';
import helmet from 'helmet';
import http from 'http';
import path from 'path';

// Express server

let app = express();

// Force HTTPS on production
if (process.env.NODE_ENV === 'production') {
  app.enable('trust proxy');
  app.use(expressEnforcesSSL());
  app.use(helmet());
}

// Serve assets using gzip compression
app.use(compression());

// Routes

app.get('/room/:roomCode', (req, res) => {
  res.sendFile(path.join(path.dirname(__dirname), 'index.html'));
});
app.get('/room', (req, res) => {
  res.sendFile(path.join(path.dirname(__dirname), 'index.html'));
});
app.use(express.static(path.dirname(__dirname)));

// HTTP server wrapper

let server = http.Server(app);
// Warning: app.listen(8080) will not work here; see
// <https://github.com/socketio/socket.io/issues/2075>
server.listen(process.env.PORT || 8080, () => {
  console.log(`Server started. Listening on port ${server.address().port}`);
});

export default server;

Move HTTP server definition to end of module


#!/usr/bin/env node

'use strict';

var MakeUp = require('../index');

var argv = require('minimist')(process.argv.slice(2));

var options = {
  dirs: argv._,
  integrations: argv.i,
  since: argv.s,
  gitBranch: argv.b
};
MakeUp.check(options, function(err, result) {
  if (err) {
    console.log('ERROR: ' + err.message);
    process.exit(1); // eslint-disable-line no-process-exit
  }
  console.log(result);
});

#!/usr/bin/env node

'use strict';

var MakeUp = require('../index');

var argv = require('minimist')(process.argv.slice(2));

var options = {
  dirs: argv._,
  integrations: argv.i,
  since: argv.s,
  gitBranch: argv.b
};
MakeUp.check(options, function(err, result) {
  if (result) {
    console.log(result);
  }
  if (err) {
    console.log('ERROR: ' + err.message);
    process.exit(1); // eslint-disable-line no-process-exit
  }
});

Make sure we always print the result if it exists.


export default {
  // Dependencies for a default Sanity installation
  core: {
    '@sanity/base': '^2.1.56',
    '@sanity/components': '^1.0.43',
    '@sanity/default-layout': '^1.0.28',
    '@sanity/default-login': '^1.0.2',
    '@sanity/desk-tool': '^1.0.32',
    'react': '^15.3.0',
    'react-dom': '^15.3.0'
  },

  // Only used for Sanity-style plugins (eg, the ones we build at Sanity.io)
  plugin: {
    dev: {
      '@sanity/check': '^1.0.0',
      'babel-cli': '^6.9.0',
      'babel-eslint': '^6.0.4',
      'babel-plugin-syntax-class-properties': '^6.8.0',
      'babel-plugin-transform-class-properties': '^6.9.1',
      'babel-preset-es2015': '^6.9.0',
      'babel-preset-react': '^6.5.0',
      'eslint': '^2.12.0',
      'eslint-config-sanity': '^1.1.1',
      'eslint-plugin-react': '^5.1.1',
      'rimraf': '^2.5.2'
    },
    prod: {
      'in-publish': '^2.0.0'
    }
  }
}

export default {
  // Dependencies for a default Sanity installation
  core: {
    '@sanity/base': '^2.1.56',
    '@sanity/components': '^1.0.43',
    '@sanity/default-layout': '^1.0.28',
    '@sanity/default-login': '^1.0.2',
    '@sanity/desk-tool': '^1.0.32',
    'react': '^15.3.0',
    'react-dom': '^15.3.0'
  },

  // Only used for Sanity-style plugins (eg, the ones we build at Sanity.io)
  plugin: {
    dev: {
      '@sanity/check': '^1.0.0',
      'babel-cli': '^6.9.0',
      'babel-eslint': '^6.0.4',
      'babel-plugin-syntax-class-properties': '^6.8.0',
      'babel-plugin-transform-class-properties': '^6.9.1',
      'babel-preset-es2015': '^6.9.0',
      'babel-preset-react': '^6.5.0',
      'eslint': '^3.4.0',
      'eslint-config-sanity': '^1.1.3',
      'eslint-plugin-react': '^6.3.0',
      'rimraf': '^2.5.2'
    },
    prod: {
      'in-publish': '^2.0.0'
    }
  }
}

Update version ranges for bootstrapping

Update version ranges for bootstrapping


Package.describe({
  summary: "Define templates inside .md files.",
  version: '2.0.0',
  name: "simple:markdown-templating",
  git: "https://github.com/stubailo/meteor-markdown-templating"
});

// Today, this package is closely intertwined with Showdown and Spacebars
Package.registerBuildPlugin({
  name: "compileMarkdownTemplates",
  use: [
    'caching-compiler@1.1.6',
    'ecmascript@0.7.0',
    'markdown@1.0.4',
    'spacebars-compiler@1.0.6',
    'underscore@1.0.3',
    'simple:highlight.js@1.0.9'
  ],
  sources: [
    'plugin/markdown-scanner.js',
    'plugin/compile-templates.js'
  ]
});

// This on_use describes the *runtime* implications of using this package.
Package.onUse(function (api) {
  api.use('isobuild:compiler-plugin@1.0.0');
  api.imply(['templating@1.3.0'], 'client');
});

Package.onTest(function (api) {
  api.use([
    "tinytest",
    "simple:markdown-templating",
    "underscore",
    "spacebars-compiler",
    "showdown"
  ]);

  api.addFiles([
    "plugin/markdown-scanner.js",
    "tests/tests.js"
  ], "server");

  api.addAssets([
    "tests/test.md"
  ], "server");
});

Package.describe({
  summary: "Define templates inside .md files.",
  version: '2.0.1',
  name: "simple:markdown-templating",
  git: "https://github.com/stubailo/meteor-markdown-templating"
});

// Today, this package is closely intertwined with Showdown and Spacebars
Package.registerBuildPlugin({
  name: "compileMarkdownTemplates",
  use: [
    'caching-compiler@1.1.6',
    'ecmascript@0.7.0',
    'markdown@1.0.4',
    'spacebars-compiler@1.0.6',
    'underscore@1.0.3',
    'simple:highlight.js@1.0.9'
  ],
  sources: [
    'plugin/markdown-scanner.js',
    'plugin/compile-templates.js'
  ]
});

// This on_use describes the *runtime* implications of using this package.
Package.onUse(function (api) {
  api.use('isobuild:compiler-plugin@1.0.0');
  api.imply(['templating@1.3.0'], 'client');
});

Package.onTest(function (api) {
  api.use([
    "tinytest",
    "simple:markdown-templating",
    "underscore",
    "spacebars-compiler",
    "showdown"
  ]);

  api.addFiles([
    "plugin/markdown-scanner.js",
    "tests/tests.js"
  ], "server");

  api.addAssets([
    "tests/test.md"
  ], "server");
});

Bump version to 2.0.1 in preparation for publishing.


Package.describe({
    name: "froatsnook:bardcode",
    version: "1.1.0",
    summary: "Draw 1-D barcodes to Canvases (client and server)",
    git: "https://github.com/froatsnook/bardcode"
});

Package.onUse(function(api) {
    api.versionsFrom("1.0.3.1");
    api.addFiles("lib/01-bardcode.js");
    api.addFiles("lib/canvas.js");
    api.addFiles("lib/Codabar.js");
    api.addFiles("lib/Code128.js");
    api.addFiles("lib/Code39.js");
    api.addFiles("lib/drawBarcode.js");
    api.addFiles("lib/EAN.js");
    api.addFiles("lib/FIM.js");
    api.addFiles("lib/ITF.js");
    api.addFiles("lib/svg.js");
    api.addFiles("lib/validations.js");

    api.export("drawBarcode");
    api.export("bardcode");
});

Package.onTest(function(api) {
    Npm.depends({
        "canvas": "1.1.6"
    });

    api.use("tinytest");
    api.use("froatsnook:bardcode");

    api.addFiles("test/tests.js");
});

Package.describe({
    name: "froatsnook:bardcode",
    version: "1.1.0",
    summary: "Draw 1-D barcodes to Canvases (client and server)",
    git: "https://github.com/froatsnook/bardcode"
});

Package.onUse(function(api) {
    api.versionsFrom("1.0.3.1");
    api.addFiles("lib/01-bardcode.js");
    api.addFiles("lib/canvas.js");
    api.addFiles("lib/Codabar.js");
    api.addFiles("lib/Code128.js");
    api.addFiles("lib/Code39.js");
    api.addFiles("lib/drawBarcode.js");
    api.addFiles("lib/EAN.js");
    api.addFiles("lib/FIM.js");
    api.addFiles("lib/ITF.js");
    api.addFiles("lib/svg.js");
    api.addFiles("lib/validations.js");

    api.export("drawBarcode");
    api.export("bardcode");
});

Package.onTest(function(api) {
    Npm.depends({
        "canvas": "1.2.1"
    });

    api.use("tinytest");
    api.use("froatsnook:bardcode");

    api.addFiles("test/tests.js");
});

Update canvas (test dependency only).

Update canvas (test dependency only).


var auto = require('auto-package')
var content = auto.content
var policystat = require('./lib')
var psPrettyName = policystat.name.pretty
var license = policystat.openSource.license.spdx

content.name = 'policystat'
content.main = 'lib/index.js'
auto.versionFile()
content.description = psPrettyName + ' strings for easy reuse'
auto.githubRepo('mightyiam/policystat.js')
content.copyright = policystat.copyrightNotice
content.author = require('mightyiam').authorStr
content.devDependencies = {
  mightyiam: '^1.1.5',
  'auto-package': '^0.2.0',
  standard: '*',
  invalid: '^0.0.2',
  'license-generator': '^0.0.13',
  'verb-cli': '^0.4.4'
}
content.scripts = {
    license: 'license-generator install ' +
      license.toLowerCase() +
      ' -n "' + psPrettyName + '"',
    lint: 'standard',
    test: 'npm run lint && npm run license'
}
content.license = license

var auto = require('auto-package')
var content = auto.content
var policystat = require('./lib')
var psPrettyName = policystat.name.pretty
var license = policystat.openSource.license.spdx

content.name = 'policystat'
content.main = 'lib/index.js'
auto.versionFile()
content.description = psPrettyName + ' strings for easy reuse'
auto.githubRepo('mightyiam/policystat.js')
content.copyright = policystat.copyrightNotice
content.author = require('mightyiam').authorStr
content.devDependencies = {
  mightyiam: '^1.1.5',
  'auto-package': '^0.2.0',
  standard: '*',
  'license-generator': '^0.0.13',
  'verb-cli': '^0.4.4'
}
content.scripts = {
    license: 'license-generator install ' +
      license.toLowerCase() +
      ' -n "' + psPrettyName + '"',
    lint: 'standard',
    test: 'npm run lint && npm run license'
}
content.license = license

Remove invalid. It was for testing

Remove invalid. It was for testing


'use strict';

const assert = require('assert');
const path = require('path');
const fse = require('fs-extra');

module.exports = dir => {
  if (!fse.existsSync(dir)) return {};

  const root = {};
  const paths = fse.readdirSync(dir, { withFileTypes: true }).filter(fd => fd.isFile());

  for (let fd of paths) {
    const { name } = fd;
    const fullPath = dir + path.sep + name;

    const ext = path.extname(name);
    const key = path.basename(name, ext);
    root[key] = loadPolicy(fullPath);
  }

  return root;
};

const loadPolicy = file => {
  try {
    const policy = require(file);

    assert(typeof policy === 'function', 'Policy must be a function.');

    return policy;
  } catch (error) {
    throw `Could not load policy ${file}: ${error.message}`;
  }
};

'use strict';

const assert = require('assert');
const _ = require('lodash');
const path = require('path');
const fse = require('fs-extra');

module.exports = dir => {
  if (!fse.existsSync(dir)) return {};

  const root = {};
  const paths = fse.readdirSync(dir, { withFileTypes: true }).filter(fd => fd.isFile());

  for (let fd of paths) {
    const { name } = fd;
    const fullPath = dir + path.sep + name;

    const ext = path.extname(name);
    const key = path.basename(name, ext);
    root[_.toLower(key)] = loadPolicy(fullPath);
  }

  return root;
};

const loadPolicy = file => {
  try {
    const policy = require(file);

    assert(typeof policy === 'function', 'Policy must be a function.');

    return policy;
  } catch (error) {
    throw `Could not load policy ${file}: ${error.message}`;
  }
};

Fix global policies case sensitive

Fix global policies case sensitive

Signed-off-by: Alexandre Bodin <70f0c7aa1e44ecfca5832512bee3743e3471816f@gmail.com>


export function support(dependencies) {

  let isLegacy = Object.getOwnPropertyNames(dependencies).filter(name => {
    return name.indexOf('corespring-legacy') === 0;
  }).length > 0;

  if (isLegacy) {
    return {
      npmDependencies: {
        'css-loader': '0.9.0',
        'file-loader': '^0.9.0',
        'less-loader': '^2.2.3'
      },
      webpackLoaders: () => {
        return [
          {
            test: /\.(eot|svg|ttf|woff|woff2)([#?].*)?$/,
            loader: 'file?name=public/fonts/[name].[ext]'
          }
        ];
      }
    }
  }
}

export function support(dependencies) {

  let isLegacy = Object.getOwnPropertyNames(dependencies).filter(name => {
    return name.indexOf('corespring-legacy') === 0;
  }).length > 0;

  if (isLegacy) {
    return {
      npmDependencies: {
        'css-loader': '0.9.0',
        'file-loader': '^0.9.0',
        'less-loader': '^2.2.3'
      },
      webpackLoaders: () => {
        return [
          {
            test: /\.(eot|svg|ttf|woff|woff2)([#?].*)?$/,
            loader: 'file?name=public/fonts/[name].[ext]'
          },
          {
            test: /\/images\/feedback\/.*\.png/,
            loader: 'file?{"name":"public/images/feedback/[name].[ext]"}'
          }
        ];
      }
    }
  }
}

Add loader for images to legacy framework


// Overwrite this file in your application /app/assets/javascripts/comfortable_mexican_sofa/admin/application.js
//= require requirejs/require
//= require require_config

window.CMS.wysiwyg = function() {
  require([
    'mas-editor'
  ], function (
    masEditor
  ) {
    var markdownEditorContentNode = document.querySelector('.js-markdown-editor-content'),
        classActive = 'is-active',
        htmlEditorNode;

    if(!markdownEditorContentNode) return;

    masEditor.init({
      editorContainer: document.querySelector('.l-editor'),
      cmsFormNode: document.querySelector('#edit_page') || document.querySelector('#new_page'),
      toolbarNode: document.querySelector('.js-html-editor-toolbar'),
      htmlEditorNode: document.querySelector('.js-html-editor'),
      htmlEditorContentNode: document.querySelector('.js-html-editor-content'),
      markdownEditorNode: document.querySelector('.js-markdown-editor'),
      markdownEditorContentNode: markdownEditorContentNode,
      switchModeButtonNodes: document.querySelectorAll('.js-switch-mode'),
      classActive : 'is-active'
    });
  });
};

// Overwrite this file in your application /app/assets/javascripts/comfortable_mexican_sofa/admin/application.js
//= require requirejs/require
//= require require_config

window.CMS.wysiwyg = function() {
  require([
    'mas-editor'
  ], function (
    masEditor
  ) {
    var markdownEditorContentNode = document.querySelector('.js-markdown-editor-content'),
        classActive = 'is-active',
        htmlEditorNode;

    if(!markdownEditorContentNode) return;

    markdownEditorContentNode.value = markdownEditorContentNode.value.split("\n").map(function(e) { return e.trim() }).join("\n");

    masEditor.init({
      editorContainer: document.querySelector('.l-editor'),
      cmsFormNode: document.querySelector('#edit_page') || document.querySelector('#new_page'),
      toolbarNode: document.querySelector('.js-html-editor-toolbar'),
      htmlEditorNode: document.querySelector('.js-html-editor'),
      htmlEditorContentNode: document.querySelector('.js-html-editor-content'),
      markdownEditorNode: document.querySelector('.js-markdown-editor'),
      markdownEditorContentNode: markdownEditorContentNode,
      switchModeButtonNodes: document.querySelectorAll('.js-switch-mode'),
      classActive : 'is-active'
    });
  });
};

Trim each line of markdown hack

Trim each line of markdown hack


pageflow.app.addInitializer(function(options) {
  var KEY_A = 65;

  $(document).on('keydown', function(event) {
    if (pageflow.features.isEnabled('atmo') && event.altKey && event.which === KEY_A) {
      if (pageflow.atmo.disabled) {
        pageflow.atmo.enable();
      }
      else {
        pageflow.atmo.disable();
      }
    }
  });
});

pageflow.app.addInitializer(function(options) {
  var KEY_A = 65;
  var KEY_X = 88;

  $(document).on('keydown', function(event) {
    if (event.altKey && event.which === KEY_A) {
      if (pageflow.features.isEnabled('atmo')) {
        if (pageflow.atmo.disabled) {
          pageflow.atmo.enable();
        }
        else {
          pageflow.atmo.disable();
        }
      }
    }
    else if (event.altKey && event.which === KEY_X) {
      pageflow.editor.navigate('pages/' + pageflow.slides.currentPage().data('id'), {trigger: true});
    }
  });
});

Add a Hotkey to Edit the Current Page

Add a Hotkey to Edit the Current Page


import React from 'react'

class LessonData extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      // state here
      // lessons data
      // polls
      newPollSelected: false
    };
  }

  render(){
    return

{this.props.className}

Polls for {this.props.className}

January 1, 1970

March 31, 2034

Students in {this.props.className}

Little Bobby Tables

Suzie CSS

Edison

      <AddPoll newPollSelected={this.state.newPollSelected}/>

  }

}

const AddPoll = () => {
  // add to state

  // post to DB

  return (

Add new poll

      <button>Thumbs Check</button>
      <button>Multiple Choice</button>

  )
};

module.exports = LessonData;

import React from 'react'

class LessonData extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      // state here

      // polls
    };
  }

  render(){
    return

{this.props.className}

Polls for {this.props.className}

January 1, 1970

March 31, 2034

Students in {this.props.className}

Little Bobby Tables

Suzie CSS

Edison

      <AddPoll />

  }

}

const AddPoll = () => {
  // add to state

  // post to DB

  return (

Add new poll

      <button>Thumbs Check</button>
      <button>Multiple Choice</button>

  )
};

module.exports = LessonData;

Remove props to AddPoll component

Remove props to AddPoll component


/* eslint no-unused-vars: 0 */

/***********************************/
/** data-calculate-row-identities **/
/***********************************/
gridState.processors['data-calculate-row-identities'] = {
    watches: ['data', 'columns'],
    runs: function (options) {
        if (!options.model.ui.selectable) {
            return;
        }
        if (options.model.logging) {
            console.log('Calculating row identities');
        }

        var identityColumns = options.model.columns.filter(function (col) {
            return col.isIdentity;
        }).sort(function (colA, colB) {
            return colA.id < colB.id ? -1 : 1;
        });

        options.model.data.forEach(function (row) {
            var identity = identityColumns.reduce(function (total, col) {
                return total + '$' + getCellData(row, col);
            }, '');
            row.$identity = identity;
        });
        // todo calculate identities
    }
};

function getCellData(row, col) {
    return row[col.id];
}

/* eslint no-unused-vars: 0 */

/***********************************/
/** data-calculate-row-identities **/
/***********************************/
gridState.processors['data-calculate-row-identities'] = {
    watches: ['data', 'columns'],
    runs: function (options) {
        if (!options.model.ui.selectable) {
            return;
        }
        if (options.model.logging) {
            console.log('Calculating row identities');
        }

        var identityColumns = options.model.columns.filter(function (col) {
            return col.isIdentity;
        }).sort(function (colA, colB) {
            return colA.id < colB.id ? -1 : 1;
        });

        options.model.data.forEach(function (row) {
            var identity = identityColumns.reduce(function (total, col) {
                return total + '_' + getCellData(row, col);
            }, '');
            row.$identity = identity.replace(/[\s\.\@\+\-\|]/g, "");
        });
        // todo calculate identities
    }
};

function getCellData(row, col) {
    return row[col.id];
}

Change $Identity so that it can be used as part of an html identifier


/* @flow */
import React from 'react';
import { GoogleMap } from 'react-google-maps';
import ScriptjsLoader from 'react-google-maps/lib/async/ScriptjsLoader';
import { latLon } from '../../../types/map';

type Props = {
  spanFullPage: ?boolean,
  defaultCenter: latLon,
};

/** @class Map */
function Map(props : Props) {
  const containerElement = (
    <div
      style={{
        height: '200px',
        ...(props.spanFullPage ? { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, height: '100%', width: '100%' } : {}),
      }}
    />
  );

  const googleMapElement = (
    <GoogleMap
      defaultZoom={15}
      defaultCenter={props.defaultCenter}
    />
  );

  return (
    <ScriptjsLoader
      hostname={'maps.googleapis.com'}
      pathname={'/maps/api/js'}
      query={{ key: process.env.GOOGLE_MAPS_API_KEY, v: '3.0' }}
      loadingElement={
        <div />
      }
      containerElement={containerElement}
      googleMapElement={googleMapElement}
    />
  );
}

export default Map;

/* @flow */
import React from 'react';
import { GoogleMap } from 'react-google-maps';
import ScriptjsLoader from 'react-google-maps/lib/async/ScriptjsLoader';
import { latLon } from '../../../types/map';

type Props = {
  spanFullPage: ?boolean,
  defaultCenter: latLon,
};

/** @class Map */
function Map(props : Props) {
  const containerElement = (
    <div
      style={{
        height: '200px',
        ...(props.spanFullPage ? { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, height: '100%', width: '100%' } : {}),
      }}
    />
  );

  const googleMapElement = (
    <GoogleMap
      defaultZoom={15}
      defaultCenter={props.defaultCenter}
    />
  );

  return (
    <ScriptjsLoader
      hostname={'maps.googleapis.com'}
      pathname={'/maps/api/js'}
      query={{
        key: process.env.GOOGLE_MAPS_API_KEY,
        v: '3.25',
      }}
      loadingElement={
        <div />
      }
      containerElement={containerElement}
      googleMapElement={googleMapElement}
    />
  );
}

export default Map;

Upgrade map from 3.0 to 3.25

Upgrade map from 3.0 to 3.25


/* global angular, console */

(function () {
    'use strict';

    angular
        .module('plotWidget')
        .controller('PlotWidgetController', PlotWidgetController);

    PlotWidgetController.$inject = ['$scope', 'weatherRestService'];

    function PlotWidgetController($scope, weatherRestService) {
        var vm = this;

        init();

        // ####################################################################

        function init() {
            $scope.plotOptions = {
                showRangeSelector: true,
                title: $scope.quantity,
                color: 'rgb(42, 101, 212)',
                gridLineColor: 'rgb(200, 200, 200)',
                rangeSelectorPlotFillColor: '#575df5',
                rangeSelectorPlotStrokeColor: '#676877'
            };
        }

        weatherRestService.data('2014-08-30', '2014-08-31', $scope.quantity)
//        weatherRestService.data(null, null, 'inHumidity')
            .then(function(data) {
            var newData = [];

            for(var i=0, len=data.data.timePoints.length; i<len; ++i) {
                newData.push([new Date(data.data.timePoints[i]), data.data.dataPoints[i]]);
            }

            $scope.plotData = newData;
        });

    }
}());

/* global angular, console */

(function () {
    'use strict';

    angular
        .module('plotWidget')
        .controller('PlotWidgetController', PlotWidgetController);

    PlotWidgetController.$inject = ['$scope', 'weatherRestService'];

    function PlotWidgetController($scope, weatherRestService) {
        var vm = this;

        init();

        // ####################################################################

        function init() {
            $scope.plotOptions = {
                showRangeSelector: true,
                title: $scope.quantity,
                color: 'rgb(42, 101, 212)',
                gridLineColor: 'rgb(200, 200, 200)',
                rangeSelectorPlotFillColor: '#575df5',
                rangeSelectorPlotStrokeColor: '#676877'
            };
        }

        weatherRestService.data('2014-08-30', '2014-09-30', $scope.quantity)
//        weatherRestService.data(null, null, $scope.quantity)
            .then(function(data) {
            var newData = [],
                conversionFunc = function(v) { return v; };

            if(/temp/i.test($scope.quantity)) {
                conversionFunc = function(v) { return (v-32)/1.8; };
                $scope.plotOptions.ylabel = "Celsius";
            }

            for(var i=0, len=data.data.timePoints.length; i<len; ++i) {
                newData.push([new Date(data.data.timePoints[i]), conversionFunc(data.data.dataPoints[i])]);
            }

            $scope.plotData = newData;
        });

    }
}());

Convert temperatures to degrees Celsius.


'use strict';

// Configuring the Groups module
angular.module('groups').run(['Menus', function (Menus) {
	// Add the dropdown manage groups
	Menus.addSubMenuItem('topbar', 'admin', {
		title: 'Groupes',
		state: 'admin.groups',
		roles: ['admin']
	});
}]);

'use strict';

// Configuring the Groups module
angular.module('groups').run(['Menus', function (Menus) {
	// Add the dropdown manage groups
	Menus.addSubMenuItem('topbar', 'admin', {
		title: 'Groupes',
		state: 'admin.groups.list',
		roles: ['admin']
	});
}]);

Fix routing bug in groups module

Fix routing bug in groups module


/**
 * The Logging layer module.
 *
 * @return LoggingLayer class (extends CartoDBLayerClass)
 */
define([
  'abstract/layer/CartoDBLayerClass',
], function(CartoDBLayerClass) {

  'use strict';

  var LoggingLayer = CartoDBLayerClass.extend({

    options: {
      sql: 'SELECT \'logging\' as tablename, cartodb_id, the_geom_webmercator, company, country, area_ha, name, source,status, \'{tableName}\' AS layer, {analysis} AS analysis FROM {tableName}',
      infowindow: true,
      interactivity: 'cartodb_id, tablename, name, company, country, area_ha, analysis',
      analysis: true
    }

  });

  return LoggingLayer;

});

/**
 * The Logging layer module.
 *
 * @return LoggingLayer class (extends CartoDBLayerClass)
 */
define([
  'abstract/layer/CartoDBLayerClass',
], function(CartoDBLayerClass) {

  'use strict';

  var LoggingLayer = CartoDBLayerClass.extend({

    options: {
      sql: 'SELECT \'logging\' as tablename, cartodb_id, the_geom_webmercator, company, country, permit_num, nat_origin, area_ha, name, \'{tableName}\' AS layer, {analysis} AS analysis FROM {tableName}',
      infowindow: true,
      interactivity: 'cartodb_id, tablename, name, company, country, permit_num, nat_origin, area_ha, analysis',
      analysis: true
    }
/*

sql: 'SELECT \'logging\' as tablename, cartodb_id, the_geom_webmercator, company, country, area_ha, name, source,status, \'{tableName}\' AS layer, {analysis} AS analysis FROM {tableName}',
      infowindow: true,
      interactivity: 'cartodb_id, tablename, name, company, country, area_ha, analysis',

      */
  });

  return LoggingLayer;

});

Change data logging origin fix revert

Change data logging origin fix revert