import React, { Component, PropTypes } from "react"
import cx from "classnames"

import Avatar from "../Avatar"

export default class Contributors extends Component {

  static propTypes = {
    author: PropTypes.string.isRequired,
    commits: PropTypes.string,
    size: PropTypes.string,
  }

  render() {
    const {
      author,
      commits,
      size,
    } = this.props

    return (
      <div
        key={ author }
        className={ cx(
          "putainde-Contributor",
          "r-Tooltip",
          "r-Tooltip--bottom",
          "r-Tooltip--allowNewLines"
        ) }
        data-r-tooltip={ [
          author,
          `(${ commits } commit${ commits > 1 ? "s" : "" })`,
        ].join("\n") }
      >
        <Avatar
          author={ author }
          className={
            `putainde-Contributor-avatar${ size ? `--${ size }` : "" }`
          }
        />
      </div>
    )
  }
}

import React, { Component, PropTypes } from "react"
import cx from "classnames"

import Avatar from "../Avatar"

export default class Contributor extends Component {

  static propTypes = {
    author: PropTypes.string.isRequired,
    commits: PropTypes.number,
    size: PropTypes.string,
  }

  render() {
    const {
      author,
      commits,
      size,
    } = this.props

    return (
      <div
        key={ author }
        className={ cx(
          "putainde-Contributor",
          "r-Tooltip",
          "r-Tooltip--bottom",
          "r-Tooltip--allowNewLines"
        ) }
        data-r-tooltip={ [
          author,
          `(${ commits } commit${ commits > 1 ? "s" : "" })`,
        ].join("\n") }
      >
        <Avatar
          author={ author }
          className={
            `putainde-Contributor-avatar${ size ? `--${ size }` : "" }`
          }
        />
      </div>
    )
  }
}

Fix minor issue with Contributor component


//
// Image loader class.
//

var DziViewer = DziViewer || {};

DziViewer.Loader = OcrJs.Base.extend({
    init: function(options) {
        this._super();
        this.options = {
            delay: null,
        };
        $.extend(this.options, options);

        this._waiting = 0;

        this._listeners = {
            loadedImage: [],
            loadedAll: [],
        };
    },

    loadImage: function(path, callback) {
        var self = this;

        var img = new Image();
        img.onload = function(e) {
            if (self.options.delay) {
                setTimeout(function() {
                    callback(path, img);
                }, self.options.delay);
            } else {
                callback(path, img);
            }
        };
        img.src = path;
    },

    loadImages: function(paths_callbacks) {
        var self = this;
        this._waiting = paths_callbacks.length;
        if (this._waiting == 0) {
            this.trigger("loadedAll");
            return;
        }

        $.each(paths_callbacks, function(i, obj) {
            var img = new Image();
            img.onload = function(e) {
                setTimeout(function() {
                    obj.callback.call(this, obj.path, img);
                    self._waiting--;
                    self.trigger("loadedImage", img, obj.path);
                    if (self._waiting == 0)
                        self.trigger("loadedAll");
                }, self.options.delay);
            }
            img.src = obj.path;
        });
    },
});

//
// Image loader class.
//

var DziViewer = DziViewer || {};

DziViewer.Loader = OcrJs.Base.extend({
    init: function(options) {
        this._super();
        this.options = {
            delay: null,
        };
        $.extend(this.options, options);

        this._waiting = 0;
        this._cachebuster = (new Date()).getTime();
        this._listeners = {
            loadedImage: [],
            loadedAll: [],
        };
    },

    loadImage: function(path, callback) {
        var self = this;

        var img = new Image();
        img.onload = function(e) {
            if (self.options.delay) {
                setTimeout(function() {
                    callback(path, img);
                }, self.options.delay);
            } else {
                callback(path, img);
            }
        };
        img.src = path + "?" + this._cachebuster;
    },

    loadImages: function(paths_callbacks) {
        var self = this;
        this._waiting = paths_callbacks.length;
        if (this._waiting == 0) {
            this.trigger("loadedAll");
            return;
        }

        $.each(paths_callbacks, function(i, obj) {
            var img = new Image();
            img.onload = function(e) {
                setTimeout(function() {
                    obj.callback.call(this, obj.path, img);
                    self._waiting--;
                    self.trigger("loadedImage", img, obj.path);
                    if (self._waiting == 0)
                        self.trigger("loadedAll");
                }, self.options.delay);
            }
            img.src = obj.path;
        });
    },
});

Add a cache-busting string to image urls. Not sure this is working though.


class BCBProcess extends CommonProcess {
  constructor() {
    super({
      name: `${Project.NAME} Process`
    });

    this.initProcess();
  }

  initProcess() {
    this.initPopover();
  }

  initPopover() {
    {
      new PopoverController({
        name: 'ID Popover',
        selector: '#login-id-help',
        help: 'ID を入力してください。'
      });
      new PopoverController({
        name: 'Password Popover',
        selector: '#login-password-help',
        help: 'パスワード を入力してください。'
      });
      new PopoverController({
        name: 'Login Check Popover',
        selector: '#login-check-help',
        help: '共有デバイスでは設定に注意してください。'
      });
    }
  }
}

class BCBProcess extends CommonProcess {
  constructor() {
    super({
      name: `${Project.NAME} Process`
    });

    this.initProcess();
  }

  initProcess() {
    this.initPopover();
  }

  initPopover() {
    {
      new PopoverController({
        name: 'ID Popover',
        selector: '#login-id-help',
        help: 'ID を入力してください。'
      });
      new PopoverController({
        name: 'Password Popover',
        selector: '#login-password-help',
        help: 'パスワード を入力してください。'
      });
      new PopoverController({
        name: 'Login Check Popover',
        selector: '#login-check-help',
        help: '共有デバイスでは設定に注意してください。'
      });
      new PopoverController({
        name: 'Logined ID Popover',
        selector: '#logined-id-help',
        help: 'ログインしている ID です。'
      });
    }
  }
}

Add Logined ID Popover in BCBProcess


var tliRegister = tliRegister || {};

tliRegister.discountCodes = function() {

	var init = function() {
		initCodeItemEnabling();
	},

	initCodeItemEnabling = function() {
		$('#discount-code-items input:checkbox')
			.change(handlePricingItemChange)
			.each(handlePricingItemChange);
	},

	handlePricingItemChange = function() {
		var row = $(this).closest('tr'),
			chekbox = this;

		$('input[type=number]', row)
			.prop('disabled', !$(chekbox).prop('checked'))
			.each(function() {
				if (!$(chekbox).prop('checked')) {
					$(this).val($(this).attr('data-value-original'));
				}
			});
	}

	return {
		init: init
	}

}();

var tliRegister = tliRegister || {};

tliRegister.discountCodes = function() {

	var init = function() {
		initCodeItemEnabling();
	},

	initCodeItemEnabling = function() {
		$('#discount-code-items input:checkbox')
			.change(handlePricingItemChange)
			.each(handlePricingItemChange);
	},

	handlePricingItemChange = function() {
		var row = $(this).closest('tr'),
			chekbox = this;

		$('input[type=number]', row)
			.prop('disabled', !$(chekbox).prop('checked'))
			.each(function() {
				if (!$(chekbox).prop('checked')) {
					$(this).val($(this).attr('data-value-original'));
					$('.has-error', row).each(function() {
						$(this).children('.help-block').slideUp(function() {
							$(this).remove();
						});
						$(this).removeClass('has-error');
					});
				}
			});
	}

	return {
		init: init
	}

}();

Reset validation status on unchecking item


var Roadmap = require('./roadmapModel.js');

module.exports = {

  createRoadmap : function (req, res, next) {
    var newRoadmap = req.body;
    Roadmap(newRoadmap).save()
      .then(function(dbResults){
        res.status(201).json(dbResults);
      })
      .catch(function(err){
        next(err);
      });
  },
  getRoadmaps : function (req, res, next) {
    Roadmap.find({})
      .then(function(dbResults){
        res.status(200).json(dbResults);
      })
      .catch(function(err){
        next(err);
      });
  },
  getRoadmapByID : function (req, res, next) {

  },
  updateRoadmap : function (req, res, next) {

  },
  deleteRoadmap : function (req, res, next) {

  }

};

var Roadmap = require('./roadmapModel.js'),
    handleError = require('../../util.js').handleError;

module.exports = {

  createRoadmap : function (req, res, next) {
    var newRoadmap = req.body;
    Roadmap(newRoadmap).save()
      .then(function(dbResults){
        res.status(201).json(dbResults);
      })
      .catch(handleError(next));
  },
  getRoadmaps : function (req, res, next) {
    Roadmap.find({})
      .then(function(dbResults){
        res.status(200).json(dbResults);
      })
      .catch(handleError(next));
  },
  getRoadmapByID : function (req, res, next) {
    var _id = req.params.roadmapID;
    Roadmap.findById(_id)
      .then(function(dbResults){
        res.json(dbResults);
      })
      .catch(handleError(next));
  },
  updateRoadmap : function (req, res, next) {

  },
  deleteRoadmap : function (req, res, next) {

  }

};

Refactor .catch's to use util.handleError


/*
Copyright 2016 Google Inc.

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

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

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

  // TODO - 3.1: Add install and activate event listeners

  // TODO - 3.3: Add a comment to change the service worker

  // TODO - 4: Add fetch listener

})();

/*
Copyright 2016 Google Inc.

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

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

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

  // TODO - 3.1: Add install and activate event listeners

  self.addEventListener('install', function(event) {
  console.log('Service worker installing...');
  // TODO 3.4: Skip waiting
  });

  // TODO - 3.3: Add a comment to change the service worker

  // TODO - 4: Add fetch listener

})();


var Activity = require('./activity');
var Readable = require('stream').Readable;
var util = require('util');

/**
 * Readable stream that emits event objects from the github events api for a
 * given user
 */
function ActivityStream() {
   this.eventsPromise = Activity.get();
   this.eventIndex = 0;
   Readable.call(this, {objectMode:true});
}
util.inherits(ActivityStream, Readable);

ActivityStream.prototype._read = function () {
   pushNextEvent(this);
};

function pushNextEvent(stream) {
   stream.eventsPromise.done(function(events) {
      if (!events) {
         return stream.push(null);
      }
      if (!events[stream.eventIndex]) {
         stream.eventsPromise = events.nextPage();
         stream.eventIndex = 0;
         pushNextEvent(stream);
      }
      stream.push(events[stream.eventIndex]);
      stream.eventIndex++;
   });
}

module.exports = ActivityStream;

var Activity = require('./activity');
var Readable = require('stream').Readable;
var util = require('util');

/**
 * Readable stream that emits event objects from the github events api for a
 * given user
 */
function ActivityStream() {
   this.eventsPromise = Activity.get();
   this.eventIndex = 0;
   Readable.call(this, {objectMode:true});
}
util.inherits(ActivityStream, Readable);

ActivityStream.prototype._read = function () {
   pushNextEvent(this);
};

function pushNextEvent(stream) {
   stream.eventsPromise.done(function(events) {
      if (!events) {
         return stream.push(null);
      }
      // If we're at the end of the current page of events,
      // load some more.
      if (!events[stream.eventIndex]) {
         stream.eventsPromise = events.nextPage();
         stream.eventIndex = 0;
         pushNextEvent(stream);
      } else {
         stream.push(events[stream.eventIndex]);
         stream.eventIndex++;
      }
   });
}

module.exports = ActivityStream;

Fix bug with repeated events


import { remote } from 'electron';
import isPlaying from './../reducers/player';
import { createStore } from 'redux';

// TODO: Make root reducer later
// import { combineReducers } from 'react-redux';

export default () => {
  if (remote.getGlobal('process').env.NODE_ENV === 'development') {
    return createStore(isPlaying,
      window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
  } else {
    return createStore(isPlaying);
  }
};

import { remote } from 'electron';
import isPlaying from './../reducers/player';
import { createStore } from 'redux';

// TODO: Make root reducer later
// import { combineReducers } from 'react-redux';

export default () => {
  if (remote.process.env.NODE_ENV === 'development') {
    return createStore(isPlaying,
      window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
  } else {
    return createStore(isPlaying);
  }
};

Use cached version of process object


import find from 'lodash.find';
import composedFetch from '../composedFetch.js';

export const sourcePostalPoint = id => composedFetch(id)
  .then(data => {
    const result = find(data.events, { key: `received.domestic-corner` });
    return result.location.en;
  })
  .catch(e => console.error(e));

export const destinationPostalPoint = id => composedFetch(id)
  .then(data => data.deliveryPoint.name.en)
  .catch(e => console.error(e));

export const destinationAsAddress = id => composedFetch(id)
  .then(data => {
    const obj = data.deliveryPoint;
    return `${obj.street.en} ${obj.streetNumber.en}, ${obj.postcode.en} ${obj.municipality.en}`;
  })
  .catch(e => console.error(e));

export const openingHours = (id, day) => {
  if (!day) throw new Error(`Please specify a day`);

  return composedFetch(id)
    .then(data => {
      const obj = find(
        data.deliveryPoint.openingSchedules,
        { dayOfTheWeek: day.toUpperCase() }
      );

      return obj.openingHours[0];
    })
    .catch(e => console.error(e));
};

export const destinationCoordinate = id => composedFetch(id)
  .then(data => {
    return {
      latitude: data.deliveryPoint.latitude,
      longitude: data.deliveryPoint.longitude,
    };
  })
  .catch(e => console.error(e));

import find from 'lodash.find';
import composedFetch from '../composedFetch.js';

export const sourcePostalPoint = id => composedFetch(id)
  .then(data => {
    const result = find(data.events, { key: `received.domestic-corner` });
    return result.location.en;
  })
  .catch(e => console.error(e));

export const destinationPostalPoint = id => composedFetch(id)
  .then(data => data.deliveryPoint.name.en)
  .catch(e => console.error(e));

export const destinationAsAddress = id => composedFetch(id)
  .then(data => {
    const obj = data.deliveryPoint;
    return `${obj.street.en} ${obj.streetNumber.en}, ${obj.postcode.en} ${obj.municipality.en}`;
  })
  .catch(e => console.error(e));

export const openingHours = (id, day) => {
  if (!day) throw new TypeError(`Please specify a day`);

  return composedFetch(id)
    .then(data => {
      const obj = find(
        data.deliveryPoint.openingSchedules,
        { dayOfTheWeek: day.toUpperCase() }
      );

      return obj.openingHours[0];
    })
    .catch(e => console.error(e));
};

export const destinationCoordinate = id => composedFetch(id)
  .then(data => {
    return {
      latitude: data.deliveryPoint.latitude,
      longitude: data.deliveryPoint.longitude,
    };
  })
  .catch(e => console.error(e));

Throw TypeError instead of Error


'use strict';

angular.module('arachne.controllers')

    .controller('SearchFormController', ['$scope', '$location', 'arachneSettings', '$http', function ($scope, $location, arachneSettings, $http) {

        $scope.search = function (fq) {
            if ($scope.q) {
                var url = '/search?q=' + $scope.q;
                if (fq) url += "&fq=" + fq;
                $scope.q = null;
                $location.url(url);
            }
        };

        $scope.getSuggestions = function (value) {
            return $http.get(arachneSettings.dataserviceUri + '/suggest?q=' + value)
                .then(function (response) {
                    return response.data.suggestions;
                });
        };
    }
    ]);

'use strict';

angular.module('arachne.controllers')

    .controller('SearchFormController', ['$scope', '$location', 'arachneSettings', '$http', function ($scope, $location, arachneSettings, $http) {

        $scope.search = function (fq) {
            if ($scope.q) {
                var url = '/search?q=' + $scope.q;
                if (fq) url += "&fq=" + fq;
                $scope.q = null;
                $location.url(url);
            }
        };

        $scope.getSuggestions = function (value) {
            var promise = $http.get(arachneSettings.dataserviceUri + '/suggest?q=' + value)
                .then(function (response) {
                    return response.data.suggestions;
                });
            if(promise != 'undefined') return promise;
        };
    }
    ]);

Revert "Revert "added promise check""


'use strict';

module.exports = function (app) {
    app.route('GET /hello/(<name>/)', 'hello_page');
};

'use strict';

module.exports = function (app) {
    app.route('GET /hello/(<name>/) s', 'hello_page');
};

Add append-slash modifier to hello example route


/*global module:false*/
module.exports = function (grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        exec: {
            removeDocs: "rm -rf docs/*",
            createDocs: 'coddoc -f multi-html -d ./lib --dir ./docs'
        },

        jshint: {
            file: "./lib/*.js",
            options: {
                jshintrc: '.jshintrc'
            }
        },

        it: {
            all: {
                src: 'test/**/*.test.js',
                options: {
                    timeout: 3000, // not fully supported yet
                    reporter: 'spec'
                }
            }
        },
        'gh-pages': {
            options: {
                base: 'docs'
            },
            src: ['**']
        }
    });

    // Default task.
    grunt.registerTask('default', ['jshint', 'it', "exec"]);
    grunt.loadNpmTasks('grunt-it');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-gh-pages');

    grunt.registerTask("benchmark", "run benchmarks", function () {
        var done = this.async();
        require("./benchmark/benchmark")(function (err) {
            if (err) {
                grunt.log.error(err.stack);
                done(false)
            } else {
                grunt.log.ok("Done running benchmarks");
                done();
            }
        });
    });

};

/*global module:false*/
module.exports = function (grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        exec: {
            removeDocs: "rm -rf docs/*",
            createDocs: 'coddoc -f multi-html -d ./lib --dir ./docs'
        },

        jshint: {
            file: "./lib/*.js",
            options: {
                jshintrc: '.jshintrc',
                reporterOutput: '',
            }
        },

        it: {
            all: {
                src: 'test/**/*.test.js',
                options: {
                    timeout: 3000, // not fully supported yet
                    reporter: 'spec'
                }
            }
        },
        'gh-pages': {
            options: {
                base: 'docs'
            },
            src: ['**']
        }
    });

    // Default task.
    grunt.registerTask('default', ['jshint', 'it', "exec"]);
    grunt.loadNpmTasks('grunt-it');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-gh-pages');

    grunt.registerTask("benchmark", "run benchmarks", function () {
        var done = this.async();
        require("./benchmark/benchmark")(function (err) {
            if (err) {
                grunt.log.error(err.stack);
                done(false)
            } else {
                grunt.log.ok("Done running benchmarks");
                done();
            }
        });
    });

};

Fix grunt errors in node > 6


module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        // contrib-watch
        watch: {
            all: {
                files: ['src/**/*.js', 'lib/**/*.js', 'test/**/*.js', 'Gruntfile.js'],
                tasks: ['test', 'build']
            }
        },
        // contrib-jshint
        jshint: {
            all: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js']
        },
        // contrib-qunit
        qunit: {
            all: 'test/**/*.html'
        },
        // contrib-uglify
        uglify: {
            options: {
                preserveComments: function(node, comment) {
                    // Preserve the license banner
                    return comment.col === 0 && comment.pos === 0;
                }
            },
            all: {
                files: {
                    'src/jquery.countdown.min.js': ['src/jquery.countdown.js']
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');

    // Project tasks
    grunt.registerTask('license', function() {

    });

    grunt.registerTask('test',      ['jshint', 'qunit']);
    grunt.registerTask('build',     ['license', 'uglify']);
    grunt.registerTask('default',   ['test', 'build', 'watch']);
};

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        // contrib-watch
        watch: {
            all: {
                files: ['src/**/*.js', 'lib/**/*.js', 'test/**/*.js', 'Gruntfile.js'],
                tasks: ['test', 'build']
            }
        },
        // contrib-jshint
        jshint: {
            all: ['Gruntfile.js', 'src/jquery.countdown.js', 'test/**/*.js']
        },
        // contrib-qunit
        qunit: {
            all: 'test/**/*.html'
        },
        // contrib-uglify
        uglify: {
            options: {
                preserveComments: function(node, comment) {
                    // Preserve the license banner
                    return comment.col === 0 && comment.pos === 0;
                }
            },
            all: {
                files: {
                    'src/jquery.countdown.min.js': ['src/jquery.countdown.js']
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-uglify');

    // Project tasks
    grunt.registerTask('license', function() {

    });

    grunt.registerTask('test',      ['jshint', 'qunit']);
    grunt.registerTask('build',     ['license', 'uglify']);
    grunt.registerTask('default',   ['test', 'build', 'watch']);
};

Remove lint from minified version


module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({

    // Project settings
    simg: {
      // configurable paths
      scriptPath: 'src',
      distPath: 'dist',
      bowerPath: 'lib',
      testPath: 'test'
    },

    pkg: grunt.file.readJSON('package.json'),

    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
        report: 'gzip'
      },
      build: {
        src: [
            '<%= simg.scriptPath %>/simg.js'
        ],
        dest: '<%= simg.distPath %>/simg.min.js'
      }
    },

    jshint: {
      options: {
          jshintrc: true
      },
      all: [
        '<%= simg.scriptPath %>/*.js'
      ]
    }
  });

  // Load tasks
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');

  grunt.registerTask('default', ['uglify']);
  grunt.registerTask('lint', ['jshint']);
};

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({

    // Project settings
    simg: {
      // configurable paths
      scriptPath: 'src',
      distPath: 'dist',
      bowerPath: 'lib',
      testPath: 'test'
    },

    pkg: grunt.file.readJSON('package.json'),

    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
        report: 'min'
      },
      build: {
        src: [
            '<%= simg.scriptPath %>/simg.js'
        ],
        dest: '<%= simg.distPath %>/simg.min.js'
      }
    },

    jshint: {
      options: {
          jshintrc: true
      },
      all: [
        '<%= simg.scriptPath %>/*.js'
      ]
    }
  });

  // Load tasks
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');

  grunt.registerTask('default', ['uglify']);
  grunt.registerTask('lint', ['jshint']);
};

Fix uglify script no longer running.


/*globals Downsampler,LoadSlicer*/

var MeritTransformator = (function () {
    'use strict';

    function transformSerieValues(serie) {
        if (this.scope.dateSelect.val() > 0) {
            return LoadSlicer.slice(serie, this.scope.dateSelect.val());
        } else {
            return Downsampler.downsample(serie);
        }
    }

    MeritTransformator.prototype = {
        transform: function () {
            this.data.forEach(function(serie) {
                serie.values = transformSerieValues.call(this, serie);
            }.bind(this));

            return this.data;
        }
    };

    function MeritTransformator (scope, data) {
        this.scope = scope;
        this.data  = $.extend(true, [], data);
    }

    return MeritTransformator;
}());

/*globals Downsampler,LoadSlicer*/

var MeritTransformator = (function () {
    'use strict';

    function transformSerieValues(serie) {
        if (this.scope.dateSelect.val() > 0) {
            return LoadSlicer.slice(serie, this.scope.dateSelect.val());
        } else {
            return Downsampler.downsample(serie);
        }
    }

    MeritTransformator.prototype = {
        transform: function () {
            return this.data.map(function(serie) {
                return $.extend(
                    {}, serie,
                    { values: transformSerieValues.call(this, serie) }
                );
            }.bind(this));
        }
    };

    function MeritTransformator (scope, data) {
        this.scope = scope;
        this.data  = data;
    }

    return MeritTransformator;
}());

Clone Merit data as late as possible


$(function(){
  function checkOverflow(){
    if($(window).width() >= "768"){
      if($(".related-positioning").length !== 0){
        var viewPort = $(window).height();
        var relatedBox = $(".related").height();
        var boxOffset = $(".related-positioning").position().top;
        if(relatedBox > (viewPort - boxOffset)){
          $(".related-positioning").css("position", "absolute");
          return true;
        } else {
          $(".related-positioning").css("position", "fixed");
          return false;
        }
      }
    }
    return false;
  }
  if(!checkOverflow()){
    window.GOVUK.stopScrollingAtFooter.addEl($('.related-positioning'), $('#related .inner').height());
  }
});

$(function(){
  function checkOverflow(){
    var $related = $(".related-positioning");
    if($related.length !== 0 && $related.css('position') == 'fixed') {
      var viewPort = $(window).height();
      var relatedBox = $(".related").height();
      var boxOffset = $related.position().top;
      if(relatedBox > (viewPort - boxOffset)){
        $related.css("position", "absolute");
        return true;
      } else {
        $related.css("position", "fixed");
        return false;
      }
    }

    return false;
  }

  if(!checkOverflow()){
    window.GOVUK.stopScrollingAtFooter.addEl($('.related-positioning'), $('#related .inner').height());
  }
});

Fix related box on tablet view


angular.module( 'App.Views' ).config( function( $stateProvider )
{
	$stateProvider.state( 'forums.topics.view', {
		url: '/f/:topicSlug/:topicId',
		controller: 'Forums.TopicCtrl',
		controllerAs: 'topicCtrl',
		templateUrl: '/app/views/forums/topics/view/view.html',
	} );
} );

angular.module( 'App.Views' ).config( function( $stateProvider )
{
	$stateProvider.state( 'forums.topics.view', {
		url: '/f/:topicSlug/:topicId',
		controller: 'Forums.Topics.ViewCtrl',
		controllerAs: 'viewCtrl',
		templateUrl: '/app/views/forums/topics/view/view.html',
	} );
} );

Fix forum topic controller name


var Client = require('node-rest-client').Client,
    clientOptions = {
      connection: {
        rejectUnauthorized: false,
        requestCert: true,
      }
    },
    client = new Client(clientOptions),
    tokenArgs = {
      'data': {
        'grant_type':'client_credentials',
        'client_id':'foo',
        'client_secret':'bar',
        'scope':'*'
      },
      headers: {
        'Content-Type':'application/json'
      }
    };

client.post('https://api.fronter.com/oauth/token', tokenArgs, function (data, response) {
    console.log(data);

    var clientArgs = {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': data['token_type'] + ' ' + data['access_token']
      }
    };

    client.get('https://api.fronter.com/planning/users/12345', clientArgs, function (data, response) {
      console.log(data);
    }).on('error', function (err) {
      console.log('err: ', err);
    });

}).on('error', function (err) {
  console.log('err: ', err);
});

var Client = require('node-rest-client').Client,
    clientOptions = {
      connection: {
        rejectUnauthorized: true,
        requestCert: true,
      }
    },
    client = new Client(clientOptions),

    token = process.argv[2],

    params = {
      headers: {
        'Content-Type' : 'application/json',
        'Authorization' : 'bearer ' + token
      }
    };

client.get('https://api.fronter.com/planning/users/12345', params, function (data, response) {
  console.log(data);
}).on('error', function (err) {
  console.log('err: ', err);
});

client.on('error', function (err) {
 console.error(' client error : ', err);
});

Use cli parameter for token.


'use babel';

import { dirname } from 'path';
import { existsSync, isFileSync, makeTreeSync, moveSync, statSync } from 'fs-plus';

/*
  code pulled from:
  https://github.com/atom/tree-view/blob/492e344149bd42755d90765607743173bb9b7c0a/lib/move-dialog.coffee
*/

function isNewPathValid(previousPath, nextPath) {
  if (!isFileSync(nextPath)) return true;

  /*
  New path exists so check if it points to the same file as the initial
  path to see if the case of the file name is being changed on a on a
  case insensitive filesystem.
  */
  const oldStat = statSync(previousPath);
  const newStat = statSync(nextPath);
  const haveSamePath = previousPath.toLowerCase() === nextPath.toLowerCase();
  const haveSameDev = oldStat.dev === newStat.dev;
  const haveSameIno = oldStat.ino === newStat.ino;

  return !(haveSamePath && haveSameDev && haveSameIno);
}

export default function renameFile(previousPath, nextPath) {
  if (!isNewPathValid(previousPath, nextPath)) return false;
  const directoryPath = dirname(nextPath);
  try {
    if (!existsSync(directoryPath)) {
      makeTreeSync(directoryPath);
    }
    moveSync(previousPath, nextPath);
    return true;
  } catch (e) {
    return false;
  }
}

'use babel';

import { isFileSync, moveSync, statSync } from 'fs-plus';

/*
  code pulled from:
  https://github.com/atom/tree-view/blob/492e344149bd42755d90765607743173bb9b7c0a/lib/move-dialog.coffee
*/

function isNewPathValid(previousPath, nextPath) {
  if (!isFileSync(nextPath)) return true;

  /*
  New path exists so check if it points to the same file as the initial
  path to see if the case of the file name is being changed on a on a
  case insensitive filesystem.
  */
  const oldStat = statSync(previousPath);
  const newStat = statSync(nextPath);
  const haveSamePath = previousPath.toLowerCase() === nextPath.toLowerCase();
  const haveSameDev = oldStat.dev === newStat.dev;
  const haveSameIno = oldStat.ino === newStat.ino;

  return !(haveSamePath && haveSameDev && haveSameIno);
}

export default function renameFile(previousPath, nextPath) {
  if (!isNewPathValid(previousPath, nextPath)) return false;

  try {
    moveSync(previousPath, nextPath);
    return true;
  } catch (e) {
    atom.notifications.addError(e.message, {
      dismissable: true,
    });
    return false;
  }
}

Remove unnecessary mkdirp before moving a file, since fs-plus handles it


var PreviewBoard = function() {
  this.board = generateEmptyBoard();
  this.tetrinimo;
}
PreviewBoard.prototype.blit = function() {
  this.board = generateEmptyBoard();

  var blockX, blockY;
  for(var block in this.tetrinimo.blocks) {
    blockX = this.tetrinimo.blocks[block].x - 4;
    blockY = this.tetrinimo.blocks[block].y;
    this.board[blockY][blockX] = this.tetrinimo.element;
  }
};

var generateEmptyBoard = function() {
  emptyBoard = new Array;
  for(var y = 0; y < 4; y++) {
    var row = new Array;
    for(var x = 0; x < 4; x++) {
      row.push(0);
    }
    emptyBoard.push(row);
  }
  return emptyBoard;
}

var PreviewBoard = function() {
  this.board = generateEmptyBoard();
  this.tetrinimo = null;
}
PreviewBoard.prototype.blit = function() {
  this.board = generateEmptyBoard();

  var blockX, blockY;
  for(var block in this.tetrinimo.blocks) {
    blockX = this.tetrinimo.blocks[block].x - 4;
    blockY = this.tetrinimo.blocks[block].y;
    this.board[blockY][blockX] = this.tetrinimo.element;
  }
};

var generateEmptyBoard = function() {
  emptyBoard = new Array;
  for(var y = 0; y < 4; y++) {
    var row = new Array;
    for(var x = 0; x < 4; x++) {
      row.push(0);
    }
    emptyBoard.push(row);
  }
  return emptyBoard;
}

Update preview board to initialize with a null tetrinimo


'use babel';

import React from 'react';
import {Transformime} from 'transformime';
import {
	StreamTransformer,
	TracebackTransformer,
	MarkdownTransformer,
}
from 'transformime-jupyter-transformers';

export default class DisplayArea extends React.Component {

  constructor(props) {
      super(props);
    this.transformer = new Transformime();
    this.transformer.transformers.push(new StreamTransformer());
    this.transformer.transformers.push(new TracebackTransformer());
      this.transformer.transformers.push(new MarkdownTransformer());
  }

  componentDidMount() {
    this.setupDOM();
  }

  // transformime-generated HTML is in outputs
  // after every render, fill our element with that HTML
  componentDidUpdate() {
    let outputs = this.props.data.get('outputs');
    let outputHTML = outputs.join('');
    this.el.innerHTML = outputHTML;
  }

  render() {
    return (
      <div className="cell-display-area">
      </div>
    );
  }

  setupDOM() {
    let container = React.findDOMNode(this);
    let outputNode = document.createElement('div');
    outputNode.style.backgroundColor = 'white';
    this.shadow = container.createShadowRoot();
    this.shadow.appendChild(outputNode);
    this.document = this.shadow.ownerDocument;
    this.el = outputNode;
  }

}

'use babel';

import React from 'react';
import {Transformime} from 'transformime';
import {
	StreamTransformer,
	TracebackTransformer,
	MarkdownTransformer,
}
from 'transformime-jupyter-transformers';

export default class DisplayArea extends React.Component {

  constructor(props) {
      super(props);
    this.transformer = new Transformime();
    this.transformer.transformers.push(new StreamTransformer());
    this.transformer.transformers.push(new TracebackTransformer());
      this.transformer.transformers.push(new MarkdownTransformer());
  }

  componentDidMount() {
    this.setupDOM();
  }

  // transformime-generated HTML is in outputs
  // after every render, fill our element with that HTML
  componentDidUpdate() {
    let outputs = this.props.data.get('outputs');
    let outputHTML = outputs.join('');
    this.el.innerHTML = outputHTML;
  }

  render() {
    return (
      <div className="cell-display-area native-key-bindings" tabIndex="-1">
      </div>
    );
  }

  setupDOM() {
    let container = React.findDOMNode(this);
    let outputNode = document.createElement('div');
    outputNode.style.backgroundColor = 'white';
    this.shadow = container.createShadowRoot();
    this.shadow.appendChild(outputNode);
    this.document = this.shadow.ownerDocument;
    this.el = outputNode;
  }

}

Enable copy on cell output


import {createReducer} from "common/utils/reducerUtils";

const initialState = {
    name : "Black Widow Company",
    affiliation : "wd",
};

export default createReducer(initialState, {

});

import {createReducer} from "common/utils/reducerUtils";

import {DATA_LOADED} from "features/tools/toolConstants";

const initialState = {
    name : "N/A",
    affiliation : "",
};

function dataLoaded(state, payload) {
    const {unit} = payload;

    return unit;
}

export default createReducer(initialState, {
    [DATA_LOADED] : dataLoaded,
});

Load unit details from sample data


/*!
 * thought <https://github.com/nknapp/thought>
 *
 * Copyright (c) 2015 Nils Knappmeier.
 * Released under the MIT license.
 */
var exec = require('./utils/exeq')
var semver = require('semver')

module.exports = function () {
  return exec('npm', ['--version'])
    .then(function (stdio) {
      if (semver.lt(stdio[0], '2.13.0')) {
        throw new Error('npm<2.13.0 will not execute the `version`-script in your package.json.\n' +
          'Please upgrade to at least 2.13.0.')
      } else {
        // eslint-disable-next-line no-console
        console.log('npm@' + stdio.trim() + ': OK')
      }
    })
}

/*!
 * thought <https://github.com/nknapp/thought>
 *
 * Copyright (c) 2015 Nils Knappmeier.
 * Released under the MIT license.
 */
var exec = require('./utils/exeq')
var semver = require('semver')

module.exports = function () {
  return exec('npm', ['--version'])
    .then(function (stdio) {
      if (semver.lt(stdio[0], '2.13.0')) {
        throw new Error('npm<2.13.0 will not execute the `version`-script in your package.json.\n' +
          'Please upgrade to at least 2.13.0.')
      } else {
        // eslint-disable-next-line no-console
        console.log('npm@' + stdio[0].trim() + ': OK')
      }
    })
}

Fix removal of q (2)


function matchMaker(userList) {
    var likeUsers = [];
    userList.unshift(userList.pop());
    for (var i = 1; i < userList.length; i++) {
        var likenessCounter = 0;
        var j = 1;
        while (j <= 4) {
            if (userList[0][j] == userList[i][j]) {
                likenessCounter++;
            }
            j++;
        }
        if (likenessCounter === 4) {
            likeUsers.push(userList[i]);
        }
    }
    return likeUsers;
};

var jose = {0: 'Jose', 1: 'tuesday', 2: '3 AM', 3: 'anytime fitness', 4: 'legs'};
var brady = {0: 'Brady',1: 'tuesday', 2: '3 AM', 3: 'anytime fitness', 4: 'legs'};
var chonson = {0: 'Chonson', 1: 'tuesday', 2: '5 AM', 3: 'anytime fitness', 4: 'legs'};
var jabroni = {0: 'Jabroni', 1: 'tuesday', 2: '5 AM', 3: 'anytime fitness', 4: 'legs'};
var users = [jose, brady, chonson, jabroni];

// Remove user from [users]
// Put into its own array
// Compare that with every entry in [users]
// Put user back into [users] after search

Add comments for probable refactor


// web analytics configuration
module.exports = {
  //ANALYTICS SETTINGS
  google: {
    enabled: true,
    key: 'UA-48605964-17'
  },
  piwik: {
    enabled: false,
    host: '',
    key: ''
  },
  dap: {
    enabled: true,
    source: 'https://analytics.usa.gov/dap/dap.min.js'
  }
};

// web analytics configuration
module.exports = {
  //ANALYTICS SETTINGS
  google: {
    enabled: true,
    key: 'UA-48605964-17'
  },
  piwik: {
    enabled: false,
    host: '',
    key: ''
  },
  dap: {
    enabled: true,
    source: 'https://dap.digitalgov.gov/Universal-Federated-Analytics-Min.js?agency=GSA'
  }
};

Update to new DAP location


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

(function (aGlobal) {
  var Ci = Components.interfaces;
  var Cc = Components.classes;

  var tbBug766495 = {
    collectDraftFolders: function() {
      var accountManager = MailServices.accounts;
      var allServers = accountManager.allServers;
      for (var i = 0,  maxi = allServers.length; i < maxi; ++i) {
        let currentServer = allServers.queryElementAt(i, Ci.nsIMsgIncomingServer);
        if (currentServer.type == "none")
          continue;

        var folderURI = currentServer.rootFolder.server.serverURI + "/" + "Drafts";
      }
    }
  };

  document.addEventListener("DOMContentLoaded", function onDOMContentLoaded(aEvent) {
    document.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
    tbBug766495.collectDraftFolders();
  });
  aGlobal.tbBug766495 = tbBug766495;
})(this);

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

(function (aGlobal) {
  var Ci = Components.interfaces;
  var Cc = Components.classes;

  var tbBug766495 = {
    collectDraftFolders: function() {
      var accountManager = MailServices.accounts;
      var allServers = accountManager.allServers;
      for (var i = 0,  maxi = allServers.length; i < maxi; ++i) {
        let currentServer = allServers.queryElementAt(i, Ci.nsIMsgIncomingServer);
        if (currentServer.type == "none")
          continue;

        var folderURI = currentServer.rootFolder.server.serverURI + "/" + "Drafts";
      }
    },
    // nsIUrlListener
    createURLListenerForFolder: function createURLListenerForFolder() {
      return {
        OnStartRunningUrl: function OnStartRunningUrl(aURL) {
        },
        OnStopRunningUrl: function OnStopRunningUrl(aURL, aExitCode) {
          this.finished = true;
        },
        folder: aFolder,
        finished: false,
      };
    }
  };

  document.addEventListener("DOMContentLoaded", function onDOMContentLoaded(aEvent) {
    document.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
    tbBug766495.collectDraftFolders();
  });
  aGlobal.tbBug766495 = tbBug766495;
})(this);

Create observer to create listener for imap folders


var util         = require("util")
  , EventEmitter = require("events").EventEmitter

module.exports = (function() {
  var CustomEventEmitter = function(fct) {
    this.fct = fct
  }
  util.inherits(CustomEventEmitter, EventEmitter)

  CustomEventEmitter.prototype.run = function() {
    var self = this

    // delay the function call and return the emitter
    setTimeout(function(){
      self.fct.call(self, self)
    }, 1)

    return this
  }

  CustomEventEmitter.prototype.success =
  CustomEventEmitter.prototype.ok =
  function(fct) {
    this.on('success', fct)
    return this
  }

  CustomEventEmitter.prototype.failure =
  CustomEventEmitter.prototype.fail =
  CustomEventEmitter.prototype.error =
  function(fct) {
    this.on('error', fct)
    return this
  }

  CustomEventEmitter.prototype.done =
  CustomEventEmitter.prototype.complete =
  function(fct) {
    this.on('error', function(err) { fct(err, null) })
        .on('success', function(result) { fct(null, result) })
    return this
  }

  return CustomEventEmitter
})()

var util         = require("util")
  , EventEmitter = require("events").EventEmitter

module.exports = (function() {
  var CustomEventEmitter = function(fct) {
    this.fct = fct;
    var self = this;
    process.nextTick(function() {
      if (self.fct) {
        self.fct.call(self, self)
      }
    }.bind(this));
  }
  util.inherits(CustomEventEmitter, EventEmitter)

  CustomEventEmitter.prototype.run = function() {
    var self = this
    return this
  }

  CustomEventEmitter.prototype.success =
  CustomEventEmitter.prototype.ok =
  function(fct) {
    this.on('success', fct)
    return this
  }

  CustomEventEmitter.prototype.failure =
  CustomEventEmitter.prototype.fail =
  CustomEventEmitter.prototype.error =
  function(fct) {
    this.on('error', fct)
    return this
  }

  CustomEventEmitter.prototype.done =
  CustomEventEmitter.prototype.complete =
  function(fct) {
    this.on('error', function(err) { fct(err, null) })
        .on('success', function(result) { fct(null, result) })
    return this
  }

  return CustomEventEmitter
})()

Remove setTimeout in favor of process.nextTick()


var exports = {};

exports.simplePrint = function(video) {
  return `**${video.title}**`;
};

exports.prettyPrint = function(video) {
  viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return `**${video.title}** by **${video.author}** *(${viewCount} views)*`;
};

exports.prettyPrintWithUser = function(video) {
  return exports.prettyPrint(video) + `, added by <@${video.userId}>`;
};

exports.simplify = function(video) {
  return {
    vid: video.vid,
    title: video.title,
    author: video.author,
    view_count: video.view_count,
  };
};

exports.prettyTime = function(ms) {
  var seconds = ms / 1000;
  var actualSeconds = Math.ceil(seconds % 60);
  var minutes = Math.round((seconds - actualSeconds) / 60);
  return `${minutes}:${actualSeconds}`;
};

module.exports = exports;

var exports = {};

exports.simplePrint = function(video) {
  return `**${video.title}**`;
};

exports.prettyPrint = function(video) {
  viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return `**${video.title}** by **${video.author}** *(${viewCount} views)*`;
};

exports.prettyPrintWithUser = function(video) {
  return exports.prettyPrint(video) + `, added by <@${video.userId}>`;
};

exports.simplify = function(video) {
  return {
    vid: video.vid,
    title: video.title,
    author: video.author,
    view_count: video.view_count,
  };
};

exports.prettyTime = function(ms) {
  var seconds = ms / 1000;
  var actualSeconds = Math.ceil(seconds % 60);
  var paddedSeconds = String('00' + actualSeconds).slice(-2);
  var minutes = Math.round((seconds - actualSeconds) / 60);
  return `${minutes}:${paddedSeconds}`;
};

module.exports = exports;

Fix a formatting issue when formatting time


(function start() {
    "use strict";

    const morgan = require("morgan");
    const express = require("express");
    const login = require(`${__dirname}/routes/login`);
    const app = express();

    /** Use Morgan to log requests */
    app.use(morgan("dev"));

    /** Add static sites */
    app.use(express.static("public"));

    /** Add login Route */
    app.use("/login", login);

    app.listen(process.env.PORT || 8080);
}());

(function start() {
    "use strict";

    const morgan = require("morgan");
    const express = require("express");
    const login = require(`${__dirname}/routes/login`);
    const jwt = require("jsonwebtoken");
    const app = express();

    /** Use Morgan to log requests */
    app.use(morgan("dev"));

    /** Add static sites */
    app.use(express.static("public"));

    app.get("/dashboard", function (req, res) {
        res.send("hello");
    });

    /** Add login Route */
    app.use("/login", login);

    app.use(authFilter);

    app.get("/secure", function (req, res) {
        res.send(`Hello from the secure route!`);
    });
    app.listen(process.env.PORT || 8080);
}());

Add filter to allow access control of endpoints


$(document).ready(function() {

    $('#id_degree_programme_options').change(function() {
        console.log('hello');
        if (this.value === 'extra') {
            $('#unknown_degree').show();
            $('#id_degree_programme').val('');
        } else {
            $('#unknown_degree').hide();
            $('#id_degree_programme').val(this.value);
        }
    });

});

function setProgrammeChoice() {
    const programmeOptionsSelector = $('#id_degree_programme_options option');
    const programmeOptions = Object.values(programmeOptionsSelector).map(option => option.value);

    const currentProgramme = $('#id_degree_programme').val();
    if (programmeOptions.indexOf(currentProgramme) !== -1) {
        $('#id_degree_programme_options').val(currentProgramme);
    } else {
        $('#id_degree_programme_options').val('extra');
        $('#unknown_degree').show();
    }
}

$(document).ready(function() {

    // Set degree choice based on pre-existing data
    setProgrammeChoice();

    $('#id_degree_programme_options').change(function() {
        console.log('hello');
        if (this.value === 'extra') {
            $('#unknown_degree').show();
            $('#id_degree_programme').val('');
        } else {
            $('#unknown_degree').hide();
            $('#id_degree_programme').val(this.value);
        }
    });

});

Set degree choice according to data


'use strict';

before(function(done) {

  // Ensure that 'should' library methods will be
  // available to all tests
  global.should = require('should');
  global.sinon = require('sinon');

  // Start and configure the server
  require('../server');

  // Wait half a second before calling "done" to ensure
  // that server is up and running
  setTimeout(done, 500);

});

'use strict';

before(function(done) {
  // Ensure that 'should' and 'sinon' library methods
  // will be available to all tests
  global.should = require('should');
  global.sinon = require('sinon');

  // Start and configure the server
  require('../server');

  // Wait one second before calling "done" to ensure
  // that server is up and running
  setTimeout(done, 1000);
});

beforeEach(function() {
  global.sandbox = sinon.sandbox.create();
});

afterEach(function() {
  global.sandbox.restore();
});

Fix comment, add sandbox for tests


'use strict';

const config = require('../configurations');

class Alarm {

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

    setup(irc) {
        this.irc = irc;
        this.irc.onCommand('alarm', this.onAlarm.bind(this));
    }

    onAlarm(channel, nickname, command, payload) {
        this.mqttClient.publish(config.mqtt.topics.alarm, payload, {
            qos: 1
        });

        this.irc.answer(channel, nickname, 'ALAAAARM');
    }
}

module.exports = Alarm;

'use strict';

const config = require('../configurations');

class Alarm {

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

    setup(irc) {
        this.irc = irc;
        this.irc.onCommand('alarm', this.onAlarm.bind(this));
    }

    onAlarm(channel, nickname, command, payload) {
        const message = `${nickname}: ${payload}`;

        this.mqttClient.publish(config.mqtt.topics.alarm, message, {
            qos: 1
        });

        this.irc.answer(channel, nickname, 'ALAAAARM');
    }
}

module.exports = Alarm;

Prepend nickname to alarm messsage


//TODO:Javacsript can check if checked Ids hasv the same scale ID
function extractSelectedItems(submitButton) {
	sourceForm = document.getElementById("modifyFormRows");
	destinationForm = submitButton.form;
	var count = 0; //enforce at least 2 check box are checked

	if (sourceForm && destinationForm) {
		var idList = "";

		// look for checkboxes which have IDs of the form "block-12-11" and keep track of the ones that are checked.
		for (var a=0; a < sourceForm.elements.length; a++) {
			if (sourceForm.elements[a].type=="checkbox" &&
sourceForm.elements[a].checked) {
				if (idList.length > 0) { idList += ","; }
				idList += sourceForm.elements[a].id.substr(sourceForm.elements[a].id.lastIndexOf('-')+1);
				count = count + 1;
			}
		}
		destinationForm.templateItemIds.value=idList;

		alert("ids="+destinationForm.templateItemIds.value);
		if(count < 2){
		 alert("you must select at least 2 items to create a block");
		 return false;
		}
		else return true;
	}

	return false;
}

//TODO:Javacsript can check if checked Ids hasv the same scale ID
function extractSelectedItems(submitButton) {
	sourceForm = document.getElementById("modifyFormRows");
	destinationForm = submitButton.form;
	var count = 0; //enforce at least 2 check box are checked

	if (sourceForm && destinationForm) {
		var idList = "";

		// look for checkboxes which have IDs of the form "block-12-11" and keep track of the ones that are checked.
		for (var a=0; a < sourceForm.elements.length; a++) {
			if (sourceForm.elements[a].type=="checkbox" &&
sourceForm.elements[a].checked) {
				if (idList.length > 0) { idList += ","; }
				idList += sourceForm.elements[a].id.substr(sourceForm.elements[a].id.lastIndexOf('-')+1);
				count = count + 1;
			}
		}
		destinationForm.templateItemIds.value=idList;

		//alert("ids="+destinationForm.templateItemIds.value);
		if(count < 2){
		 alert("you must select at least 2 items to create a block");
		 return false;
		}
		else return true;
	}

	return false;
}

Remove the lert message of passing id info for Block creation


describe('Directive: ivhMultiSelect', function() {
  'use strict';

  beforeEach(module('ivh.multiSelect'));

  var collect;

  beforeEach(inject(function(ivhMultiSelectCollectFilter) {
    collect = ivhMultiSelectCollectFilter;
  }));

  it('should gather collect selected item ids', function() {
    var list = []
      , item = {selected: true, id: 'foo'};
    collect(list, item);
    expect(list.length).toBe(1);
    expect(list[0]).toBe('foo');
  });

  it('should remove deselected item ids', function() {
    var list = ['foo', 'bar']
      , item = {selected: false, id: 'foo'};
    collect(list, item);
    expect(list.length).toBe(1);
    expect(list[0]).toBe('bar');
  });
});

describe('Filter: ivhMultiSelectCollect', function() {
  'use strict';

  beforeEach(module('ivh.multiSelect'));

  var collect;

  beforeEach(inject(function(ivhMultiSelectCollectFilter) {
    collect = ivhMultiSelectCollectFilter;
  }));

  it('should gather collect selected item ids', function() {
    var list = []
      , item = {selected: true, id: 'foo'};
    collect(list, item);
    expect(list.length).toBe(1);
    expect(list[0]).toBe('foo');
  });

  it('should remove deselected item ids', function() {
    var list = ['foo', 'bar']
      , item = {selected: false, id: 'foo'};
    collect(list, item);
    expect(list.length).toBe(1);
    expect(list[0]).toBe('bar');
  });
});

Fix describe label for ivhMultiSelectCollect tests


'use strict';

var logger = require('./logger'),
    mongoose = require('mongoose');

// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
  mongoose.connection.on(event, function() {
    logger.warning('Mongo '+ event, arguments);
  });
});

module.exports = function(callback) {
  var config = require('api-umbrella-config').global();

  // Connect to mongo using mongoose.
  //
  // Note: For this application, we don't particularly need an ODM like
  // Mongoose, and the lower-level mongodb driver would meet our needs.
  // However, when using the standalone driver, we were experiencing
  // intermittent mongo connection drops in staging and production
  // environments. I can't figure out how to reproduce the original issue in a
  // testable way, so care should be taken if switching how mongo connects. See
  // here for more details: https://github.com/NREL/api-umbrella/issues/17
  mongoose.connect(config.get('mongodb.url'), config.get('mongodb.options'), callback);
};

'use strict';

var logger = require('./logger'),
    mongoose = require('mongoose');

// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
  mongoose.connection.on(event, function(error) {
    var logEvent = true;

    if(event === 'disconnecting') {
      mongoose.expectedCloseInProgress = true;
    }

    if(mongoose.expectedCloseInProgress) {
      if(event === 'disconnecting' || event === 'disconnected' || event === 'close') {
        logEvent = false;
      }
    }

    if(event === 'close') {
      mongoose.expectedCloseInProgress = false;
    }

    if(logEvent) {
      logger.error('Mongo event: ' + event, error);
    }
  });
});

module.exports = function(callback) {
  var config = require('api-umbrella-config').global();

  // Connect to mongo using mongoose.
  //
  // Note: For this application, we don't particularly need an ODM like
  // Mongoose, and the lower-level mongodb driver would meet our needs.
  // However, when using the standalone driver, we were experiencing
  // intermittent mongo connection drops in staging and production
  // environments. I can't figure out how to reproduce the original issue in a
  // testable way, so care should be taken if switching how mongo connects. See
  // here for more details: https://github.com/NREL/api-umbrella/issues/17
  mongoose.connect(config.get('mongodb.url'), config.get('mongodb.options'), callback);
};

Improve mongo logging, so we only log unexpected disconnects.


// Node modules
const bodyParser   = require('body-parser');
const cookieParser = require('cookie-parser');
const express	   = require('express');
const session	   = require('express-session');
// Custom Middleware
const passport	   = require('./auth/');
const configRoutes = require('./routes');
const exhbs		   = require('./views');

let app = express();
// Log incoming requests
app.use((req, res, next) => {
	console.log(`${req.method} ${req.path}`);
	next();
});
// Parse cookies and POST body
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Enable Cookie session
app.use(session({
	secret: 'keyboard cat',
	resave: false,
	saveUninitialized: false,
	cookie: { maxAge : 3600000 },
}));
// Enable Passport middleware
app.use(passport.initialize());
app.use(passport.session());
// Serve static files
exhbs(app, express.static(__dirname + '/public'));
// API routing
configRoutes(app);

// Enable API Server
const server = app.listen(3000, (err) => {
	if (err) {
		throw err;
	}
	const server_ip = server.address().address;
	const server_port = server.address().port;
	console.log(`Server running on ${server_ip}:${server_port}`);
});

Create express server that serves middleware, webpage, auth, and API routing


const express = require('express');
const app = express();
const portNumber = process.env.PORT || 3000;

const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
const path = require('path');

const users = require('./routes/users');
const token = require('./routes/token');
const resorts = require('./routes/resorts');
const trails = require('./routes/trails');
const ratings = require('./routes/ratings');
const favorites = require('./routes/favorites');

app.use(bodyParser.json());
app.use(cookieParser());

app.use('/apidoc', express.static(path.join(__dirname, 'apidoc')));
app.get('/', (req, res) => {
  res.status(200).send('Welcome to skiski.');
};

app.use(users);
app.use(token);
app.use(resorts);
app.use(trails);
app.use(ratings);
app.use(favorites);

app.use((req, res) => {
  res.sendStatus(404);
});

app.listen(portNumber, () => {
  console.log(`Listening on port ${portNumber}`);
});

module.exports = app;

const express = require('express');
const app = express();
const portNumber = process.env.PORT || 3000;

const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
const path = require('path');

const users = require('./routes/users');
const token = require('./routes/token');
const resorts = require('./routes/resorts');
const trails = require('./routes/trails');
const ratings = require('./routes/ratings');
const favorites = require('./routes/favorites');

app.use(bodyParser.json());
app.use(cookieParser());

app.use('/apidoc', express.static(path.join(__dirname, 'apidoc')));
app.get('/', (req, res) => {
  res.status(200).send('Welcome to skiski.');
});

app.use(users);
app.use(token);
app.use(resorts);
app.use(trails);
app.use(ratings);
app.use(favorites);

app.use((req, res) => {
  res.sendStatus(404);
});

app.listen(portNumber, () => {
  console.log(`Listening on port ${portNumber}`);
});

module.exports = app;

Fix defect for root route


/* eslint-env node */
'use strict';

module.exports = {
  allowedVersions: {
    'ember-in-element-polyfill': '*',
    'ember-get-config': '0.2.4 || 0.3.0',
    '@embroider/util': '*',
    '@ember/test-waiters': '2.4.5 || 3.0.0',
  },
};

/* eslint-env node */
'use strict';

module.exports = {
  allowedVersions: {
    'ember-in-element-polyfill': '*',
    'ember-get-config': '0.3.0 || 0.4.0',
    '@embroider/util': '*',
    '@ember/test-waiters': '2.4.5 || 3.0.0',
  },
};

Allow dependency lint to float for ember-get-config


/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var lib = process.env.GEAR_COVER ? './lib-cov/' : './lib/';

exports.Registry = require(lib + 'registry').Registry;
exports.Queue = require(lib + 'queue').Queue;
exports.Blob = require(lib + 'blob').Blob;
exports.Util = require(lib + 'Util');

/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var lib = process.env.GEAR_COVER ? './lib-cov/' : './lib/';

exports.Registry = require(lib + 'registry').Registry;
exports.Queue = require(lib + 'queue').Queue;
exports.Blob = require(lib + 'blob').Blob;
exports.Util = require(lib + 'util');

Fix typo of Util export


(function(module) {
	"use strict";

	var nico = {},
  embed = '';

	nico.parse = function(postContent, callback) {
		postContent = postContent.replace(/.+<\/a>/g, embed);
		callback(null, postContent);
	};

	module.exports = nico;
}(module));

Remove the ugly iframe border.


#!/usr/bin/env node

/**
 * Parses an equation given as a command-line argument
 * into an object and computes it. Prints the result into stdout.
 *
 * Usage:
 *   ./index.js 1+2-3*4/5%6^7
 */

'use strict';

var EquationParser = require('./EquationParser');

var EquationParser = new EquationParser();
var equationStr = process.argv[2];

if (!equationStr) {
  return console.log('Usage: ./index.js 1+2-3*4/5%6^7');
}

var equation = EquationParser.parseEquation(equationStr);

console.log(equation.compute());

#!/usr/bin/env node

/**
 * Parses an equation given as a command-line argument
 * into an object and computes it. Prints the result into stdout.
 *
 * Usage:
 *   ./index.js 1+2-3*4/5%6^7
 */

'use strict';

var EquationParser = require('./EquationParser');

var equationParser = new EquationParser();
var equationStr = process.argv[2];

if (!equationStr) {
  return console.log('Usage: ./index.js 1+2-3*4/5%6^7');
}

var equation = equationParser.parseEquation(equationStr);

console.log(equation.compute());

Fix a typo in instance name


var request=require('request');
var BASE_URL='https://kat.cr';

/**
 * {String|Object} query string or options f.x {}
 * avaliable options are any url options that kickass.to accepts
 * f.x. {field:'seeders', order:'desc', q: 'test',page: 2}
 * http://kickass.to/json.php?q=test&field=seeders&order=desc&page=2
 */
module.exports=function(options, callback){
    var url=(options.url || BASE_URL) + '/json.php';

    options.url = null;
    var params = {
      qs: options,
      url: url
    };

    request(params, function(err, response, raw){
      if(err) { return callback(err, null); }

      try {
        var data = JSON.parse(raw);
      } catch(err) {
        return callback(err, null);
      }

      callback(null, data);
    });
}

Use 4 spaces as indentation


var DEFAULT_PAGE = 'about';

// Given an HTML string response, set it as the page content.
var onChangePage = function(/*string*/ response) {
  var body = document.getElementById('body');
  body.innerHTML = response;
}

// Given a URL, load the contents into the body of the page.
var loadPage = function(/*string*/ url) {
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      onChangePage(request.responseText);
    }
  };
  request.open('GET', url, true);
  request.send();
};

var loadPageAndUpdateNavFromCurrentHash = function() {
  var hash = window.location.hash.replace('#', '') || DEFAULT_PAGE;

  var links = {
    about: document.getElementById('nav-about'),
    projects: document.getElementById('nav-projects')
  };

  for (var link_name in links) {
    if (links.hasOwnProperty(link_name)) {
      if (link_name === hash) {
        links[link_name].classList.add('selected');
      } else {
        links[link_name].classList.remove('selected');
      }
    }
  }

  loadPage(hash + '.html');
}

window.onhashchange = loadPageAndUpdateNavFromCurrentHash;
window.onload = loadPageAndUpdateNavFromCurrentHash;

var DEFAULT_PAGE = 'about';

// Given an HTML string response, set it as the page content.
var onChangePage = function(/*string*/ response) {
  var body = document.getElementById('body');
  body.innerHTML = response;
}

// Given a URL, load the contents into the body of the page.
var loadPage = function(/*string*/ url) {
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      onChangePage(request.responseText);
    }
  };
  request.open('GET', url, true);
  request.send();
};

var loadPageAndUpdateNavFromCurrentHash = function() {

  var links = {
    about: document.getElementById('nav-about'),
    projects: document.getElementById('nav-projects')
  };

  var hash = window.location.hash.replace('#', '');
  hash = hash in links ? hash : DEFAULT_PAGE;

  for (var link_name in links) {
    if (links.hasOwnProperty(link_name)) {
      if (link_name === hash) {
        links[link_name].classList.add('selected');
      } else {
        links[link_name].classList.remove('selected');
      }
    }
  }

  loadPage(hash + '.html');
}

window.onhashchange = loadPageAndUpdateNavFromCurrentHash;
window.onload = loadPageAndUpdateNavFromCurrentHash;

Make hashes that are not valid redirect to DEFAULT_PAGE


var http = require("http");

http.createServer(function (request, response) {
   // Send the HTTP header
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

// var http = require("http");
// app.set('view engine', 'html');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/scripts'));

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.post('/', function (req, res) {
  res.send('Got a POST request')
})

app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})

app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})

Use express instead of http


const release = require('./package.json').version

if (process.env.RAVEN_DSN) {
  var Raven = require('raven')
  Raven.config(process.env.RAVEN_DSN, {release}).install()
}

const url = require('url')
const { send } = require('micro')

const { parse } = require('./parser')
const { InvalidInputError } = require('./errors')

const exampleLink = (host) => `http://${host}/?feed=https://rolflekang.com/feed.xml`

module.exports = async (req, res) => {
  const { query } = url.parse(req.url, true)
  try {
    if (!query.feed) {
      return { usage: exampleLink(req.headers.host) }
    }

    if (typeof query.feed !== 'string') {
      throw new InvalidInputError()
    }

    return await parse(query.feed)
  } catch (error) {
    if (process.env.RAVEN_DSN) {
      Raven.captureException(error, {
        extra: {query}
      })
    }
    send(res, error.statusCode || 500, { error: error.constructor.name })
    console.error(error)
  }
}

const release = require('./package.json').version

if (process.env.RAVEN_DSN) {
  var Raven = require('raven')
  Raven.config(process.env.RAVEN_DSN, {release}).install()
}

const url = require('url')
const { send } = require('micro')

const { parse } = require('./parser')
const { InvalidInputError } = require('./errors')

const exampleLink = (host) => `http://${host}/?feed=https://rolflekang.com/feed.xml`

module.exports = async (req, res) => {
  const { query } = url.parse(req.url, true)
  try {
    if (!query.feed) {
      return { usage: exampleLink(req.headers.host) }
    }

    if (typeof query.feed !== 'string') {
      throw new InvalidInputError()
    }

    return await parse(query.feed)
  } catch (error) {
    if (process.env.RAVEN_DSN) {
      Raven.captureException(error, {
        extra: {query, url: req.url}
      })
    }
    send(res, error.statusCode || 500, { error: error.constructor.name })
    console.error(error)
  }
}

Add url to raven extra info


var time = require('time');
exports.handler = (event, context, callback) => {
    var currentTime = new time.Date();
    currentTime.setTimezone("America/Los_Angeles");
    callback(null, {
        statusCode: '200',
        body: 'The time in Los Angeles is: ' + currentTime.toString(),
    });
};

var time = require('time');
exports.handler = (event, context, callback) => {
    var currentTime = new time.Date();
    currentTime.setTimezone("America/New_York");
    callback(null, {
        statusCode: '200',
        body: 'The time in New York is: ' + currentTime.toString(),
    });
};

Change timezone to New York


var ejs = require("ejs");
var fs = require("fs");
var template = null;
fs.readFile("template.ejs","utf-8",function (err,data) {
    if (err) throw new Error(err);
    template = ejs.compile(data);
});

module.exports = function (options) {
    return function (options) {
        var snippet = template(options).replace("\n","").replace(/\s+/g," ");
        return function (req,res,next) {
            req.locals.piwik = function () {
                return snippet;
            }
        };
    }(options);
};

var ejs = require("ejs");
var fs = require("fs");
var path = require("path");

var template = null;
fs.readFile(path.join(__dirname,"template.ejs"),"utf-8",function (err,data) {
    if (err) throw new Error(err);
    template = ejs.compile(data);
});

module.exports = function (options) {
    return function (options) {
        var snippet = template(options).replace("\n","").replace(/\s+/g," ");
        return function (req,res,next) {
            req.locals.piwik = function () {
                return snippet;
            }
        };
    }(options);
};

Fix template path for use in a module


/* eslint-env node */
'use strict';

module.exports = {
  name: 'ember-cli-chart',
  included: function(app, parentAddon) {
    this._super.included.apply(this, arguments);

    var target = (parentAddon || app);
    if (target.app) {
      target = target.app;
    }

    var bowerDir = target.bowerDirectory;
    app.import(bowerDir + '/chartjs/dist/Chart.js');
  }
};

/* eslint-env node */
'use strict';

module.exports = {
  name: 'ember-cli-chart',
  included: function() {
    this._super.included.apply(this, arguments);

    var app;

    // If the addon has the _findHost() method (in ember-cli >= 2.7.0), we'll just
    // use that.
    if (typeof this._findHost === 'function') {
      app = this._findHost();
    } else {
      // Otherwise, we'll use this implementation borrowed from the _findHost()
      // method in ember-cli.
      var current = this;
      do {
        app = current.app || app;
      } while (current.parent.parent && (current = current.parent));
    }

    app.import(app.bowerDirectory + '/chartjs/dist/Chart.js');
  }
};

Use the find host method


'use strict';

var Cleaner  = require('clean-css');
var defaultCleaner = new Cleaner();

var versions = {};

exports.name = 'remarkable';
exports.outputFormat = 'html';
exports.render = function (str, options) {
  var cleaner;
  if (!options ||
      (typeof options === 'object' && Object.keys(options).length === 0)) {
    cleaner = defaultCleaner;
  } else {
    cleaner = new Cleaner(options);
  }
  return cleaner.minify(str).styles;
};

'use strict';

var Cleaner  = require('clean-css');
var defaultCleaner = new Cleaner();

exports.name = 'clean-css';
exports.outputFormat = 'css';
exports.render = function (str, options) {
  var cleaner;
  if (!options ||
      (typeof options === 'object' && Object.keys(options).length === 0)) {
    cleaner = defaultCleaner;
  } else {
    cleaner = new Cleaner(options);
  }
  return cleaner.minify(str).styles;
};

Update the name and outputFormat


(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.deepmerge = factory();
    }
}(this, function () {

return function deepmerge(target, src) {
    var array = Array.isArray(src);
    var dst = array && [] || {};

    if (array) {
        target = target || [];
        dst = dst.concat(target);
        src.forEach(function(e, i) {
            if (typeof dst[i] === 'undefined') {
                dst[i] = e;
            } else if (typeof e === 'object') {
                dst[i] = deepmerge(target[i], e);
            } else {
                if (target.indexOf(e) === -1) {
                    dst.push(e);
                }
            }
        });
    } else {
        if (target && typeof target === 'object') {
            Object.keys(target).forEach(function (key) {
                dst[key] = target[key];
            })
        }
        Object.keys(src).forEach(function (key) {
            if (typeof src[key] !== 'object' || !src[key]) {
                dst[key] = src[key];
            }
            else {
                if (!target[key]) {
                    dst[key] = src[key];
                } else {
                    dst[key] = deepmerge(target[key], src[key]);
                }
            }
        });
    }

    return dst;
}

}));

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.deepmerge = factory();
    }
}(this, function () {

return function deepmerge(target, src) {
    var array = Array.isArray(src);
    var dst = array && [] || {};

    if (array) {
        target = target || [];
        dst = dst.concat(target);
        src.forEach(function(e, i) {
            if (typeof dst[i] === 'undefined') {
                dst[i] = e;
            } else if (typeof e === 'object' && e !== null) {
                dst[i] = deepmerge(target[i], e);
            } else {
                if (target.indexOf(e) === -1) {
                    dst.push(e);
                }
            }
        });
    } else {
        if (target && typeof target === 'object') {
            Object.keys(target).forEach(function (key) {
                dst[key] = target[key];
            })
        }
        Object.keys(src).forEach(function (key) {
            if (typeof src[key] !== 'object' || !src[key]) {
                dst[key] = src[key];
            }
            else {
                if (!target[key]) {
                    dst[key] = src[key];
                } else {
                    dst[key] = deepmerge(target[key], src[key]);
                }
            }
        });
    }

    return dst;
}

}));

Resolve an issue when null is in an array


'use strict';

var pug = require('pug');

exports.name = 'pug';
exports.outputFormat = 'html';

exports.compile = function (source, options) {
  var fn = pug.compile(source, options);
  return {fn: fn, dependencies: fn.dependencies}
};
exports.compileClient = function (source, options) {
  return pug.compileClientWithDependenciesTracked(source, options);
};
exports.compileFile = function (path, options) {
  var fn = pug.compileFile(path, options);
  return {fn: fn, dependencies: fn.dependencies}
};
exports.compileFileClient = function (path, options) {
  var fs   = require('fs');

  // There is no compileFileClientWithDependenciesTracked so gotta do it
  // manually.
  options = options || {};
  options.filename = options.filename || path;
  return exports.compileClient(fs.readFileSync(path, 'utf8'), options);
};

'use strict';

var pug = require('pug');

exports.name = 'pug';
exports.inputFormats = ['pug', 'jade'];
exports.outputFormat = 'html';

exports.compile = function (source, options) {
  var fn = pug.compile(source, options);
  return {fn: fn, dependencies: fn.dependencies}
};
exports.compileClient = function (source, options) {
  return pug.compileClientWithDependenciesTracked(source, options);
};
exports.compileFile = function (path, options) {
  var fn = pug.compileFile(path, options);
  return {fn: fn, dependencies: fn.dependencies}
};
exports.compileFileClient = function (path, options) {
  var fs   = require('fs');

  // There is no compileFileClientWithDependenciesTracked so gotta do it
  // manually.
  options = options || {};
  options.filename = options.filename || path;
  return exports.compileClient(fs.readFileSync(path, 'utf8'), options);
};

Add `jade` to the list of inputformats for Pug


import Ember from 'ember';

const { assign } = Ember;

/**
 * @class Row
 * @extends Ember.ObjectProxy
 * @namespace SemanticUI
 */
const Row = Ember.ObjectProxy.extend({
  /**
   * Whether the row is currently selected.
   *
   * @property selected
   * @type Boolean
   * @default false
   * @public
   */
  selected: false,

  /**
   * Content for this row. See {{#crossLink "Ember.ObjectProxy"}}{{/crossLink}}.
   *
   * @property content
   * @type Object
   * @public
   */
  content: null
});

Row.reopenClass({
  /**
   * @method create
   * @param {Object} content Content for this row.
   * @param {Object} options Properties to initialize in this object.
   * @return Row
   * @static
   */
  create(content, options = {}) {
    let _options = assign({ content }, options);
    return this._super(_options);
  }
});

export default Row;

import Ember from 'ember';

const assign = Ember.assign || Ember.merge;

/**
 * @class Row
 * @extends Ember.ObjectProxy
 * @namespace SemanticUI
 */
const Row = Ember.ObjectProxy.extend({
  /**
   * Whether the row is currently selected.
   *
   * @property selected
   * @type Boolean
   * @default false
   * @public
   */
  selected: false,

  /**
   * Content for this row. See {{#crossLink "Ember.ObjectProxy"}}{{/crossLink}}.
   *
   * @property content
   * @type Object
   * @public
   */
  content: null
});

Row.reopenClass({
  /**
   * @method create
   * @param {Object} content Content for this row.
   * @param {Object} options Properties to initialize in this object.
   * @return Row
   * @static
   */
  create(content, options = {}) {
    let _options = assign({ content }, options);
    return this._super(_options);
  }
});

export default Row;

Remove usage of Ember.assign to support older version of Ember


const downloadObjectAsJson = (exportObj, exportName) => {
    const dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(exportObj))
    let downloadAnchorNode = document.createElement('a')

    downloadAnchorNode.setAttribute('href', dataStr)
    downloadAnchorNode.setAttribute('download', exportName + '.json')
    downloadAnchorNode.click()
    downloadAnchorNode.remove()
}

export default downloadObjectAsJson

Copy and download is implemented on the list and edit pages


import React, {PropTypes} from 'react'

const UsersTable = ({users}) => (

            User
            Roles
            Permissions

          {
            users.length ? users.map((user) => (

                {user.name}
                {user.roles.map((r) => r.name).join(', ')}
                {user.permissions.map((p) => p.scope).join(', ')}

            )) : (() => (

You don't have any Users,
why not create one?

            ))()
          }

)

const {
  arrayOf,
  shape,
  string,
} = PropTypes

UsersTable.propTypes = {
  users: arrayOf(shape({
    name: string.isRequired,
    roles: arrayOf(shape({
      name: string,
    })),
    permissions: arrayOf(shape({
      name: string,
      scope: string.isRequired,
    })),
  })),
}

export default UsersTable

import React, {PropTypes} from 'react'

const UsersTable = ({users}) => (

            User
            Roles
            Permissions

          {
            users.length ? users.map((user) => (

                {user.name}
                {users.roles && user.roles.map((r) => r.name).join(', ')}
                {user.permissions.map((p) => p.scope).join(', ')}

            )) : (() => (

You don't have any Users,
why not create one?

            ))()
          }

)

const {
  arrayOf,
  shape,
  string,
} = PropTypes

UsersTable.propTypes = {
  users: arrayOf(shape({
    name: string.isRequired,
    roles: arrayOf(shape({
      name: string,
    })),
    permissions: arrayOf(shape({
      name: string,
      scope: string.isRequired,
    })),
  })),
}

export default UsersTable

Handle no roles on users table


// Requires
var _ = require('lodash');
var glob = require("glob");
var Q = require('q');

function setup(options, imports, register) {
    // Import
    var vfs = imports.vfs;
    var workspace = imports.workspace;

    // Construct
    var filesSearch = function(args) {
        var d = Q.defer();

        args = _.defaults({}, args || {}, {
            'start': 0,
            'limit': 30
        });

        glob("**/*"+args.query+"*", {
            'cwd': workspace.root
        }, function (err, files) {
            if (err) {
                d.reject(err);
            } else {
                var results = _.map(files.slice(args.start, args.start+args.limit), function(path) {
                    return "/"+path;
                });

                d.resolve({
                    'files': results,
                    'n': _.size(files)
                });
            }
        });

        return d.promise;
    };

    // Register
    register(null, {
        "search": {
            files: filesSearch
        }
    });
}

// Exports
module.exports = setup;

// Requires
var _ = require('lodash');
var glob = require("glob");
var Q = require('q');

function setup(options, imports, register) {
    // Import
    var vfs = imports.vfs;
    var workspace = imports.workspace;

    // Construct
    var filesSearch = function(args) {
        var d = Q.defer();

        args = _.defaults({}, args || {}, {
            'start': 0,
            'limit': 30
        });

        glob("**/*"+args.query+"*", {
            'cwd': workspace.root,
            'mark': true
        }, function (err, files) {
            if (err) {
                d.reject(err);
            } else {
                var results = _.chain(files)
                .filter(function(path) {
                    return !(!path.length || path[path.length-1] == "/");
                })
                .map(function(path) {
                    return "/"+path;
                })
                .value();

                d.resolve({
                    'files': results.slice(args.start, args.start+args.limit),
                    'n': _.size(results)
                });
            }
        });

        return d.promise;
    };

    // Register
    register(null, {
        "search": {
            files: filesSearch
        }
    });
}

// Exports
module.exports = setup;

Remove folder from files search


// see web_modules folder for references

export Page from "Page" // default layout

export Home from "Home"
export Post from "Post"
export Collection from "Collection"

Add comment about location of layouts


function exchanges() {
	return [
		{
			"short_name": "NYSE",
			"full_name": "New York Stock Exchange",
			"timezone": "America/New_York",
			"trading_hours": [
				{
					"days": "Mon-Fri",
					"type": "regular",
					"start": "08:30",
					"end": "16:30"
				}
			],
			"holidays": [
				{ref: "USA"}
			]
		}
	]
}

function holidays() {
	return {
		"USA": [
			"2015-01-01"
		]
	}
}

function exchanges() {
	return [
		{
			"short_name": "NYSE",
			"full_name": "New York Stock Exchange",
			"timezone": "America/New_York",
			"trading_hours": [
				{
					"days": "Mon-Fri",
					"type": "regular",
					"start": "08:30",
					"end": "16:30"
				}
			]
		}
	]
}

Remove holidays from data file (not supported yet)


var express = require('express'),
  cons = require('consolidate'),
  nunjucks = require('nunjucks'),
  moment = require('moment'),
  path = require('path');

var app = module.exports = express();

/**
 * Configuration
 */

var view_paths = [
  path.join(__dirname,'views'),
  path.join(__dirname, 'node_modules', 'gn_components', 'views')
];

var env = new nunjucks.Environment(new nunjucks.FileSystemLoader(view_paths));

env.addFilter('date', function(date, format) {
  return moment(date).format(format);
});

env.addFilter('shorten', function(word) {
  if(word)
    return '(' + word.substr(0,1).toUpperCase() + ')';
});

env.express(app);

// all environments

app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', cons.nunjucks);

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// development only

/**
 * Routes
 */

var resumeJSON = require('./json/resume.json');

resumeJSON['levels'] = require('./json/skills.json');
resumeJSON['links'] = require('./json/links.json');
resumeJSON['acknowledgements'] = require('./json/footer.json').acknowledgements;

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

var express = require('express'),
  cons = require('consolidate'),
  nunjucks = require('nunjucks'),
  moment = require('moment'),
  path = require('path');

var app = module.exports = express();

/**
 * Configuration
 */

var view_paths = [
  path.join(__dirname,'views'),
  path.join(__dirname, 'node_modules', 'gn_components', 'views'),
  path.join(__dirname, '..', 'gn_components', 'views')
];

var env = new nunjucks.Environment(new nunjucks.FileSystemLoader(view_paths));

env.addFilter('date', function(date, format) {
  return moment(date).format(format);
});

env.addFilter('shorten', function(word) {
  if(word)
    return '(' + word.substr(0,1).toUpperCase() + ')';
});

env.express(app);

// all environments

app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', cons.nunjucks);

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// development only

/**
 * Routes
 */

var resumeJSON = require('./json/resume.json');

resumeJSON['levels'] = require('./json/skills.json');
resumeJSON['links'] = require('./json/links.json');
resumeJSON['acknowledgements'] = require('./json/footer.json').acknowledgements;

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

Add new viewpath for components


define([
    'jquery',
    'underscore',
    'backbone',
    'router',
    'jquerySidr'
], function($, _, Backbone, Router){

    var initialize = function(){
        $(document).ready(function() {
            $('#sidr').show();
            $('#menu').sidr();
            $("#sidr li a" ).bind('touchstart click', function() {
                if(null != Backbone.history.fragment){
                    _.each($("#sidr li"),function(li){
                        $(li).removeClass()
                    });

                    $('a[href$="#/'+Backbone.history.fragment+'"]').parent().addClass("active");
                    $.sidr('close');
                }
            });
        });
        Router.initialize();
    };

    return {
        initialize: initialize
    };
});

define([
    'jquery',
    'underscore',
    'backbone',
    'router',
    'jquerySidr'
], function($, _, Backbone, Router){

    var initialize = function(){
        $(document).ready(function() {
            $('#sidr').show();
            $('#menu').sidr();
            $("#sidr li a" ).bind('touchstart click', function() {
                if(null != Backbone.history.fragment){
                    _.each($("#sidr li"),function(li){
                        $(li).removeClass()
                    });

                    $('a[href$="#/'+Backbone.history.fragment+'"]').parent().addClass("active");
                    $.sidr('close');
                    window.scrollTo(0,0);
                }
            });
        });
        Router.initialize();
    };

    return {
        initialize: initialize
    };
});

Add the scroll top when switch channel


#!/usr/bin/env/node

/*

   Provide a command-line interface for `reconfigure`.
  ___ greeting, usage ___ en_US ___
  usage: node.bin.js

  ___ serve, usage ___ en_US ___
  usage: node bin.js reconfigure server

  options:
  -l, --listen      [string]    IP and port to bind to.
  -i, --id          [string]    reconfigure instance ID (or IP)
  ___ ___ ___
*/

require('arguable')(module, require('cadence')(function (async, options) {
    switch (options.command[0]) {
        case 'serve':
            var ip, port
            console.log('coming soon')
            ip = options.param.listen.split(':')
            if (ip.length) {
                port = ip[1]
                ip = ip[0]
            } else {
                port = '8080'
                ip = ip[0]
            }
            console.log('ip: ' + ip + ' port: ' + port)
            break
        case 'greeting':
            if (options.param.string != null) {
                console.log(options.param.string)
            } else {
                console.log('Hello, World!')
            }
            break
    }
}))

#!/usr/bin/env/node

/*

   Provide a command-line interface for `reconfigure`.
  ___ greeting, usage ___ en_US ___
  usage: node.bin.js

  ___ serve, usage ___ en_US ___
  usage: node bin.js reconfigure server

  options:
  -l, --listen      [string]    IP and port to bind to.
  -i, --id          [string]    reconfigure instance ID (or IP)
  ___ ___ ___
*/

require('arguable')(module, require('cadence')(function (async, options) {
    var UserAgent = require('./reconfigure/ua.js')
    var Consensus = require('./reconfigure/consensus.js')
    var Coordinator = require('./reconfigure/coordinator.js')
    var http = require ('./reconfigure/http.js')
    switch (options.command[0]) {
        case 'serve':
            console.log('coming soon')
            serve(options.param.listen.split(':'))
            break

        case 'greeting':
            if (options.param.string != null) {
                console.log(options.param.string)
            } else {
                console.log('Hello, World!')
            }
            break
    }

    function serve (ip) {
        var port
        if (ip.length) {
            port = ip[1]
            ip = ip[0]
        } else {
            port = '8080'
            ip = ip[0]
        }
        async(function () {
            var server = new http({
                coordinator: new Coordinator(
                    new Consensus('reconfigure', ip, port, async()),
                    new UserAgent()
                )
            })
            var disp = server.dispatcher()
            disp.server()
        }, function () {
            //Consensus stopped
        })
    }
}))

Create an HTTP with a coordinator.


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

if (!argv.length || argv.h || argv.help) {
  console.log(help())
}

function help () {
  return [
    'Usage:',
    '  matrix-bundler [entry] [opts]',
    '',
    'Options:',
    '  --help, -h           show help message',
    '  --entry, -e          the enrty point for bundler, default "."',
    '  --output, -o         the exported file bundle, default "./export.tgz"',
    '  --parent, -p         an asset id to import the files under, default "1"',
    '  --link, -l           the link type all assets will be imported as, default "TYPE_1"',
    '  --unrestricted, -u   whether unrestricted access is allowed, default "false"',
    '',
    'Examples:',
    '  matrix-bundler --entry ./files --link 2 --unrestricted --output ./files.tgz'
  ].join('\n')
}

var Bundler = require('../')
var argv = require('minimist')(process.argv.slice(2))
var fs = require('fs')

var bundle = Bundler()
var entry = argv.entry || argv.e || '.'
var output = argv.output || argv.o || './export.tgz'

if (!argv.length || argv.h || argv.help) {
  console.log(help())
}

bundle.createBundle()
  .pipe(fs.createWriteStream(output))

function help () {
  return [
    'Usage:',
    '  matrix-bundler [entry] [opts]',
    '',
    'Options:',
    '  --help, -h           show help message',
    '  --entry, -e          the enrty point for bundler, default "."',
    '  --output, -o         the exported file bundle, default "./export.tgz"',
    '  --parent, -p         an asset id to import the files under, default "1"',
    '  --link, -l           the link type all assets will be imported as, default "TYPE_1"',
    '  --unrestricted, -u   whether unrestricted access is allowed, default "false"',
    '',
    'Examples:',
    '  matrix-bundler --entry ./files --link 2 --unrestricted --output ./files.tgz'
  ].join('\n')
}

Add output variable to CLI


let CACHE_NAME = 'order-splitter-cache-%%GULP_INJECT_VERSION%%';
let urlsToCache = ['/', '/main.js'];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
    .then(function(cache) {
      console.log('Opened cache');
      return cache.addAll(urlsToCache);
    })
  );
});

self.addEventListener('activate', function(event) {
  let cacheWhiteList = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(
        keyList.filter(function(key) {
          return cacheWhiteList.indexOf(key) === -1;
        }).map(function(key) {
          return caches.delete(key);
        })
      );
    })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
    .then(function(response) {
      // Cache hit - return response
      if (response) {
        return response;
      }
      return fetch(event.request);
    })
  );
});

let CACHE_NAME = 'order-splitter-cache-%%GULP_INJECT_VERSION%%';
let urlsToCache = ['/', '/styles.css', '/all.min.js'];

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(CACHE_NAME)
    .then(function(cache) {
      console.log('Opened cache');
      return cache.addAll(urlsToCache);
    })
  );
});

self.addEventListener('activate', function(event) {
  let cacheWhiteList = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(
        keyList.filter(function(key) {
          return cacheWhiteList.indexOf(key) === -1;
        }).map(function(key) {
          return caches.delete(key);
        })
      );
    })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
    .then(function(response) {
      // Cache hit - return response
      if (response) {
        return response;
      }
      return fetch(event.request);
    })
  );
});

Update service worker URLs to cache


const { readFileSync } = require('fs');
const { join, isAbsolute } = require('path');

const LAYOUTS_DIR = join(__dirname, '..', 'layouts');
const THEMES_DIR = join(__dirname, '..', 'themes');

module.exports = function (options) {
  const { layout, theme, css } = options;
  const pathPrefix = isAbsolute(css) ? '' : process.cwd();
  const layoutCSS = readFileSync(join(LAYOUTS_DIR, layout + '.css'));
  const themeCSS = readFileSync(join(THEMES_DIR, theme + '.css'));
  const customCSS = css ? readFileSync(join(pathPrefix, css)) : '';

  return [layoutCSS, themeCSS, customCSS].join('\n');
}

const { readFileSync } = require('fs');
const { join, isAbsolute } = require('path');

const LAYOUTS_DIR = join(__dirname, '..', 'layouts');
const THEMES_DIR = join(__dirname, '..', 'themes');

module.exports = function (options) {
  const { layout, theme, css } = options;
  const pathPrefix = css && isAbsolute(css) ? '' : process.cwd();
  const layoutCSS = readFileSync(join(LAYOUTS_DIR, layout + '.css'));
  const themeCSS = readFileSync(join(THEMES_DIR, theme + '.css'));
  const customCSS = css ? readFileSync(join(pathPrefix, css)) : '';

  return [layoutCSS, themeCSS, customCSS].join('\n');
}

Check for optional CSS path before inspecting it