<commit_before>//require('load-grunt-tasks')(grunt);

module.exports = function(grunt) {
    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    // Project configuration.
    grunt.initConfig({
        stylus: {
          compile: {
              options: {
                  paths: ["node_modules/axis/",
                          "node_modules/jeet/stylus/",
                          "node_modules/rupture/",
                  ],
                  urlfunc: "embedurl",
              },
              files: {
                  "static/css/s.css": "styl/s.styl"
              }
          }
        },
         shell: {
             build: {
                 command: function () {
                     comm = "hugo"
                     return comm
                 },
             },
             update: {
                 command: function () {
                     comm = "npm update caniuse-db"
                     return comm
                 }
             },
         },
        autoprefixer: {
             single_file: {
                 options: {
                     browsers: ["> 1%", "ie10", "ie11"]
                 },
                 src: 'static/css/s.css',
                 dest: 'static/css/s.css'
             },
        },
        cssmin: {
            options: {
                report: 'min'
            },
            main: {
                expand: true,
                cwd: 'public/',
                src: '**/*.css',
                dest: 'public/'
            }
        },
        compress: {
            main: {
                options: { mode: 'gzip', pretty: true, level: 9},
                expand: true,
                cwd: "public/",
                src: ["**/*.html", "**/*.css"],
                dest: "preflight/",
            },
        },
        htmlmin: {
            dist: {
                options: {
                    removeComments: true,
                    collapseWhitespace: true
                },
                expand: true,
                cwd: 'public',
                src: ['**/*.html'],
                dest: 'public/'
            }
        },
        concat: {
          css: {
              src: ['static/css/s.css', "node_modules/grunt-highlight/node_modules/highlight.js/styles/tomorrow.css"],
              dest: 'static/css/s.css'
          },
        },
   dom_munger: {
    archive: {
      options: {
        read: [
          //{selector:'link',attribute:'href',writeto:'myCssRefs',isPath:true},
          //{selector:'script[src]',attribute:'src',writeto:'myJsRefs',isPath:true}
        ],
          //remove: 'div#archiveblock>div#archiveitem:first-child',
          remove: "#archiveblock>div:first-child"
      },
      src: 'public/archive/index.html', //could be an array of files
    },
  },
  highlight: {
    task: {
      options: {},
        expand: true,
        cwd: 'public',
        src: ["**/*.html"],
        dest: "public/"
    }
  },
        clean: {
            build: ["public/*", "preflight/*"],
        },
  });

    require('matchdep').filter('grunt-*').forEach(grunt.loadNpmTasks);
    grunt.registerTask('cl', ['clean:build','shell:update']);
    grunt.registerTask("css", ["stylus","concat", "cssmin"]);
    grunt.registerTask("cssdev", ["stylus", "concat"]);
    grunt.registerTask("push_production", ["aws_s3:production", "aws_s3:gzipd"]);
    grunt.registerTask("hugo", ["shell:build"]);
    grunt.registerTask("kill", ["cloudfront:all"]);
    grunt.registerTask('dev', ['clean:build',
                               'css',
                               'shell:build',
                               'dom_munger:archive'
                              ]);
    grunt.registerTask("build", ['clean:build',
                               "css",
                               "shell:update",
                               "autoprefixer",
                               "hugo",
                               "dom_munger:archive",
                               "htmlmin",
                               "compress",
                              ]);
        };
<commit_msg>specify which version of hugo<commit_after>//require('load-grunt-tasks')(grunt);

module.exports = function(grunt) {
    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    // Project configuration.
    grunt.initConfig({
        stylus: {
          compile: {
              options: {
                  paths: ["node_modules/axis/",
                          "node_modules/jeet/stylus/",
                          "node_modules/rupture/",
                  ],
                  urlfunc: "embedurl",
              },
              files: {
                  "static/css/s.css": "styl/s.styl"
              }
          }
        },
         shell: {
             build: {
                 command: function () {
                     comm = "hugo_0.19"
                     return comm
                 },
             },
             update: {
                 command: function () {
                     comm = "npm update caniuse-db"
                     return comm
                 }
             },
         },
        autoprefixer: {
             single_file: {
                 options: {
                     browsers: ["> 1%", "ie10", "ie11"]
                 },
                 src: 'static/css/s.css',
                 dest: 'static/css/s.css'
             },
        },
        cssmin: {
            options: {
                report: 'min'
            },
            main: {
                expand: true,
                cwd: 'public/',
                src: '**/*.css',
                dest: 'public/'
            }
        },
        compress: {
            main: {
                options: { mode: 'gzip', pretty: true, level: 9},
                expand: true,
                cwd: "public/",
                src: ["**/*.html", "**/*.css"],
                dest: "preflight/",
            },
        },
        htmlmin: {
            dist: {
                options: {
                    removeComments: true,
                    collapseWhitespace: true
                },
                expand: true,
                cwd: 'public',
                src: ['**/*.html'],
                dest: 'public/'
            }
        },
        concat: {
          css: {
              src: ['static/css/s.css', "node_modules/grunt-highlight/node_modules/highlight.js/styles/tomorrow.css"],
              dest: 'static/css/s.css'
          },
        },
   dom_munger: {
    archive: {
      options: {
        read: [
          //{selector:'link',attribute:'href',writeto:'myCssRefs',isPath:true},
          //{selector:'script[src]',attribute:'src',writeto:'myJsRefs',isPath:true}
        ],
          //remove: 'div#archiveblock>div#archiveitem:first-child',
          remove: "#archiveblock>div:first-child"
      },
      src: 'public/archive/index.html', //could be an array of files
    },
  },
  highlight: {
    task: {
      options: {},
        expand: true,
        cwd: 'public',
        src: ["**/*.html"],
        dest: "public/"
    }
  },
        clean: {
            build: ["public/*", "preflight/*"],
        },
  });

    require('matchdep').filter('grunt-*').forEach(grunt.loadNpmTasks);
    grunt.registerTask('cl', ['clean:build','shell:update']);
    grunt.registerTask("css", ["stylus","concat", "cssmin"]);
    grunt.registerTask("cssdev", ["stylus", "concat"]);
    grunt.registerTask("push_production", ["aws_s3:production", "aws_s3:gzipd"]);
    grunt.registerTask("hugo", ["shell:build"]);
    grunt.registerTask("kill", ["cloudfront:all"]);
    grunt.registerTask('dev', ['clean:build',
                               'css',
                               'shell:build',
                               'dom_munger:archive'
                              ]);
    grunt.registerTask("build", ['clean:build',
                               "css",
                               "shell:update",
                               "autoprefixer",
                               "hugo",
                               "dom_munger:archive",
                               "htmlmin",
                               "compress",
                              ]);
        };
<|endoftext|>


<commit_before>$(document).ready(function() {

    var $graph = $(".graph");
    var $mainContainer = $(".main-container");
    var width = $mainContainer.outerWidth();
    var height = $mainContainer.outerHeight();
    var AXES = {
        x1: {
            x1: 10,
            y1: 500,
            x2: width - 10,
            y2: 500
        },
        x2: {
            y1: height - 10,
            y2: 10,
        },
        x: function (x) {
            return (AXES.x1.x2 - AXES.x1.x1) / 2 + x;
        },
        y: function (y) {
            return AXES.x2.y2 - 10 + (AXES.x2.y1 - AXES.x2.y2) / 2 - y;
        },
        setPosition: function (x, y, el) {
            var tr = "translate(" + AXES.x(x) + "," + AXES.y(y) + ")";
            if (el) {
                el.attr("transform", tr);
            }
            return tr;
        }
    };
    AXES.x2.x1 = AXES.x2.x2 = (AXES.x1.x2 - AXES.x1.x1) / 2;
    AXES.x1.y1 = AXES.x1.y2 = (AXES.x2.y1 - AXES.x2.y2) / 2;

    var svg = d3.select(".graph").append("svg:svg")
        .attr("width", width)
        .attr("height", height);

    var container = svg.append("g");
    var markerWidth = 6,
        markerHeight = 6,
        cRadius = 8,
        refX = cRadius + (markerWidth * 2),
        refY = -Math.sqrt(cRadius),
        drSub = cRadius + refY;

    var force = d3.layout.force()
        .nodes(d3.values([
            {
                x: 0,
                y: 0
            }
        ]))
        .size([width, height])
        .start();

    container.append("svg:defs").selectAll("marker")
        .data(["arrow"])
        .enter().append("svg:marker")
        .attr("id", String)
        .attr("viewBox", "0 -5 10 10")
        .attr("refX", 0)
        .attr("refY", "0")
        .attr("markerWidth", markerWidth)
        .attr("markerHeight", markerHeight)
        .attr("orient", "auto")
        .append("svg:path")
        .attr("d", "M0,-5L10,0L0,5");

    var lines = container.append("svg:g").selectAll("line")
        .data([
            "x1",
            "x2"
        ])
        .enter().append("line")
        .attr("x1", function(d) {
            return AXES[d].x1;
        })
        .attr("y1", function(d) {
            return AXES[d].y1;
        })
        .attr("x2", function(d) {
            return AXES[d].x2;
        })
        .attr("y2", function(d) {
            return AXES[d].y2;
        })
        .attr("marker-end", "url(#arrow)")
        .attr("class", "link");

    var circle = container.append("svg:g").selectAll("circle")
        .data([
            {}
        ])
        .enter().append("circle")
        .attr("transform", function(d) {
            return AXES.setPosition(0, 0);
        })
        .attr("r", "4")
        .attr("fill", "#c0392b");

    var circleShadow = container.append("svg:g").selectAll("circle")
        .data([
            {

            }, {}, {}
        ])
        .enter().append("circle")
        .attr("transform", function(d) {
            return AXES.setPosition(0, 0);
        })
        .attr("r", function (d, i) {
            return 3 - i;
        });

    var text = container.append("svg:g").selectAll("text")
        .data([
            {}
        ])
        .enter().append("text")
        .attr({
            x: 10
          , y: 10
        }).text("Hello World");

    B1 = [
        [-1, 1],
        [1, 2]
    ];
    B2 = [
        [1, 1],
        [0, 2]
    ];

    W = [10, -10];

window.getBx = function(t) {
    return [
        [
            (1 - t) * B1[0][0] + t * B2[0][0],
            (1 - t) * B1[0][1] + t * B2[0][1]
        ],
        [
            (1 - t) * B1[1][0] + t * B2[1][0],
            (1 - t) * B1[1][1] + t * B2[1][1]
        ]
    ]
}

window.computeXY = function(xy) {
    xy.x *= 10;
    xy.y *= 10;
}

    var content = "B1 = " + JSON.stringify(B1);
    content += "\nB2 = " + JSON.stringify(B2);
    content += "\nW = " + JSON.stringify(W);
    content += "\ngetBx = " + getBx.toString();
    content += "\ncomputeXY = " + computeXY.toString();
    content += "\nRANGE = [0, 1]";
    $("#inputData").val(content);

    var intervals = [];
    $(".btn.start").on("click", function () {

        for (var i in intervals) {
            clearInterval(intervals[i]);
        }

        try {
            eval($("#inputData").val());
        } catch (e) {
            alert(e.message);
            return;
        }
        var values = [];
        for (var t = RANGE[0]; t < RANGE[1]; t += 0.001) {
            var xy = getXY(t);
            if (typeof computeXY === "function") {
                computeXY(xy);
            }
            values.push(xy);
        }

        var howMany = 4;
        var cHowMany = 0;
        var tmp = setInterval(function () {

            if (++cHowMany >= howMany) {
                clearInterval(tmp);
            }

            var i = -1;
            var cInterval = null;
            var cCircle = d3.select(circleShadow[0][cHowMany - 2]);
            if (cHowMany === 1) {
                cCircle = circle;
            }
            intervals.push(cInterval = setInterval(function () {
                var xy = null;
                if (!(xy = values[++i])) {
                    return clearInterval(cInterval);
                }

                text.text("x = " + xy.x.toFixed(2) + ", y = " + xy.y.toFixed(2));
                AXES.setPosition(xy.x, xy.y, cCircle);
            }, 0.1));
        }, 100);
    });

    function getXY(t) {

        var g = getBx(t);

        // x * i[0][0] + x * i[1][0] = W[0]
        // y * i[0][1] + y * i[1][1] = W[1]
        // x = W[0] / (i[0][0] + i[1][0])
        // y = W[1] / (i[0][1] + i[1][1])

        // x * i[0][0] + y * i[1][0] = W[0]
        // x * i[0][1] + y * i[1][1] = W[1]
        console.log("x * " + g[0][0] + " + y * " + g[1][0]  + " = " + W[0]);
        console.log("x * " + g[0][1] + " + y * " + g[1][1]  + " = " + W[1]);
        var dm = g[0][0] * g[1][1] - g[0][1] * g[1][0];
        var x = (W[0] * g[1][1] - W[1] * g[1][0]) / dm;
        var y = (g[0][0] * W[1] - g[0][1] * W[0]) / dm;

        return {
            x: x,
            y: y
        }
    }

    getXY(0);

});
<commit_msg>Set x = 0 and y = 0 instead of dummy text<commit_after>$(document).ready(function() {

    var $graph = $(".graph");
    var $mainContainer = $(".main-container");
    var width = $mainContainer.outerWidth();
    var height = $mainContainer.outerHeight();
    var AXES = {
        x1: {
            x1: 10,
            y1: 500,
            x2: width - 10,
            y2: 500
        },
        x2: {
            y1: height - 10,
            y2: 10,
        },
        x: function (x) {
            return (AXES.x1.x2 - AXES.x1.x1) / 2 + x;
        },
        y: function (y) {
            return AXES.x2.y2 - 10 + (AXES.x2.y1 - AXES.x2.y2) / 2 - y;
        },
        setPosition: function (x, y, el) {
            var tr = "translate(" + AXES.x(x) + "," + AXES.y(y) + ")";
            if (el) {
                el.attr("transform", tr);
            }
            return tr;
        }
    };
    AXES.x2.x1 = AXES.x2.x2 = (AXES.x1.x2 - AXES.x1.x1) / 2;
    AXES.x1.y1 = AXES.x1.y2 = (AXES.x2.y1 - AXES.x2.y2) / 2;

    var svg = d3.select(".graph").append("svg:svg")
        .attr("width", width)
        .attr("height", height);

    var container = svg.append("g");
    var markerWidth = 6,
        markerHeight = 6,
        cRadius = 8,
        refX = cRadius + (markerWidth * 2),
        refY = -Math.sqrt(cRadius),
        drSub = cRadius + refY;

    var force = d3.layout.force()
        .nodes(d3.values([
            {
                x: 0,
                y: 0
            }
        ]))
        .size([width, height])
        .start();

    container.append("svg:defs").selectAll("marker")
        .data(["arrow"])
        .enter().append("svg:marker")
        .attr("id", String)
        .attr("viewBox", "0 -5 10 10")
        .attr("refX", 0)
        .attr("refY", "0")
        .attr("markerWidth", markerWidth)
        .attr("markerHeight", markerHeight)
        .attr("orient", "auto")
        .append("svg:path")
        .attr("d", "M0,-5L10,0L0,5");

    var lines = container.append("svg:g").selectAll("line")
        .data([
            "x1",
            "x2"
        ])
        .enter().append("line")
        .attr("x1", function(d) {
            return AXES[d].x1;
        })
        .attr("y1", function(d) {
            return AXES[d].y1;
        })
        .attr("x2", function(d) {
            return AXES[d].x2;
        })
        .attr("y2", function(d) {
            return AXES[d].y2;
        })
        .attr("marker-end", "url(#arrow)")
        .attr("class", "link");

    var circle = container.append("svg:g").selectAll("circle")
        .data([
            {}
        ])
        .enter().append("circle")
        .attr("transform", function(d) {
            return AXES.setPosition(0, 0);
        })
        .attr("r", "4")
        .attr("fill", "#c0392b");

    var circleShadow = container.append("svg:g").selectAll("circle")
        .data([
            {

            }, {}, {}
        ])
        .enter().append("circle")
        .attr("transform", function(d) {
            return AXES.setPosition(0, 0);
        })
        .attr("r", function (d, i) {
            return 3 - i;
        });

    var text = container.append("svg:g").selectAll("text")
        .data([
            {}
        ])
        .enter().append("text")
        .attr({
            x: 10
          , y: 10
        }).text("x = 0, y = 0");

    B1 = [
        [-1, 1],
        [1, 2]
    ];
    B2 = [
        [1, 1],
        [0, 2]
    ];

    W = [10, -10];

window.getBx = function(t) {
    return [
        [
            (1 - t) * B1[0][0] + t * B2[0][0],
            (1 - t) * B1[0][1] + t * B2[0][1]
        ],
        [
            (1 - t) * B1[1][0] + t * B2[1][0],
            (1 - t) * B1[1][1] + t * B2[1][1]
        ]
    ]
}

window.computeXY = function(xy) {
    xy.x *= 10;
    xy.y *= 10;
}

    var content = "B1 = " + JSON.stringify(B1);
    content += "\nB2 = " + JSON.stringify(B2);
    content += "\nW = " + JSON.stringify(W);
    content += "\ngetBx = " + getBx.toString();
    content += "\ncomputeXY = " + computeXY.toString();
    content += "\nRANGE = [0, 1]";
    $("#inputData").val(content);

    var intervals = [];
    $(".btn.start").on("click", function () {

        for (var i in intervals) {
            clearInterval(intervals[i]);
        }

        try {
            eval($("#inputData").val());
        } catch (e) {
            alert(e.message);
            return;
        }
        var values = [];
        for (var t = RANGE[0]; t < RANGE[1]; t += 0.001) {
            var xy = getXY(t);
            if (typeof computeXY === "function") {
                computeXY(xy);
            }
            values.push(xy);
        }

        var howMany = 4;
        var cHowMany = 0;
        var tmp = setInterval(function () {

            if (++cHowMany >= howMany) {
                clearInterval(tmp);
            }

            var i = -1;
            var cInterval = null;
            var cCircle = d3.select(circleShadow[0][cHowMany - 2]);
            if (cHowMany === 1) {
                cCircle = circle;
            }
            intervals.push(cInterval = setInterval(function () {
                var xy = null;
                if (!(xy = values[++i])) {
                    return clearInterval(cInterval);
                }

                text.text("x = " + xy.x.toFixed(2) + ", y = " + xy.y.toFixed(2));
                AXES.setPosition(xy.x, xy.y, cCircle);
            }, 0.1));
        }, 100);
    });

    function getXY(t) {

        var g = getBx(t);

        // x * i[0][0] + x * i[1][0] = W[0]
        // y * i[0][1] + y * i[1][1] = W[1]
        // x = W[0] / (i[0][0] + i[1][0])
        // y = W[1] / (i[0][1] + i[1][1])

        // x * i[0][0] + y * i[1][0] = W[0]
        // x * i[0][1] + y * i[1][1] = W[1]
        console.log("x * " + g[0][0] + " + y * " + g[1][0]  + " = " + W[0]);
        console.log("x * " + g[0][1] + " + y * " + g[1][1]  + " = " + W[1]);
        var dm = g[0][0] * g[1][1] - g[0][1] * g[1][0];
        var x = (W[0] * g[1][1] - W[1] * g[1][0]) / dm;
        var y = (g[0][0] * W[1] - g[0][1] * W[0]) / dm;

        return {
            x: x,
            y: y
        }
    }

    getXY(0);

});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/animated-orphans';
import { task } from '../ember-scheduler';
import { afterRender, microwait } from '../concurrency-helpers';
import TransitionContext from '../transition-context';
import { spawnChild, childrenSettled } from '../scheduler';
import Sprite from '../sprite';
import partition from '../partition';

export default Ember.Component.extend({
  layout,
  classNames: ['animated-orphans'],
  motionService: Ember.inject.service('-ea-motion'),

  init() {
    this._super();
    this._newOrphanTransitions = [];
    this._elementToChild = new WeakMap();
    this._childToTransition = new WeakMap();
    this._inserted = false;
    this._cycleCounter = 0;

  },

  didInsertElement() {
    this._inserted = true;
    this.animateOrphans = this.animateOrphans.bind(this);
    this.reanimate = this.reanimate.bind(this);
    this.get("motionService")
      .register(this)
      .observeOrphans(this.animateOrphans)
      .observeAnimations(this.reanimate);
  },

  willDestroyElement() {
    this.get("motionService")
      .unregister(this)
      .unobserveOrphans(this.animateOrphans)
      .unobserveAnimations(this.reanimate);
  },

  animateOrphans(removedSprites, transition, duration) {
    this._newOrphanTransitions.push({ removedSprites, transition, duration });
    this.get('startAnimation').perform();
  },

  reanimate() {
    this.get('startAnimation').perform();
  },

  beginStaticMeasurement() {
    // we don't have any impact on static layout
  },

  endStaticMeasurement() {},

  isAnimating: Ember.computed.or('startAnimation.isRunning', 'animate.isRunning'),

  startAnimation: task(function * () {
    yield afterRender();
    let ownSprite = new Sprite(this.element, true, null, null);
    ownSprite.measureFinalBounds();
    let activeSprites = this._findActiveSprites(ownSprite);
    this.get('animate').perform(activeSprites, ownSprite);
  }).drop(),

  animate: task(function * (activeSprites, ownSprite) {
    // we don't need any static measurements, but we wait for this so
    // we stay on the same timing as all the other animators
    yield * this.get('motionService').staticMeasurement(() => {});

    // our sprites from prior animation runs are eligible to be
    // matched by other animators (this is how an orphan sprites that
    // are animating away can get interrupted into coming back)
    let farMatches = yield this.get('motionService.farMatch').perform(
      [],
      [],
      activeSprites.concat(...this._newOrphanTransitions.map(t => t.removedSprites))
    );

    let cycle = this._cycleCounter++;

    for (let { transition, duration, sprites } of this._groupActiveSprites(activeSprites)) {
      let [sentSprites, removedSprites] = partition(sprites, sprite => {
        let other = farMatches.get(sprite);
        if (other) {
          sprite.endAtSprite(other);
          if (other.revealed && !sprite.revealed) {
            sprite.startAtSprite(other);
          }
          return true;
        }
      });
      let context = new TransitionContext(
        duration,
        [],
        [],
        removedSprites,
        sentSprites,
        []
      );
      context.onMotionStart = this._onMotionStart.bind(this, cycle);
      context.onMotionEnd = this._onMotionEnd.bind(this, cycle);
      spawnChild(function * () {
        // let other animators make their own partitioning decisions
        // before we start hiding the sent & received sprites yield
        yield microwait();
        sentSprites.forEach(s => s.hide());
        yield * context._runToCompletion(transition);
      });
    }

    while (this._newOrphanTransitions.length > 0) {
      let entry = this._newOrphanTransitions.shift();
      let { transition, duration, removedSprites } = entry;
      let [sentSprites, unmatchedRemovedSprites] = partition(removedSprites, sprite => {
        let other = farMatches.get(sprite);
        if (other) {
          sprite.endAtSprite(other);
          if (other.revealed && !sprite.revealed) {
            sprite.startAtSprite(other);
          }
          return true;
        }
      });

      let context = new TransitionContext(
        duration,
        [],
        [],
        unmatchedRemovedSprites,
        sentSprites,
        []
      );
      for (let sprite of removedSprites) {
        sprite.rehome(ownSprite);
        this._childToTransition.set(sprite.owner, entry);
      }
      context.onMotionStart = this._onFirstMotionStart.bind(this, activeSprites, cycle);
      context.onMotionEnd = this._onMotionEnd.bind(this, cycle);
      spawnChild(function * () {
        yield microwait();
        sentSprites.forEach(s => s.hide());
        yield * context._runToCompletion(transition);
      });
    }

    yield childrenSettled();
    for (let sprite of activeSprites) {
      sprite.element.remove();
    }
  }).restartable(),

  _findActiveSprites(ownSprite) {
    if (!this._inserted) { return []; }
    return [...this.element.children].map(element => {
      let child = this._elementToChild.get(element);
      if (child.shouldRemove) {
        // child was not animating in the previously interrupted
        // animation, so its safe to remove
        element.remove();
      } else {
        let sprite = Sprite.positionedStartingAt(element, ownSprite);
        sprite.owner = child;
        return sprite;
      }
    }).filter(Boolean);
  },

  _groupActiveSprites(activeSprites) {
    let groups = [];
    for (let sprite of activeSprites) {
      let { transition, duration } = this._childToTransition.get(sprite.owner);
      let group = groups.find(g => g.transition === transition);
      if (!group) {
        group = { transition, duration, sprites: []};
        groups.push(group);
      }
      group.sprites.push(sprite);
    }
    return groups;
  },

  _onFirstMotionStart(activeSprites, cycle, sprite) {
    if (activeSprites.indexOf(sprite) === -1) {
      if (inDOM(sprite.element)) {
        sprite.element = sprite.element.cloneNode(true);
      }
      sprite.lock();
      this.element.appendChild(sprite.element);
      activeSprites.push(sprite);
      this._elementToChild.set(sprite.element, sprite.owner);
      sprite.owner.flagForRemoval();
    }
    sprite.owner.block(cycle);
  },

  _onMotionStart(cycle, sprite) {
    sprite.owner.block(cycle);
  },

  _onMotionEnd(cycle, sprite) {
    sprite.owner.unblock(cycle);
  }

});

function inDOM(element) {
  let pointer = element;
  while (true) {
    if (!pointer) {
      return false;
    }
    if (pointer.tagName === 'BODY') {
      return true;
    }
    pointer = pointer.parentElement;
  }
}
<commit_msg>orphaned sprites should reveal automatically upon animation<commit_after>import Ember from 'ember';
import layout from '../templates/components/animated-orphans';
import { task } from '../ember-scheduler';
import { afterRender, microwait } from '../concurrency-helpers';
import TransitionContext from '../transition-context';
import { spawnChild, childrenSettled } from '../scheduler';
import Sprite from '../sprite';
import partition from '../partition';

export default Ember.Component.extend({
  layout,
  classNames: ['animated-orphans'],
  motionService: Ember.inject.service('-ea-motion'),

  init() {
    this._super();
    this._newOrphanTransitions = [];
    this._elementToChild = new WeakMap();
    this._childToTransition = new WeakMap();
    this._inserted = false;
    this._cycleCounter = 0;

  },

  didInsertElement() {
    this._inserted = true;
    this.animateOrphans = this.animateOrphans.bind(this);
    this.reanimate = this.reanimate.bind(this);
    this.get("motionService")
      .register(this)
      .observeOrphans(this.animateOrphans)
      .observeAnimations(this.reanimate);
  },

  willDestroyElement() {
    this.get("motionService")
      .unregister(this)
      .unobserveOrphans(this.animateOrphans)
      .unobserveAnimations(this.reanimate);
  },

  animateOrphans(removedSprites, transition, duration) {
    this._newOrphanTransitions.push({ removedSprites, transition, duration });
    this.get('startAnimation').perform();
  },

  reanimate() {
    this.get('startAnimation').perform();
  },

  beginStaticMeasurement() {
    // we don't have any impact on static layout
  },

  endStaticMeasurement() {},

  isAnimating: Ember.computed.or('startAnimation.isRunning', 'animate.isRunning'),

  startAnimation: task(function * () {
    yield afterRender();
    let ownSprite = new Sprite(this.element, true, null, null);
    ownSprite.measureFinalBounds();
    let activeSprites = this._findActiveSprites(ownSprite);
    this.get('animate').perform(activeSprites, ownSprite);
  }).drop(),

  animate: task(function * (activeSprites, ownSprite) {
    // we don't need any static measurements, but we wait for this so
    // we stay on the same timing as all the other animators
    yield * this.get('motionService').staticMeasurement(() => {});

    // our sprites from prior animation runs are eligible to be
    // matched by other animators (this is how an orphan sprites that
    // are animating away can get interrupted into coming back)
    let farMatches = yield this.get('motionService.farMatch').perform(
      [],
      [],
      activeSprites.concat(...this._newOrphanTransitions.map(t => t.removedSprites))
    );

    let cycle = this._cycleCounter++;

    for (let { transition, duration, sprites } of this._groupActiveSprites(activeSprites)) {
      let [sentSprites, removedSprites] = partition(sprites, sprite => {
        let other = farMatches.get(sprite);
        if (other) {
          sprite.endAtSprite(other);
          if (other.revealed && !sprite.revealed) {
            sprite.startAtSprite(other);
          }
          return true;
        }
      });
      let context = new TransitionContext(
        duration,
        [],
        [],
        removedSprites,
        sentSprites,
        []
      );
      context.onMotionStart = this._onMotionStart.bind(this, cycle);
      context.onMotionEnd = this._onMotionEnd.bind(this, cycle);
      spawnChild(function * () {
        // let other animators make their own partitioning decisions
        // before we start hiding the sent & received sprites yield
        yield microwait();
        sentSprites.forEach(s => s.hide());
        yield * context._runToCompletion(transition);
      });
    }

    while (this._newOrphanTransitions.length > 0) {
      let entry = this._newOrphanTransitions.shift();
      let { transition, duration, removedSprites } = entry;
      let [sentSprites, unmatchedRemovedSprites] = partition(removedSprites, sprite => {
        let other = farMatches.get(sprite);
        if (other) {
          sprite.endAtSprite(other);
          if (other.revealed && !sprite.revealed) {
            sprite.startAtSprite(other);
          }
          return true;
        }
      });

      let context = new TransitionContext(
        duration,
        [],
        [],
        unmatchedRemovedSprites,
        sentSprites,
        []
      );
      for (let sprite of removedSprites) {
        sprite.rehome(ownSprite);
        this._childToTransition.set(sprite.owner, entry);
      }
      context.onMotionStart = this._onFirstMotionStart.bind(this, activeSprites, cycle);
      context.onMotionEnd = this._onMotionEnd.bind(this, cycle);
      spawnChild(function * () {
        yield microwait();
        sentSprites.forEach(s => s.hide());
        yield * context._runToCompletion(transition);
      });
    }

    yield childrenSettled();
    for (let sprite of activeSprites) {
      sprite.element.remove();
    }
  }).restartable(),

  _findActiveSprites(ownSprite) {
    if (!this._inserted) { return []; }
    return [...this.element.children].map(element => {
      let child = this._elementToChild.get(element);
      if (child.shouldRemove) {
        // child was not animating in the previously interrupted
        // animation, so its safe to remove
        element.remove();
      } else {
        let sprite = Sprite.positionedStartingAt(element, ownSprite);
        sprite.owner = child;
        return sprite;
      }
    }).filter(Boolean);
  },

  _groupActiveSprites(activeSprites) {
    let groups = [];
    for (let sprite of activeSprites) {
      let { transition, duration } = this._childToTransition.get(sprite.owner);
      let group = groups.find(g => g.transition === transition);
      if (!group) {
        group = { transition, duration, sprites: []};
        groups.push(group);
      }
      group.sprites.push(sprite);
    }
    return groups;
  },

  _onFirstMotionStart(activeSprites, cycle, sprite) {
    if (activeSprites.indexOf(sprite) === -1) {
      if (inDOM(sprite.element)) {
        sprite.element = sprite.element.cloneNode(true);
      }
      sprite.lock();
      sprite.reveal();
      this.element.appendChild(sprite.element);
      activeSprites.push(sprite);
      this._elementToChild.set(sprite.element, sprite.owner);
      sprite.owner.flagForRemoval();
    }
    sprite.owner.block(cycle);
  },

  _onMotionStart(cycle, sprite) {
    sprite.owner.block(cycle);
  },

  _onMotionEnd(cycle, sprite) {
    sprite.owner.unblock(cycle);
  }

});

function inDOM(element) {
  let pointer = element;
  while (true) {
    if (!pointer) {
      return false;
    }
    if (pointer.tagName === 'BODY') {
      return true;
    }
    pointer = pointer.parentElement;
  }
}
<|endoftext|>


<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

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

var path = require('path'),
    optimist, // required in try-catch below to print a nice error message if it's not installed.
    help = require('./help'),
    _;

module.exports = function CLI(inputArgs) {
    try {
        optimist = require('optimist');
        _ = require('underscore');
    } catch (e) {
        console.error("Please run npm install from this directory:\n\t" +
                      path.dirname(__dirname));
        process.exit(2);
    }
    var cordova_lib = require('cordova-lib'),
        CordovaError = cordova_lib.CordovaError,
        cordova = cordova_lib.cordova,
        plugman = cordova_lib.plugman;

    // If no inputArgs given, use process.argv.
    var tokens;
    if (inputArgs) {
        tokens = inputArgs.slice(2);
    } else {
        tokens = process.argv.slice(2);
    }

    // When changing command line arguments, update doc/help.txt accordingly.
    var args = optimist(tokens)
        .boolean('d')
        .boolean('verbose')
        .boolean('v')
        .boolean('version')
        .boolean('silent')
        .boolean('experimental')
        .boolean('noregistry')
        .string('copy-from')
        .alias('copy-from', 'src')
        .string('link-to')
        .string('searchpath')
        .argv;

    if (args.v || args.version) {
        return console.log(require('../package').version);
    }

    var opts = {
            platforms: [],
            options: [],
            verbose: (args.d || args.verbose),
            silent: args.silent,
        };

    // For CrodovaError print only the message without stack trace.
    process.on('uncaughtException', function(err){
        if (err instanceof CordovaError) {
            console.error(err.message);
        } else {
            console.error(err.stack);
        }
        process.exit(1);
    });

    cordova.on('results', console.log);

    if (!opts.silent) {
        cordova.on('log', console.log);
        cordova.on('warn', console.warn);
        plugman.on('log', console.log);
        plugman.on('results', console.log);
        plugman.on('warn', console.warn);
    } else {
        // Remove the token.
        tokens.splice(tokens.indexOf('--silent'), 1);
    }

    if (opts.verbose) {
        // Add handlers for verbose logging.
        cordova.on('verbose', console.log);
        plugman.on('verbose', console.log);

        //Remove the corresponding token
        if(args.d && args.verbose) {
            tokens.splice(Math.min(tokens.indexOf("-d"), tokens.indexOf("--verbose")), 1);
        } else if (args.d) {
            tokens.splice(tokens.indexOf("-d"), 1);
        } else if (args.verbose) {
            tokens.splice(tokens.indexOf("--verbose"), 1);
        }
    }

    if (args.experimental) {
        tokens.splice(tokens.indexOf("--experimental"), 1);
    }

    if (args.noregistry) {
        tokens.splice(tokens.indexOf("--noregistry"), 1);
    }

    var cmd = tokens && tokens.length ? tokens.splice(0,1) : undefined;
    if (cmd === undefined) {
        return help();
    }

    if (!cordova.hasOwnProperty(cmd)) {
        throw new CordovaError('Cordova does not know ' + cmd + '; try help for a list of all the available commands.');
    }

    if (cmd == 'emulate' || cmd == 'build' || cmd == 'prepare' || cmd == 'compile' || cmd == 'run') {
        // Filter all non-platforms into options
        var platforms = cordova_lib.cordova_platforms;
        tokens.forEach(function(option, index) {
            if (platforms.hasOwnProperty(option)) {
                opts.platforms.push(option);
            } else {
                opts.options.push(option);
            }
        });
        cordova.raw[cmd].call(this, opts).done();
    } else if (cmd == 'serve') {
        cordova.raw[cmd].apply(this, tokens).done();
    } else if (cmd == 'create') {
        var cfg = {};
        // If we got a forth parameter, consider it to be JSON to init the config.
        if (args._[4]) {
            cfg = JSON.parse(args._[4]);
        }
        var customWww = args['copy-from'] || args['link-to'];
        if (customWww) {
            if (customWww.indexOf(':') != -1) {
                throw new CordovaError('Only local paths for custom www assets are supported.');
            }
            if (customWww.substr(0,1) === '~') {  // resolve tilde in a naive way.
                customWww = path.join(process.env.HOME,  customWww.substr(1));
            }
            customWww = path.resolve(customWww);
            var wwwCfg = {uri: customWww};
            if (args['link-to']) {
                wwwCfg.link = true;
            }
            cfg.lib = cfg.lib || {};
            cfg.lib.www = wwwCfg;
        }
        // create(dir, id, name, cfg)
        cordova.raw[cmd].call(this, args._[1], args._[2], args._[3], cfg).done();
    } else if (cmd == 'help') {
        return help();
    } else {
        // platform/plugins add/rm [target(s)]
        var subcommand = tokens[0]; // this has the sub-command, like "add", "ls", "rm" etc.
        var targets = tokens.slice(1); // this should be an array of targets, be it platforms or plugins
        cordova.raw[cmd].call(this, subcommand, targets, { searchpath: args.searchpath, noregistry: args.noregistry }).done();
    }
};
<commit_msg>CLI implementation for the save and restore plugins<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

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

var path = require('path'),
    optimist, // required in try-catch below to print a nice error message if it's not installed.
    help = require('./help'),
    _;

module.exports = function CLI(inputArgs) {
    try {
        optimist = require('optimist');
        _ = require('underscore');
    } catch (e) {
        console.error("Please run npm install from this directory:\n\t" +
                      path.dirname(__dirname));
        process.exit(2);
    }
    var cordova_lib = require('cordova-lib'),
        CordovaError = cordova_lib.CordovaError,
        cordova = cordova_lib.cordova,
        plugman = cordova_lib.plugman;

    // If no inputArgs given, use process.argv.
    var tokens;
    if (inputArgs) {
        tokens = inputArgs.slice(2);
    } else {
        tokens = process.argv.slice(2);
    }

    // When changing command line arguments, update doc/help.txt accordingly.
    var args = optimist(tokens)
        .boolean('d')
        .boolean('verbose')
        .boolean('v')
        .boolean('version')
        .boolean('silent')
        .boolean('experimental')
        .boolean('noregistry')
        .boolean('shrinkwrap')
        .string('copy-from')
        .alias('copy-from', 'src')
        .string('link-to')
        .string('searchpath')
        .argv;

    if (args.v || args.version) {
        return console.log(require('../package').version);
    }

    var opts = {
            platforms: [],
            options: [],
            verbose: (args.d || args.verbose),
            silent: args.silent,
        };

    // For CrodovaError print only the message without stack trace.
    process.on('uncaughtException', function(err){
        if (err instanceof CordovaError) {
            console.error(err.message);
        } else {
            console.error(err.stack);
        }
        process.exit(1);
    });

    cordova.on('results', console.log);

    if (!opts.silent) {
        cordova.on('log', console.log);
        cordova.on('warn', console.warn);
        plugman.on('log', console.log);
        plugman.on('results', console.log);
        plugman.on('warn', console.warn);
    } else {
        // Remove the token.
        tokens.splice(tokens.indexOf('--silent'), 1);
    }

    if (opts.verbose) {
        // Add handlers for verbose logging.
        cordova.on('verbose', console.log);
        plugman.on('verbose', console.log);

        //Remove the corresponding token
        if(args.d && args.verbose) {
            tokens.splice(Math.min(tokens.indexOf("-d"), tokens.indexOf("--verbose")), 1);
        } else if (args.d) {
            tokens.splice(tokens.indexOf("-d"), 1);
        } else if (args.verbose) {
            tokens.splice(tokens.indexOf("--verbose"), 1);
        }
    }

    if (args.experimental) {
        tokens.splice(tokens.indexOf("--experimental"), 1);
    }

    if (args.noregistry) {
        tokens.splice(tokens.indexOf("--noregistry"), 1);
    }

    var cmd = tokens && tokens.length ? tokens.splice(0,1) : undefined;
    if (cmd === undefined) {
        return help();
    }

    if (!cordova.hasOwnProperty(cmd)) {
        throw new CordovaError('Cordova does not know ' + cmd + '; try help for a list of all the available commands.');
    }

    if (cmd == 'emulate' || cmd == 'build' || cmd == 'prepare' || cmd == 'compile' || cmd == 'run') {
        // Filter all non-platforms into options
        var platforms = cordova_lib.cordova_platforms;
        tokens.forEach(function(option, index) {
            if (platforms.hasOwnProperty(option)) {
                opts.platforms.push(option);
            } else {
                opts.options.push(option);
            }
        });
        cordova.raw[cmd].call(this, opts).done();
    } else if (cmd == 'serve') {
        cordova.raw[cmd].apply(this, tokens).done();
    } else if (cmd == 'create') {
        var cfg = {};
        // If we got a forth parameter, consider it to be JSON to init the config.
        if (args._[4]) {
            cfg = JSON.parse(args._[4]);
        }
        var customWww = args['copy-from'] || args['link-to'];
        if (customWww) {
            if (customWww.indexOf(':') != -1) {
                throw new CordovaError('Only local paths for custom www assets are supported.');
            }
            if (customWww.substr(0,1) === '~') {  // resolve tilde in a naive way.
                customWww = path.join(process.env.HOME,  customWww.substr(1));
            }
            customWww = path.resolve(customWww);
            var wwwCfg = {uri: customWww};
            if (args['link-to']) {
                wwwCfg.link = true;
            }
            cfg.lib = cfg.lib || {};
            cfg.lib.www = wwwCfg;
        }
        // create(dir, id, name, cfg)
        cordova.raw[cmd].call(this, args._[1], args._[2], args._[3], cfg).done();
    } else if( cmd == 'save' || cmd == 'restore'){
        if(!opts.experimental && !args.experimental ){
          throw new CordovaError('save and restore commands are experimental, please add "--experimental" to indicate that you understand that it may change in the future');
        }
        var subcommand = tokens[0]
        if(subcommand == 'plugins'){
          cordova.raw[cmd].call(this,'plugins',{ shrinkwrap:args.shrinkwrap });
        }else{
          throw new CordovaError('Let cordova know what you want to '+ cmd + ', try "cordova '+ cmd +' plugins"');
        }
    } else if (cmd == 'help') {
        return help();
    } else {
        // platform/plugins add/rm [target(s)]
        var subcommand = tokens[0]; // this has the sub-command, like "add", "ls", "rm" etc.
        var targets = tokens.slice(1); // this should be an array of targets, be it platforms or plugins
        cordova.raw[cmd].call(this, subcommand, targets, { searchpath: args.searchpath, noregistry: args.noregistry }).done();
    }
};
<|endoftext|>


<commit_before>import fs                      from 'fs'
import minify                  from 'html-minify'
import mjmlEngine              from './index'
import { version as VERSION }  from '../package.json'

const engine = mjmlEngine.mjml2html

/*
 * The version number is the NPM
 * version number. It should be the same as the MJML engine
 */
const version = () => VERSION

/*
 * Turns a callback style to a Promise style one
 */
const promisify = fn =>
  (...args) =>
    new Promise((resolve, reject) =>
      fn(...args.concat((err, ...data) =>
        err ? reject(err) : resolve(...data))))

/*
 * Minimal Error Handling
 */
const error   = (e) => {
  console.log(e.stack ? e.stack : e)
  process.exit(42)
}

/*
 * Utility functions
 * write: write to a file
 * read: read a fileexists: ensure the file exists
 */
const write   = promisify(fs.writeFile)
const read    = promisify(fs.readFile)
const exists  = promisify((file, cb) => fs.access(file, fs.R_OK | fs.W_OK, cb))

/*
 * Turns an MJML input file into a pretty HTML file
 * min: boolean that specify the output format (pretty/minified)
 */
const render = (input, { min, output }) => {
  exists(input)
    .then(()      => read(input))
    .then(mjml    => engine(mjml.toString()))
    .then(html    => min ? minify(html) : html)
    .then(result  => write(output, result))
    .catch(error)
}

/*
 * Watch changes on a specific input file by calling render on each change
 */
const watch = (input, options) =>
  fs.watch(input, () => render(input, options))

const capitalize = name => name.charAt(0).toUpperCase() + name.slice(1).toLowerCase().replace(/-/g, '')

/*
* Return the code of an MJML component for a given name
*/
const createComponent = (name, ending) => {
  const lowerName = name.toLowerCase()

  return `
import React, { Component } from 'react'
import _ from 'loadash'
import {
  MJMLColumnElement,
  elements,
  registerElement,
} from 'mjml'

/*
 * Wrap your dependencies here.
 */
const {
  text: MjText,
} = elements;

const NAME = '${lowerName}'

@MJMLColumnElement({
  tagName: 'mj-${lowerName}',
  content: ' ',

  /*
   * These are your default css attributes
   */
  attributes: {
    'color': '#424242',
    'font-family': 'Helvetica',
    'margin-top': '10px'
  }
})
class ${name} extends Component {

  /*
   * Build your styling here
   */
  getStyles() {
    const { mjAttribute, color } = this.props

    return _.merge({}, this.constructor.baseStyles, {
      text: {
      /*
       * Get the color attribute
       * Example: <mj-${lowerName} color="blue">content</mj-${lowerName}>
       */
        color: mjAttribute('color')
      }
    })
  }

  render() {

    const css = this.getStyles(),
          content = 'Hello World!'

    return (
      <MjText style={ css }>
        { content }
      </MjText>
    )
  }
}

registerElement('${lowerName}', ${name}${ending ? ', true' : ''})
export default ${name}
`
}

/*
 * Create a new component based on the default template
 */
const initComponent = (name, ending) =>
  write(`./${capitalize(name)}.js`, createComponent(capitalize(name), ending))
    .then(() => console.log(`Component created: ${capitalize(name)}`))

module.exports = {
  initComponent: initComponent,
  render: render,
  watch: watch,
  version: version
}
<commit_msg>cli fix<commit_after>import fs                      from 'fs'
import minify                  from 'html-minify'
import mjmlEngine              from './index'
import { version as VERSION }  from '../package.json'

const engine = mjmlEngine.mjml2html

/*
 * The version number is the NPM
 * version number. It should be the same as the MJML engine
 */
const version = () => VERSION

/*
 * Turns a callback style to a Promise style one
 */
const promisify = fn =>
  (...args) =>
    new Promise((resolve, reject) =>
      fn(...args.concat((err, ...data) =>
        err ? reject(err) : resolve(...data))))

/*
 * Minimal Error Handling
 */
const error   = (e) => {
  console.log(e.stack ? e.stack : e)
}

/*
 * Utility functions
 * write: write to a file
 * read: read a fileexists: ensure the file exists
 */
const write   = promisify(fs.writeFile)
const read    = promisify(fs.readFile)
const exists  = promisify((file, cb) => fs.access(file, fs.R_OK | fs.W_OK, cb))

/*
 * Turns an MJML input file into a pretty HTML file
 * min: boolean that specify the output format (pretty/minified)
 */
const render = (input, { min, output }) => {
  exists(input)
    .then(()      => read(input))
    .then(mjml    => engine(mjml.toString()))
    .then(html    => min ? minify(html) : html)
    .then(result  => write(output, result))
    .catch(error)
}

/*
 * Watch changes on a specific input file by calling render on each change
 */
const watch = (input, options) => {
  fs.watch(input, () => {
      render(input, options)
  })
}

const capitalize = name => name.charAt(0).toUpperCase() + name.slice(1).toLowerCase().replace(/-/g, '')

/*
* Return the code of an MJML component for a given name
*/
const createComponent = (name, ending) => {
  const lowerName = name.toLowerCase()

  return `
import React, { Component } from 'react'
import _ from 'loadash'
import {
  MJMLColumnElement,
  elements,
  registerElement,
} from 'mjml'

/*
 * Wrap your dependencies here.
 */
const {
  text: MjText,
} = elements;

const NAME = '${lowerName}'

@MJMLColumnElement({
  tagName: 'mj-${lowerName}',
  content: ' ',

  /*
   * These are your default css attributes
   */
  attributes: {
    'color': '#424242',
    'font-family': 'Helvetica',
    'margin-top': '10px'
  }
})
class ${name} extends Component {

  /*
   * Build your styling here
   */
  getStyles() {
    const { mjAttribute, color } = this.props

    return _.merge({}, this.constructor.baseStyles, {
      text: {
      /*
       * Get the color attribute
       * Example: <mj-${lowerName} color="blue">content</mj-${lowerName}>
       */
        color: mjAttribute('color')
      }
    })
  }

  render() {

    const css = this.getStyles(),
          content = 'Hello World!'

    return (
      <MjText style={ css }>
        { content }
      </MjText>
    )
  }
}

registerElement('${lowerName}', ${name}${ending ? ', true' : ''})
export default ${name}
`
}

/*
 * Create a new component based on the default template
 */
const initComponent = (name, ending) =>
  write(`./${capitalize(name)}.js`, createComponent(capitalize(name), ending))
    .then(() => console.log(`Component created: ${capitalize(name)}`))

module.exports = {
  initComponent: initComponent,
  render: render,
  watch: watch,
  version: version
}
<|endoftext|>


<commit_before>'use strict';
module.exports = function(grunt) {
	grunt.loadNpmTasks('grunt-npm-install');
	require('load-grunt-tasks')(grunt);
	require('time-grunt')(grunt);

	grunt
			.initConfig({
				pkg : grunt.file.readJSON('package.json'),
				copy : {
					main : {
						files : [
								// js
								{
									expand : true,
									flatten : true,
									// min bez jquery
									src : [ 'vendor/**/*.min.js',
											'!vendor/**/defaults*',
											'!vendor/**/jquery*',
											'!vendor/**/sizzle*',
											'!vendor/**/bootstrap-table-*'
											],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/jquery.fancybox.pack.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/jquery.dataTables.min.js' ],
									dest : './js',
									filter : 'isFile'
								},
								// bootstrap table + table export
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/bootstrap-table.min.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/bootstrap-table-export.min.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/jquery.base64.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/tableExport.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/bootstrap-datepicker.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/bootstrap-datepicker.pl.js' ],
									dest : './js',
									filter : 'isFile'
								},
								// css
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/jquery.fancybox.css' ],
									dest : './css',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/datepicker.css' ],
									dest : './css',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/*.min.css' ],
									dest : './css',
									filter : 'isFile'
								},
								// other
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/fancybox_overlay.png' ],
									dest : './css',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/fancybox_sprite.png' ],
									dest : './css',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/media/images/sort_*.png' ],
									dest : './css',
									filter : 'isFile'
								}, ]
					}
				},
				curl : {
					'./js/dataTables.bootstrap.js' : 'https://github.com/DataTables/Plugins/raw/master/integration/bootstrap/3/dataTables.bootstrap.js',
					'./css/dataTables.bootstrap.css' : 'https://github.com/DataTables/Plugins/raw/master/integration/bootstrap/3/dataTables.bootstrap.css'
				}
			});

	// Register tasks
	grunt.registerTask('default', [ 'build' ]);
	grunt.registerTask('build', [
	// 'curl',
	'copy', ]);

};
<commit_msg>removed - no table export libs for bootstrap table<commit_after>'use strict';
module.exports = function(grunt) {
	grunt.loadNpmTasks('grunt-npm-install');
	require('load-grunt-tasks')(grunt);
	require('time-grunt')(grunt);

	grunt
			.initConfig({
				pkg : grunt.file.readJSON('package.json'),
				copy : {
					main : {
						files : [
								// js
								{
									expand : true,
									flatten : true,
									// min bez jquery
									src : [ 'vendor/**/*.min.js',
											'!vendor/**/defaults*',
											'!vendor/**/jquery*',
											'!vendor/**/sizzle*',
											'!vendor/**/bootstrap-table-*'
											],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/jquery.fancybox.pack.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/jquery.dataTables.min.js' ],
									dest : './js',
									filter : 'isFile'
								},
								// bootstrap table + table export
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/bootstrap-table.min.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/bootstrap-datepicker.js' ],
									dest : './js',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/bootstrap-datepicker.pl.js' ],
									dest : './js',
									filter : 'isFile'
								},
								// css
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/jquery.fancybox.css' ],
									dest : './css',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/datepicker.css' ],
									dest : './css',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/*.min.css' ],
									dest : './css',
									filter : 'isFile'
								},
								// other
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/fancybox_overlay.png' ],
									dest : './css',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/fancybox_sprite.png' ],
									dest : './css',
									filter : 'isFile'
								},
								{
									expand : true,
									flatten : true,
									src : [ 'vendor/**/media/images/sort_*.png' ],
									dest : './css',
									filter : 'isFile'
								}, ]
					}
				},
				curl : {
					'./js/dataTables.bootstrap.js' : 'https://github.com/DataTables/Plugins/raw/master/integration/bootstrap/3/dataTables.bootstrap.js',
					'./css/dataTables.bootstrap.css' : 'https://github.com/DataTables/Plugins/raw/master/integration/bootstrap/3/dataTables.bootstrap.css'
				}
			});

	// Register tasks
	grunt.registerTask('default', [ 'build' ]);
	grunt.registerTask('build', [
	// 'curl',
	'copy', ]);

};
<|endoftext|>


<commit_before>/* Grunt is an automation tool to make doing some stuff easier - http://gruntjs.com/

For example:
Running tests
Building client-side js
*/

module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-compass');

  grunt.initConfig({
    compass: {
      dist: {
        options: {
          cssDir: 'server/static/css',
          imagesDir: 'server/static/images',
          sassDir: 'app/sass'
        }
      }
    },
    mochaTest: {
      test: {
        options: {
          reporter: 'nyan'
        },
        src: ['test/**/*.spec.js']
      }
    },
    browserify: {
      'server/static/lib/bundle.js': ['app/app.js'],
      options: {
        transform: ['hbsfy'],
        // detectGlobals: false,
        // cache: true,
        // debug: false
      }
    },
    watch: {
      files: [ 'app/*.js', 'app/**/*.js', 'app/**/**/*.hbs', 'app/**/*.scss'],
      tasks: [ 'browserify', 'compass' ],
      options: {
        spawn: false,
        debounceDelay: 100,
        livereload: true,
        hostname: 'localhost'
      }
    }
  });

  grunt.registerTask('default', ['browserify', 'compass', 'mochaTest']); // By default run tests
  grunt.registerTask('tests', 'mochaTest');   // Only run tests
};<commit_msg>Grunt will now compile css, js, etc when you trigger watch<commit_after>/* Grunt is an automation tool to make doing some stuff easier - http://gruntjs.com/

For example:
Running tests
Building client-side js
*/

module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-compass');

  grunt.initConfig({
    compass: {
      dist: {
        options: {
          cssDir: 'server/static/css',
          imagesDir: 'server/static/images',
          sassDir: 'app/sass'
        }
      }
    },
    mochaTest: {
      test: {
        options: {
          reporter: 'nyan'
        },
        src: ['test/**/*.spec.js']
      }
    },
    browserify: {
      'server/static/lib/bundle.js': ['app/app.js'],
      options: {
        transform: ['hbsfy'],
        // detectGlobals: false,
        // cache: true,
        // debug: false
      }
    },
    watch: {
      files: [ 'app/*.js', 'app/**/*.js', 'app/**/**/*.hbs', 'app/**/*.scss'],
      tasks: [ 'browserify', 'compass' ],
      options: {
        spawn: false,
        debounceDelay: 100,
        livereload: true,
        hostname: 'localhost',
        atBegin: true
      }
    }
  });

  grunt.registerTask('default', ['browserify', 'compass', 'mochaTest']); // By default run tests
  grunt.registerTask('tests', 'mochaTest');   // Only run tests
};<|endoftext|>


<commit_before>/******************************************************************************
 *                                   ~boo~                                    *
 *                                 ‾‾‾‾‾‾‾‾‾                                  *
 * Provides prototypal utilities for inheritance + basic traits system.       *
 *     _________________________________________________________________      *
 *        Copyright (c) 2011 Quildreen Motta // Licenced under MIT/X11        *
 ******************************************************************************/

//// ~ Module proto //////////////////////////////////////////////////////////
//
// The goal is to provide a handier prototypal inheritance structure for
// JavaScript programs, by adding new functions to deal with the usual
// pattern in an abstract way, as well as introducing a new system to
// deal with *multiple-inheritance* — traits.
//
// Note that the Traits system implemented by this library is not the
// same as the one in Self: prototype inheritance in JavaScript is
// one->one. Thus, this system is, in fact, closer to `mixins` than
// actual Traits. With the exception that these `traits` are burned in
// the object's prototype rather than directly in the object itself.

//// Objects and inheritance /////////////////////////////////////////////////
//
// There are a handful of problems with the way JavaScript handles
// inheritance out of the box. And I'm not talking about being
// Prototypal — since that's one of the best things about it.
//
// For one, you can't inherit directly from other objects. ES5
// introduced Object.create, but it's not available everywhere.
//
// There's no `extend` function built-in, which means that once you've
// set the prototype for a constructor, you have to manually set all of
// the functions too. This also means you don't get to extend the
// prototype with other objects very nicely (out of the box, of
// course).
//
// Calling `super` methods requires hard-coded parents, which doesn't
// work when you have things like traits extended directly on the
// prototype. Capatibilities of parents aren't implemented either —
// testing which one implements which attributes.
//
// To solve this, the module provides three new functions: `inherit`,
// `upper` and `can`, which are discussed in more detail below.
'@boo',
function (root) {

	if (typeof exports == "undefined") {
		root.b = root.b || {}
		mod    = root.b.oo = {} }
	else
		mod    = exports

	// Some alias for rather JavaLongCommandNamesAndIReallyMeanLong.
	var proto  = Object.getPrototypeOf
	  , create = Object.create
	  , slice  = Array.prototype.slice
	  , has    = Object.prototype.hasOwnProperty
	  , mod

	///// Function `inherit` /////////////////////////////////////////////////
	//
	//     inherit(Fun:ctor, Obj:base[, Obj:props]) → Fun:ctor
	//
	// Takes a constructor and a base object, and sets the prototype in
	// the constructor without breaking `instanceof`.
	//
	// If an additional object is passed (as `props`), the properties
	// defined in that object will be copied into the prototype of the
	// constructor as well.
	//
	// Note that these *additional properties* won't have a special
	// inheritance relationship with the constructor's prototype. In
	// fact, they **will** be treated as just being the constructor's
	// own prototype properties.
	//
	function inherit(ctor, base, props) {
		/*** IFDEF DEBUG
		 assert(base, "Missing `base' parameter")
		 assert(dbg.isfn(ctor), "`ctor' isn't a function")
		 *** ENDIF */

		if (!props) props = {}

		props.constructor = ctor
		props.__super__   = base
		ctor.prototype    = create(base)
		return extend(ctor.prototype, props)
	}

	///// Function `extend' //////////////////////////////////////////////////
	//
	//    extend(Obj:obj, Obj:sources...) → Obj:obj
	//
	// Copies the given source's **own** properties in `obj', and returns
	// the object.
	//
	// > Note that this is only a **shallow** copy, anything other than
	// > primitives will be copied just as a reference to the original
	// > object.
	//
	function extend(obj) {
		var sources = slice.call(arguments, 1)
		  , src, prop

		while (src = sources.shift()) {
			for (prop in src)
				if (has.call(src, prop)) obj[prop] = src[prop] }

		return obj
	}

	///// Function `can` /////////////////////////////////////////////////////
	//
	//     can(Obj:obj, Str:attr[, Bool:allow_traits=true]) → Obj
	//
	// Searches which of the parents of the given objects implement the
	// attribute, and returns it.
	//
	// Sometimes you want to know which object is capable of doing
	// something, and most of the times a simple `in` check will be
	// enough. For those times where you want to check which of the
	// **ancestors** of an object implement a certain functionality (for
	// calling a `super` method, for example), you have this method.
	//
	// By default, this function will search any of the objects that
	// provides the requested functionality for the base object —
	// traits included.
	//
	// The prototype is searched first, then, if the functionality is
	// not found, we move on to searching the trait list, in the reverse
	// order they were plugged in.
	//
	// If the method is not found in the immediate accessors, the
	// function will keep searching up the prototype chain to try to
	// find the requested functionality. And if it really can't find the
	// attribute, `null` is returned.
	//
	// > Note that the trait's prototypes and the object itself are
	// > **not** included in this search chain.
	//
	function can(obj, attr, allow_traits) {
		/*** IFDEF DEBUG
		 assert(dbg.isobj(obj), "`obj' is not an object")
		 assert(attr, "Missing `attr' parameter")
		 *** ENDIF */
		function add_traits(){ bases.push.apply(bases, obj.__traits__ || []) }
		function get_base()  { return cur.__super__ || cur                   }
		function has_attr()  { return cur && cur.hasOwnProperty(attr)        }

		var bases, cur
		if (allow_traits == null) allow_traits = true

		while (obj) {
			// Build a list of all the immediate accessors we should
			// look at
			bases = [proto(obj)]
			if (allow_traits) add_traits()

			// Then check each one, in order, to see if they have the
			// requested property
			while (bases.length) {
				cur = bases.shift()
				if (has_attr()) return get_base() }

			// If none of them does, continue on to the next accessors
			obj = proto(obj) }
	}

	///// Function `upper` ///////////////////////////////////////////////////
	//
	//     upper(Obj:obj[, Obj:base][, Str:meth][, args...]) → ?
	//
	// Calls a parent method in the context of the given object.
	//
	// This allows for fully prototypal inheritance, without loosing
	// overwritten methods. Because, you see, we assume that methods
	// that were overwritten are somehow **important** and you will want
	// to refer to them on your functions.
	//
	// The given method will **always** be searched on all of the
	// accessors, traits included, and it'll be called in the context of
	// the given object.
	//
	// To avoid errors with *endless recursion*, the super call state
	// (the object that was looked upon last time) is saved on each
	// call, and removed when the function returns.
	//
	// This is done by simple writing to the `__$ctx__` property, and
	// expects your function to be **synchronous**. If you're calling
	// any asynchronous super method, you'll need to pass the previous
	// stored context explicitly.
	//
	//     b.one.proto.upper(this, this.__$ctx__, "show")
	//
	// > Note that this assumes you won't be writing to `__$ctx__` in
	// > your code. As a rule of thumb, you shouldn't ever have an
	// > actual property with a dollar sign anyways.
	//
	function upper(obj) {
		// Sanitize the arguments passed to the function
		var args = slice.call(arguments, 1)
		  , base = args.shift()
		  , meth

		if (Object(base) !== base) meth = base, base = null
		else                       meth = args.shift()

		if (!base)                 base = obj.__$ctx__ || obj

		return __upper(obj, base, meth, args)
	}

	function __upper(obj, base, meth, args) {
		var _super, rv

		// try to find the first accessor to implement the method, then
		// return the result of calling this method.
		_super       = can(base, meth)
		obj.__$ctx__ = _super

		rv = _super[meth].apply(obj, args)
		delete obj.__$ctx__
		return rv
	}

	///// Function `plugin' //////////////////////////////////////////////////
	//
	//     plugin(Fun|Obj:obj, Obj:traits...) → Fun|Obj:obj
	//
	// Takes a constructor or an object, and adds traits to the
	// prototype, returning the given object/constructor.
	//
	// Traits are a mechanism to handle the same issue as
	// multiple-inheritance, but in a Prototypal OO manner. The idea is
	// that traits provide just a collection of, perhaps, incomplete
	// functionality that's intended to be plugged in an object.
	//
	// This is more powerful than the classical multiple-inheritance
	// system, because you can plugin traits in the constructor, long
	// after several instances of an object have been created, and all
	// of those instances will magically have that trait available too:
	//
	//     function Mage() {}
	//     Mage.cast = function(spell){ return "You've cast " + spell }
	//
	//     var RedMage = { fira: function(){ this.cast("Fira") }}
	//     var Vivi    = new Mage
	//     Vivi.cast("Blizzard") // You've cast Blizzard
	//
	//     // Makes all Mages learn fire magic
	//     b.one.proto.plugin(Mage, RedMage)
	//     Vivi.fira()          // You've cast Fira
	//
	// Not only this, but the traits plugged to a constructor are
	// tracked, and you can call their methods as `super` methods. And
	// as with the prototypal inheritance, you don't need to create a
	// separate meta-object for your functionality, ANY object can be a
	// trait :3
	//
	function plugin(obj) {
		function get_traits() {return (ctor.__traits__ || []).concat(args)}

		var args = slice.call(arguments, 1)
		  , base = typeof obj == "function"? obj.prototype
                                           : proto(obj)
		  , ctor = base.constructor

		ctor.__traits__ = get_traits()
		extend.apply(obj, [base].concat(args))
		return obj
	}

	///// Exports ////////////////////////////////////////////////////////////
	mod.inherit = inherit
	mod.extend  = extend
	mod.can     = can
	mod.upper   = upper
	mod.plugin  = plugin
}(this);
<commit_msg>Adds a no-conflict method<commit_after>/******************************************************************************
 *                                   ~boo~                                    *
 *                                 ‾‾‾‾‾‾‾‾‾                                  *
 * Provides prototypal utilities for inheritance + basic traits system.       *
 *     _________________________________________________________________      *
 *        Copyright (c) 2011 Quildreen Motta // Licenced under MIT/X11        *
 ******************************************************************************/

//// ~ Module proto //////////////////////////////////////////////////////////
//
// The goal is to provide a handier prototypal inheritance structure for
// JavaScript programs, by adding new functions to deal with the usual
// pattern in an abstract way, as well as introducing a new system to
// deal with *multiple-inheritance* — traits.
//
// Note that the Traits system implemented by this library is not the
// same as the one in Self: prototype inheritance in JavaScript is
// one->one. Thus, this system is, in fact, closer to `mixins` than
// actual Traits. With the exception that these `traits` are burned in
// the object's prototype rather than directly in the object itself.

//// Objects and inheritance /////////////////////////////////////////////////
//
// There are a handful of problems with the way JavaScript handles
// inheritance out of the box. And I'm not talking about being
// Prototypal — since that's one of the best things about it.
//
// For one, you can't inherit directly from other objects. ES5
// introduced Object.create, but it's not available everywhere.
//
// There's no `extend` function built-in, which means that once you've
// set the prototype for a constructor, you have to manually set all of
// the functions too. This also means you don't get to extend the
// prototype with other objects very nicely (out of the box, of
// course).
//
// Calling `super` methods requires hard-coded parents, which doesn't
// work when you have things like traits extended directly on the
// prototype. Capatibilities of parents aren't implemented either —
// testing which one implements which attributes.
//
// To solve this, the module provides three new functions: `inherit`,
// `upper` and `can`, which are discussed in more detail below.
'@boo',
function (root) {

    if (typeof exports == "undefined") {
        old = root.boo
        boo = root.boo = {}
        boo.clean = function() {
            root.boo = old
            return boo
        }}
    else
        boo = exports

    // Some alias for rather JavaLongCommandNamesAndIReallyMeanLong.
    var boo, old
      , proto  = Object.getPrototypeOf
      , create = Object.create
      , slice  = Array.prototype.slice
      , has    = Object.prototype.hasOwnProperty

    ///// Function `inherit` /////////////////////////////////////////////////
    //
    //     inherit(Fun:ctor, Obj:base[, Obj:props]) → Fun:ctor
    //
    // Takes a constructor and a base object, and sets the prototype in
    // the constructor without breaking `instanceof`.
    //
    // If an additional object is passed (as `props`), the properties
    // defined in that object will be copied into the prototype of the
    // constructor as well.
    //
    // Note that these *additional properties* won't have a special
    // inheritance relationship with the constructor's prototype. In
    // fact, they **will** be treated as just being the constructor's
    // own prototype properties.
    //
    function inherit(ctor, base, props) {
        /*** IFDEF DEBUG
         assert(base, "Missing `base' parameter")
         assert(dbg.isfn(ctor), "`ctor' isn't a function")
         *** ENDIF */

        if (!props) props = {}

        props.constructor = ctor
        props.__super__   = base
        ctor.prototype    = create(base)
        return extend(ctor.prototype, props)
    }

    ///// Function `extend' //////////////////////////////////////////////////
    //
    //    extend(Obj:obj, Obj:sources...) → Obj:obj
    //
    // Copies the given source's **own** properties in `obj', and returns
    // the object.
    //
    // > Note that this is only a **shallow** copy, anything other than
    // > primitives will be copied just as a reference to the original
    // > object.
    //
    function extend(obj) {
        var sources = slice.call(arguments, 1)
          , src, prop

        while (src = sources.shift()) {
            for (prop in src)
                if (has.call(src, prop)) obj[prop] = src[prop] }

        return obj
    }

    ///// Function `can` /////////////////////////////////////////////////////
    //
    //     can(Obj:obj, Str:attr[, Bool:allow_traits=true]) → Obj
    //
    // Searches which of the parents of the given objects implement the
    // attribute, and returns it.
    //
    // Sometimes you want to know which object is capable of doing
    // something, and most of the times a simple `in` check will be
    // enough. For those times where you want to check which of the
    // **ancestors** of an object implement a certain functionality (for
    // calling a `super` method, for example), you have this method.
    //
    // By default, this function will search any of the objects that
    // provides the requested functionality for the base object —
    // traits included.
    //
    // The prototype is searched first, then, if the functionality is
    // not found, we move on to searching the trait list, in the reverse
    // order they were plugged in.
    //
    // If the method is not found in the immediate accessors, the
    // function will keep searching up the prototype chain to try to
    // find the requested functionality. And if it really can't find the
    // attribute, `null` is returned.
    //
    // > Note that the trait's prototypes and the object itself are
    // > **not** included in this search chain.
    //
    function can(obj, attr, allow_traits) {
        /*** IFDEF DEBUG
         assert(dbg.isobj(obj), "`obj' is not an object")
         assert(attr, "Missing `attr' parameter")
         *** ENDIF */
        function add_traits(){ bases.push.apply(bases, obj.__traits__ || []) }
        function get_base()  { return cur.__super__ || cur                   }
        function has_attr()  { return cur && cur.hasOwnProperty(attr)        }

        var bases, cur
        if (allow_traits == null) allow_traits = true

        while (obj) {
            // Build a list of all the immediate accessors we should
            // look at
            bases = [proto(obj)]
            if (allow_traits) add_traits()

            // Then check each one, in order, to see if they have the
            // requested property
            while (bases.length) {
                cur = bases.shift()
                if (has_attr()) return get_base() }

            // If none of them does, continue on to the next accessors
            obj = proto(obj) }
    }

    ///// Function `upper` ///////////////////////////////////////////////////
    //
    //     upper(Obj:obj[, Obj:base][, Str:meth][, args...]) → ?
    //
    // Calls a parent method in the context of the given object.
    //
    // This allows for fully prototypal inheritance, without loosing
    // overwritten methods. Because, you see, we assume that methods
    // that were overwritten are somehow **important** and you will want
    // to refer to them on your functions.
    //
    // The given method will **always** be searched on all of the
    // accessors, traits included, and it'll be called in the context of
    // the given object.
    //
    // To avoid errors with *endless recursion*, the super call state
    // (the object that was looked upon last time) is saved on each
    // call, and removed when the function returns.
    //
    // This is done by simple writing to the `__$ctx__` property, and
    // expects your function to be **synchronous**. If you're calling
    // any asynchronous super method, you'll need to pass the previous
    // stored context explicitly.
    //
    //     b.one.proto.upper(this, this.__$ctx__, "show")
    //
    // > Note that this assumes you won't be writing to `__$ctx__` in
    // > your code. As a rule of thumb, you shouldn't ever have an
    // > actual property with a dollar sign anyways.
    //
    function upper(obj) {
        // Sanitize the arguments passed to the function
        var args = slice.call(arguments, 1)
          , base = args.shift()
          , meth

        if (Object(base) !== base) meth = base, base = null
        else                       meth = args.shift()

        if (!base)                 base = obj.__$ctx__ || obj

        return __upper(obj, base, meth, args)
    }

    function __upper(obj, base, meth, args) {
        var _super, rv

        // try to find the first accessor to implement the method, then
        // return the result of calling this method.
        _super       = can(base, meth)
        obj.__$ctx__ = _super

        rv = _super[meth].apply(obj, args)
        delete obj.__$ctx__
        return rv
    }

    ///// Function `plugin' //////////////////////////////////////////////////
    //
    //     plugin(Fun|Obj:obj, Obj:traits...) → Fun|Obj:obj
    //
    // Takes a constructor or an object, and adds traits to the
    // prototype, returning the given object/constructor.
    //
    // Traits are a mechanism to handle the same issue as
    // multiple-inheritance, but in a Prototypal OO manner. The idea is
    // that traits provide just a collection of, perhaps, incomplete
    // functionality that's intended to be plugged in an object.
    //
    // This is more powerful than the classical multiple-inheritance
    // system, because you can plugin traits in the constructor, long
    // after several instances of an object have been created, and all
    // of those instances will magically have that trait available too:
    //
    //     function Mage() {}
    //     Mage.cast = function(spell){ return "You've cast " + spell }
    //
    //     var RedMage = { fira: function(){ this.cast("Fira") }}
    //     var Vivi    = new Mage
    //     Vivi.cast("Blizzard") // You've cast Blizzard
    //
    //     // Makes all Mages learn fire magic
    //     b.one.proto.plugin(Mage, RedMage)
    //     Vivi.fira()          // You've cast Fira
    //
    // Not only this, but the traits plugged to a constructor are
    // tracked, and you can call their methods as `super` methods. And
    // as with the prototypal inheritance, you don't need to create a
    // separate meta-object for your functionality, ANY object can be a
    // trait :3
    //
    function plugin(obj) {
        function get_traits() {return (ctor.__traits__ || []).concat(args)}

        var args = slice.call(arguments, 1)
          , base = typeof obj == "function"? obj.prototype
                                           : proto(obj)
          , ctor = base.constructor

        ctor.__traits__ = get_traits()
        extend.apply(obj, [base].concat(args))
        return obj
    }

    ///// Exports ////////////////////////////////////////////////////////////
    boo.inherit = inherit
    boo.extend  = extend
    boo.can     = can
    boo.upper   = upper
    boo.plugin  = plugin
}(this);
<|endoftext|>


<commit_before>import Ember from 'ember';

const { assert, assign, get, inject: { service }, observer, set } = Ember;

export default Ember.Component.extend({

  gaEmbed: service(),

  classNames: ['ga-embed-authorize'],
  classNameBindings: ['gaEmbed.isAuthorized:ga-embed-is-authorized'],

  clientId: null,

  didInsertElement() {

    get(this, 'gaEmbed')._onApiReady(() => {
      this.authorize();
    });

  },

  authorize() {
    const clientid = get(this, 'clientId') || get(this, 'gaEmbed.config.clientId');

    assert('[ember-google-analytics-embed] No Google Analytics clientId set in config/environment.js', clientid);

    let params = {
      container: this.elementId,
      clientid
    };

    const apiKey = get(this, 'apiKey') || get(this, 'gaEmbed.config.apiKey');

    if (apiKey) { assign(params, { apiKey }); }

    let authorize = window.gapi.analytics.auth.authorize(params);

    authorize.on('success', () => {
      set(this, 'gaEmbed.isAuthorized', true);

    });

  },

  hideOnAuthorize: observer('gaEmbed.isAuthorized', function() {
    const isAuthorized = get(this, 'gaEmbed.isAuthorized');
    let display = isAuthorized ? 'none' : 'block';

    Ember.run.next(() => {
      this.$().css({ display });
    });

  })

});
<commit_msg>Adds access token authorization<commit_after>import Ember from 'ember';

const { assert, assign, get, inject: { service }, observer, set } = Ember;

export default Ember.Component.extend({

  gaEmbed: service(),

  classNames: ['ga-embed-authorize'],
  classNameBindings: ['gaEmbed.isAuthorized:ga-embed-is-authorized'],

  clientId: null,

  didInsertElement() {

    get(this, 'gaEmbed')._onApiReady(() => {
      this.authorize();
    });

  },

  authorize() {

    if (get(this, 'accessToken')) { return this.authorizeWithAccessToken(); }

    const clientid = get(this, 'clientId') || get(this, 'gaEmbed.config.clientId');

    assert('[ember-google-analytics-embed] No Google Analytics clientId set in config/environment.js', clientid);

    let params = {
      container: this.elementId,
      clientid
    };

    const apiKey = get(this, 'apiKey') || get(this, 'gaEmbed.config.apiKey');

    if (apiKey) { assign(params, { apiKey }); }

    this._authorize(params);

  },

  authorizeWithAccessToken() {

    this._authorize({
      'serverAuth': {
        'access_token': get(this, 'accessToken')
      }
    });

    set(this, 'gaEmbed.isAuthorized', true);
    this.sendAction('onSignIn');

  },

  _authorize(params) {
    let authorize = window.gapi.analytics.auth.authorize(params);

    authorize.on('signIn', () => {
      set(this, 'gaEmbed.isAuthorized', true);
      this.sendAction('onSignIn');

    });

    authorize.on('signOut', () => {
      set(this, 'gaEmbed.isAuthorized', false);
      this.sendAction('onSignOut');

    });

    authorize.on('error', (err) => {
      this.sendAction('onError', err);
    });

  },

  hideOnAuthorize: observer('gaEmbed.isAuthorized', function() {
    const isAuthorized = get(this, 'gaEmbed.isAuthorized');
    let display = isAuthorized ? 'none' : 'block';

    Ember.run.next(() => {
      this.$().css({ display });
    });

  })

});
<|endoftext|>


<commit_before>import program from 'commander'
import pkg from '../package.json'
import bundle from './commands/bundle'
import lint from './commands/lint'

program
  .command('bundle [entry] [bundle]')
  .description([
    'bundles the given entry file (and the dependencies) into the bundle file',
    'entry defaults to "./src/index.js" and bundle defaults to "./dist/bundle.js"'
  ].join('\n\t\t\t\t\t'))
  .option('-d, --dev', 'start the dev server')
  .option('-b, --base <dir>', 'directory to host the dev server from')
  .action(bundle)

program
  .command('lint [sources...]')
  .description('lint the given source globs, defaults to all files in the project')
  .action(lint)

program
  .action(() => program.outputHelp())

program
  .version(pkg.version)
  .parse(process.argv)

if (!program.args.length) {
  program.help()
}
<commit_msg>Remove too long cli help<commit_after>import program from 'commander'
import pkg from '../package.json'
import bundle from './commands/bundle'
import lint from './commands/lint'

program
  .command('bundle [entry] [bundle]')
  .description('bundles the given entry file (and the dependencies) into the bundle file')
  .option('-d, --dev', 'start the dev server')
  .option('-b, --base <dir>', 'directory to host the dev server from')
  .action(bundle)

program
  .command('lint [sources...]')
  .description('lint the given source globs, defaults to all files in the project')
  .action(lint)

program
  .action(() => program.outputHelp())

program
  .version(pkg.version)
  .parse(process.argv)

if (!program.args.length) {
  program.help()
}
<|endoftext|>


<commit_before>module.exports = function(grunt) {
	'use strict';

  // Project configuration.
  grunt.initConfig({
	clean : ['doc'],
    jsdoc : {
		dist: {
			src: ['tasks/**.js', 'tasks/lib/*.js'],
			options: {
				destination: 'doc'
			}
		},
        tmpl : {
            src: ['tasks/**.js', 'tasks/lib/*.js'],
            options:{
				destination: 'doc',
                template: "node_modules/ink-docstrap/template",
                configure: "node_modules/ink-docstrap/template/jsdoc.conf.json"
			}
        }
	},
	nodeunit : {
        unit : ['test/jsdoc-plugin_test.js'],
        int : ['test/jsdoc-task_test.js']
	},
	jshint : {
		files : ['Gruntfile.js', 'tasks/*.js', 'tasks/lib/*.js', 'test/*.js'],
		options: {
			node : true,
			smarttabs : true
		}
	}
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');

  // Load local tasks.
  grunt.loadTasks('tasks');

  // Default task.
  grunt.registerTask('default', ['jshint', 'nodeunit']);

  grunt.registerTask('test-dist', ['clean', 'jsdoc:dist', 'nodeunit:int']);
  grunt.registerTask('test-tmpl', ['clean', 'jsdoc:tmpl', 'nodeunit:int']);

  grunt.registerTask('test', ['nodeunit:unit', 'test-dist', 'test-tmpl']);

};
<commit_msg>update the default task<commit_after>module.exports = function(grunt) {
	'use strict';

  // Project configuration.
  grunt.initConfig({
	clean : ['doc'],
    jsdoc : {
		dist: {
			src: ['tasks/**.js', 'tasks/lib/*.js'],
			options: {
				destination: 'doc'
			}
		},
        tmpl : {
            src: ['tasks/**.js', 'tasks/lib/*.js'],
            options:{
				destination: 'doc',
                template: "node_modules/ink-docstrap/template",
                configure: "node_modules/ink-docstrap/template/jsdoc.conf.json"
			}
        }
	},
	nodeunit : {
        unit : ['test/jsdoc-plugin_test.js'],
        int : ['test/jsdoc-task_test.js']
	},
	jshint : {
		files : ['Gruntfile.js', 'tasks/*.js', 'tasks/lib/*.js', 'test/*.js'],
		options: {
			node : true,
			smarttabs : true
		}
	}
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-nodeunit');

  // Load local tasks.
  grunt.loadTasks('tasks');

  // Default task.
  grunt.registerTask('default', ['jshint', 'test']);

  grunt.registerTask('test-dist', ['clean', 'jsdoc:dist', 'nodeunit:int']);
  grunt.registerTask('test-tmpl', ['clean', 'jsdoc:tmpl', 'nodeunit:int']);

  grunt.registerTask('test', ['nodeunit:unit', 'test-dist', 'test-tmpl']);

};
<|endoftext|>


<commit_before>/* run 'grunt' to listen for changes */

(function () {
   'use strict';
}());
module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        concat: {
            options: {
                separator: 'rnrn'
            },
            dist: {
                src: ['resources/scripts/*.js'],
                dest: 'public_html/js/main.js'
            }
        },

        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */n'
            },
            dist: {
                files: {
                    'public_html/js/main.min.js': ['public_html/js/main.js']
                }
            }
        },

        sass: {
            options: {
                sourceMap: true,
                sourceComments: false
            },
            dist: {
                files: {
                    'public_html/css/main.css': 'resources/scss/main.scss'
                }
            }
        },

        watch: {
            files: ['resources/scss/**/*.scss', 'resources/scripts/*.js'],
            tasks: ['concat', 'uglify', 'sass']
        }

    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.registerTask('default', ['concat', 'uglify', 'sass', 'watch']);
};<commit_msg>Update Gruntfile.js<commit_after>/* run 'grunt' to listen for changes */

(function () {
   'use strict';
}());
module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        concat: {
            options: {
                separator: 'rnrn'
            },
            dist: {
                src: ['resources/scripts/*.js'],
                dest: 'public_html/js/main.js'
            }
        },

        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
            },
            dist: {
                files: {
                    'public_html/js/main.min.js': ['public_html/js/main.js']
                }
            }
        },

        sass: {
            options: {
                sourceMap: true,
                sourceComments: false
            },
            dist: {
                files: {
                    'public_html/css/main.css': 'resources/scss/main.scss'
                }
            }
        },

        watch: {
            files: ['resources/scss/**/*.scss', 'resources/scripts/*.js'],
            tasks: ['concat', 'uglify', 'sass']
        }

    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.registerTask('default', ['concat', 'uglify', 'sass', 'watch']);
};<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash');
const config = require('./config');
const rp = require('request-promise');
const slack = require('slack');

const webhookSlackBot = slack.rtm.client();

webhookSlackBot.started(payload => {
  this.self = payload.self;
});

webhookSlackBot.message(msg => {
  console.log('New message: ', JSON.stringify(msg));

  const filterField = config('MESSAGE_FILTER_FIELD');
  const filterText = config('MESSAGE_FILTER_TEXT');
  console.log('Testing filters: ', filterField, filterText);
  if (filterField && filterText && _.get(msg, filterField, '').indexOf(filterText) === -1) {
    console.log('Message filtered');
    return;
  }

  const webhookUrls = config('WEBHOOK_URLS');
  _.forEach(webhookUrls, webhookUrl => {
    const webhookPayload = msg;

    // Support signing of the payload.
    const options = {
      method: 'POST',
      uri: webhookUrl,
      body: webhookPayload,
      json: true,
    };

    console.log(`Sending Webhook to ${webhookUrl}`);
    rp(options)
      .then(parsedBody => {
        console.log('POST succeeded...');
      })
      .catch(err => {
        console.log(`POST failed...${err}`);
      });
  });
});

module.exports = webhookSlackBot;
<commit_msg>Update logging statement<commit_after>'use strict'

const _ = require('lodash');
const config = require('./config');
const rp = require('request-promise');
const slack = require('slack');

const webhookSlackBot = slack.rtm.client();

webhookSlackBot.started(payload => {
  this.self = payload.self;
});

webhookSlackBot.message(msg => {
  console.log('New message: ', JSON.stringify(msg));

  const filterField = config('MESSAGE_FILTER_FIELD');
  const filterText = config('MESSAGE_FILTER_TEXT');
  if (filterField && filterText && _.get(msg, filterField, '').indexOf(filterText) === -1) {
    console.log(`Message filtered - message.${filterField} does not contain '${filterText}'`);
    return;
  }

  const webhookUrls = config('WEBHOOK_URLS');
  _.forEach(webhookUrls, webhookUrl => {
    const webhookPayload = msg;

    // Support signing of the payload.
    const options = {
      method: 'POST',
      uri: webhookUrl,
      body: webhookPayload,
      json: true,
    };

    console.log(`Sending Webhook to ${webhookUrl}`);
    rp(options)
      .then(parsedBody => {
        console.log('POST succeeded...');
      })
      .catch(err => {
        console.log(`POST failed...${err}`);
      });
  });
});

module.exports = webhookSlackBot;
<|endoftext|>