<commit_before>/**
 * blame.js is user JavaScript file wich will be include to github page and adds new feachures on blame page.i
 *
 * @author Andrew Kulakov <avk@8xx8.ru>
 * @version 1.0.0
 * @license https://github.com/Andrew8xx8/blame.js/blob/master/MIT-LICENSE.txt
 * @copyright Andrew Kulakov (c) 2011
 */

(function (globals) {

    var apiRoot = "https://github.com/api/v2/json/",

    jsonp = function (url, callback, context) {
        var script = document.createElement("script");

        var prefix = "?";
        if (url.indexOf("?") >= 0)
            prefix = "&";

        url += prefix + "callback=" + encodeURIComponent(callback);

        url += "&login=&authToken=";

        script.setAttribute("src", apiRoot + url);

        document.getElementsByTagName('head')[0].appendChild(script);
    },

    blame = globals.blame = {};

    blame.cache = {
        store: new Array(),
        add : function (hash, data){
            if (this.store[hash] == null) {
                this.store[hash] = data;
            }
        },
        clear: function (){
            this.store = Array();
        },
        get: function (hash){
            if (this.store[hash] != null) {
                return this.store[hash];
            } else {
                return false;
            }
        }
    };

    blame.diffPlusLine = '{line}
';
    blame.diffMinusLine = '{line}
';
    blame.diffHeadLine = '{line}
';
    blame.diffLine = '{line}
';

	blame.showTemplate = "[ show \u2193 ]";
	blame.hideTemplate = "[ hide \u2191 ]";

    blame.fileTemplate = '
{name}

';

    blame.popupTemplate =
	'
[ X ]
' +
    '
' +
        '
Commit: {commit_hash}
' +
        '
' +
            '
Committed: {committed_time} ({committed_date})
'+
            'Authored: {authored_time} ({authored_date})
'+
            'by {username}
'+
            '
Message
' +
            '
{message}
' +
       '
' +
    '
' +
    '
' +
        '
Diff
' +
		'' + blame.showTemplate + ''+
        '
' +
            '
' +
                '{diff}' +
            '
' +
       '
' +
    '
' +
    '
' +
        '
Files
' +
		'' + blame.showTemplate + ''+
        '
' +
            '
Added:
' +
            '
{added}
' +
            '
Modified
' +
            '
{modified}
' +
            '
Deleted
' +
            '
{deleted}
' +
       '
' +
    '
';

    blame.popupPosition = {x: '0px', y: '0px'};
    blame.lock = false;

    blame.loadCommit = function (data){

        blame.cache.add(data.id, data);

        var popup = ' ', added = 'none', deleted = 'none', modified = 'none', diff = 'none';

        if ( data.commit.added != null) {
            added = '';
            for (var i = 0; i < data.commit.added['length']; i++) {
                added += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.added[i],
                    'href' :  data.commit.added[i],
                    'color': 'green'
                });
            }
        }

        if ( data.commit.modified != null) {
            modified = '';
            diff = '';
            for (var i = 0; i < data.commit.modified['length']; i++) {
                diff +=  data.commit.modified[i].diff;
                modified += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.modified[i].filename,
                    'href' :  data.commit.modified[i].filename,
                    'color' : 'blue',
                });
            }
        }

        if ( data.commit.deleted != null) {
            deleted = '';
            for (var i = 0; i < data.commit.deleted['length']; i++) {
                deleted += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.deleted[i],
                    'href' :  data.commit.deleted[i],
                    'color':'red'
                });
            }
        }

        committed_date = new Date(data.commit.committed_date);
        authored_date = new Date(data.commit.authored_date);

        popup = blame.fetchTemplate(blame.popupTemplate, {
            'modified'  : modified,
            'added'     : added,
            'deleted'   : deleted,
            'username'  : data.commit.author.name,
            'email'     : data.commit.author.email,
            'userlogin' : data.commit.author.login,
            'message'   : blame.escape(data.commit.message),
            'commit_hash' : data.commit.id,
            'committed_time' : committed_date.toLocaleTimeString(),
            'committed_date' : committed_date.toLocaleDateString(),
            'authored_time'  : authored_date.toLocaleTimeString(),
            'authored_date'  : authored_date.toLocaleDateString(),
            'diff': blame.colorDiff(diff)
        });

        $('#blame-popup').html(popup);

        $('#blame-popup').css({
            'right': blame.popupPosition.x,
            'top':  blame.popupPosition.y,
        });

        $('#blame-popup').fadeIn();
        blame.lock = false;
    };

	blame.showHide = function(){
			var info = $(this).parent().find('.blame-info')
			if(info.is(':visible')){
				info.slideUp(300, function(){
                    $(this).parent().find('.s-h').html(blame.showTemplate);
                });
			} else {
				info.slideDown(300, function(){
                    $(this).parent().find('.s-h').html(blame.hideTemplate);
                });
			}
	}

    blame.fetchTemplate = function(template, data){
        var result = template;

        for(var i in data) {
            name = '{' + i + '}';
            result = result.replace(name, data[i]);
        }
        return result;
    };

    blame.escape = function (string) {
        return string.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    }

    blame.colorDiff = function(diff) {
        function wrapDiff(string) {
            if (string.indexOf('@@ ') == 0) {
                string = blame.fetchTemplate(blame.diffHeadLine,{'line': blame.escape(string)});
            } else if (string.indexOf('+') == 0) {
                string = blame.fetchTemplate(blame.diffPlusLine,{'line': blame.escape(string)});
            } else if (string.indexOf('-') == 0) {
                string = blame.fetchTemplate(blame.diffMinusLine,{'line': blame.escape(string)});
            } else {
                string = blame.fetchTemplate(blame.diffLine,{'line': blame.escape(string)});
            }

            return string;
        }

        lines = diff.split(/\n/);
        _diff = '';

        for (var i in lines){
            _diff += wrapDiff(lines[i]);
        }
        return _diff;
    }
    blame.register = function() {
        $('.blame .commitinfo').click(function(){
//            if (blame.lock) return;
            blame.lock = true;

            blame.popupPosition.x = '20px';
            blame.popupPosition.y = $(this).offset().top + 'px';

            current_commit = $(this).find('a:first').html();
            $('.blame .commitinfo').css({'background-color': 'transparent'});
            $('.blame .commitinfo code a').each(function(index, value){
                if(current_commit == $(value).html()) {
                    $(value).parent().parent().css({'background-color': '#dfa'});
                }
            });

            commit_id = $(this).find('a:first').attr('href').match(/\/commit\/(\S*?)$/)[1];

            data = blame.cache.get(commit_id);

            if (data !== false) {
                blame.loadCommit(data);
            } else{
                jsonp("commits/show" + $(this).find('a:first').attr('href').replace(/\/commit\//, '/'), 'blame.loadCommit');
            }
        });

        $('body').append('

');
        $('#blame-popup').css({
            'position': 'absolute',
            'width':    'auto',
            'z-index': '100500',
            'display': 'none',
            'background': '#fff',
            'padding': '6px',
            'padding-top': '10px',
            'color' :  '#444',
			'border-radius': '8px',
			'box-shadow': '0px 0px 10px 0px #888'
        });
		$('#blame-popup .close').live('click', function(){
			$('#blame-popup').fadeOut();
		});
		$('#blame-popup .blame-block h3').live('click', blame.showHide);
		$('#blame-popup .blame-block .s-h').live('click', blame.showHide);
    }

}(window));

$(document).ready(function(){
    blame.register();
});
<commit_msg>[+] Loadding animation added.<commit_after>/**
 * blame.js is user JavaScript file wich will be include to github page and adds new feachures on blame page.i
 *
 * @author Andrew Kulakov <avk@8xx8.ru>
 * @version 1.0.0
 * @license https://github.com/Andrew8xx8/blame.js/blob/master/MIT-LICENSE.txt
 * @copyright Andrew Kulakov (c) 2011
 */

(function (globals) {

    var apiRoot = "https://github.com/api/v2/json/",

    jsonp = function (url, callback, context) {
        var script = document.createElement("script");

        var prefix = "?";
        if (url.indexOf("?") >= 0)
            prefix = "&";

        url += prefix + "callback=" + encodeURIComponent(callback);

        url += "&login=&authToken=";

        script.setAttribute("src", apiRoot + url);

        document.getElementsByTagName('head')[0].appendChild(script);
    },

    blame = globals.blame = {};

    blame.cache = {
        store: new Array(),
        add : function (hash, data){
            if (this.store[hash] == null) {
                this.store[hash] = data;
            }
        },
        clear: function (){
            this.store = Array();
        },
        get: function (hash){
            if (this.store[hash] != null) {
                return this.store[hash];
            } else {
                return false;
            }
        }
    };

    blame.diffPlusLine = '{line}
';
    blame.diffMinusLine = '{line}
';
    blame.diffHeadLine = '{line}
';
    blame.diffLine = '{line}
';

    blame.loadding = '';
	blame.showTemplate = "[ show \u2193 ]";
	blame.hideTemplate = "[ hide \u2191 ]";

    blame.fileTemplate = '
{name}

';

    blame.popupTemplate =
	'
[ X ]
' +
    '
' +
        '
Commit: {commit_hash}
' +
        '
' +
            '
Committed: {committed_time} ({committed_date})
'+
            'Authored: {authored_time} ({authored_date})
'+
            'by {username}
'+
            '
Message
' +
            '
{message}
' +
       '
' +
    '
' +
    '
' +
        '
Diff
' +
		'' + blame.showTemplate + ''+
        '
' +
            '
' +
                '{diff}' +
            '
' +
       '
' +
    '
' +
    '
' +
        '
Files
' +
		'' + blame.showTemplate + ''+
        '
' +
            '
Added:
' +
            '
{added}
' +
            '
Modified
' +
            '
{modified}
' +
            '
Deleted
' +
            '
{deleted}
' +
       '
' +
    '
';

    blame.lock = false;

    blame.loadCommit = function (data){

        blame.cache.add(data.id, data);

        var popup = ' ', added = 'none', deleted = 'none', modified = 'none', diff = 'none';

        if ( data.commit.added != null) {
            added = '';
            for (var i = 0; i < data.commit.added['length']; i++) {
                added += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.added[i],
                    'href' :  data.commit.added[i],
                    'color': 'green'
                });
            }
        }

        if ( data.commit.modified != null) {
            modified = '';
            diff = '';
            for (var i = 0; i < data.commit.modified['length']; i++) {
                diff +=  data.commit.modified[i].diff;
                modified += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.modified[i].filename,
                    'href' :  data.commit.modified[i].filename,
                    'color' : 'blue',
                });
            }
        }

        if ( data.commit.deleted != null) {
            deleted = '';
            for (var i = 0; i < data.commit.deleted['length']; i++) {
                deleted += blame.fetchTemplate(blame.fileTemplate, {
                    'name' :  data.commit.deleted[i],
                    'href' :  data.commit.deleted[i],
                    'color':'red'
                });
            }
        }

        committed_date = new Date(data.commit.committed_date);
        authored_date = new Date(data.commit.authored_date);

        popup = blame.fetchTemplate(blame.popupTemplate, {
            'modified'  : modified,
            'added'     : added,
            'deleted'   : deleted,
            'username'  : data.commit.author.name,
            'email'     : data.commit.author.email,
            'userlogin' : data.commit.author.login,
            'message'   : blame.escape(data.commit.message),
            'commit_hash' : data.commit.id,
            'committed_time' : committed_date.toLocaleTimeString(),
            'committed_date' : committed_date.toLocaleDateString(),
            'authored_time'  : authored_date.toLocaleTimeString(),
            'authored_date'  : authored_date.toLocaleDateString(),
            'diff': blame.colorDiff(diff)
        });

        $('#blame-popup').html(popup);

        blame.lock = false;
    };

	blame.showHide = function(){
			var info = $(this).parent().find('.blame-info')
			if(info.is(':visible')){
				info.slideUp(300, function(){
                    $(this).parent().find('.s-h').html(blame.showTemplate);
                });
			} else {
				info.slideDown(300, function(){
                    $(this).parent().find('.s-h').html(blame.hideTemplate);
                });
			}
	}

    blame.fetchTemplate = function(template, data){
        var result = template;

        for(var i in data) {
            name = '{' + i + '}';
            result = result.replace(name, data[i]);
        }
        return result;
    };

    blame.escape = function (string) {
        return string.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    }

    blame.colorDiff = function(diff) {
        function wrapDiff(string) {
            if (string.indexOf('@@ ') == 0) {
                string = blame.fetchTemplate(blame.diffHeadLine,{'line': blame.escape(string)});
            } else if (string.indexOf('+') == 0) {
                string = blame.fetchTemplate(blame.diffPlusLine,{'line': blame.escape(string)});
            } else if (string.indexOf('-') == 0) {
                string = blame.fetchTemplate(blame.diffMinusLine,{'line': blame.escape(string)});
            } else {
                string = blame.fetchTemplate(blame.diffLine,{'line': blame.escape(string)});
            }
            return string;
        }

        lines = diff.split(/\n/);
        _diff = '';

        for (var i in lines){
            _diff += wrapDiff(lines[i]);
        }

        return _diff;
    }
    blame.register = function() {
        $('.blame .commitinfo').click(function(){
            //if (blame.lock) return;
            blame.lock = true;

            $('#blame-popup').html(blame.loadding);
            $('#blame-popup').css({
                'right': '20px',
                'top':   $(this).offset().top + 'px',
            });

            $('#blame-popup').fadeIn(500);

            current_commit = $(this).find('a:first').html();
            $('.blame .commitinfo').css({'background-color': 'transparent'});
            $('.blame .commitinfo code a').each(function(index, value){
                if(current_commit == $(value).html()) {
                    $(value).parent().parent().css({'background-color': '#dfa'});
                }
            });

            commit_id = $(this).find('a:first').attr('href').match(/\/commit\/(\S*?)$/)[1];

            data = blame.cache.get(commit_id);

            if (data !== false) {
                blame.loadCommit(data);
            } else{
                jsonp("commits/show" + $(this).find('a:first').attr('href').replace(/\/commit\//, '/'), 'blame.loadCommit');
            }
        });

        $('body').append('

');
        $('#blame-popup').css({
            'position': 'absolute',
            'width':    'auto',
            'z-index': '100500',
            'display': 'none',
            'background': '#fff',
            'padding': '6px',
            'padding-top': '10px',
            'color' :  '#444',
			'border-radius': '8px',
			'box-shadow': '0px 0px 10px 0px #888'
        });
		$('#blame-popup .close').live('click', function(){
			$('#blame-popup').fadeOut();
		});
		$('#blame-popup .blame-block h3').live('click', blame.showHide);
		$('#blame-popup .blame-block .s-h').live('click', blame.showHide);
    }

}(window));

$(document).ready(function(){
    blame.register();
});
<|endoftext|>


<commit_before>/**
 * e2e tests for the login functionality
 */

var helper = require('../protractor-help');

describe('login', function() {

  it('should show a form', function() {
    browser.get('/#/login');

    element.all(by.css('main form input')).then(function(inputs) {
      expect( // at least 3 input fields: tenant, username, password
        inputs.length >= 3
      ).toBe(true);

    });

  });

  describe('when logged in', function() {
    beforeEach(helper.loginAsAdmin);
    afterEach(helper.logout);

    it('should redirect home', function() {
      browser.get('/#/login');

      expect(
        $('body').getAttribute('class')
      ).toContain('state-home');

      expect(
        browser.getLocationAbsUrl()
      ).toMatch(/\/#\/$/);
    });

  });
});

<commit_msg>simplify test<commit_after>/**
 * e2e tests for the login functionality
 */

var helper = require('../protractor-help');

describe('login', function() {

  it('should show a form', function() {
    browser.get('/#/login');

    expect(
      element.all(by.css('main form input')).count()
    ).toBe(4); // tenant, username, password, remember

  });

  describe('when logged in', function() {
    beforeEach(helper.loginAsAdmin);
    afterEach(helper.logout);

    it('should redirect home', function() {
      browser.get('/#/login');

      expect(
        $('body').getAttribute('class')
      ).toContain('state-home');

      expect(
        browser.getLocationAbsUrl()
      ).toMatch(/\/#\/$/);
    });

  });
});

<|endoftext|>


<commit_before>// require mechanics.js
// require elements.js

var TILE_SIZE = 80;
var TIME_STEP = 500;
var VIZ_IS_ON = false;

var i2x = function (i) { return TILE_SIZE * i; }
var j2y = function (j) { return TILE_SIZE * j; }

var x2i = function (x) { return Math.floor(x / TILE_SIZE); }
var y2j = function (y) { return Math.floor(y / TILE_SIZE); }

function Board (nX, nY) {

  this.nX = nX;
  this.nY = nY;

  var i, j;

  // or sparse representation
  this.board = [];

  for (i = 0; i < nX; i++) {
    this.board[i] = [];
    for (j = 0; j < nY; j++) {
      this.board[i][j] = new Elements.Vacuum();
    }
  }

  this.stateSpatial = [];

  for (i = 0; i < nX; i++) {
    this.stateSpatial[i] = [];
    for (j = 0; j < nY; j++) {
      this.stateSpatial[i][j] = {};
    }
  }

}

Board.prototype.drawBackground = function () {
  var boardFlat = [];
  var i, j;

  for (i = 0; i < this.nX; ++i) {
    for (j = 0; j < this.nY; ++j) {
      boardFlat.push({i: i, j: j});
    }
  }

  d3.select("svg").append("g")
    .attr("id", "background")
    .selectAll(".tile")
    .data(boardFlat)
    .enter()
      .append("rect")
      .attr({
        class: 'tile',
        x: function (d) { return i2x(d.i) },
        y: function (d) { return j2y(d.j) },
        width: TILE_SIZE,
        height: TILE_SIZE,
      });

  // just to have it at the right layer
  d3.select("svg").append("g")
    .attr("id", "photons");

}

Board.prototype.draw = function () {

  var i, j, v, s;
  var boardFlat = [];

  var thisBoard = this;

  for (i = 0; i < this.nX; i++) {
    for (j = 0; j < this.nY; j++) {
      v = this.board[i][j];
      v.i = i;
      v.j = j;
      if (v instanceof Elements.Vacuum) {
        continue;
      }
      boardFlat.push({i: i, j: j, val: v});
    }
  }

  var tiles = d3.select("svg").append("g")
    .attr("id", "board")
    .selectAll(".tile")
    .data(boardFlat)
    .enter()
      .append("g")
      .attr({
        class: 'tile',
        transform: function (d) {
          return 'translate(' + (i2x(d.i) + TILE_SIZE/2) + ',' + (j2y(d.j) + TILE_SIZE/2) + ')';
        },
      });

  // Keep tile node reference
  tiles.each(function (d) {
    d.val.node = this;
  });

  // Create element
  tiles
      .append("use")
      .attr({
        'xlink:href': function (d) { return "#" + d.val.name; },
        'class': 'element',
        transform: function (d) {
          return 'rotate(' + (d.val.angleOfRotation * d.val.rotation) + ',0,0)';
        },
      });
  // Create hitbox
  tiles
      .append("use")
      .attr({
        'xlink:href': '#hitbox',
        class: 'hitbox',
      })
      .on('click', function (d) {

        if (d3.event.defaultPrevented) return;

        var element = d3.select(d.val.node).select('.element');

        d.val.rotation = (d.val.rotation + 1) % d.val.maxRotation;

        // Assure that rotation animation is clockwise.
        element
          .attr('transform', 'rotate(' +  (d.val.angleOfRotation * (d.val.rotation - 1)) + ',0,0)');

        element.transition().duration(300)
          .attr('transform', 'rotate(' +  (d.val.angleOfRotation * d.val.rotation) + ',0,0)');
      });

  // Drag and drop

  var drag = d3.behavior.drag()
      .on('dragstart', function (d) {
        d3.event.sourceEvent.stopPropagation();
      })
      .on('drag', function (d) {
        d3.select(this).attr("transform", 'translate(' + d3.event.x + ',' + d3.event.y + ')');
        d.val.newI = x2i(d3.event.x);
        d.val.newJ = y2j(d3.event.y);
      })
      .on('dragend', function (d) {
        // No drag?
        if (d.val.newI == null || d.val.newJ == null) {
          return;
        }

        if ((d.val.newI < 0) || (d.val.newI >  thisBoard.nX - 1) || (d.val.newJ < 0) || (d.val.newJ >  thisBoard.nY - 1)) {

          d.val.newI = d.val.i;
          d.val.newI = d.val.j;

          d3.select(d.val.node).transition().duration(300).attr('transform',
              'translate(' + (i2x(d.val.i) + TILE_SIZE/2) +
              ',' + (j2y(d.val.j) + TILE_SIZE/2) + ')'
          );

          return;

        }

        // Intuitive naming
        var from = d.val;

        var to = thisBoard.board[from.newI][from.newJ];

        // Swap items if it's possible
        var canSwap = true; // TODO detect if "to" element is frozen. If not, let it go.
        if (canSwap) {
          // Swap items in matrix
          thisBoard.board[from.i][from.j] = to;
          thisBoard.board[from.newI][from.newJ] = from;
          // Swap items' positions
          to.i = from.i;
          to.j = from.j;
          from.i = from.newI;
          from.j = from.newJ;
        }
        delete from.newI;
        delete from.newJ;
        // Move element (if exists)
        if (to.node) {
          d3.select(to.node).transition().duration(300).attr('transform',
              'translate(' + (i2x(to.i) + TILE_SIZE/2) +
              ',' + (j2y(to.j) + TILE_SIZE/2) + ')'
          );
        }
        // "from" element is draggable, so it exists
        d3.select(from.node).transition().duration(300).attr('transform',
            'translate(' + (i2x(from.i) + TILE_SIZE/2) +
            ',' + (j2y(from.j) + TILE_SIZE/2) + ')'
        );
      });
  tiles
      .call(drag);

}

// only single photon sources
Board.prototype.stateInit = function () {

  var sources = 0;

  this.stateSpatial = [];

  var stateSpatial = this.stateSpatial;  // this issue

  _.forEach(this.board, function (col, i) {
    _.forEach(col, function (el, j) {
      if (el.name === 'source') {
        sources += 1;
        _.forEach(el.generateSv(), function (out) {
          stateSpatial.push({
            i:  i,
            j:  j,
            to: out.to,  // for more particles, more things will go it 'to'
            re: out.re,
            im: out.im
          })
        })
      }
    });
  });

  if (sources > 1) {
    console.log("As of now only one source, sorry.");
  }

  this.stateHistory = [_.cloneDeep(this.stateSpatial)];

};

// as of now - only single particle interactions
// as of now - very inefficient (I should query elements only once)
// as of now - without absorption
// some of it should go to mechanics.js BTW
Board.prototype.statePropagate = function () {

  var board = this.board;
  var stateSpatial0 = this.stateSpatial;
  var stateSpatialDict = {};

  var keyOut, diffRe, diffIm;

  stateSpatial0 = _.map(stateSpatial0, function (stateIn) {
    stateIn.i += speedX[stateIn.to[0]];
    stateIn.j += speedY[stateIn.to[0]];
    return stateIn;
  });

  _.forEach(stateSpatial0, function (stateIn) {

    var transitionAmps = board[stateIn.i][stateIn.j].transitionSm();

    _.forEach(transitionAmps[stateIn.to], function (out) {

      keyOut = [stateIn.i, stateIn.j, out.to].join("_");
      diffRe = stateIn.re * out.re - stateIn.im * out.im;
      diffIm = stateIn.re * out.im + stateIn.im * out.re;

      if (out.to in stateSpatialDict) {
        stateSpatialDict[keyOut].re += diffRe;
        stateSpatialDict[keyOut].im += diffIm;

      } else {
        stateSpatialDict[keyOut] = {i:  stateIn.i,
                                    j:  stateIn.j,
                                    to: out.to,
                                    re: diffRe,
                                    im: diffIm};
      }

    });

  });

  this.stateSpatial = _.values(stateSpatialDict)
    .filter(function (state) { return Math.pow(state.re, 2) + Math.pow(state.im, 2) > 1e-5; });

  this.stateHistory.push(_.cloneDeep(this.stateSpatial));

}

Board.prototype.animationRun = function () {

  this.step = this.step || 0;

  if (this.step === 0) {
    VIZ_IS_ON = true;
  }

  d3.select("#photons").selectAll(".photon").remove();;

  var photons = d3.select("#photons").selectAll(".photon")
    .data(this.stateHistory[this.step]);

  photons.enter()
    .append("circle")
      .attr("class", "photon")
      .attr("r", 10)
      .attr("cx", function (d) { return i2x(d.i) + TILE_SIZE/2; })
      .attr("cy", function (d) { return j2y(d.j) + TILE_SIZE/2; })
      .style("opacity", function (d) { return Math.sqrt(d.re*d.re + d.im*d.im); });

  photons.transition()
    .ease([0,1])
    .duration(TIME_STEP)
      .attr("cx", function (d) { return i2x(d.i + speedX[d.to[0]]) + TILE_SIZE/2; })
      .attr("cy", function (d) { return j2y(d.j + speedY[d.to[0]]) + TILE_SIZE/2; });

  var thisFunction = this.animationRun.bind(this);
  this.step += 1;

  if ( this.step < this.stateHistory.length && VIZ_IS_ON) {
    setTimeout(thisFunction, TIME_STEP);
  } else {
    this.step = 0;
    VIZ_IS_ON = false;
  }

};

Board.prototype.exportJSON = function () {

  var elements = [];
  var i, j, el;

  for (i = 0; i < this.nX; i++) {
    for (j = 0; j < this.nY; j++) {

      el = this.board[i][j];

      if (el instanceof Elements.Vacuum) {
        continue;
      } else {
        elements.push({name:     el.name,
                       i:        i,
                       j:        j,
                       rotation: el.rotation});
      }
    }
  }

  return JSON.stringify({
    board: {
      width: this.nX,
      height: this.nY
    },
    elements: elements
  }, null, 2);

}
<commit_msg>interference bug fixed<commit_after>// require mechanics.js
// require elements.js

var TILE_SIZE = 80;
var TIME_STEP = 500;
var VIZ_IS_ON = false;

var i2x = function (i) { return TILE_SIZE * i; }
var j2y = function (j) { return TILE_SIZE * j; }

var x2i = function (x) { return Math.floor(x / TILE_SIZE); }
var y2j = function (y) { return Math.floor(y / TILE_SIZE); }

function Board (nX, nY) {

  this.nX = nX;
  this.nY = nY;

  var i, j;

  // or sparse representation
  this.board = [];

  for (i = 0; i < nX; i++) {
    this.board[i] = [];
    for (j = 0; j < nY; j++) {
      this.board[i][j] = new Elements.Vacuum();
    }
  }

  this.stateSpatial = [];

  for (i = 0; i < nX; i++) {
    this.stateSpatial[i] = [];
    for (j = 0; j < nY; j++) {
      this.stateSpatial[i][j] = {};
    }
  }

}

Board.prototype.drawBackground = function () {
  var boardFlat = [];
  var i, j;

  for (i = 0; i < this.nX; ++i) {
    for (j = 0; j < this.nY; ++j) {
      boardFlat.push({i: i, j: j});
    }
  }

  d3.select("svg").append("g")
    .attr("id", "background")
    .selectAll(".tile")
    .data(boardFlat)
    .enter()
      .append("rect")
      .attr({
        class: 'tile',
        x: function (d) { return i2x(d.i) },
        y: function (d) { return j2y(d.j) },
        width: TILE_SIZE,
        height: TILE_SIZE,
      });

  // just to have it at the right layer
  d3.select("svg").append("g")
    .attr("id", "photons");

}

Board.prototype.draw = function () {

  var i, j, v, s;
  var boardFlat = [];

  var thisBoard = this;

  for (i = 0; i < this.nX; i++) {
    for (j = 0; j < this.nY; j++) {
      v = this.board[i][j];
      v.i = i;
      v.j = j;
      if (v instanceof Elements.Vacuum) {
        continue;
      }
      boardFlat.push({i: i, j: j, val: v});
    }
  }

  var tiles = d3.select("svg").append("g")
    .attr("id", "board")
    .selectAll(".tile")
    .data(boardFlat)
    .enter()
      .append("g")
      .attr({
        class: 'tile',
        transform: function (d) {
          return 'translate(' + (i2x(d.i) + TILE_SIZE/2) + ',' + (j2y(d.j) + TILE_SIZE/2) + ')';
        },
      });

  // Keep tile node reference
  tiles.each(function (d) {
    d.val.node = this;
  });

  // Create element
  tiles
      .append("use")
      .attr({
        'xlink:href': function (d) { return "#" + d.val.name; },
        'class': 'element',
        transform: function (d) {
          return 'rotate(' + (d.val.angleOfRotation * d.val.rotation) + ',0,0)';
        },
      });
  // Create hitbox
  tiles
      .append("use")
      .attr({
        'xlink:href': '#hitbox',
        class: 'hitbox',
      })
      .on('click', function (d) {

        if (d3.event.defaultPrevented) return;

        var element = d3.select(d.val.node).select('.element');

        d.val.rotation = (d.val.rotation + 1) % d.val.maxRotation;

        // Assure that rotation animation is clockwise.
        element
          .attr('transform', 'rotate(' +  (d.val.angleOfRotation * (d.val.rotation - 1)) + ',0,0)');

        element.transition().duration(300)
          .attr('transform', 'rotate(' +  (d.val.angleOfRotation * d.val.rotation) + ',0,0)');
      });

  // Drag and drop

  var drag = d3.behavior.drag()
      .on('dragstart', function (d) {
        d3.event.sourceEvent.stopPropagation();
      })
      .on('drag', function (d) {
        d3.select(this).attr("transform", 'translate(' + d3.event.x + ',' + d3.event.y + ')');
        d.val.newI = x2i(d3.event.x);
        d.val.newJ = y2j(d3.event.y);
      })
      .on('dragend', function (d) {
        // No drag?
        if (d.val.newI == null || d.val.newJ == null) {
          return;
        }

        if ((d.val.newI < 0) || (d.val.newI >  thisBoard.nX - 1) || (d.val.newJ < 0) || (d.val.newJ >  thisBoard.nY - 1)) {

          d.val.newI = d.val.i;
          d.val.newI = d.val.j;

          d3.select(d.val.node).transition().duration(300).attr('transform',
              'translate(' + (i2x(d.val.i) + TILE_SIZE/2) +
              ',' + (j2y(d.val.j) + TILE_SIZE/2) + ')'
          );

          return;

        }

        // Intuitive naming
        var from = d.val;

        var to = thisBoard.board[from.newI][from.newJ];

        // Swap items if it's possible
        var canSwap = true; // TODO detect if "to" element is frozen. If not, let it go.
        if (canSwap) {
          // Swap items in matrix
          thisBoard.board[from.i][from.j] = to;
          thisBoard.board[from.newI][from.newJ] = from;
          // Swap items' positions
          to.i = from.i;
          to.j = from.j;
          from.i = from.newI;
          from.j = from.newJ;
        }
        delete from.newI;
        delete from.newJ;
        // Move element (if exists)
        if (to.node) {
          d3.select(to.node).transition().duration(300).attr('transform',
              'translate(' + (i2x(to.i) + TILE_SIZE/2) +
              ',' + (j2y(to.j) + TILE_SIZE/2) + ')'
          );
        }
        // "from" element is draggable, so it exists
        d3.select(from.node).transition().duration(300).attr('transform',
            'translate(' + (i2x(from.i) + TILE_SIZE/2) +
            ',' + (j2y(from.j) + TILE_SIZE/2) + ')'
        );
      });
  tiles
      .call(drag);

}

// only single photon sources
Board.prototype.stateInit = function () {

  var sources = 0;

  this.stateSpatial = [];

  var stateSpatial = this.stateSpatial;  // this issue

  _.forEach(this.board, function (col, i) {
    _.forEach(col, function (el, j) {
      if (el.name === 'source') {
        sources += 1;
        _.forEach(el.generateSv(), function (out) {
          stateSpatial.push({
            i:  i,
            j:  j,
            to: out.to,  // for more particles, more things will go it 'to'
            re: out.re,
            im: out.im
          })
        })
      }
    });
  });

  if (sources > 1) {
    console.log("As of now only one source, sorry.");
  }

  this.stateHistory = [_.cloneDeep(this.stateSpatial)];

};

// as of now - only single particle interactions
// as of now - very inefficient (I should query elements only once)
// as of now - without absorption
// some of it should go to mechanics.js BTW
Board.prototype.statePropagate = function () {

  var board = this.board;
  var stateSpatial0 = this.stateSpatial;
  var stateSpatialDict = {};

  var keyOut, diffRe, diffIm;

  stateSpatial0 = _.map(stateSpatial0, function (stateIn) {
    stateIn.i += speedX[stateIn.to[0]];
    stateIn.j += speedY[stateIn.to[0]];
    return stateIn;
  });

  _.forEach(stateSpatial0, function (stateIn) {

    var transitionAmps = board[stateIn.i][stateIn.j].transitionSm();

    _.forEach(transitionAmps[stateIn.to], function (out) {

      keyOut = [stateIn.i, stateIn.j, out.to].join("_");
      diffRe = stateIn.re * out.re - stateIn.im * out.im;
      diffIm = stateIn.re * out.im + stateIn.im * out.re;

      if (keyOut in stateSpatialDict) {
        stateSpatialDict[keyOut].re += diffRe;
        stateSpatialDict[keyOut].im += diffIm;

      } else {
        stateSpatialDict[keyOut] = {i:  stateIn.i,
                                    j:  stateIn.j,
                                    to: out.to,
                                    re: diffRe,
                                    im: diffIm};
      }

    });

  });

  this.stateSpatial = _.values(stateSpatialDict)
    .filter(function (state) { return Math.pow(state.re, 2) + Math.pow(state.im, 2) > 1e-5; });

  this.stateHistory.push(_.cloneDeep(this.stateSpatial));

}

Board.prototype.animationRun = function () {

  this.step = this.step || 0;

  if (this.step === 0) {
    VIZ_IS_ON = true;
  }

  d3.select("#photons").selectAll(".photon").remove();;

  var photons = d3.select("#photons").selectAll(".photon")
    .data(this.stateHistory[this.step]);

  photons.enter()
    .append("circle")
      .attr("class", "photon")
      .attr("r", 10)
      .attr("cx", function (d) { return i2x(d.i) + TILE_SIZE/2; })
      .attr("cy", function (d) { return j2y(d.j) + TILE_SIZE/2; })
      .style("opacity", function (d) { return Math.sqrt(d.re*d.re + d.im*d.im); });

  photons.transition()
    .ease([0,1])
    .duration(TIME_STEP)
      .attr("cx", function (d) { return i2x(d.i + speedX[d.to[0]]) + TILE_SIZE/2; })
      .attr("cy", function (d) { return j2y(d.j + speedY[d.to[0]]) + TILE_SIZE/2; });

  var thisFunction = this.animationRun.bind(this);
  this.step += 1;

  if ( this.step < this.stateHistory.length && VIZ_IS_ON) {
    setTimeout(thisFunction, TIME_STEP);
  } else {
    this.step = 0;
    VIZ_IS_ON = false;
  }

};

Board.prototype.exportJSON = function () {

  var elements = [];
  var i, j, el;

  for (i = 0; i < this.nX; i++) {
    for (j = 0; j < this.nY; j++) {

      el = this.board[i][j];

      if (el instanceof Elements.Vacuum) {
        continue;
      } else {
        elements.push({name:     el.name,
                       i:        i,
                       j:        j,
                       rotation: el.rotation});
      }
    }
  }

  return JSON.stringify({
    board: {
      width: this.nX,
      height: this.nY
    },
    elements: elements
  }, null, 2);

}
<|endoftext|>


<commit_before>var Board = (function() {
  var constructor = function(board_size) {
    this.board_size = board_size;

    // needs to be a var since `this` has a different context in #times
    var row = _(this.board_size).times(function() {
      return 0;
    });
    this.row = row;

    this.board = _(this.board_size).times(function() {
      return _.clone(row);
    });
  };

  constructor.prototype = {
    // returns the Board object
    get_board: function() {
      return this.board;
    },

    // asserts whether the board contains a given value
    // this is used mostly for testing
    contains: function(value) {
      return _.chain(this.board).flatten().contains(value).value();
    },

    // returns the 0-((board_size ^ 2) - 1) indexes of all empty nodes
    find_empty_nodes: function() {
      return _.flatten(this.board).reduce(function(memo, value, index) {
        if(value === 0) {
          memo.push(index);
        }

        return memo;
      }, []);
    },

    // returns the 0-((board_size ^ 2) - 1) index of a random empty tile
    select_random_empty_tile: function() {
      var possible_nodes = this.find_empty_nodes();
      var selected_node = Math.floor(Math.random() * possible_nodes.length);
      return possible_nodes[selected_node];
    },

    // converts a 0-((board_size ^ 2) - 1) index to xy coordinates
    get_tile_coords: function(index) {
      var x = index % this.board_size;
      var y = ((index - x) / this.board_size);
      return { x: x, y: y };
    },

    // predicate to determine if there are any empty tiles
    has_empty_tile: function() {
      return this.contains(0);
    },

    // sets a random empty file to 2 or 4 and returns the value
    set_random_empty_tile: function() {
      var numbers = [2, 4];
      var random_number = numbers[Math.floor(Math.random() * 2)];
      var coords = this.get_tile_coords(this.select_random_empty_tile());
      this.board[coords.y][coords.x] = random_number;

      return random_number;
    },

    // removes all left space between tiles
    collapse: function() {
      var zerofilled = this.row;
      var board_size = this.board_size;
      this.board = _.map(this.board, function(row) {
        var compacted_row = _.compact(row);
        var padding = zerofilled.slice(0, board_size - compacted_row.length);
        return compacted_row.concat(padding);
      });
    },

    // merges tiles into their immediate identical left neighbor
    fold: function() {
      this.board = _.map(this.board, function(row) {
        // iterates over each tile
        for(var x = 0; x < row.length; x++) {
          // compares against the tile immediately to the right
          if(row[x] === row[x + 1]) {
            row[x] *= 2;
            // unsets the next tile, so that when the
            // pointer advances, it won't compute again
            row[x + 1] = 0;
          }
        }

        return row;
      });
    },

    // rotate the board counterclockwise
    rotate_ccw: function() {
      this.board = _.map(this.board, function(row) {
        return row.reverse();
      });

      this.board = _.zip.apply(_, this.board);
    },

    // rotate the board clockwise
    rotate_cw: function() {
      this.board = _.zip.apply(_, this.board).map(function(row) {
        return row.reverse();
      });
    },

    // predicate to determine if another move is possible
    has_possible_move: function() {
      // always has a possible move if a tile is empty
      if(this.has_empty_tile()) return true;

      for(var y = 0; y < this.board_size; y++) {
        for(var x = 0; x < this.board_size; x++) {
          if(this.can_move_left(x, y) ||
             this.can_move_right(x, y) ||
             this.can_move_up(x, y) ||
             this.can_move_down(x, y)) {
            return true;
          }
        }
      }

      return false;
    },

    // predicate to determine if a cell can move left
    can_move_left: function(x, y) {
      if(x > 0 && this.board[y][x - 1] === 0) return true;
      return x > 0 && this.board[y][x - 1] === this.board[y][x];
    },

    // predicate to determine if a cell can move right
    can_move_right: function(x, y) {
      if(x < (this.board_size - 1) && this.board[y][x + 1] === 0) return true;
      return x < (this.board_size - 1) && this.board[y][x + 1] === this.board[y][x];
    },

    // predicate to determine if a cell can move up
    can_move_up: function(x, y) {
      if(y > 0 && this.board[y - 1][x] === 0) return true;
      return y > 0 && this.board[y - 1][x] === this.board[y][x];
    },

    // predicate to determine if a cell can move down
    can_move_down: function(x, y) {
      if(y < (this.board_size - 1) && this.board[y + 1][x] === 0) return true;
      return y < (this.board_size - 1) && this.board[y + 1][x] === this.board[y][x];
    }
  };

  return constructor;
})();
<commit_msg>Clean up Board#can_move_* methods.<commit_after>var Board = (function() {
  var constructor = function(board_size) {
    this.board_size = board_size;

    // needs to be a var since `this` has a different context in #times
    var row = _(this.board_size).times(function() {
      return 0;
    });
    this.row = row;

    this.board = _(this.board_size).times(function() {
      return _.clone(row);
    });
  };

  constructor.prototype = {
    // returns the Board object
    get_board: function() {
      return this.board;
    },

    // asserts whether the board contains a given value
    // this is used mostly for testing
    contains: function(value) {
      return _.chain(this.board).flatten().contains(value).value();
    },

    // returns the 0-((board_size ^ 2) - 1) indexes of all empty nodes
    find_empty_nodes: function() {
      return _.flatten(this.board).reduce(function(memo, value, index) {
        if(value === 0) {
          memo.push(index);
        }

        return memo;
      }, []);
    },

    // returns the 0-((board_size ^ 2) - 1) index of a random empty tile
    select_random_empty_tile: function() {
      var possible_nodes = this.find_empty_nodes();
      var selected_node = Math.floor(Math.random() * possible_nodes.length);
      return possible_nodes[selected_node];
    },

    // converts a 0-((board_size ^ 2) - 1) index to xy coordinates
    get_tile_coords: function(index) {
      var x = index % this.board_size;
      var y = ((index - x) / this.board_size);
      return { x: x, y: y };
    },

    // predicate to determine if there are any empty tiles
    has_empty_tile: function() {
      return this.contains(0);
    },

    // sets a random empty file to 2 or 4 and returns the value
    set_random_empty_tile: function() {
      var numbers = [2, 4];
      var random_number = numbers[Math.floor(Math.random() * 2)];
      var coords = this.get_tile_coords(this.select_random_empty_tile());
      this.board[coords.y][coords.x] = random_number;

      return random_number;
    },

    // removes all left space between tiles
    collapse: function() {
      var zerofilled = this.row;
      var board_size = this.board_size;
      this.board = _.map(this.board, function(row) {
        var compacted_row = _.compact(row);
        var padding = zerofilled.slice(0, board_size - compacted_row.length);
        return compacted_row.concat(padding);
      });
    },

    // merges tiles into their immediate identical left neighbor
    fold: function() {
      this.board = _.map(this.board, function(row) {
        // iterates over each tile
        for(var x = 0; x < row.length; x++) {
          // compares against the tile immediately to the right
          if(row[x] === row[x + 1]) {
            row[x] *= 2;
            // unsets the next tile, so that when the
            // pointer advances, it won't compute again
            row[x + 1] = 0;
          }
        }

        return row;
      });
    },

    // rotate the board counterclockwise
    rotate_ccw: function() {
      this.board = _.map(this.board, function(row) {
        return row.reverse();
      });

      this.board = _.zip.apply(_, this.board);
    },

    // rotate the board clockwise
    rotate_cw: function() {
      this.board = _.zip.apply(_, this.board).map(function(row) {
        return row.reverse();
      });
    },

    // predicate to determine if another move is possible
    has_possible_move: function() {
      // always has a possible move if a tile is empty
      if(this.has_empty_tile()) return true;

      // each row
      for(var y = 0; y < this.board_size; y++) {
        // each cell
        for(var x = 0; x < this.board_size; x++) {
          if(this.can_move_left(x, y) ||
             this.can_move_right(x, y) ||
             this.can_move_up(x, y) ||
             this.can_move_down(x, y)) {
            return true;
          }
        }
      }

      return false;
    },

    // predicate to determine if a cell can move left
    can_move_left: function(x, y) {
      if(!(x > 0)) return false;
      if(this.board[y][x - 1] === 0) return true;
      return this.board[y][x - 1] === this.board[y][x];
    },

    // predicate to determine if a cell can move right
    can_move_right: function(x, y) {
      if(!(x < (this.board_size - 1))) return false;
      if(this.board[y][x + 1] === 0) return true;
      return this.board[y][x + 1] === this.board[y][x];
    },

    // predicate to determine if a cell can move up
    can_move_up: function(x, y) {
      if(!(y > 0)) return false;
      if(this.board[y - 1][x] === 0) return true;
      return this.board[y - 1][x] === this.board[y][x];
    },

    // predicate to determine if a cell can move down
    can_move_down: function(x, y) {
      if(!(y < (this.board_size - 1))) return false;
      if(this.board[y + 1][x] === 0) return true;
      return this.board[y + 1][x] === this.board[y][x];
    }
  };

  return constructor;
})();
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2014 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License (MPL), version 2.0. If a copy of the MPL was not distributed
**  with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

describe("ComponentJS Application Structuring: Classes and Traits", function () {
    describe("clazz() & trait()", function () {
        it("should create reasonable classes", function () {
            var log = ""
            var sentinel = [ "42" ]
            var Trait = cs.trait({
                dynamics: {
                    _quux: "quux"
                },
                protos: {
                    quux: function () {
                        return this._quux
                    }
                }
            })
            var Parent1 = cs.clazz({
                protos: {
                    baz1: function (arg) {
                        return "<Parent1 arg=" + arg + "/>"
                    },
                    baz2: function (arg) {
                        return "<Parent1 arg=" + arg + "/>"
                    }
                }
            })
            var Parent2 = cs.clazz({
                extend: Parent1,
                mixin: [ Trait ],
                protos: {
                    baz1: function (arg) {
                        return "<Parent2 arg=" + arg + ">" + this.base(arg) + "</Parent2>"
                    }
                }
            })
            var Foo = cs.clazz({
                extend: Parent2,
                statics: {
                    BAR: "BAZ"
                },
                dynamics: {
                    _bar: "",
                    sentinel: sentinel
                },
                cons: function (bar) {
                    if (typeof bar !== "undefined")
                        this._bar = bar
                },
                protos: {
                    bar: function (value_new) {
                        var value_old = this._bar
                        if (typeof value_new !== "undefined")
                            this._bar = value_new
                        return value_old
                    },
                    baz1: function (arg) {
                        return "<Foo arg=" + arg + ">" + this.base(arg) + "</Foo>"
                    },
                    baz2: function (arg) {
                        return "<Foo arg=" + arg + ">" + this.base(arg) + "</Foo>"
                    }
                }
            })
            expect(Foo).to.be.a("function")
            expect(Foo.BAR).to.be.equal("BAZ")
            var foo = new Foo()
            expect(foo).to.be.a("object")
            expect(foo instanceof Foo).to.be.true
            expect(foo instanceof Parent2).to.be.true
            expect(foo instanceof Parent1).to.be.true
            expect(foo.bar()).to.be.equal("")
            expect(foo.bar("quux")).to.be.equal("")
            expect(foo.bar()).to.be.equal("quux")
            expect(foo.sentinel).to.be.like(sentinel)
            expect(foo.sentinel).to.be.not.equal(sentinel)
            expect(foo.quux()).to.be.equal("quux")
            expect(foo.baz1("baz")).to.be.equal("<Foo arg=baz><Parent2 arg=baz><Parent1 arg=baz/></Parent2></Foo>")
            expect(foo.baz2("baz")).to.be.equal("<Foo arg=baz><Parent1 arg=baz/></Foo>")
        })
    })
})
<commit_msg>ensure Classes do not extend from Traits and Classes do not mixin Classes<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2014 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License (MPL), version 2.0. If a copy of the MPL was not distributed
**  with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

describe("ComponentJS Application Structuring: Classes and Traits", function () {
    describe("clazz() & trait()", function () {
        it("should create reasonable classes", function () {
            var log = ""
            var sentinel = [ "42" ]
            var Trait = cs.trait({
                dynamics: {
                    _quux: "quux"
                },
                protos: {
                    quux: function () {
                        return this._quux
                    }
                }
            })
            var Parent1 = cs.clazz({
                protos: {
                    baz1: function (arg) {
                        return "<Parent1 arg=" + arg + "/>"
                    },
                    baz2: function (arg) {
                        return "<Parent1 arg=" + arg + "/>"
                    }
                }
            })
            var Parent2 = cs.clazz({
                extend: Parent1,
                mixin: [ Trait ],
                protos: {
                    baz1: function (arg) {
                        return "<Parent2 arg=" + arg + ">" + this.base(arg) + "</Parent2>"
                    }
                }
            })
            var Foo = cs.clazz({
                extend: Parent2,
                statics: {
                    BAR: "BAZ"
                },
                dynamics: {
                    _bar: "",
                    sentinel: sentinel
                },
                cons: function (bar) {
                    if (typeof bar !== "undefined")
                        this._bar = bar
                },
                protos: {
                    bar: function (value_new) {
                        var value_old = this._bar
                        if (typeof value_new !== "undefined")
                            this._bar = value_new
                        return value_old
                    },
                    baz1: function (arg) {
                        return "<Foo arg=" + arg + ">" + this.base(arg) + "</Foo>"
                    },
                    baz2: function (arg) {
                        return "<Foo arg=" + arg + ">" + this.base(arg) + "</Foo>"
                    }
                }
            })
            expect(function () { var Bad = cs.clazz({ extend: Trait }) }).to.throw(Error)
            expect(function () { var Bad = cs.clazz({ mixin: [ Foo ] }) }).to.throw(Error)
            expect(Foo).to.be.a("function")
            expect(Foo.BAR).to.be.equal("BAZ")
            var foo = new Foo()
            expect(foo).to.be.a("object")
            expect(foo instanceof Foo).to.be.true
            expect(foo instanceof Parent2).to.be.true
            expect(foo instanceof Parent1).to.be.true
            expect(foo.bar()).to.be.equal("")
            expect(foo.bar("quux")).to.be.equal("")
            expect(foo.bar()).to.be.equal("quux")
            expect(foo.sentinel).to.be.like(sentinel)
            expect(foo.sentinel).to.be.not.equal(sentinel)
            expect(foo.quux()).to.be.equal("quux")
            expect(foo.baz1("baz")).to.be.equal("<Foo arg=baz><Parent2 arg=baz><Parent1 arg=baz/></Parent2></Foo>")
            expect(foo.baz2("baz")).to.be.equal("<Foo arg=baz><Parent1 arg=baz/></Foo>")
        })
    })
})
<|endoftext|>


<commit_before>var PluginPage = require("./PluginPage");

var page = new PluginPage("Badge", "de.appplant.cordova.plugin.badge", function(parent) {

  cordova.plugins.notification.badge.promptForPermission();

  var input = tabris.create("TextInput", {
    text: "23",
    layoutData: {left: 10, top: 10, right: 10}
  }).appendTo(parent);

  tabris.create("Button", {
    layoutData: {left: 10, top: [input, 10], right: 10},
    text: "Set Badge"
  }).appendTo(parent).on("selection", function() {
    var badge = input.get("text");
    cordova.plugins.notification.badge.set(badge);
  });

});

module.exports = page;
<commit_msg>Fix cordova example error caused by badge plugin update<commit_after>var PluginPage = require("./PluginPage");

var page = new PluginPage("Badge", "de.appplant.cordova.plugin.badge", function(parent) {

  var input = tabris.create("TextInput", {
    text: "23",
    layoutData: {left: 10, top: 10, right: 10}
  }).appendTo(parent);

  tabris.create("Button", {
    layoutData: {left: 10, top: [input, 10], right: 10},
    text: "Set Badge"
  }).appendTo(parent).on("selection", function() {
    var badge = input.get("text");
    cordova.plugins.notification.badge.set(badge);
  });

});

module.exports = page;
<|endoftext|>


<commit_before>exports.XJSAttribute = function (node, print) {
  print(node.name);
  if (node.value) {
    this.push("=");
    print(node.value);
  }
};

exports.XJSIdentifier = function (node) {
  this.push(node.name);
};

exports.XJSNamespacedName = function (node, print) {
  print(node.namespace)
  this.push(":");
  print(node.name);
};

exports.XJSMemberExpression = function (node, print) {
  print(node.object);
  this.push(".");
  print(node.property);
};

exports.XJSSpreadAttribute = function (node, print) {
  this.push("{...");
  print(node.argument);
  this.push("}");
};

exports.XJSExpressionContainer = function (node, print) {
  this.push("{");
  print(node.expression);
  this.push("}");
};

exports.XJSElement = function () {
  throw new Error("XJSElement");
};

exports.XJSOpeningElement = function (node, print) {
  this.push("<");
  print(node.name);
  if (node.attributes.length < 0) {
    this.push(" ");
    this.printJoin(print, node.attributes, " ");
  }
  this.push(node.selfClosing ? " />" : ">");;
};

exports.XJSClosingElement = function (node) {
  this.push("</" + node.name + ">");
};

exports.XJSEmptyExpression = function () {

};
<commit_msg>finish jsx generator<commit_after>var _ = require("lodash");

exports.XJSAttribute = function (node, print) {
  print(node.name);
  if (node.value) {
    this.push("=");
    print(node.value);
  }
};

exports.XJSIdentifier = function (node) {
  this.push(node.name);
};

exports.XJSNamespacedName = function (node, print) {
  print(node.namespace)
  this.push(":");
  print(node.name);
};

exports.XJSMemberExpression = function (node, print) {
  print(node.object);
  this.push(".");
  print(node.property);
};

exports.XJSSpreadAttribute = function (node, print) {
  this.push("{...");
  print(node.argument);
  this.push("}");
};

exports.XJSExpressionContainer = function (node, print) {
  this.push("{");
  print(node.expression);
  this.push("}");
};

exports.XJSElement = function (node, print) {
  var self = this;

  var open = node.openingElement;
  print(open);
  if (open.selfClosing) return;

  this.indent();
  _.each(node.children, function (child) {
    if (child.type === "Literal" && typeof child.value === "string") {
      if (/\S/.test(child.value)) {
        return self.push(child.value.replace(/^\s+|\s+$/g, ""));
      } else if (/\n/.test(child.value)) {
        return self.newline();
      }
    }

    print(child);
  });
  this.dedent();

  print(node.closingElement);
};

exports.XJSOpeningElement = function (node, print) {
  this.push("<");
  print(node.name);
  if (node.attributes.length > 0) {
    this.push(" ");
    this.printJoin(print, node.attributes, " ");
  }
  this.push(node.selfClosing ? " />" : ">");;
};

exports.XJSClosingElement = function (node, print) {
  this.push("</");
  print(node.name);
  this.push(">");
};

exports.XJSEmptyExpression = function () {

};
<|endoftext|>


<commit_before>"use strict";

module.exports = Scope;

var traverse = require("./index");
var object   = require("../helpers/object");
var t        = require("../types");
var _        = require("lodash");

var FOR_KEYS = ["left", "init"];

/**
 * This searches the current "scope" and collects all references/declarations
 * within.
 *
 * @param {Node} block
 * @param {Scope} [parent]
 * @param {File} [file]
 */

function Scope(block, parent, file) {
  this.parent = parent;
  this.block  = block;
  this.file   = parent ? parent.file : file;

  var info = this.getInfo();
  this.references = info.references;
  this.declarations = info.declarations;
  this.declarationKinds = info.declarationKinds;
}

Scope.defaultDeclarations = require("./global-keys");

Scope.prototype._add = function (node, references, throwOnDuplicate) {
  if (!node) return;

  var ids = t.getIds(node, true);

  for (var key in ids) {
    var id = ids[key];

    if (throwOnDuplicate && references[key]) {
      throw this.file.errorWithNode(id, "Duplicate declaration", TypeError);
    }

    references[key] = id;
  }
};

/**
 * Description
 *
 * @param {File} file
 * @param {String} [name="temp"]
 */

Scope.prototype.generateTemp = function (file, name) {
  var id = file.generateUidIdentifier(name || "temp", this);
  this.push({
    key: id.name,
    id: id
  });
  return id;
};

/**
 * Description
 *
 * @param {String} name
 */

Scope.prototype.generateUidIdentifier = function (name) {
  return this.file.generateUidIdentifier(name, this);
};

/*
 * Description
 *
 * @param {Object} parent
 * @returns {Object}
 */

Scope.prototype.generateUidBasedOnNode = function (parent) {
  var node = parent;

  if (t.isAssignmentExpression(parent)) {
    node = parent.left;
  } else if (t.isVariableDeclarator(parent)) {
    node = parent.id;
  } else if (t.isProperty(node)) {
    node = node.key;
  }

  var parts = [];

  var add = function (node) {
    if (t.isMemberExpression(node)) {
      add(node.object);
      add(node.property);
    } else if (t.isIdentifier(node)) {
      parts.push(node.name);
    } else if (t.isLiteral(node)) {
      parts.push(node.value);
    } else if (t.isCallExpression(node)) {
      add(node.callee);
    }
  };

  add(node);

  var id = parts.join("$");
  id = id.replace(/^_/, "") || "ref";

  return this.file.generateUidIdentifier(id, this);
};

/**
 * Description
 *
 * @param {Object} node
 * @returns {Object}
 */

Scope.prototype.generateTempBasedOnNode = function (node) {
  if (t.isIdentifier(node) && this.has(node.name, true)) {
    return null;
  }

  var id = this.generateUidBasedOnNode(node);
  this.push({
    key: id.name,
    id: id
  });
  return id;
};

var functionVariableVisitor = {
  enter: function (node, parent, scope, context, state) {
    if (t.isFor(node)) {
      _.each(FOR_KEYS, function (key) {
        var declar = node[key];
        if (t.isVar(declar)) state.add(declar);
      });
    }

    // this block is a function so we'll stop since none of the variables
    // declared within are accessible
    if (t.isFunction(node)) return context.skip();

    // function identifier doesn't belong to this scope
    if (state.blockId && node === state.blockId) return;

    // we've ran into a declaration!
    // we'll let the BlockStatement scope deal with `let` declarations unless
    if (t.isDeclaration(node) && !t.isBlockScoped(node)) {
      state.add(node);
    }
  }
};

var programReferenceVisitor = {
  enter: function (node, parent, scope, context, add) {
    if (t.isReferencedIdentifier(node, parent) && !scope.has(node.name)) {
      add(node, true);
    }
  }
};

var blockVariableVisitor = {
  enter: function (node, parent, scope, context, add) {
    if (t.isBlockScoped(node)) {
      add(node, false, true);
    } else if (t.isScope(node)) {
      context.stop();
    }
  }
};

Scope.prototype.getInfo = function () {
  var parent = this.parent;
  var block  = this.block;
  var self   = this;
  if (block._scopeInfo) return block._scopeInfo;

  var info = block._scopeInfo = {};
  var references = info.references = object();
  var declarations = info.declarations = object();
  var declarationKinds = info.declarationKinds = {};

  var add = function (node, reference, throwOnDuplicate) {
    self._add(node, references);

    if (!reference) {
      self._add(node, declarations, throwOnDuplicate);
      self._add(node, declarationKinds[node.kind] = declarationKinds[node.kind] || object());
    }
  };

  if (parent && t.isBlockStatement(block) && t.isFor(parent.block)) {
    return info;
  }

  // ForStatement - left, init

  if (t.isFor(block)) {
    _.each(FOR_KEYS, function (key) {
      var node = block[key];
      if (t.isBlockScoped(node)) add(node, false, true);
    });

    if (t.isBlockStatement(block.body)) {
      block = block.body;
    }
  }

  // Program, BlockStatement - let variables

  if (t.isBlockStatement(block) || t.isProgram(block)) {
    traverse(block, blockVariableVisitor, this, add);
  }

  // CatchClause - param

  if (t.isCatchClause(block)) {
    add(block.param);
  }

  // ComprehensionExpression - blocks

  if (t.isComprehensionExpression(block)) {
    add(block);
  }

  // Program, Function - var variables

  if (t.isProgram(block) || t.isFunction(block)) {
    traverse(block, functionVariableVisitor, this, {
      blockId: block.id,
      add:     add
    });
  }

  // Program

  if (t.isProgram(block)) {
    traverse(block, programReferenceVisitor, this, add);
  }

  // Function - params, rest

  if (t.isFunction(block)) {
    _.each(block.params, function (param) {
      add(param);
    });
  }

  return info;
};

/**
 * Description
 *
 * @param {Object} opts
 */

Scope.prototype.push = function (opts) {
  var block = this.block;

  if (t.isFor(block) || t.isCatchClause(block) || t.isFunction(block)) {
    t.ensureBlock(block);
    block = block.body;
  }

  if (t.isBlockStatement(block) || t.isProgram(block)) {
    block._declarations = block._declarations || {};
    block._declarations[opts.key] = {
      kind: opts.kind,
      id: opts.id,
      init: opts.init
    };
  } else {
    throw new TypeError("cannot add a declaration here in node type " + block.type);
  }
};

/**
 * Walk up the scope tree until we hit a `Function` and then
 * push our `node` to it's references.
 *
 * @param {Object} node
 */

Scope.prototype.add = function (node) {
  var scope = this.getFunctionParent();
  scope._add(node, scope.references);
};

/**
 * Walk up the scope tree until we hit either a Function or reach the
 * very top at hit Program.
 */

Scope.prototype.getFunctionParent = function () {
  var scope = this;
  while (scope.parent && !t.isFunction(scope.block)) {
    scope = scope.parent;
  }
  return scope;
};

/**
 * Walks the scope tree and gathers all declarations of `kind`.
 *
 * @returns {Object}
 */

Scope.prototype.getAllOfKind = function (kind) {
  var ids = object();

  var scope = this;
  do {
    _.defaults(ids, scope.declarationKinds[kind]);
    scope = scope.parent;
  } while (scope);

  return ids;
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 */

Scope.prototype.get = function (id, decl) {
  return id && (this.getOwn(id, decl) || this.parentGet(id, decl));
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 */

Scope.prototype.getOwn = function (id, decl) {
  var refs = this.references;
  if (decl) refs = this.declarations;
  return _.has(refs, id) && refs[id];
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 */

Scope.prototype.parentGet = function (id, decl) {
  return this.parent && this.parent.get(id, decl);
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 * @returns {Boolean}
 */

Scope.prototype.has = function (id, decl) {
  return (id && (this.hasOwn(id, decl) || this.parentHas(id, decl))) ||
         _.contains(Scope.defaultDeclarations, id);
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 * @returns {Boolean}
 */

Scope.prototype.hasOwn = function (id, decl) {
  return !!this.getOwn(id, decl);
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 * @returns {Boolean}
 */

Scope.prototype.parentHas = function (id, decl) {
  return this.parent && this.parent.has(id, decl);
};
<commit_msg>only check for duplicates for let variables<commit_after>"use strict";

module.exports = Scope;

var traverse = require("./index");
var object   = require("../helpers/object");
var t        = require("../types");
var _        = require("lodash");

var FOR_KEYS = ["left", "init"];

/**
 * This searches the current "scope" and collects all references/declarations
 * within.
 *
 * @param {Node} block
 * @param {Scope} [parent]
 * @param {File} [file]
 */

function Scope(block, parent, file) {
  this.parent = parent;
  this.block  = block;
  this.file   = parent ? parent.file : file;

  var info = this.getInfo();
  this.references = info.references;
  this.declarations = info.declarations;
  this.declarationKinds = info.declarationKinds;
}

Scope.defaultDeclarations = require("./global-keys");

Scope.prototype._add = function (node, references, throwOnDuplicate) {
  if (!node) return;

  var ids = t.getIds(node, true);

  for (var key in ids) {
    var id = ids[key];

    if (throwOnDuplicate && references[key]) {
      throw this.file.errorWithNode(id, "Duplicate declaration", TypeError);
    }

    references[key] = id;
  }
};

/**
 * Description
 *
 * @param {File} file
 * @param {String} [name="temp"]
 */

Scope.prototype.generateTemp = function (file, name) {
  var id = file.generateUidIdentifier(name || "temp", this);
  this.push({
    key: id.name,
    id: id
  });
  return id;
};

/**
 * Description
 *
 * @param {String} name
 */

Scope.prototype.generateUidIdentifier = function (name) {
  return this.file.generateUidIdentifier(name, this);
};

/*
 * Description
 *
 * @param {Object} parent
 * @returns {Object}
 */

Scope.prototype.generateUidBasedOnNode = function (parent) {
  var node = parent;

  if (t.isAssignmentExpression(parent)) {
    node = parent.left;
  } else if (t.isVariableDeclarator(parent)) {
    node = parent.id;
  } else if (t.isProperty(node)) {
    node = node.key;
  }

  var parts = [];

  var add = function (node) {
    if (t.isMemberExpression(node)) {
      add(node.object);
      add(node.property);
    } else if (t.isIdentifier(node)) {
      parts.push(node.name);
    } else if (t.isLiteral(node)) {
      parts.push(node.value);
    } else if (t.isCallExpression(node)) {
      add(node.callee);
    }
  };

  add(node);

  var id = parts.join("$");
  id = id.replace(/^_/, "") || "ref";

  return this.file.generateUidIdentifier(id, this);
};

/**
 * Description
 *
 * @param {Object} node
 * @returns {Object}
 */

Scope.prototype.generateTempBasedOnNode = function (node) {
  if (t.isIdentifier(node) && this.has(node.name, true)) {
    return null;
  }

  var id = this.generateUidBasedOnNode(node);
  this.push({
    key: id.name,
    id: id
  });
  return id;
};

var functionVariableVisitor = {
  enter: function (node, parent, scope, context, state) {
    if (t.isFor(node)) {
      _.each(FOR_KEYS, function (key) {
        var declar = node[key];
        if (t.isVar(declar)) state.add(declar);
      });
    }

    // this block is a function so we'll stop since none of the variables
    // declared within are accessible
    if (t.isFunction(node)) return context.skip();

    // function identifier doesn't belong to this scope
    if (state.blockId && node === state.blockId) return;

    // we've ran into a declaration!
    // we'll let the BlockStatement scope deal with `let` declarations unless
    if (t.isDeclaration(node) && !t.isBlockScoped(node)) {
      state.add(node);
    }
  }
};

var programReferenceVisitor = {
  enter: function (node, parent, scope, context, add) {
    if (t.isReferencedIdentifier(node, parent) && !scope.has(node.name)) {
      add(node, true);
    }
  }
};

var blockVariableVisitor = {
  enter: function (node, parent, scope, context, add) {
    if (t.isBlockScoped(node)) {
      add(node, false, t.isLet(node));
    } else if (t.isScope(node)) {
      context.stop();
    }
  }
};

Scope.prototype.getInfo = function () {
  var parent = this.parent;
  var block  = this.block;
  var self   = this;
  if (block._scopeInfo) return block._scopeInfo;

  var info = block._scopeInfo = {};
  var references = info.references = object();
  var declarations = info.declarations = object();
  var declarationKinds = info.declarationKinds = {};

  var add = function (node, reference, throwOnDuplicate) {
    self._add(node, references);

    if (!reference) {
      self._add(node, declarations, throwOnDuplicate);
      self._add(node, declarationKinds[node.kind] = declarationKinds[node.kind] || object());
    }
  };

  if (parent && t.isBlockStatement(block) && t.isFor(parent.block)) {
    return info;
  }

  // ForStatement - left, init

  if (t.isFor(block)) {
    _.each(FOR_KEYS, function (key) {
      var node = block[key];
      if (t.isBlockScoped(node)) add(node, false, true);
    });

    if (t.isBlockStatement(block.body)) {
      block = block.body;
    }
  }

  // Program, BlockStatement - let variables

  if (t.isBlockStatement(block) || t.isProgram(block)) {
    traverse(block, blockVariableVisitor, this, add);
  }

  // CatchClause - param

  if (t.isCatchClause(block)) {
    add(block.param);
  }

  // ComprehensionExpression - blocks

  if (t.isComprehensionExpression(block)) {
    add(block);
  }

  // Program, Function - var variables

  if (t.isProgram(block) || t.isFunction(block)) {
    traverse(block, functionVariableVisitor, this, {
      blockId: block.id,
      add:     add
    });
  }

  // Program

  if (t.isProgram(block)) {
    traverse(block, programReferenceVisitor, this, add);
  }

  // Function - params, rest

  if (t.isFunction(block)) {
    _.each(block.params, function (param) {
      add(param);
    });
  }

  return info;
};

/**
 * Description
 *
 * @param {Object} opts
 */

Scope.prototype.push = function (opts) {
  var block = this.block;

  if (t.isFor(block) || t.isCatchClause(block) || t.isFunction(block)) {
    t.ensureBlock(block);
    block = block.body;
  }

  if (t.isBlockStatement(block) || t.isProgram(block)) {
    block._declarations = block._declarations || {};
    block._declarations[opts.key] = {
      kind: opts.kind,
      id: opts.id,
      init: opts.init
    };
  } else {
    throw new TypeError("cannot add a declaration here in node type " + block.type);
  }
};

/**
 * Walk up the scope tree until we hit a `Function` and then
 * push our `node` to it's references.
 *
 * @param {Object} node
 */

Scope.prototype.add = function (node) {
  var scope = this.getFunctionParent();
  scope._add(node, scope.references);
};

/**
 * Walk up the scope tree until we hit either a Function or reach the
 * very top at hit Program.
 */

Scope.prototype.getFunctionParent = function () {
  var scope = this;
  while (scope.parent && !t.isFunction(scope.block)) {
    scope = scope.parent;
  }
  return scope;
};

/**
 * Walks the scope tree and gathers all declarations of `kind`.
 *
 * @returns {Object}
 */

Scope.prototype.getAllOfKind = function (kind) {
  var ids = object();

  var scope = this;
  do {
    _.defaults(ids, scope.declarationKinds[kind]);
    scope = scope.parent;
  } while (scope);

  return ids;
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 */

Scope.prototype.get = function (id, decl) {
  return id && (this.getOwn(id, decl) || this.parentGet(id, decl));
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 */

Scope.prototype.getOwn = function (id, decl) {
  var refs = this.references;
  if (decl) refs = this.declarations;
  return _.has(refs, id) && refs[id];
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 */

Scope.prototype.parentGet = function (id, decl) {
  return this.parent && this.parent.get(id, decl);
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 * @returns {Boolean}
 */

Scope.prototype.has = function (id, decl) {
  return (id && (this.hasOwn(id, decl) || this.parentHas(id, decl))) ||
         _.contains(Scope.defaultDeclarations, id);
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 * @returns {Boolean}
 */

Scope.prototype.hasOwn = function (id, decl) {
  return !!this.getOwn(id, decl);
};

/**
 * Description
 *
 * @param {String} [id]
 * @param {Boolean} [decl]
 * @returns {Boolean}
 */

Scope.prototype.parentHas = function (id, decl) {
  return this.parent && this.parent.has(id, decl);
};
<|endoftext|>


<commit_before>import pkg from './package'

const { CI_PAGES_URL } = process.env
const base = CI_PAGES_URL && new URL(CI_PAGES_URL).pathname

export default {
  // Disable server-side rendering (https://go.nuxtjs.dev/ssr-mode)
  ssr: false,

  // Target (https://go.nuxtjs.dev/config-target)
  target: 'static',

  // Global page headers (https://go.nuxtjs.dev/config-head)
  head: {
    title: 'dereknutile.github.io',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.png' }
    ]
  },

  /*
  ** Customize the generated output folder
  */
  generate: {
    dir: 'public'
  },

  /*
  ** Customize the base url
  */
  router: {
  base: ''
  },

  // Global CSS (https://go.nuxtjs.dev/config-css)
  css: [
    'vue-slick-carousel/dist/vue-slick-carousel.css',
  ],

  plugins: [
    { src: './plugins/vue-slick-carousel.js' },
  ],

  // Auto import components (https://go.nuxtjs.dev/config-components)
  components: true,

  // Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
  buildModules: [
    // https://go.nuxtjs.dev/tailwindcss
    '@nuxtjs/tailwindcss',
  ],

  // Modules (https://go.nuxtjs.dev/config-modules)
  modules: [
    // Simple usage
    '@nuxtjs/component-cache',
  ],

  // Build Configuration (https://go.nuxtjs.dev/config-build)
  build: {
  }
}
<commit_msg>Change generate path to dist<commit_after>import pkg from './package'

const { CI_PAGES_URL } = process.env
const base = CI_PAGES_URL && new URL(CI_PAGES_URL).pathname

export default {
  // Disable server-side rendering (https://go.nuxtjs.dev/ssr-mode)
  ssr: false,

  // Target (https://go.nuxtjs.dev/config-target)
  target: 'static',

  // Global page headers (https://go.nuxtjs.dev/config-head)
  head: {
    title: 'dereknutile.github.io',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.png' }
    ]
  },

  /*
  ** Customize the generated output folder
  */
  generate: {
    dir: 'dist'
  },

  /*
  ** Customize the base url
  */
  router: {
  base: ''
  },

  // Global CSS (https://go.nuxtjs.dev/config-css)
  css: [
    'vue-slick-carousel/dist/vue-slick-carousel.css',
  ],

  plugins: [
    { src: './plugins/vue-slick-carousel.js' },
  ],

  // Auto import components (https://go.nuxtjs.dev/config-components)
  components: true,

  // Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
  buildModules: [
    // https://go.nuxtjs.dev/tailwindcss
    '@nuxtjs/tailwindcss',
  ],

  // Modules (https://go.nuxtjs.dev/config-modules)
  modules: [
    // Simple usage
    '@nuxtjs/component-cache',
  ],

  // Build Configuration (https://go.nuxtjs.dev/config-build)
  build: {
  }
}
<|endoftext|>


<commit_before>// Info about configuration https://nuxtjs.org/guide/configuration/
var StyleLintPlugin = require('stylelint-webpack-plugin');
var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

console.log(`Environment: ${process.env.NODE_ENV}`);

module.exports = {
    env: require(`./environments/${process.env.NODE_ENV}`),
    head: {
        title: 'PWABuilder',
        meta: [
            { charset: 'utf-8' },
            { name: 'viewport', content: 'width=device-width, initial-scale=1' },
            { hid: 'description', name: 'description', content: 'All the tools you need to build and deploy your Progressive Web Apps.' }
        ],
        link: [
            { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
            { rel: 'manifest', href: '/manifest.json' }
        ]
    },
    loading: { color: '#1FC2C8' },
    css: ['tachyons/css/tachyons.min.css', 'prismjs/themes/prism-okaidia.css', '~/assets/scss/app.scss'],
    build: {
        extractCSS: true,
        vendor: ['babel-polyfill', 'gsap', 'vuex-class', 'nuxt-class-component', 'vue-i18n', 'prismjs'],
        plugins: [
            new StyleLintPlugin({
                files: ['**/*.scss', '**/*.vue'],
                failOnError: false,
                syntax: 'scss'
            }),
            // new ForkTsCheckerWebpackPlugin({
            //   tslint: true,
            //   vue: true
            // })
        ]
    },
    router: {
        middleware: 'i18n'
    },
    plugins: ['~/plugins/i18n.js'],
    modules: [
        '~/modules/typescript',
        '@nuxtjs/axios',
        '@nuxtjs/font-awesome'
    ]
}
<commit_msg>Add relevant pwa info<commit_after>// Info about configuration https://nuxtjs.org/guide/configuration/
var StyleLintPlugin = require('stylelint-webpack-plugin');
var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

console.log(`Environment: ${process.env.NODE_ENV}`);

module.exports = {
    env: require(`./environments/${process.env.NODE_ENV}`),
    head: {
        title: 'PWABuilder',
        meta: [
            { charset: 'utf-8' },
            { name: 'viewport', content: 'width=device-width, initial-scale=1' },
            { hid: 'description', name: 'description', content: 'All the tools you need to build and deploy your Progressive Web Apps.' },
            { name: 'msapplication-TileImage', content: '/Images/assets/icons/ms-icon-144x144-487a503e5cb29bbe0df7296db4093b7e.png' },
            { name: 'msapplication-TileColor', content: '#1FC2C8' }
        ],
        link: [
            { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
            { rel: 'manifest', href: '/manifest.json' },
            { rel: 'apple-touch-icon', href: '/Images/assets/icons/apple-icon-06144a2a7b5101d447ecb4832502e73e.png' },
            { rel: 'apple-touch-icon', sizes: '57x57', href: '/Images/assets/icons/apple-icon-57x57-b82ef058b133f3197df61c326fa7cd6d.png' },
            { rel: 'apple-touch-icon', sizes: '72x72', href: '/Images/assets/icons/apple-icon-72x72-66bbf8447788cee426eebcddfa8eede8.png' },
            { rel: 'apple-touch-icon', sizes: '76x76', href: '/Images/assets/icons/apple-icon-76x76-8e88034967133f6a0454fe32e2070ffd.png' },
            { rel: 'apple-touch-icon', sizes: '114x114', href: '/Images/assets/icons/apple-icon-114x114-a2731f540851db0ed9fb4a7c74e2c6ce.png' },
            { rel: 'apple-touch-icon', sizes: '120x120', href: '/Images/assets/icons/apple-icon-120x120-06144a2a7b5101d447ecb4832502e73e.png' },
            { rel: 'apple-touch-icon', sizes: '144x144', href: '/Images/assets/icons/apple-icon-144x144-487a503e5cb29bbe0df7296db4093b7e.png' },
            { rel: 'apple-touch-icon', sizes: '152x152', href: '/Images/assets/icons/apple-icon-152x152-b600c0b40a21bbb9f8c1d18acde168e9.png' },
            { rel: 'apple-touch-icon', sizes: '180x180', href: '/Images/assets/icons/apple-icon-180x180-f0f5be1ded11c7ec66b00dd23c277a5d.png' },
        ]
    },
    loading: { color: '#1FC2C8' },
    css: ['tachyons/css/tachyons.min.css', 'prismjs/themes/prism-okaidia.css', '~/assets/scss/app.scss'],
    build: {
        extractCSS: true,
        vendor: ['babel-polyfill', 'gsap', 'vuex-class', 'nuxt-class-component', 'vue-i18n', 'prismjs'],
        plugins: [
            new StyleLintPlugin({
                files: ['**/*.scss', '**/*.vue'],
                failOnError: false,
                syntax: 'scss'
            }),
            // new ForkTsCheckerWebpackPlugin({
            //   tslint: true,
            //   vue: true
            // })
        ]
    },
    router: {
        middleware: 'i18n'
    },
    plugins: ['~/plugins/i18n.js'],
    modules: [
        '~/modules/typescript',
        '@nuxtjs/axios',
        '@nuxtjs/font-awesome'
    ]
}
<|endoftext|>


<commit_before>var camelcase = require('camelcase-css')

function atRule (node) {
  if (typeof node.nodes === 'undefined') {
    return true
  } else {
    return process(node)
  }
}

function process (node) {
  var name
  var result = { }
  node.each(function (child) {
    var rules = {}
    node.each(function (rule) {
      if (rule.type !== 'rule') {

      } else if (rules[rule.selector]) {
        if (rules[rule.selector].append) {
          rules[rule.selector].append(rule.nodes)
          rule.remove()
        }
      } else {
        rules[rule.selector] = rule
      }
    })

    if (child.type === 'atrule') {
      name = '@' + child.name
      if (child.params) name += ' ' + child.params
      if (typeof result[name] === 'undefined') {
        result[name] = atRule(child)
      } else if (Array.isArray(result[name])) {
        result[name].push(atRule(child))
      } else {
        result[name] = [result[name], atRule(child)]
      }
    } else if (child.type === 'rule') {
      result[child.selector] = process(child)
    } else if (child.type === 'decl') {
      name = camelcase(child.prop)
      child.value = child.important ? child.value + ' !important' : child.value
      if (typeof result[name] === 'undefined') {
        result[name] = child.value
      } else if (Array.isArray(result[name])) {
        result[name].push(child.value)
      } else {
        result[name] = [result[name], child.value]
      }
    }
  })
  return result
}

module.exports = process
<commit_msg>Clean up code<commit_after>var camelcase = require('camelcase-css')

function atRule (node) {
  if (typeof node.nodes === 'undefined') {
    return true
  } else {
    return process(node)
  }
}

function process (node) {
  var name
  var result = { }

  var rules = {}
  node.each(function (rule) {
    if (rule.type === 'rule') {
      if (rules[rule.selector]) {
        if (rules[rule.selector].append) {
          rules[rule.selector].append(rule.nodes)
          rule.remove()
        }
      } else {
        rules[rule.selector] = rule
      }
    }
  })

  node.each(function (child) {
    if (child.type === 'atrule') {
      name = '@' + child.name
      if (child.params) name += ' ' + child.params
      if (typeof result[name] === 'undefined') {
        result[name] = atRule(child)
      } else if (Array.isArray(result[name])) {
        result[name].push(atRule(child))
      } else {
        result[name] = [result[name], atRule(child)]
      }
    } else if (child.type === 'rule') {
      result[child.selector] = process(child)
    } else if (child.type === 'decl') {
      name = camelcase(child.prop)
      child.value = child.important ? child.value + ' !important' : child.value
      if (typeof result[name] === 'undefined') {
        result[name] = child.value
      } else if (Array.isArray(result[name])) {
        result[name].push(child.value)
      } else {
        result[name] = [result[name], child.value]
      }
    }
  })
  return result
}

module.exports = process
<|endoftext|>