<commit_before>(function(joint, $) {

    var graph = new joint.dia.Graph;
    var paper = new joint.dia.Paper({
        el: document.getElementById('paper'),
        width: 650,
        height: 400,
        model: graph
    });

    // Create a custom element.
    // ------------------------

    joint.dia.Element.define('html.Element', {
        attrs: {
            placeholder: {
                refWidth: '100%',
                refHeight: '100%',
                stroke: 'gray'
            }
        }
    }, {
        markup: [{
            tagName: 'rect',
            selector: 'placeholder'
        }]
    });

    // Create a custom view for that element that displays an HTML div above it.
    // -------------------------------------------------------------------------

    joint.shapes.html.ElementView = joint.dia.ElementView.extend({

        template: [
            '
',
            '',
            '<input data-attribute="myinput" type="text"/>',
            '
'
        ].join(''),

        init: function() {

            // Update the box position whenever the underlying model changes.
            this.listenTo(this.model, 'change', this.updateBox);
        },

        onBoxChange: function(evt) {

            var input = evt.target;
            var attribute = input.dataset.attribute;
            if (attribute) {
                this.model.set(attribute, input.value);
            }
        },

        onRender: function() {

            if (this.$box) this.$box.remove();

            var boxMarkup = joint.util.template(this.template)();
            var $box = this.$box = $(boxMarkup);

            this.$attributes = $box.find('[data-attribute]');

            // React on all box changes. e.g. input change
            $box.on('change', this.onBoxChange.bind(this));

            // Update the box size and position whenever the paper transformation changes.
            // Note: there is no paper yet on `init` method.
            this.listenTo(this.paper, 'scale translate', this.updateBox);

            $box.appendTo(this.paper.el);
            this.updateBox();

            return this;
        },

        updateBox: function() {

            // Set the position and the size of the box so that it covers the JointJS element
            // (taking the paper transformations into account).
            var bbox = this.getBBox({ useModelGeometry: true });
            var scale = paper.scale();

            this.$box.css({
                transform: 'scale(' + scale.sx + ',' + scale.sy + ')',
                transformOrigin: '0 0',
                width: bbox.width / scale.sx,
                height: bbox.height / scale.sy,
                left: bbox.x,
                top: bbox.y
            });

            this.updateAttributes();
        },

        updateAttributes: function() {

            var model = this.model;

            this.$attributes.each(function() {

                var value = model.get(this.dataset.attribute);

                switch (this.tagName.toUpperCase()) {
                    case 'LABEL':
                        this.textContent = value;
                        break;
                    case 'INPUT':
                        this.value = value;
                        break;
                }
            });
        },

        onRemove: function() {

            this.$box.remove();
        }

    });

    // Create JointJS elements and add them to the graph as usual.
    // -----------------------------------------------------------

    var el1 = new joint.shapes.html.Element({
        position: { x: 80, y: 80 },
        size: { width: 150, height: 80 },
        myinput: 'I am an input',
        mylabel: 'I am a label'
    });

    var el2 = new joint.shapes.html.Element({
        position: { x: 350, y: 150 },
        size: { width: 150, height: 80 },
        myinput: 'I am HTML input',
        mylabel: 'I am HTML label'
    });

    var l = new joint.shapes.standard.Link({
        source: { id: el1.id },
        target: { id: el2.id }
    });

    graph.addCells([el1, el2, l]);

    // Zooming
    // ------------

    var zoomLevel = 1;

    $('#zoom-in').on('click', function() {
        zoomLevel = Math.min(3, zoomLevel + 0.2);
        var size = paper.getComputedSize();
        paper.translate(0,0);
        paper.scale(zoomLevel, zoomLevel, size.width / 2, size.height / 2);
    });

    $('#zoom-out').on('click', function() {
        zoomLevel = Math.max(0.2, zoomLevel - 0.2);
        var size = paper.getComputedSize();
        paper.translate(0,0);
        paper.scale(zoomLevel, zoomLevel, size.width / 2, size.height / 2);
    });

})(joint, $);
<commit_msg>demo.HTML: use proper paper reference inside view (#1223)<commit_after>(function(joint, $) {

    var graph = new joint.dia.Graph;
    var paper = new joint.dia.Paper({
        el: document.getElementById('paper'),
        width: 650,
        height: 400,
        model: graph
    });

    // Create a custom element.
    // ------------------------

    joint.dia.Element.define('html.Element', {
        attrs: {
            placeholder: {
                refWidth: '100%',
                refHeight: '100%',
                stroke: 'gray'
            }
        }
    }, {
        markup: [{
            tagName: 'rect',
            selector: 'placeholder'
        }]
    });

    // Create a custom view for that element that displays an HTML div above it.
    // -------------------------------------------------------------------------

    joint.shapes.html.ElementView = joint.dia.ElementView.extend({

        template: [
            '
',
            '',
            '<input data-attribute="myinput" type="text"/>',
            '
'
        ].join(''),

        init: function() {

            // Update the box position whenever the underlying model changes.
            this.listenTo(this.model, 'change', this.updateBox);
        },

        onBoxChange: function(evt) {

            var input = evt.target;
            var attribute = input.dataset.attribute;
            if (attribute) {
                this.model.set(attribute, input.value);
            }
        },

        onRender: function() {

            if (this.$box) this.$box.remove();

            var boxMarkup = joint.util.template(this.template)();
            var $box = this.$box = $(boxMarkup);

            this.$attributes = $box.find('[data-attribute]');

            // React on all box changes. e.g. input change
            $box.on('change', this.onBoxChange.bind(this));

            // Update the box size and position whenever the paper transformation changes.
            // Note: there is no paper yet on `init` method.
            this.listenTo(this.paper, 'scale translate', this.updateBox);

            $box.appendTo(this.paper.el);
            this.updateBox();

            return this;
        },

        updateBox: function() {

            // Set the position and the size of the box so that it covers the JointJS element
            // (taking the paper transformations into account).
            var bbox = this.getBBox({ useModelGeometry: true });
            var scale = this.paper.scale();
            this.$box.css({
                transform: 'scale(' + scale.sx + ',' + scale.sy + ')',
                transformOrigin: '0 0',
                width: bbox.width / scale.sx,
                height: bbox.height / scale.sy,
                left: bbox.x,
                top: bbox.y
            });

            this.updateAttributes();
        },

        updateAttributes: function() {

            var model = this.model;

            this.$attributes.each(function() {

                var value = model.get(this.dataset.attribute);

                switch (this.tagName.toUpperCase()) {
                    case 'LABEL':
                        this.textContent = value;
                        break;
                    case 'INPUT':
                        this.value = value;
                        break;
                }
            });
        },

        onRemove: function() {

            if (this.$box) this.$box.remove();
        }

    });

    // Create JointJS elements and add them to the graph as usual.
    // -----------------------------------------------------------

    var el1 = new joint.shapes.html.Element({
        position: { x: 80, y: 80 },
        size: { width: 150, height: 80 },
        myinput: 'I am an input',
        mylabel: 'I am a label'
    });

    var el2 = new joint.shapes.html.Element({
        position: { x: 350, y: 150 },
        size: { width: 150, height: 80 },
        myinput: 'I am HTML input',
        mylabel: 'I am HTML label'
    });

    var l = new joint.shapes.standard.Link({
        source: { id: el1.id },
        target: { id: el2.id }
    });

    graph.addCells([el1, el2, l]);

    // Zooming
    // ------------

    var zoomLevel = 1;

    $('#zoom-in').on('click', function() {
        zoomLevel = Math.min(3, zoomLevel + 0.2);
        var size = paper.getComputedSize();
        paper.translate(0,0);
        paper.scale(zoomLevel, zoomLevel, size.width / 2, size.height / 2);
    });

    $('#zoom-out').on('click', function() {
        zoomLevel = Math.max(0.2, zoomLevel - 0.2);
        var size = paper.getComputedSize();
        paper.translate(0,0);
        paper.scale(zoomLevel, zoomLevel, size.width / 2, size.height / 2);
    });

})(joint, $);
<|endoftext|>


<commit_before>var fs = require('fs'),
  lang = require('lodash/lang'),
  path = require('path'),
  util = require('util');

module.exports = function taskLoader(taskDir, gulp) {

  var customOptions = ['usage',
    'description',
    'seq',
    'options',
    'isDefault'
  ];

  var defaultTaskNames = [];

  var args = [];

  var sequenceCount = 0;
  var currentPriority = -10;

  if (arguments.length > 0) {
    args = Array.prototype.slice.call(arguments)
      .splice(1);
  }
  // get all tasks

  var runSequence = require('run-sequence')
    .use(gulp),
    taskNames = [];

  // todo: clean this mess up
  fs.readdirSync(taskDir)
    .map(function(file) {
      var stats = fs.statSync(taskDir + path.sep + file);
      if (stats.isFile() && path.extname(file) === '.js') {
        var tasks;
        var requiredTasks = require(taskDir + path.sep + file);
        if (lang.isFunction(requiredTasks)) {

          tasks =
            requiredTasks.apply(null, args);
          if (lang.isFunction(tasks)) {
            var taskFn = tasks;
            var taskName = path.basename(file, '.js');
            tasks = {};
            tasks[taskName] = {
              fn: taskFn
            };
          }
        } else {
          tasks = requiredTasks;
        }
        // let's assume it's an object
        if (lang.isObject(tasks)) {
          Object.keys(tasks)
            .map(function(taskName) {
              var task = tasks[taskName];
              var taskArgs = [taskName];
              if (lang.isFunction(task)) {
                taskArgs.push([]);
                taskArgs.push(task);
              } else if (lang.isObject(task)) {
                if (task.isDefault) {
                  defaultTaskNames.push(taskName);
                }
                if (task.seq) {
                  sequenceCount++;
                  var sequence = [];
                  var seqIndex = 1;
                  var anonCount = 0;

                  var _p = function(seqTasks) {
                    return seqTasks.map(function(seqTask) {
                      if (lang.isString(seqTask)) {
                        return seqTask;
                      } else if (lang.isFunction(seqTask)) {
                        var fnName = _functionName(seqTask);
                        if (!fnName) {
                          anonCount++;
                          fnName = util.format('anonymous-%s',
                            anonCount);
                        }

                        var seqName = util.format(
                          '%s-(index: %s, fnName: %s)', taskName,
                          seqIndex, fnName);
                        gulp.task.apply(gulp, [
                          seqName, [],
                          seqTask
                        ]);

                        console.log(_functionName(seqTask));

                        seqIndex++;
                        return seqName;
                      } else if (lang.isArray(seqTask)) {
                        console.log('array', seqTask);
                        sequenceCount++;
                        return _p(seqTask);
                      }

                    });
                  }
                  task.seq = _p(task.seq);
                  if (!task.fn) {
                    task.fn = function(done) {
                      runSequence.apply(
                        null, task.seq
                        .concat(
                          done));
                    }
                  } else {
                    var subName = 'post-' +
                      taskName;
                    var origFn = task.fn;
                    gulp.task.apply(gulp, [
                      subName, [],
                      origFn
                    ]);

                    task.fn = function(done) {
                      runSequence.apply(
                        null, task.seq
                        .concat(
                          subName
                        )
                        .concat(
                          done));
                    }
                  }
                }
                var deps = [];
                var depIndex = 1;
                var anonCount = 0;
                if (lang.isArray(task.dep)) {
                  task.dep.map(function(taskDep) {
                    var dep = taskDep;
                    if (lang.isFunction(taskDep)) {
                      var fnName = _functionName(taskDep);
                      if (!fnName) {
                        anonCount++;
                        fnName = util.format('anonymous-%s',
                          anonCount);
                      }
                      var depName = util.format(
                        '%s-(index: %s, fnName: %s)', taskName,
                        depIndex, fnName);
                      gulp.task.apply(gulp, [
                        depName, [],
                        taskDep
                      ]);
                      depIndex++;
                      dep = depName;
                      console.log('--', depName);
                    }
                    deps.push(dep);
                  });
                }
                taskArgs.push(deps);
                if (task.fn) {
                  taskArgs.push(task.fn);
                }
              } else if (lang.isArray(task)) {
                taskArgs.push(task);
              }

              if (taskArgs.length > 1) {
                taskNames.push(taskArgs[0]);
                gulp.task.apply(gulp,
                  taskArgs);

                // priority
                if (task.description) {

                  var priority = task.priority;
                  if (!priority) {
                    priority = currentPriority;
                    currentPriority = currentPriority - 10;
                  }
                  gulp.tasks[taskName].priority = priority;
                }
                customOptions.map(function(
                  customOption) {
                  var taskOption = task[
                    customOption];

                  if (taskOption) {

                    gulp.tasks[taskName]
                      [
                        customOption
                      ] = taskOption;
                  }
                });

              }
            });
        }
      }
    });

  if (defaultTaskNames.length) {
    gulp.task('default', defaultTaskNames);
  }
  return {
    taskNames: taskNames
  };
}

function _functionName(fun) {
  var ret = fun.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}
<commit_msg>Some decomp<commit_after>var fs = require('fs'),
  lang = require('lodash/lang'),
  path = require('path'),
  util = require('util');
var _task;
var runSequence;

module.exports = function taskLoader(taskDir, gulp) {
  runSequence = require('run-sequence')
    .use(gulp);
  if (arguments.length < 2) {
    throw 'Expecting at least two arguments: taskDir and gulp';
  }

  // let's first catch all the arguments here
  var args = Array.prototype.slice.apply(arguments);

  // let's add a state object we need to haul with the parser
  var state = {
    defaultTaskNames: [],
    sequenceCount: 0
  };

  args.unshift(state);

  var taskNames = [];

  _task = function() {
    var args = Array.prototype.slice.apply(arguments);
    taskNames.push(args[0]);
    console.log('_task', args);
    return gulp.task.apply(gulp, args);
  };

  _parse.apply(this, args);

  if (state.defaultTaskNames.length) {
    _task('default', state.defaultTaskNames);
  }
  return {
    task: _task,
    taskNames: taskNames,
    defaultTaskNames: state.defaultTaskNames
  };
};

function _parse(state, taskDir, gulp) {
  var customOptions = ['usage',
    'description',
    'seq',
    'options',
    'isDefault'
  ];

  var args = Array.prototype.slice.call(arguments)
    .splice(2);

  var currentPriority = -10;

  // get all tasks

  // todo: clean this mess up
  fs.readdirSync(taskDir)
    .map(function(file) {
      var stats = fs.statSync(taskDir + path.sep + file);
      if (stats.isFile() && path.extname(file) === '.js') {
        var tasks;
        var requiredTasks = require(taskDir + path.sep + file);
        if (lang.isFunction(requiredTasks)) {

          tasks =
            requiredTasks.apply(null, args);
          if (lang.isFunction(tasks)) {
            var taskFn = tasks;
            var taskName = path.basename(file, '.js');
            tasks = {};
            tasks[taskName] = {
              fn: taskFn
            };
          }
        } else {
          tasks = requiredTasks;
        }
        // let's assume it's an object
        if (lang.isObject(tasks)) {
          Object.keys(tasks)
            .map(function(taskName) {
              var task = tasks[taskName];
              var taskArgs = [taskName];
              if (lang.isFunction(task)) {
                taskArgs.push([]);
                taskArgs.push(task);
              } else if (lang.isObject(task)) {

                // Check for default tasks
                _defaultTasks(gulp, taskName, task, state);

                // sequences
                _sequences(gulp, taskName, task, state);

                // dependencies
                var deps = [];
                var depIndex = 1;
                var anonCount = 0;
                if (lang.isArray(task.dep)) {
                  task.dep.map(function(taskDep) {
                    var dep = taskDep;
                    if (lang.isFunction(taskDep)) {
                      var fnName = _getFunctionName(taskDep);
                      if (!fnName) {
                        anonCount++;
                        fnName = util.format('anonymous-%s',
                          anonCount);
                      }
                      var depName = util.format(
                        '%s-(index: %s, fnName: %s)', taskName,
                        depIndex, fnName);
                      _task.apply(gulp, [
                        depName, [],
                        taskDep
                      ]);
                      depIndex++;
                      dep = depName;
                      console.log('--', depName);
                    }
                    deps.push(dep);
                  });
                }
                taskArgs.push(deps);
                if (task.fn) {
                  taskArgs.push(task.fn);
                }
              } else if (lang.isArray(task)) {
                taskArgs.push(task);
              }

              if (taskArgs.length > 1) {
                _task.apply(gulp,
                  taskArgs);

                // priority
                if (task.description) {

                  var priority = task.priority;
                  if (!priority) {
                    priority = currentPriority;
                    currentPriority = currentPriority - 10;
                  }
                  gulp.tasks[taskName].priority = priority;
                }

                customOptions.map(function(
                  customOption) {
                  var taskOption = task[
                    customOption];

                  if (taskOption) {

                    gulp.tasks[taskName]
                      [
                        customOption
                      ] = taskOption;
                  }
                });

              }
            });
        }
      }
    });
}

function _defaultTasks(gulp, taskName, task, state) {
  // default task(s)
  if (task.isDefault) {
    state.defaultTaskNames.push(taskName);
  }
}

function _sequences(gulp, taskName, task, state) {
  if (task.seq) {
    state.sequenceCount++;
    var sequence = [];

    var localState = {
      seqIndex: 1,
      anonCount: 0
    };

    task.seq = _parseSequence(gulp, taskName, task.seq, state, localState);

    // If task does not have a function assigned then create one...
    if (!task.fn) {
      task.fn = function(done) {
        runSequence.apply(
          null, task.seq
          .concat(
            done));
      };

    } else {
      // ... otherwise chop it off, and place it in a new task at the very end
      // of the sequence. Yes I could monkey patch the task function but that's
      // a bit too ghetto I think.
      var subName = 'post-' +
        taskName;
      var origFn = task.fn;
      _task.apply(gulp, [
        subName, [],
        origFn
      ]);

      task.fn = function(done) {
        runSequence.apply(
          null, task.seq
          .concat(
            subName
          )
          .concat(
            done));
      };
    }
  }
}

function _parseSequence(gulp, taskName, seqTasks, state, localState) {

  return seqTasks.map(function(seqTask) {
    if (lang.isString(seqTask)) {
      return seqTask;
    } else if (lang.isFunction(seqTask)) {
      var fnName = _getFunctionName(seqTask);
      if (!fnName) {
        localState.anonCount++;
        fnName = util.format('anonymous-%s',
          localState.anonCount);
      }

      var seqName = util.format(
        '%s-(index: %s, fnName: %s)',
        taskName,
        localState.seqIndex, fnName);
      _task.apply(gulp, [
        seqName, [],
        seqTask
      ]);

      console.log(_getFunctionName(seqTask));

      localState.seqIndex++;
      return seqName;
    } else if (lang.isArray(seqTask)) {
      console.log('array', seqTask);
      state.sequenceCount++;
      return _parseSequence(gulp, taskName, seqTask, state, localState);
    }

  });
}

function _getFunctionName(fn) {
  var fnName = fn.toString();
  fnName = fnName.substr('function '.length);
  fnName = fnName.substr(0, fnName.indexOf('('));
  return fnName;
}
<|endoftext|>


<commit_before>/*
 * grunt-cfpathcheck
 * https://github.com/timbeadle/grunt-cfpathcheck
 *
 * Copyright (c) 2015 Tim Beadle
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('cfpathcheck', 'Grunt wrapper for cfpathcheck', function () {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      punctuation: '.',
      separator: ', '
    });

    // Iterate over all specified file groups.
    this.files.forEach(function (file) {
      // Concat specified files.
      var src = file.src.filter(function (filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function (filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).join(grunt.util.normalizelf(options.separator));

      // Handle options.
      src += options.punctuation;

      // Write the destination file.
      grunt.file.write(file.dest, src);

      // Print a success message.
      grunt.log.writeln('File "' + file.dest + '" created.');
    });
  });

};
<commit_msg>Added wrap around cfpathcheck api<commit_after>/*
 * grunt-cfpathcheck
 * https://github.com/timbeadle/grunt-cfpathcheck
 *
 * Copyright (c) 2015 Tim Beadle
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

	// Please see the Grunt documentation for more information regarding task
	// creation: http://gruntjs.com/creating-tasks

	grunt.registerMultiTask('cfpathcheck', 'Grunt wrapper for cfpathcheck', function() {

		var cfpathcheck = require('cfpathcheck/lib/cfpathcheck');
		var path = require('path');

		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({
			reporter: 'console',
			outFile: undefined
		});
		var file;

		if (this.filesSrc.length === 1) {
			file = this.filesSrc[0];
		}

		// Iterate over all specified file groups.
		if (typeof file !== 'undefined') {
			var violations = cfpathcheck.check(file, 'json');
			var output = cfpathcheck.formatter(violations, options.reporter);

			cfpathcheck.writeOutput(output);

			if (options.outFile) {
				cfpathcheck.writeFile(cfpathcheck.formatter(violations, 'checkstyle'), options.outFile);
			}

		}
	});

};
<|endoftext|>


<commit_before>/**
 * Copy files and folders.
 *
 * ---------------------------------------------------------------
 *
 * # dev task config
 * Copies all directories and files, exept coffescript and less fiels, from the sails
 * assets folder into the .tmp/public directory.
 *
 * # build task config
 * Copies all directories nd files from the .tmp/public directory into a www directory.
 *
 * For usage docs see:
 * 		https://github.com/gruntjs/grunt-contrib-copy
 */
module.exports = function(grunt) {

	grunt.config.set('copy', {
		dev: {
			files: [{
				expand: true,
				cwd: './assets',
				// src: ['**/*.!(coffee|less)'],
				src: ['**/*.!(coffee|less|scss|sass)'],
				dest: '.tmp/public'
			},

			//Add angular2
			{
				expand:true,
				cwd: './node_modules',
				src:[
						'rxjs/bundles/Rx.umd.js',
					 	'angular2/bundles/angular2-polyfills.js',
					 	'angular2/bundles/angular2-all.umd.js'
					]
				dest: '.tmp/public/js/dependencies/angular2'
			}]
		},
		build: {
			files: [{
				expand: true,
				cwd: '.tmp/public',
				src: ['**/*'],
				dest: 'www'
			}]
		}
	});

	grunt.loadNpmTasks('grunt-contrib-copy');
};
<commit_msg>Modified angular2 version<commit_after>/**
 * Copy files and folders.
 *
 * ---------------------------------------------------------------
 *
 * # dev task config
 * Copies all directories and files, exept coffescript and less fiels, from the sails
 * assets folder into the .tmp/public directory.
 *
 * # build task config
 * Copies all directories nd files from the .tmp/public directory into a www directory.
 *
 * For usage docs see:
 * 		https://github.com/gruntjs/grunt-contrib-copy
 */
module.exports = function(grunt) {

	grunt.config.set('copy', {
		dev: {
			files: [{
				expand: true,
				cwd: './assets',
				// src: ['**/*.!(coffee|less)'],
				src: ['**/*.!(coffee|less|scss|sass)'],
				dest: '.tmp/public'
			},

			//Add angular2
			{
				expand:true,
				cwd: './node_modules',
				src:[
						'rxjs/bundles/Rx.umd.js',
					 	'angular2/bundles/angular2-polyfills.js',
					 	'angular2/bundles/angular2-all.umd.js'
					],
				dest: '.tmp/public/js/dependencies/angular2'
			}]
		},
		build: {
			files: [{
				expand: true,
				cwd: '.tmp/public',
				src: ['**/*'],
				dest: 'www'
			}]
		}
	});

	grunt.loadNpmTasks('grunt-contrib-copy');
};
<|endoftext|>


<commit_before>/*!
 * Angular Responsive Parallax
 *
 * (c) 2014-2015 Markus Riegel <riegel.markus@googlemail.com>
 * License: MIT
 */
!function(t,e,n){var i=e.module("mrResponsiveParallax",[]);i.value("containerDivId","mr-px-container"),i.directive("mrPxParallax",["containerDivId","$timeout",function(i,o){return{restrict:"A",scope:{mrPxMaxPx:"="},link:function(r,a,l){var s,h,d,c,p,m,u,g,x=function(){if(!s){var t=document.getElementById(i);null===t?(t=e.element('

'),t.attr("id",i),e.element(document.body).prepend(t)):t=e.element(t),s=e.element('

'),h=e.element(''),t.append(s),s.append(h)}var n=a.find("img"),o=n.parent(),r=o.attr("mr-px-size").split(","),l="true"===o.attr("mr-px-no-px"),d=parseFloat(o.attr("mr-px-focal"))>=-1&&parseFloat(o.attr("mr-px-focal"))<=1?parseFloat(o.attr("mr-px-focal")):0;return l?(s.css("display","none"),h.attr("src",""),a.css("display","block")):(s.css("display","block"),h.attr("src",n.attr("src")),a.css("display","none")),{elem:n,oWidth:parseInt(r[0]),oHeight:parseInt(r[1]),noPx:l,focal:d}},f=function(){e.element(t).unbind("scroll",k),p=x(),m=parseFloat(r.mrPxMaxPx),u={width:t.innerWidth||document.documentElement.clientWidth,height:t.innerHeight||document.documentElement.clientHeight},p.noPx===!0?m=0:e.element(t).bind("scroll",k)},v=function(){var t=d[0].getBoundingClientRect();c={width:u.width,height:0},m>=0&&1>=m&&(c.height=u.height*(1-m)+t.height*m);var e=p.noPx?t:c,n=p.noPx?p.elem:h,i=e.width/e.height,o=p.oWidth/p.oHeight;o>i?(p.height=e.height,p.width=p.height*o):(p.width=e.width,p.height=p.width/o),n.css("width",p.width+"px"),n.css("height",p.height+"px"),s.css("height",t.height+"px")},w=function(){var t,e=d[0].getBoundingClientRect(),n=0,i=0,o=m,r=p.noPx?p.elem:h;t=.5*-(p.width-c.width),p.noPx?i=.5*-(p.height-e.height):(n=e.top/(u.height-e.height),m>=0&&1>=m&&(i=(u.height-c.height)*n*(1-o)+e.top*o),i=i-e.top-.5*(p.height-c.height)*(1-p.focal)),"none"!==g?(s.css(g,"translate3d(0px,"+e.top+"px,0)"),r.css(g,"translate3d("+t+"px, "+i+"px,0px)")):(s.css("top",e.top+"px"),r.css("top",i+"px"),r.css("left",t+"px"))},y=function(){e.element(t).unbind("resize",z),e.element(t).unbind("scroll",k),s&&(s.parent().remove(s),h=null)},b=function(){var e,i,o=document.createElement("p"),r={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(o,null);for(var a in r)o.style[a]!==n&&(o.style[a]="translate3d(1px,1px,1px)",e=t.getComputedStyle(o).getPropertyValue(r[a]),i=a);return document.body.removeChild(o),e!==n&&e.length>0&&"none"!==e?i:"none"},P=function(){e.element(t).unbind("load",P),e.element(t).bind("resize",z),z()},z=function(){f(),v(),k()},k=function(){w()};g=b(),d=a.parent(),a.css("display","none"),o(P),r.$on("$destroy",function(){y()})}}}])}(window,window.angular);<commit_msg>(chore) gulp<commit_after>/*!
 * Angular Responsive Parallax
 *
 * (c) 2014-2015 Markus Riegel <riegel.markus@googlemail.com>
 * License: MIT
 */
!function(t,e,n){var i=e.module("mrResponsiveParallax",[]);i.value("containerDivId","mr-px-container"),i.directive("mrPxParallax",["containerDivId","$timeout",function(i,o){return{restrict:"A",scope:{mrPxMaxPx:"="},link:function(r,a,l){var s,h,d,m,c,p,u,f,g;t.picturefill();var x=function(){if(!s){var t=document.getElementById(i);null===t?(t=e.element('

'),t.attr("id",i),e.element(document.body).prepend(t)):t=e.element(t),s=e.element('

'),h=e.element(''),t.append(s),s.append(h)}var n=a.find("img"),o=n.parent(),r=o.attr("mr-px-size").split(","),l="true"===o.attr("mr-px-no-px"),d=parseFloat(o.attr("mr-px-focal"))>=-1&&parseFloat(o.attr("mr-px-focal"))<=1?parseFloat(o.attr("mr-px-focal")):0;return l?(s.css("display","none"),h.attr("src",""),a.css("display","block")):(s.css("display","block"),h.attr("src",n.attr("src")),a.css("display","none")),{elem:n,oWidth:parseInt(r[0]),oHeight:parseInt(r[1]),noPx:l,focal:d}},v=function(){g||(t.cancelAnimationFrame(g),g=null),c=x(),p=parseFloat(r.mrPxMaxPx),u={width:t.innerWidth||document.documentElement.clientWidth,height:t.innerHeight||document.documentElement.clientHeight},c.noPx===!0?p=0:g=t.requestAnimationFrame(k)},w=function(){var t=d[0].getBoundingClientRect();m={width:u.width,height:0},p>=0&&1>=p&&(m.height=u.height*(1-p)+t.height*p);var e=c.noPx?t:m,n=c.noPx?c.elem:h,i=e.width/e.height,o=c.oWidth/c.oHeight;o>i?(c.height=e.height,c.width=c.height*o):(c.width=e.width,c.height=c.width/o),n.css("width",c.width+"px"),n.css("height",c.height+"px"),s.css("height",t.height+"px")},y=function(){var t,e=d[0].getBoundingClientRect(),n=0,i=0,o=p,r=c.noPx?c.elem:h;t=.5*-(c.width-m.width),c.noPx?i=.5*-(c.height-e.height):(n=e.top/(u.height-e.height),p>=0&&1>=p&&(i=(u.height-m.height)*n*(1-o)+e.top*o),i=i-e.top-.5*(c.height-m.height)*(1-c.focal)),"none"!==f?(s.css(f,"translate3d(0px,"+e.top+"px,0)"),r.css(f,"translate3d("+t+"px, "+i+"px,0px)")):(s.css("top",e.top+"px"),r.css("top",i+"px"),r.css("left",t+"px"))},P=function(){e.element(t).unbind("resize",z),e.element(t).unbind("scroll",onScrollHandler),s&&(s.parent().remove(s),h=null)},b=function(){var e,i,o=document.createElement("p"),r={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(o,null);for(var a in r)o.style[a]!==n&&(o.style[a]="translate3d(1px,1px,1px)",e=t.getComputedStyle(o).getPropertyValue(r[a]),i=a);return document.body.removeChild(o),e!==n&&e.length>0&&"none"!==e?i:"none"},F=function(){e.element(t).unbind("load",F),e.element(t).bind("resize",z),z()},z=function(){v(),w(),g||(g=t.requestAnimationFrame(k))},k=function(){y(),g=t.requestAnimationFrame(k)};f=b(),d=a.parent(),a.css("display","none"),o(F),r.$on("$destroy",function(){P()})}}}])}(window,window.angular);<|endoftext|>


<commit_before>import { src, dest } from 'gulp';

export default function copyAssetsTask() {
  return src('assets/**/*')
    .pipe(dest('lib/assets/'));
}
<commit_msg>build: copy favicon to build root<commit_after>import gulp from 'gulp';
import seq from 'run-sequence';

gulp.task('assets:favicon', () =>
  gulp.src('assets/favicon.ico')
    .pipe(gulp.dest('lib/'))
);

gulp.task('assets:copy', () =>
  gulp.src('assets/**/*')
    .pipe(gulp.dest('lib/assets/'))
);

export default function copyAssetsTask() {
  return seq(['assets:copy', 'assets:favicon']);
}
<|endoftext|>


<commit_before>'use strict';
/*eslint global-require:0*/
const fs = require('fs');
const path = require('path');
let mods = [];

fs.readdirSync(__dirname)
	.filter(item => !(/(^|\/)\.[^\/\.]/g).test(item))
	.filter(item => item !== "index.js")
	.filter(item => item !== "help.js")
	.forEach((file) => {
		mods.push(require(path.join(__dirname, "\\", file)));
	});
module.exports=mods;
<commit_msg>[ci skip] fixed linux path issue<commit_after>'use strict';
/*eslint global-require:0*/
const fs = require('fs');
const path = require('path');
let mods = [];

fs.readdirSync(__dirname)
	.filter(item => !(/(^|\/)\.[^\/\.]/g).test(item))
	.filter(item => item !== "index.js")
	.filter(item => item !== "help.js")
	.forEach((file) => {
		mods.push(require(path.join(__dirname, file)));
	});
module.exports=mods;
<|endoftext|>


<commit_before>/*
 * grunt-html2object
 * https://github.com/antonheryanto/grunt-html2object
 *
 * Copyright (c) 2013 Anton Heryanto
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var minify = require('html-minifier').minify;

  grunt.registerMultiTask('html2object', 'Convert HTML into Javascript Object and used directly in Application', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      target: 'window.$.html',
      storage: '{}',
      htmlmin: {
        collapseBooleanAttributes: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true,
        removeEmptyAttributes: true,
        removeRedundantAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true
      }
    });
    var counter = 0,
        target = options.target + ' || (' + options.target + ' = ' + options.storage + ')';
    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        counter++;
        // Read file source.
        var content = grunt.file.read(filepath).replace(/'/g,"\\'");
        return "$['" + filepath + "']='" + minify(content, options.htmlmin) + "';";
      }).join('\n');

      // Handle options.
      src = '(function($){\n' + src + '\n})(' + target + ')';

      // Write the destination file.
      grunt.file.write(f.dest, grunt.util.normalizelf(src));
    });
    // Print a success message.
    grunt.log.writeln("Successfully converted "+(""+counter).green +
        " html to " + options.target + " and using " + options.storage + " as storage");
  });

};
<commit_msg>add missing semicolon<commit_after>/*
 * grunt-html2object
 * https://github.com/antonheryanto/grunt-html2object
 *
 * Copyright (c) 2013 Anton Heryanto
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var minify = require('html-minifier').minify;

  grunt.registerMultiTask('html2object', 'Convert HTML into Javascript Object and used directly in Application', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      target: 'window.$.html',
      storage: '{}',
      htmlmin: {
        collapseBooleanAttributes: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true,
        removeEmptyAttributes: true,
        removeRedundantAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true
      }
    });
    var counter = 0,
        target = options.target + ' || (' + options.target + ' = ' + options.storage + ')';
    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        counter++;
        // Read file source.
        var content = grunt.file.read(filepath).replace(/'/g,"\\'");
        return "$['" + filepath + "']='" + minify(content, options.htmlmin) + "';";
      }).join('\n');

      // Handle options.
      src = '(function($){\n' + src + '\n})(' + target + ');';

      // Write the destination file.
      grunt.file.write(f.dest, grunt.util.normalizelf(src));
    });
    // Print a success message.
    grunt.log.writeln("Successfully converted "+(""+counter).green +
        " html to " + options.target + " and using " + options.storage + " as storage");
  });

};
<|endoftext|>


<commit_before>var config = require('../relay-config');
var SerialPort = require("serialport");
var socket = require('socket.io-client')(config.serverUrl);
var fs = require('fs')

// Connects the Arduino port with following settings
// Newline parser trigger 'data' event when reaching '\n'
var port = new SerialPort(config.arduinoPort, {
  baudRate: 9600,
  parser: SerialPort.parsers.readline('\n')
});

// Trigged when port connection opens
port.on('open', function() {
	// Fires requests ever 2 seconds
	var interval = setInterval(function () {
		port.write('temp\n')
	}, 10000);
});

// Triggered when arduino sends data followed by '\n'
port.on('data', function (temp) {
	// Creates timestamp
	var d = new Date()
	var date = [d.getFullYear() , d.getMonth()+1, d.getDate()].join('-');
	var time = [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');
	var mysql_datetime = date + ' ' + time;

	// Send data to server
	socket.emit('temp', {datetime: mysql_datetime, temp: temp});
 	console.log('sending ' + mysql_datetime + ' ' + temp);

});

// open errors will be emitted as an error event
port.on('error', function(err) {
  console.log('Error: ', err.message);
});

// Triggered when socket is connected
socket.on('connect', function (err) {
	console.log('connected to server')
	if(err) {
		console.log(err)
	}
});

socket.on('error', function () {
	console.log('error')
});<commit_msg>changed date transfer to ISO 8601<commit_after>var config = require('../relay-config');
var SerialPort = require("serialport");
var socket = require('socket.io-client')(config.serverUrl);
var fs = require('fs')

// Connects the Arduino port with following settings
// Newline parser trigger 'data' event when reaching '\n'
var port = new SerialPort(config.arduinoPort, {
  baudRate: 9600,
  parser: SerialPort.parsers.readline('\n')
});

// Trigged when port connection opens
port.on('open', function() {
	// Fires requests ever 2 seconds
	var interval = setInterval(function () {
		port.write('temp\n')
	}, 10000);
});

// Triggered when arduino sends data followed by '\n'
port.on('data', function (temp) {
	// Creates timestamp
	// var d = new Date()
	// var date = [d.getFullYear() , d.getMonth()+1, d.getDate()].join('-');
	// var time = [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');
	// var mysql_datetime = date + ' ' + time;
	var date = new Date();
	var mysql_datetime = date.toISOString();
	// Send data to server
	socket.emit('temp', {datetime: mysql_datetime, temp: temp});
 	console.log('sending ' + mysql_datetime + ' ' + temp);

});

// open errors will be emitted as an error event
port.on('error', function(err) {
  console.log('Error: ', err.message);
});

// Triggered when socket is connected
socket.on('connect', function (err) {
	console.log('connected to server')
	if(err) {
		console.log(err)
	}
});

socket.on('error', function () {
	console.log('error')
});<|endoftext|>


<commit_before>/*
 * grunt-maven-tasks
 * https://github.com/smh/grunt-maven-tasks
 *
 * Copyright (c) 2013 Stein Martin Hustad
 * Licensed under the MIT license.
 */

'use strict';

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

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  grunt.registerMultiTask('maven', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;
    options.commitPrefix = options.commitPrefix || '%s';

    var pkg = grunt.file.readJSON(options.versionFile || 'package.json');

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this, pkg);
    } else if (options.goal === 'install') {
      install(this, pkg);
    } else if (options.goal === 'release') {
      requireOptionProps(options, ['url']);
      release(this, pkg, version, mode);
    }
  });

  function install(task, pkg) {
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:install-file');
  }

  function deploy(task, pkg) {
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:deploy-file');
  }

  function release(task, pkg, version, mode) {
    var options = task.options({
      artifactId: pkg.name,
      packaging: 'zip',
      mode: 'minor',
      gitpush: false
    });

    if (version && !mode && isValidMode(version)) {
      mode = version;
      version = null;
    }

    options.mode = mode || options.mode;
    options.version = version || pkg.version.substr(0, pkg.version.length - '-SNAPSHOT'.length);

    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }
    options.nextVersion = semver.inc(options.version, options.mode) + '-SNAPSHOT';
    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run(
      'maven:version:' + options.version,
      'maven:package',
      'maven:deploy-file',
      'maven:version:' + options.nextVersion + ':deleteTag'
    );

    if (options.gitpush) {
      grunt.task.run(
        'maven:gitpush'
      );
    }

  }

  function getFileNameBase(options) {
    return options.artifactId + '-' + options.version +
      (options.classifier ? '-' + options.classifier : '');
  }

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = getFileNameBase(options) + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      var fileNameBase = options.destFolder ? options.destFolder : getFileNameBase(options);
      task.files = injectDestFolder(fileNameBase, task.files);
    }
    grunt.config.set('grunt.maven.commitPrefix', options.commitPrefix);
  }

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', { archive: options.file, mode: options.packaging });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  grunt.registerTask('maven:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.packaging = (options.type === 'war' || options.type === 'jar') ? options.type : options.packaging;
    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }
    if (options.uniqueVersion) {
      args.push('-DuniqueVersion=' + options.classifier);
    }
    // The lack of a space after the -s is critical
    // otherwise the path will be processed by maven incorrectly.
    if (options.settingsXml) {
      args.push('-s' + options.settingsXml);
    }
    if (grunt.debug || options.debug) {
      args.push('-e');
      args.push('-X');
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.packaging = (options.type === 'war' || options.type === 'jar') ? options.type : options.packaging;
    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.unsecure){
      args.push('-Dmaven.wagon.http.ssl.insecure='+options.unsecure);
      args.push('-Dmaven.wagon.http.ssl.allowall='+options.unsecure);
    }
    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }
    if (options.settingsXml) {
      // The lack of a space after the -s is critical
      // otherwise the path will be processed by maven incorrectly.
      args.push('-s' + options.settingsXml);
    }
    if (grunt.debug || options.debug) {
      args.push('-e');
      args.push('-X');
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:version', 'Bumps version', function(version, deleteTag) {
    var done = this.async();
    var commitPrefix = grunt.config('grunt.maven.commitPrefix') || '';

    var msg = 'Bumping version to ' + version.cyan + '...';
    grunt.verbose.write(msg);

    grunt.util.spawn({ cmd: 'npm', args: ['version', version, '-m', commitPrefix + '%s'] }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to bump version to ' + version.cyan);
        return done(err);
      }

      grunt.verbose.ok();
      grunt.log.writeln('Version bumped to ' + version.cyan);

      if (!deleteTag) {
        return done();
      }

      isGitRepo(function(isGit) {
        if (!isGit) { return done(); }
        msg = 'Deleting tag v' + version.cyan + '...';
        grunt.verbose.write(msg);
        grunt.util.spawn({ cmd: 'git', args: ['tag', '-d', 'v' + version] }, function(err, result, code) {
          if (err) {
            grunt.verbose.or.write(msg);
            grunt.log.error().error('Failed to delete tag ' + ('v' + version).cyan);
          }

          grunt.verbose.ok();
          grunt.log.writeln('Deleted tag ' + ('v' + version).cyan);

          done(err);
        });
      });
    });
  });

  grunt.registerTask('maven:gitpush', 'Pushes to git', function() {
    var done = this.async();

    grunt.verbose.write('Pushing to git');

    gitPush(function(err) {
      if (err) {
        grunt.log.error().error('Failed to push new version to remote');
      } else {
        grunt.log.writeln('Pushed new version to remote');
      }
      done(err);
    });
  });

  function isGitRepo(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['status', '--porcelain'] }, function(err, result, code) {
      fn(!err);
    });
  }

  function gitPush(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['push'] }, function(err, result, code) {
      fn(err);
    });
  }

  function isValidMode(mode) {
    var validModes = ['major', 'minor', 'patch', 'build'].join('|');

    return mode.indexOf('|') < 0 && validModes.indexOf(mode) >=0;
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

  function renameForKnownPackageTypeArtifacts(fileName, packaging) {

      var newFileName = fileName;
      if (packaging === 'war') {
          newFileName = fileName.replace('zip', 'war');
      } else if (packaging === 'jar') {
          newFileName = fileName.replace('zip', 'jar');
      }

      try {
          fs.renameSync(fileName, newFileName);
          return newFileName;
      } catch (e) {
          throw e;
      }
  }
};
<commit_msg>Fix patch / shame on me<commit_after>/*
 * grunt-maven-tasks
 * https://github.com/smh/grunt-maven-tasks
 *
 * Copyright (c) 2013 Stein Martin Hustad
 * Licensed under the MIT license.
 */

'use strict';

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

function injectDestFolder(targetPath, files) {
  var path = require('path');
  files.forEach(function(file) {
    file.dest = path.join(targetPath, file.dest || '');
  });
  return files;
}

module.exports = function(grunt) {

  grunt.registerMultiTask('maven', 'Packages and deploys artifact to maven repo', function(version, mode) {
    var options = this.options();

    requireOptionProps(options, ['groupId']);

    options.goal = options.goal || this.target;
    options.commitPrefix = options.commitPrefix || '%s';

    var pkg = grunt.file.readJSON(options.versionFile || 'package.json');

    if (options.goal === 'deploy') {
      requireOptionProps(options, ['url']);
      deploy(this, pkg);
    } else if (options.goal === 'install') {
      install(this, pkg);
    } else if (options.goal === 'release') {
      requireOptionProps(options, ['url']);
      release(this, pkg, version, mode);
    }
  });

  function install(task, pkg) {
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:install-file');
  }

  function deploy(task, pkg) {
    var options = task.options({
      artifactId: pkg.name,
      version: pkg.version,
      packaging: 'zip'
    });

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run('maven:package',
      'maven:deploy-file');
  }

  function release(task, pkg, version, mode) {
    var options = task.options({
      artifactId: pkg.name,
      packaging: 'zip',
      mode: 'minor',
      gitpush: false
    });

    if (version && !mode && isValidMode(version)) {
      mode = version;
      version = null;
    }

    options.mode = mode || options.mode;
    options.version = version || pkg.version.substr(0, pkg.version.length - '-SNAPSHOT'.length);

    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }
    options.nextVersion = semver.inc(options.version, options.mode) + '-SNAPSHOT';
    if (options.nextVersion === 'null-SNAPSHOT') {
      grunt.fail.fatal('Failed to determine next development version ' +
        'based on version (' + options.version.cyan +
        ') and mode (' + options.mode.cyan + ')');
    }

    guaranteeFileName(options);
    configureDestination(options, task);
    configureMaven(options, task);

    grunt.task.run(
      'maven:version:' + options.version,
      'maven:package',
      'maven:deploy-file',
      'maven:version:' + options.nextVersion + ':deleteTag'
    );

    if (options.gitpush) {
      grunt.task.run(
        'maven:gitpush'
      );
    }

  }

  function getFileNameBase(options) {
    return options.artifactId + '-' + options.version +
      (options.classifier ? '-' + options.classifier : '');
  }

  function guaranteeFileName(options) {
    if (!options.file) {
      options.file = getFileNameBase(options) + '.' + options.packaging;
    }
  }

  function configureDestination(options, task) {
    if (typeof options.injectDestFolder === 'undefined' || options.injectDestFolder === true) {
      var fileNameBase = options.destFolder ? options.destFolder : getFileNameBase(options);
      task.files = injectDestFolder(fileNameBase, task.files);
    }
    grunt.config.set('grunt.maven.commitPrefix', options.commitPrefix);
  }

  function configureMaven(options, task) {
    grunt.config.set('maven.package.options', { archive: options.file, mode: options.packaging });
    grunt.config.set('maven.package.files', task.files);
    grunt.config.set('maven.deploy-file.options', options);
    grunt.config.set('maven.install-file.options', options);
  }

  grunt.registerTask('maven:package', function() {
    var compress = require('grunt-contrib-compress/tasks/lib/compress')(grunt);
    compress.options = grunt.config('maven.package.options');
    compress.tar(grunt.config('maven.package.files'), this.async());
  });

  grunt.registerTask('maven:install-file', function() {
    var options = grunt.config('maven.install-file.options');

    options.packaging = (options.type === 'war' || options.type === 'jar') ? options.type : options.packaging;
    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'install:install-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }
    if (options.uniqueVersion === 'true') {
      args.push('-DuniqueVersion=true');
    }
    // The lack of a space after the -s is critical
    // otherwise the path will be processed by maven incorrectly.
    if (options.settingsXml) {
      args.push('-s' + options.settingsXml);
    }
    if (grunt.debug || options.debug) {
      args.push('-e');
      args.push('-X');
    }

    var done = this.async();
    var msg = 'Installing to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to install to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Installed ' + options.file.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:deploy-file', function() {
    var options = grunt.config('maven.deploy-file.options');

    options.packaging = (options.type === 'war' || options.type === 'jar') ? options.type : options.packaging;
    options.file = renameForKnownPackageTypeArtifacts(options.file, options.packaging);

    var args = [ 'deploy:deploy-file' ];
    args.push('-Dfile='         + options.file);
    args.push('-DgroupId='      + options.groupId);
    args.push('-DartifactId='   + options.artifactId);
    args.push('-Dpackaging='    + options.packaging);
    args.push('-Dversion='      + options.version);
    if (options.unsecure){
      args.push('-Dmaven.wagon.http.ssl.insecure='+options.unsecure);
      args.push('-Dmaven.wagon.http.ssl.allowall='+options.unsecure);
    }
    if (options.classifier) {
      args.push('-Dclassifier=' + options.classifier);
    }
    if (options.uniqueVersion === 'true') {
      args.push('-DuniqueVersion=true');
    }
    args.push('-Durl='          + options.url);
    if (options.repositoryId) {
      args.push('-DrepositoryId=' + options.repositoryId);
    }
    if (options.settingsXml) {
      // The lack of a space after the -s is critical
      // otherwise the path will be processed by maven incorrectly.
      args.push('-s' + options.settingsXml);
    }
    if (grunt.debug || options.debug) {
      args.push('-e');
      args.push('-X');
    }

    var done = this.async();
    var msg = 'Deploying to maven...';
    grunt.verbose.write(msg);
    grunt.log.debug('Running command "mvn ' + args.join(' ') + '"');
    grunt.util.spawn({ cmd: 'mvn', args: args, opts: {stdio: 'inherit'} }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to deploy to maven');
      } else {
        grunt.verbose.ok();
        grunt.log.writeln('Deployed ' + options.file.cyan + ' to ' + options.url.cyan);
      }
      done(err);
    });
  });

  grunt.registerTask('maven:version', 'Bumps version', function(version, deleteTag) {
    var done = this.async();
    var commitPrefix = grunt.config('grunt.maven.commitPrefix') || '';

    var msg = 'Bumping version to ' + version.cyan + '...';
    grunt.verbose.write(msg);

    grunt.util.spawn({ cmd: 'npm', args: ['version', version, '-m', commitPrefix + '%s'] }, function(err, result, code) {
      if (err) {
        grunt.verbose.or.write(msg);
        grunt.log.error().error('Failed to bump version to ' + version.cyan);
        return done(err);
      }

      grunt.verbose.ok();
      grunt.log.writeln('Version bumped to ' + version.cyan);

      if (!deleteTag) {
        return done();
      }

      isGitRepo(function(isGit) {
        if (!isGit) { return done(); }
        msg = 'Deleting tag v' + version.cyan + '...';
        grunt.verbose.write(msg);
        grunt.util.spawn({ cmd: 'git', args: ['tag', '-d', 'v' + version] }, function(err, result, code) {
          if (err) {
            grunt.verbose.or.write(msg);
            grunt.log.error().error('Failed to delete tag ' + ('v' + version).cyan);
          }

          grunt.verbose.ok();
          grunt.log.writeln('Deleted tag ' + ('v' + version).cyan);

          done(err);
        });
      });
    });
  });

  grunt.registerTask('maven:gitpush', 'Pushes to git', function() {
    var done = this.async();

    grunt.verbose.write('Pushing to git');

    gitPush(function(err) {
      if (err) {
        grunt.log.error().error('Failed to push new version to remote');
      } else {
        grunt.log.writeln('Pushed new version to remote');
      }
      done(err);
    });
  });

  function isGitRepo(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['status', '--porcelain'] }, function(err, result, code) {
      fn(!err);
    });
  }

  function gitPush(fn) {
    grunt.util.spawn({ cmd: 'git', args: ['push'] }, function(err, result, code) {
      fn(err);
    });
  }

  function isValidMode(mode) {
    var validModes = ['major', 'minor', 'patch', 'build'].join('|');

    return mode.indexOf('|') < 0 && validModes.indexOf(mode) >=0;
  }

  function requireOptionProps(options, props) {
    var msg = 'Verifying properties ' + grunt.log.wordlist(props) + ' exists in options...';
    grunt.verbose.write(msg);

    var failProps = props.filter(function(p) {
      return !options.hasOwnProperty(p);
    }).map(function(p) {
      return '"' + p + '"';
    });

    if (failProps.length === 0) {
      grunt.verbose.ok();
    } else {
      grunt.verbose.or.write(msg);
      grunt.log.error().error('Unable to process task.');
      throw grunt.util.error('Required options ' + failProps.join(', ') + ' missing.');
    }
  }

  function renameForKnownPackageTypeArtifacts(fileName, packaging) {

      var newFileName = fileName;
      if (packaging === 'war') {
          newFileName = fileName.replace('zip', 'war');
      } else if (packaging === 'jar') {
          newFileName = fileName.replace('zip', 'jar');
      }

      try {
          fs.renameSync(fileName, newFileName);
          return newFileName;
      } catch (e) {
          throw e;
      }
  }
};
<|endoftext|>


<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end

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

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
  return path.resolve(appDirectory, relativePath);
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.

// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421

var nodePaths = (process.env.NODE_PATH || '')
  .split(process.platform === 'win32' ? ';' : ':')
  .filter(Boolean)
  .filter(folder => !path.isAbsolute(folder))
  .map(resolveApp);

// config after eject: we're in ./config/
module.exports = {
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  ownNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths
};

// @remove-on-eject-begin
function resolveOwn(relativePath) {
  return path.resolve(__dirname, relativePath);
}

// config before eject: we're in ./node_modules/react-scripts/config/
module.exports = {
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  // this is empty with npm3 but node resolution searches higher anyway:
  ownNodeModules: resolveOwn('../node_modules'),
  nodePaths: nodePaths
};

// config before publish: we're in ./packages/react-scripts/config/
if (__dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1) {
  module.exports = {
    appBuild: resolveOwn('../../../build'),
    appPublic: resolveOwn('../template/public'),
    appHtml: resolveOwn('../template/public/index.html'),
    appIndexJs: resolveOwn('../template/src/index.js'),
    appPackageJson: resolveOwn('../package.json'),
    appSrc: resolveOwn('../template/src'),
    yarnLockFile: resolveOwn('../template/yarn.lock'),
    testsSetup: resolveOwn('../template/src/setupTests.js'),
    appNodeModules: resolveOwn('../node_modules'),
    ownNodeModules: resolveOwn('../node_modules'),
    nodePaths: nodePaths
  };
}
// @remove-on-eject-end
<commit_msg>update paths for correct ejecting<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end

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

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
  return path.resolve(appDirectory, relativePath);
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.

// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421

var nodePaths = (process.env.NODE_PATH || '')
  .split(process.platform === 'win32' ? ';' : ':')
  .filter(Boolean)
  .filter(folder => !path.isAbsolute(folder))
  .map(resolveApp);

// config after eject: we're in ./config/
module.exports = {
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  ownNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths
};

// @remove-on-eject-begin
function resolveOwn(relativePath) {
  return path.resolve(__dirname, relativePath);
}

// config before eject: we're in ./node_modules/react-scripts/config/
module.exports = {
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  // this is empty with npm3 but node resolution searches higher anyway:
  ownNodeModules: resolveOwn('../node_modules'),
  nodePaths: nodePaths
};

// config before publish: we're in ./packages/react-scripts/config/
if (__dirname.indexOf(path.join('packages', '@just-boris', 'preact-scripts', 'config')) !== -1) {
  module.exports = {
    appBuild: resolveOwn('../../../build'),
    appPublic: resolveOwn('../template/public'),
    appHtml: resolveOwn('../template/public/index.html'),
    appIndexJs: resolveOwn('../template/src/index.js'),
    appPackageJson: resolveOwn('../package.json'),
    appSrc: resolveOwn('../template/src'),
    yarnLockFile: resolveOwn('../template/yarn.lock'),
    testsSetup: resolveOwn('../template/src/setupTests.js'),
    appNodeModules: resolveOwn('../node_modules'),
    ownNodeModules: resolveOwn('../node_modules'),
    nodePaths: nodePaths
  };
}
// @remove-on-eject-end
<|endoftext|>


<commit_before>// @remove-file-on-eject
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
"use strict";

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on("unhandledRejection", err => {
  throw err;
});

const fs = require("fs-extra");
const path = require("path");
const chalk = require("chalk");
const spawn = require("react-dev-utils/crossSpawn");

module.exports = function(
  appPath,
  appName,
  verbose,
  originalDirectory,
  template
) {
  const ownPackageName = require(path.join(__dirname, "..", "package.json"))
    .name;
  const ownPath = path.join(appPath, "node_modules", ownPackageName);
  const appPackage = require(path.join(appPath, "package.json"));
  const useYarn = fs.existsSync(path.join(appPath, "yarn.lock"));

  // Copy over some of the devDependencies
  appPackage.dependencies = appPackage.dependencies || {};

  // Setup the script rules
  appPackage.scripts = {
    analyze: "source-map-explorer build/static/js/main.*",
    start: "react-scripts start",
    build: "react-scripts build",
    test: "react-scripts test --env=jsdom",
    ["test-ci"]:
      "set CI=true && yarn test -- --testResultsProcessor jest-junit --coverage --coverageDirectory=../../../target/reports/cobertura",
    coverage: "yarn test -- --coverage",
    eject: "react-scripts eject",
    precommit: "pretty-quick --staged",
    postcommit: "cd ../../../ && git reset"
  };

  // Setup custom Jest config with jest-junit package
  appPackage.jest = {
    coverageReporters: ["cobertura"]
  };

  appPackage["jest-junit"] = {
    suiteName: "Jest Tests",
    output: "../../../target/surefire-reports/frontend-tests.xml",
    classNameTemplate: "{classname}-{title}",
    titleTemplate: "{classname}-{title}",
    ancestorSeparator: " › ",
    usePathForSuiteName: "true"
  };

  fs.writeFileSync(
    path.join(appPath, "package.json"),
    JSON.stringify(appPackage, null, 2)
  );

  const readmeExists = fs.existsSync(path.join(appPath, "README.md"));
  if (readmeExists) {
    fs.renameSync(
      path.join(appPath, "README.md"),
      path.join(appPath, "README.old.md")
    );
  }

  // Copy the files for the user
  const templatePath = template
    ? path.resolve(originalDirectory, template)
    : path.join(ownPath, "template");
  if (fs.existsSync(templatePath)) {
    fs.copySync(templatePath, appPath);
  } else {
    console.error(
      `Could not locate supplied template: ${chalk.green(templatePath)}`
    );
    return;
  }

  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  // See: https://github.com/npm/npm/issues/1862
  fs.move(
    path.join(appPath, "gitignore"),
    path.join(appPath, ".gitignore"),
    [],
    err => {
      if (err) {
        // Append if there's already a `.gitignore` file there
        if (err.code === "EEXIST") {
          const data = fs.readFileSync(path.join(appPath, "gitignore"));
          fs.appendFileSync(path.join(appPath, ".gitignore"), data);
          fs.unlinkSync(path.join(appPath, "gitignore"));
        } else {
          throw err;
        }
      }
    }
  );

  let command;
  let args;

  if (useYarn) {
    command = "yarnpkg";
    args = ["add"];
  } else {
    command = "npm";
    args = ["install", "--save", verbose && "--verbose"].filter(e => e);
  }
  args.push("react", "react-dom");

  // Install additional template dependencies, if present
  const templateDependenciesPath = path.join(
    appPath,
    ".template.dependencies.json"
  );
  if (fs.existsSync(templateDependenciesPath)) {
    const templateDependencies = require(templateDependenciesPath).dependencies;
    args = args.concat(
      Object.keys(templateDependencies).map(key => {
        return `${key}@${templateDependencies[key]}`;
      })
    );
    fs.unlinkSync(templateDependenciesPath);
  }

  // Install react and react-dom for backward compatibility with old CRA cli
  // which doesn't install react and react-dom along with react-scripts
  // or template is presetend (via --internal-testing-template)
  if (!isReactInstalled(appPackage) || template) {
    console.log(`Installing react and react-dom using ${command}...`);
    console.log();

    const proc = spawn.sync(command, args, { stdio: "inherit" });
    if (proc.status !== 0) {
      console.error(`\`${command} ${args.join(" ")}\` failed`);
      return;
    }
  }

  // Display the most elegant way to cd.
  // This needs to handle an undefined originalDirectory for
  // backward compatibility with old global-cli's.
  let cdpath;
  if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
    cdpath = appName;
  } else {
    cdpath = appPath;
  }

  // Change displayed command to yarn instead of yarnpkg
  const displayedCommand = useYarn ? "yarn" : "npm";

  console.log();
  console.log(`Success! Created ${appName} at ${appPath}`);
  console.log("Inside that directory, you can run several commands:");
  console.log();
  console.log(chalk.cyan(`  ${displayedCommand} start`));
  console.log("    Starts the development server.");
  console.log();
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? "" : "run "}build`)
  );
  console.log("    Bundles the app into static files for production.");
  console.log();
  console.log(chalk.cyan(`  ${displayedCommand} test`));
  console.log("    Starts the test runner.");
  console.log();
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? "" : "run "}eject`)
  );
  console.log(
    "    Removes this tool and copies build dependencies, configuration files"
  );
  console.log(
    "    and scripts into the app directory. If you do this, you can’t go back!"
  );
  console.log();
  console.log("We suggest that you begin by typing:");
  console.log();
  console.log(chalk.cyan("  cd"), cdpath);
  console.log(`  ${chalk.cyan(`${displayedCommand} start`)}`);
  if (readmeExists) {
    console.log();
    console.log(
      chalk.yellow(
        "You had a `README.md` file, we renamed it to `README.old.md`"
      )
    );
  }
  console.log();
  console.log("Happy hacking!");
};

function isReactInstalled(appPackage) {
  const dependencies = appPackage.dependencies || {};

  return (
    typeof dependencies.react !== "undefined" &&
    typeof dependencies["react-dom"] !== "undefined"
  );
}
<commit_msg>refactor: update junit reporter<commit_after>// @remove-file-on-eject
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
"use strict";

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on("unhandledRejection", err => {
  throw err;
});

const fs = require("fs-extra");
const path = require("path");
const chalk = require("chalk");
const spawn = require("react-dev-utils/crossSpawn");

module.exports = function(
  appPath,
  appName,
  verbose,
  originalDirectory,
  template
) {
  const ownPackageName = require(path.join(__dirname, "..", "package.json"))
    .name;
  const ownPath = path.join(appPath, "node_modules", ownPackageName);
  const appPackage = require(path.join(appPath, "package.json"));
  const useYarn = fs.existsSync(path.join(appPath, "yarn.lock"));

  // Copy over some of the devDependencies
  appPackage.dependencies = appPackage.dependencies || {};

  // Setup the script rules
  appPackage.scripts = {
    analyze: "source-map-explorer build/static/js/main.*",
    start: "react-scripts start",
    build: "react-scripts build",
    test: "react-scripts test --env=jsdom",
    ["test-ci"]:
      "set CI=true && yarn test --testResultsProcessor jest-junit --coverage --coverageDirectory=../../../target/reports/cobertura",
    coverage: "yarn test --coverage",
    eject: "react-scripts eject",
    precommit: "pretty-quick --staged",
    postcommit: "cd ../../../ && git reset"
  };

  // Setup custom Jest config with jest-junit package
  appPackage.jest = {
    coverageReporters: ["cobertura"],
    reporters: [
      "default",
      [
        "jest-junit",
        {
          suiteName: "Jest Tests",
          output: "../../../target/surefire-reports/frontend-tests.xml",
          classNameTemplate: "{classname}-{title}",
          titleTemplate: "{classname}-{title}",
          ancestorSeparator: " › ",
          usePathForSuiteName: "true"
        }
      ]
    ]
  };

  fs.writeFileSync(
    path.join(appPath, "package.json"),
    JSON.stringify(appPackage, null, 2)
  );

  const readmeExists = fs.existsSync(path.join(appPath, "README.md"));
  if (readmeExists) {
    fs.renameSync(
      path.join(appPath, "README.md"),
      path.join(appPath, "README.old.md")
    );
  }

  // Copy the files for the user
  const templatePath = template
    ? path.resolve(originalDirectory, template)
    : path.join(ownPath, "template");
  if (fs.existsSync(templatePath)) {
    fs.copySync(templatePath, appPath);
  } else {
    console.error(
      `Could not locate supplied template: ${chalk.green(templatePath)}`
    );
    return;
  }

  // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
  // See: https://github.com/npm/npm/issues/1862
  fs.move(
    path.join(appPath, "gitignore"),
    path.join(appPath, ".gitignore"),
    [],
    err => {
      if (err) {
        // Append if there's already a `.gitignore` file there
        if (err.code === "EEXIST") {
          const data = fs.readFileSync(path.join(appPath, "gitignore"));
          fs.appendFileSync(path.join(appPath, ".gitignore"), data);
          fs.unlinkSync(path.join(appPath, "gitignore"));
        } else {
          throw err;
        }
      }
    }
  );

  let command;
  let args;

  if (useYarn) {
    command = "yarnpkg";
    args = ["add"];
  } else {
    command = "npm";
    args = ["install", "--save", verbose && "--verbose"].filter(e => e);
  }
  args.push("react", "react-dom");

  // Install additional template dependencies, if present
  const templateDependenciesPath = path.join(
    appPath,
    ".template.dependencies.json"
  );
  if (fs.existsSync(templateDependenciesPath)) {
    const templateDependencies = require(templateDependenciesPath).dependencies;
    args = args.concat(
      Object.keys(templateDependencies).map(key => {
        return `${key}@${templateDependencies[key]}`;
      })
    );
    fs.unlinkSync(templateDependenciesPath);
  }

  // Install react and react-dom for backward compatibility with old CRA cli
  // which doesn't install react and react-dom along with react-scripts
  // or template is presetend (via --internal-testing-template)
  if (!isReactInstalled(appPackage) || template) {
    console.log(`Installing react and react-dom using ${command}...`);
    console.log();

    const proc = spawn.sync(command, args, { stdio: "inherit" });
    if (proc.status !== 0) {
      console.error(`\`${command} ${args.join(" ")}\` failed`);
      return;
    }
  }

  // Display the most elegant way to cd.
  // This needs to handle an undefined originalDirectory for
  // backward compatibility with old global-cli's.
  let cdpath;
  if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
    cdpath = appName;
  } else {
    cdpath = appPath;
  }

  // Change displayed command to yarn instead of yarnpkg
  const displayedCommand = useYarn ? "yarn" : "npm";

  console.log();
  console.log(`Success! Created ${appName} at ${appPath}`);
  console.log("Inside that directory, you can run several commands:");
  console.log();
  console.log(chalk.cyan(`  ${displayedCommand} start`));
  console.log("    Starts the development server.");
  console.log();
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? "" : "run "}build`)
  );
  console.log("    Bundles the app into static files for production.");
  console.log();
  console.log(chalk.cyan(`  ${displayedCommand} test`));
  console.log("    Starts the test runner.");
  console.log();
  console.log(
    chalk.cyan(`  ${displayedCommand} ${useYarn ? "" : "run "}eject`)
  );
  console.log(
    "    Removes this tool and copies build dependencies, configuration files"
  );
  console.log(
    "    and scripts into the app directory. If you do this, you can’t go back!"
  );
  console.log();
  console.log("We suggest that you begin by typing:");
  console.log();
  console.log(chalk.cyan("  cd"), cdpath);
  console.log(`  ${chalk.cyan(`${displayedCommand} start`)}`);
  if (readmeExists) {
    console.log();
    console.log(
      chalk.yellow(
        "You had a `README.md` file, we renamed it to `README.old.md`"
      )
    );
  }
  console.log();
  console.log("Happy hacking!");
};

function isReactInstalled(appPackage) {
  const dependencies = appPackage.dependencies || {};

  return (
    typeof dependencies.react !== "undefined" &&
    typeof dependencies["react-dom"] !== "undefined"
  );
}
<|endoftext|>


<commit_before>// Example of currently available facts
console.log(facts.Hostname)
console.log(facts.Domain)
console.log(facts.Fqdn)
console.log(facts.Cpus)
console.log(facts.Os)
for (interface in facts.Interfaces) {
	console.log("##########################")
	console.log(interface)
	console.log(facts.Interfaces[interface]["MTU"])
	console.log(facts.Interfaces[interface]["HardwareAddr"])
	var addresses = facts.Interfaces[interface]["Addresses"]
	for (address in addresses) {
		console.log(addresses[address]["Address"])
	}

}
<commit_msg>Update facts to reflect change to lowercase.<commit_after>// Example of currently available facts
console.log(facts.hostname)
console.log(facts.domain)
console.log(facts.fqdn)
console.log(facts.cpus)
console.log(facts.os)
for (interface in facts.interfaces) {
	console.log("##########################")
	console.log(interface)
	console.log(facts.Interfaces[interface]["mtu"])
	console.log(facts.Interfaces[interface]["hardware_addr"])
	var addresses = facts.Interfaces[interface]["addresses"]
	for (address in addresses) {
		console.log(addresses[address]["address"])
	}

}
<|endoftext|>


<commit_before>var Hubfs = require('hubfs.js')
var pkg = require('../package.json')

var config = {
  version: pkg.version,
  githubToken: process.env.GITHUB_TOKEN,
  repo: 'digital-democracy.org',
  owner: 'digidem',
  branches: process.env.GITHUB_BRANCH ? process.env.GITHUB_BRANCH.split(',') : ['master'],
  filename: '_redirects'
}
var UPDATE_MESSAGE = '[UPDATE-MAPEO-VERSION] update ' + config.filename

var hubfsOptions = {
  owner: config.owner,
  repo: config.repo,
  auth: {
    token: config.githubToken
  }
}

var gh = Hubfs(hubfsOptions)

gh.readFile(config.filename, { ref: config.branches[0] }, function (err, data) {
  if (err) {
    if (!(/not found/i.test(err) || err.notFound)) {
      return onError(err)
    }
  }
  var version = config.version
  var macLine = `/mapeo/latest/mac https://github.com/digidem/mapeo-desktop/releases/download/v${version}/Installar_Mapeo_v${version}_macOS.dmg`
  var windowsLine = `/mapeo/latest/windows https://github.com/digidem/mapeo-desktop/releases/download/v${version}/Installar_Mapeo_${version}_Windows.exe`
  var res = []
  data.toString().split('\n').map(function (line) {
    if (line.length > 0 && !line.match(/mapeo\/latest\//)) {
      res.push(line.trim())
    }
  })
  res.push(macLine)
  res.push(windowsLine)
  data = res.join('\n')

  var pending = config.branches.length
  config.branches.forEach(function (branch) {
    var opts = {
      message: UPDATE_MESSAGE,
      branch: branch
    }
    gh.writeFile(config.filename, data, opts, done)
  })

  function done (err) {
    if (err) return onError(err)
    if (--pending > 0) return
    process.exit(0)
  }
})

function onError (err) {
  console.trace(err)
}
<commit_msg>chore(release): Fix website release update script<commit_after>#!/usr/bin/env node

var Hubfs = require('hubfs.js')
var pkg = require('../package.json')

var config = {
  version: pkg.version,
  githubToken: process.env.GITHUB_TOKEN,
  repo: 'digital-democracy.org',
  owner: 'digidem',
  branches: process.env.GITHUB_BRANCH
    ? process.env.GITHUB_BRANCH.split(',')
    : ['master'],
  filename: '_redirects'
}
var UPDATE_MESSAGE = '[UPDATE-MAPEO-VERSION] update ' + config.filename

var hubfsOptions = {
  owner: config.owner,
  repo: config.repo,
  auth: {
    token: config.githubToken
  }
}

var gh = Hubfs(hubfsOptions)

gh.readFile(config.filename, { ref: config.branches[0] }, function (err, data) {
  if (err) {
    if (!(/not found/i.test(err) || err.notFound)) {
      return onError(err)
    }
  }
  var version = config.version
  var macLine = `/mapeo/latest/mac https://github.com/digidem/mapeo-desktop/releases/download/v${version}/Installar_Mapeo_v${version}_mac.dmg 302`
  var windowsLine = `/mapeo/latest/windows https://github.com/digidem/mapeo-desktop/releases/download/v${version}/Installar_Mapeo_v${version}_win.exe 302`
  var res = []
  data
    .toString()
    .split('\n')
    .map(function (line) {
      if (line.length > 0 && !line.match(/mapeo\/latest\//)) {
        res.push(line.trim())
      }
    })
  res.push(macLine)
  res.push(windowsLine)
  data = res.join('\n') + '\n'

  var pending = config.branches.length
  config.branches.forEach(function (branch) {
    var opts = {
      message: UPDATE_MESSAGE,
      branch: branch
    }
    gh.writeFile(config.filename, data, opts, done)
  })

  function done (err) {
    if (err) return onError(err)
    if (--pending > 0) return
    process.exit(0)
  }
})

function onError (err) {
  console.trace(err)
}
<|endoftext|>


<commit_before>var _ = require("lodash");
var pkgm = require("../packages").manager;

// List packages
var list = function(args) {
    return _.map(pkgm.orderedPackages(), function(pkg) {
        return pkg.infos();
    });
};

// Install packages
var install = function(args) {
    if (!args.url) throw "Need 'url'";

    return pkgm.installByUri(args.url).post("infos");
};

module.exports = {
    'list': list,
    'install': install
};
<commit_msg>Add method 'install' to service 'packages'<commit_after>var _ = require("lodash");
var pkgm = require("../packages").manager;

// List packages
var list = function(args) {
    return _.map(pkgm.orderedPackages(), function(pkg) {
        return pkg.infos();
    });
};

// Install packages
var install = function(args) {
    if (!args.url) throw "Need 'url'";

    return pkgm.installByUri(args.url).post("infos");
};

// Uninstall package
var uninstall = function(args) {
    if (!args.name) throw "Need 'name'";

    return pkgm.uninstall(args.name).post("infos");
};

module.exports = {
    'list': list,
    'install': install,
    'uninstall': uninstall
};
<|endoftext|>


<commit_before>jQuery(function($) {
  window.dataExplorer = null;
  window.explorerDiv = $('.data-explorer-here');

  // see if we have any configuration from query string
  var state = recline.View.parseQueryString(decodeURIComponent(window.location.search));
  if (state) {
    _.each(state, function(value, key) {
      try {
        value = JSON.parse(value);
      } catch(e) {}
      state[key] = value;
    });
  } else {
    state.url = 'demo';
  }
  var dataset = null;
  if (state.dataset || state.url) {
    dataset = recline.Model.Dataset.restore(state);
  } else {
    dataset = localDataset();
  }
  createExplorer(dataset, state);
});

// make Explorer creation / initialization in a function so we can call it
// again and again
var createExplorer = function(dataset, state) {
  // remove existing data explorer view
  var reload = false;
  if (window.dataExplorer) {
    window.dataExplorer.remove();
    reload = true;
  }
  window.dataExplorer = null;
  var $el = $('<div />');
  $el.appendTo(window.explorerDiv);

  window.dataExplorer = new recline.View.MultiView({
    model: dataset,
    el: $el,
    state: state
  });
}

// provide a demonstration in memory dataset
function localDataset() {
  var dataset = Fixture.getDataset();
  return dataset;
}

<commit_msg>[demos/multiview][s]: explicitly configure views for multiview (so as to hide timeline which is misehaving at that width/size).<commit_after>jQuery(function($) {
  window.dataExplorer = null;
  window.explorerDiv = $('.data-explorer-here');

  // This is some fancy stuff to allow configuring the multiview from
  // parameters in the query string
  //
  // For more on state see the view documentation.
  var state = recline.View.parseQueryString(decodeURIComponent(window.location.search));
  if (state) {
    _.each(state, function(value, key) {
      try {
        value = JSON.parse(value);
      } catch(e) {}
      state[key] = value;
    });
  } else {
    state.url = 'demo';
  }
  var dataset = null;
  if (state.dataset || state.url) {
    dataset = recline.Model.Dataset.restore(state);
  } else {
    dataset = localDataset();
  }
  createExplorer(dataset, state);
});

// make Explorer creation / initialization in a function so we can call it
// again and again
var createExplorer = function(dataset, state) {
  // remove existing data explorer view
  var reload = false;
  if (window.dataExplorer) {
    window.dataExplorer.remove();
    reload = true;
  }
  window.dataExplorer = null;
  var $el = $('<div />');
  $el.appendTo(window.explorerDiv);

  var views = [
    {
      id: 'grid',
      label: 'Grid',
      view: new recline.View.SlickGrid({
        model: dataset
      }),
    },
    {
      id: 'graph',
      label: 'Graph',
      view: new recline.View.Graph({
        model: dataset
      }),
    },
    {
      id: 'map',
      label: 'Map',
      view: new recline.View.Map({
        model: dataset
      }),
    },
    {
      id: 'transform',
      label: 'Transform',
      view: new recline.View.Transform({
        model: dataset
      })
    }
  ];

  window.dataExplorer = new recline.View.MultiView({
    model: dataset,
    el: $el,
    state: state,
    views: views
  });
}

// provide a demonstration in memory dataset
function localDataset() {
  var dataset = Fixture.getDataset();
  return dataset;
}

<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import ifReact from 'enzyme-adapter-react-helper/build/ifReact';
import Portal from '../src/PortalCompat';
import PortalWithState from '../src/PortalWithState';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isPortalOneActive: false,
      isPortalTwoActive: false
    };
  }

  render() {
    return (

React Portal Examples

            https://github.com/tajo/react-portal

Portal (stateless)

        <button
          onClick={() =>
            this.setState(prevState => ({
              isPortalOneActive: !prevState.isPortalOneActive
            }))
          }
        >
          Toggle
        </button>
        {this.state.isPortalOneActive && (
          <Portal>

This thing was portaled!

          </Portal>
        )}

Portal (stateless, custom node)

        <button
          onClick={() =>
            this.setState(prevState => ({
              isPortalTwoActive: !prevState.isPortalTwoActive
            }))
          }
        >
          Toggle
        </button>
        {this.state.isPortalTwoActive && (
          <Portal node={document && document.getElementById('user-node')}>

This thing was portaled with custom node!

          </Portal>
        )}

PortalWithState

        <PortalWithState closeOnOutsideClick closeOnEsc>
          {ifReact(
            '< 16',
            ({ openPortal, closePortal, isOpen, portal }) => (

                <button key="foo" onClick={openPortal}>
                  Open Portal {isOpen && '(this counts as an outside click)'}
                </button>
                {portal(

                    This is more advanced Portal. It handles its own state.{' '}
                    <button onClick={closePortal}>Close me!</button>, hit ESC or
                    click outside of me.

                )}

            ),
            ({ openPortal, closePortal, isOpen, portal }) => [
              <button key="foo" onClick={openPortal}>
                Open Portal {isOpen && '(this counts as an outside click)'}
              </button>,
              portal(

                  This is more advanced Portal. It handles its own state.{' '}
                  <button onClick={closePortal}>Close me!</button>, hit ESC or
                  click outside of me.

              )
            ]
          )}
        </PortalWithState>

    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<commit_msg>Updated examples with Fragment syntax<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import ifReact from 'enzyme-adapter-react-helper/build/ifReact';
import Portal from '../src/PortalCompat';
import PortalWithState from '../src/PortalWithState';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isPortalOneActive: false,
      isPortalTwoActive: false
    };
  }

  render() {
    return (

React Portal Examples

            https://github.com/tajo/react-portal

Portal (stateless)

        <button
          onClick={() =>
            this.setState(prevState => ({
              isPortalOneActive: !prevState.isPortalOneActive
            }))
          }
        >
          Toggle
        </button>
        {this.state.isPortalOneActive && (
          <Portal>

This thing was portaled!

          </Portal>
        )}

Portal (stateless, custom node)

        <button
          onClick={() =>
            this.setState(prevState => ({
              isPortalTwoActive: !prevState.isPortalTwoActive
            }))
          }
        >
          Toggle
        </button>
        {this.state.isPortalTwoActive && (
          <Portal node={document && document.getElementById('user-node')}>

This thing was portaled with custom node!

          </Portal>
        )}

PortalWithState

        <PortalWithState closeOnOutsideClick closeOnEsc>
          {ifReact(
            '< 16.2',
            ({ openPortal, closePortal, isOpen, portal }) => (

                <button key="foo" onClick={openPortal}>
                  Open Portal {isOpen && '(this counts as an outside click)'}
                </button>
                {portal(

                    This is more advanced Portal. It handles its own state.{' '}
                    <button onClick={closePortal}>Close me!</button>, hit ESC or
                    click outside of me.

                )}

            ),
            ({ openPortal, closePortal, isOpen, portal }) => (
              <React.Fragment>
                <button onClick={openPortal}>
                  Open Portal {isOpen && '(this counts as an outside click)'}
                </button>
                {portal(

                    This is more advanced Portal. It handles its own state.{' '}
                    <button onClick={closePortal}>Close me!</button>, hit ESC or
                    click outside of me.

                )}
              </React.Fragment>
            )
          )}
        </PortalWithState>

    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<|endoftext|>