<commit_before>/*eslint-env node*/
// FUSION SEED APP GULPFILE
// -------------------------------------
// This file processes all of the assets in the "client" folder, combines them with the Foundation for Apps assets, and outputs the finished files in the "build" folder as a finished app.

// 1. LIBRARIES
// - - - - - - - - - - - - - - -
//

/*
 * gulpfile.js
 * ===========
 * Rather than manage one giant configuration file responsible
 * for creating multiple tasks, each task has been broken out into
 * its own file in the 'gulp' folder. Any files in that directory get
 *  automatically required below.
 *
 * To add a new task, simply add a new task file in that directory.
 */

var gulp       = require('gulp');
var argv       = require('yargs').argv;
var requireDir = require('require-dir');

// 2. FILE PATHS
// - - - - - - - - - - - - - - -
// Specify paths & globbing patterns for tasks.
global.paths = {
  assets: [
    './client/**/*.*',
    '!./client/templates/**/*.*',
    '!./client/assets/{scss,js,components}/**/*.*'
  ],
  // Sass will check these folders for files when you use @import.
  sass: [
    'client/assets/scss',
    'bower_components/foundation-apps/scss',
    'bower_components/angucomplete-alt/angucomplete-alt.css',
    'client/assets/components/**/*.scss'
  ],
  // These files include Foundation for Apps and its dependencies
  foundationJS: [
    'bower_components/lodash/lodash.js',
    'bower_components/fastclick/lib/fastclick.js',
    'bower_components/viewport-units-buggyfill/viewport-units-buggyfill.js',
    'bower_components/tether/tether.js',
    'bower_components/hammerjs/hammer.js',
    'bower_components/angular/angular.js',
    'bower_components/angular-animate/angular-animate.js',
    'bower_components/angular-sanitize/angular-sanitize.js',
    'bower_components/angular-ui-router/release/angular-ui-router.js',
    'bower_components/angucomplete-alt/angucomplete-alt.js',
    'bower_components/angular-rison/dist/angular-rison.js',
    'bower_components/foundation-apps/js/vendor/**/*.js',
    'bower_components/foundation-apps/js/angular/**/*.js',
    '!bower_components/foundation-apps/js/angular/app.js',
    'bower_components/ng-orwell/Orwell.js'
  ],
  // These files are for your app's JavaScript
  appJS: [
    'client/assets/js/app.js',
    'client/assets/js/services/*.js',
    'client/assets/js/controllers/*.js',
    'client/assets/js/utils/**/*.js',
    'client/assets/components/**/*.js'
  ],
  components: [
    'client/assets/components/**/*.html',
    'bower_components/foundation-apps/js/angular/components/**/*.html'
  ],
  configJS: [
    './FUSION_CONFIG.js'
  ],
  configJSSample: [
    './FUSION_CONFIG.sample.js'
  ]
};

// Check for --production flag
global.isProduction = !!(argv.production);

// 3. TASKS
// - - - - - - - - - - - - - - -

// Require all tasks in the 'gulp' folder.
requireDir('./gulp', { recurse: false });

// Default task
//
// builds your app, starts a server, and recompiles assets when they change.

gulp.task('default', ['serve']);
<commit_msg>fix humaize bugs<commit_after>/*eslint-env node*/
// FUSION SEED APP GULPFILE
// -------------------------------------
// This file processes all of the assets in the "client" folder, combines them with the Foundation for Apps assets, and outputs the finished files in the "build" folder as a finished app.

// 1. LIBRARIES
// - - - - - - - - - - - - - - -
//

/*
 * gulpfile.js
 * ===========
 * Rather than manage one giant configuration file responsible
 * for creating multiple tasks, each task has been broken out into
 * its own file in the 'gulp' folder. Any files in that directory get
 *  automatically required below.
 *
 * To add a new task, simply add a new task file in that directory.
 */

var gulp       = require('gulp');
var argv       = require('yargs').argv;
var requireDir = require('require-dir');

// 2. FILE PATHS
// - - - - - - - - - - - - - - -
// Specify paths & globbing patterns for tasks.
global.paths = {
  assets: [
    './client/**/*.*',
    '!./client/templates/**/*.*',
    '!./client/assets/{scss,js,components}/**/*.*'
  ],
  // Sass will check these folders for files when you use @import.
  sass: [
    'client/assets/scss',
    'bower_components/foundation-apps/scss',
    'bower_components/angucomplete-alt/angucomplete-alt.css',
    'client/assets/components/**/*.scss'
  ],
  // These files include Foundation for Apps and its dependencies
  foundationJS: [
    'bower_components/lodash/lodash.js',
    'bower_components/fastclick/lib/fastclick.js',
    'bower_components/viewport-units-buggyfill/viewport-units-buggyfill.js',
    'bower_components/tether/tether.js',
    'bower_components/hammerjs/hammer.js',
    'bower_components/angular/angular.js',
    'bower_components/angular-animate/angular-animate.js',
    'bower_components/angular-sanitize/angular-sanitize.js',
    'bower_components/angular-ui-router/release/angular-ui-router.js',
    'bower_components/angucomplete-alt/angucomplete-alt.js',
    'bower_components/angular-rison/dist/angular-rison.js',
    'bower_components/foundation-apps/js/vendor/**/*.js',
    'bower_components/foundation-apps/js/angular/**/*.js',
    '!bower_components/foundation-apps/js/angular/app.js',
    'bower_components/ng-orwell/Orwell.js',
    'bower_components/humanize/humanize.js',
    'bower_components/angularjs-humanize/src/angular-humanize.js'
  ],
  // These files are for your app's JavaScript
  appJS: [
    'client/assets/js/app.js',
    'client/assets/js/services/*.js',
    'client/assets/js/controllers/*.js',
    'client/assets/js/utils/**/*.js',
    'client/assets/components/**/*.js'
  ],
  components: [
    'client/assets/components/**/*.html',
    'bower_components/foundation-apps/js/angular/components/**/*.html'
  ],
  configJS: [
    './FUSION_CONFIG.js'
  ],
  configJSSample: [
    './FUSION_CONFIG.sample.js'
  ]
};

// Check for --production flag
global.isProduction = !!(argv.production);

// 3. TASKS
// - - - - - - - - - - - - - - -

// Require all tasks in the 'gulp' folder.
requireDir('./gulp', { recurse: false });

// Default task
//
// builds your app, starts a server, and recompiles assets when they change.

gulp.task('default', ['serve']);
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import { Link } from 'react-router'
import styles from './Header.css';

export default class Header extends Component {
  render() {
    return (

<Link to="/" onlyActiveOnIndex>Umich DPS</Link>

<Link to='/statistics'>Statistics</Link>

<Link to='/about'>About</Link>

    );
  }
}
<commit_msg>Keep header font with link<commit_after>import React, {Component} from 'react';
import { Link } from 'react-router'
import styles from './Header.css';

export default class Header extends Component {
  render() {
    return (

           <Link to="/" onlyActiveOnIndex>
Umich DPS
</Link>

<Link to='/statistics'>Statistics</Link>

<Link to='/about'>About</Link>

    );
  }
}
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var sass = require('grunt-sass/node_modules/node-sass');

module.exports = function(grunt){
  return {
    options: {
      includePaths: [
        path.join(process.cwd(), 'node_modules/css-smart-grid/sass')
      ],
      functions: {
        'image-url($filename)': function(filename) {
          var imageUrl = grunt.config.get('imageUrl');
          var fileName = filename.getValue();

          var imagePath = 'url("' + path.join(imageUrl, fileName) + '")';
          return new sass.types.String(imagePath);
        }
      }
    },
    prod: {
      options: {
        sourceMap: false,
        imagePath: '<%= grunt.config.get("sassImagePath") %>',
        precision: 3,
        outputStyle: 'compressed',
      },
      files: [
        {
        src: '<%= config.guts %>/assets/css/styles.scss',
        dest: '<%= config.temp %>/css/styles.css'
      },
      {
        src: '<%= config.guts %>/assets/css/om/styles.scss',
        dest: '<%= config.temp %>/css/om/styles.css'
      }
      ]
    },
    dev: {
      options: {
        sourceMap: false,
        imagePath: '<%= grunt.config.get("sassImagePath") %>',
        precision: 3,
      },
      files: [
        {
        src: '<%= config.guts %>/assets/css/styles.scss',
        dest: '<%= config.temp %>/css/styles.css'
      },
      {
        src: '<%= config.guts %>/assets/css/om/styles.scss',
        dest: '<%= config.temp %>/css/om/styles.css'
      }
      ]
    }

  };
};
<commit_msg>remove path.join from custom sass function<commit_after>var path = require('path');
var fs = require('fs');
var sass = require('grunt-sass/node_modules/node-sass');

module.exports = function(grunt){
  return {
    options: {
      includePaths: [
        path.join(process.cwd(), 'node_modules/css-smart-grid/sass')
      ],
      functions: {
        'image-url($filename)': function(filename) {
          var imageUrl = grunt.config.get('imageUrl');
          var fileName = filename.getValue();

          var imagePath = 'url("' + imageUrl + '/' + fileName + '")';
          return new sass.types.String(imagePath);
        }
      }
    },
    prod: {
      options: {
        sourceMap: false,
        imagePath: '<%= grunt.config.get("sassImagePath") %>',
        precision: 3,
        outputStyle: 'compressed',
      },
      files: [
        {
        src: '<%= config.guts %>/assets/css/styles.scss',
        dest: '<%= config.temp %>/css/styles.css'
      },
      {
        src: '<%= config.guts %>/assets/css/om/styles.scss',
        dest: '<%= config.temp %>/css/om/styles.css'
      }
      ]
    },
    dev: {
      options: {
        sourceMap: false,
        imagePath: '<%= grunt.config.get("sassImagePath") %>',
        precision: 3,
      },
      files: [
        {
        src: '<%= config.guts %>/assets/css/styles.scss',
        dest: '<%= config.temp %>/css/styles.css'
      },
      {
        src: '<%= config.guts %>/assets/css/om/styles.scss',
        dest: '<%= config.temp %>/css/om/styles.css'
      }
      ]
    }

  };
};
<|endoftext|>


<commit_before>(function() {
	var app = angular.module('noticeListBuilder', []);

	app.controller('NoticeListController', ['$scope', '$sce', 'noticeListService', 'previewService',
		function($scope, $sce, noticeListService, previewService) {
			$scope.notices = noticeListService.notices;
			$scope.previewHTML = previewService.updatePreview($scope.notices);

			$scope.addNotice = function() {
				noticeListService.addNotice();
			};

			$scope.updatePreview = function() {
				$scope.previewHTML = previewService.updatePreview($scope.notices);
			};
		}
	]);

	app.factory('noticeListService', function() {
		var notices = [];

		var addNotice = function() {
			notices.push({
				title: "",
				body: ""
			});
		};

		return {
			notices: notices,
			addNotice: addNotice
		};
	});

	app.factory('previewService', ['$sce',
		function($sce) {

			var updatePreview = function(notices) {
				var preview = document.createElement('div');
				preview.innerHTML = '';

				var index = 1;
				Array.prototype.forEach.call(notices, function(notice) {
					var span = document.createElement('span');
					span.innerHTML = index + '. ' + notice.title;
					++index;

					preview.appendChild(span);
					preview.appendChild(document.createElement('br'));
				});

				return $sce.trustAsHtml(preview.innerHTML);
			}

			return {
				updatePreview: updatePreview
			}
		}
	]);

	app.directive('noticeEditor', function() {
		return {
			templateUrl: 'assets/templates/noticeEditor.html'
		}
	});

	app.directive('preview', function() {
		return {
			templateUrl: 'assets/templates/preview.html'
		}
	});

	// based directly on https://fdietz.github.io/recipes-with-angular-js
	app.directive("contenteditable", ['$sce', function($sce) {
		return {
			restrict: "A",
			require: "ngModel",
			link: function(scope, element, attrs, ngModel) {

				function read() {
					ngModel.$setViewValue($sce.trustAsHtml(element.html()));
				}

				ngModel.$render = function() {
					element.html(ngModel.$viewValue || "");
				};

				element.bind("blur keyup change", function() {
					scope.$apply(read);
				});
			}
		};
	}]);
})();

/*******/

function cleanUp() {
	var notices = document.getElementsByClassName("notice");

	Array.prototype.forEach.call(notices, function(notice) {
		cleanChildNodes(notice);
	});

	var titles = document.getElementsByClassName("notice-title");

	Array.prototype.forEach.call(titles, function(title) {
		cleanChildNodes(title);
	});
}

function cleanChildNodes(element) {
	var nodes = element.childNodes;
	for (var i = 0; i < nodes.length; ++i) {
		fixNodeStyle(nodes[i]);
		cleanChildNodes(nodes[i]);
	}
}

function fixNodeStyle(node) {
	// clean up
	if (node.nodeName.toLowerCase() == 'font') {
		node.removeAttribute("face");
		node.removeAttribute("size");
	}

	var classes = ['span', 'p', 'div', 'code', 'pre', 'a', 'font'];

	if (classes.indexOf(node.nodeName.toLowerCase()) > -1) {
		node.style.fontSize = '';
		node.style.fontFamily = '';
		node.style.lineHeight = '';
	}

	if (node.nodeName.toLowerCase() == 'p') {
		node.style.paddingBottom = '5pt';
	}
}

function generate() {
	var resultElement = document.getElementById("result");
	var previewElement = document.getElementById("preview");
	var notices = JSON.parse(localStorage.getItem('notices'));
	var titles = JSON.parse(localStorage.getItem('titles'));

	previewElement.innerHTML = '';

	if (titles !== null) {
		var index = 1;
		Array.prototype.forEach.call(titles, function(title) {
			var span = document.createElement('span');
			span.innerHTML = index + '. ' + title;
			++index;

			previewElement.appendChild(span);
			previewElement.appendChild(document.createElement('br'));
		});

		previewElement.appendChild(document.createElement('br'));
	}

	var table = document.createElement("table");
	table.style.width = '100%';
	previewElement.appendChild(table);

	if (notices !== null) {
		var index = 1;
		Array.prototype.forEach.call(notices, function(notice) {
			var tr = document.createElement("tr");

			var tdIndex = document.createElement("td");
			tdIndex.style.paddingRight = '20pt';
			tdIndex.style.borderTop = '1px solid #777777';
			tdIndex.style.verticalAlign = 'top';
			tdIndex.style.fontSize = '20pt';
			tdIndex.style.color = '#444444';
			tdIndex.style.fontWeight = 'bold';
			tdIndex.style.width = '40pt';

			tdIndex.textContent = index;
			++index;

			var tdContent = document.createElement("td");
			tdContent.style.paddingBottom = '20pt';
			tdContent.style.borderTop = '1px solid #777777';
			tdContent.innerHTML = notice;

			tr.appendChild(tdIndex);
			tr.appendChild(tdContent);

			table.appendChild(tr);
		});
	}

	resultElement.textContent = previewElement.innerHTML;
}

function readNotices() {
	var noticesContainer = document.getElementById('notices');
	noticesContainer.innerHTML = '';

	var storedNotices = JSON.parse(localStorage.getItem('notices'));
	var storedTitles = JSON.parse(localStorage.getItem('titles'));
	if (storedNotices !== null && storedTitles !== null) {
		console.log(storedNotices);
		console.log(storedTitles);

		var numberOfNotices = storedNotices.length;

		for (var i = 0; i < numberOfNotices; ++i) {
			addNotice(storedTitles[i], storedNotices[i]);
		}
	}
}

function saveNotices() {
	var notices = document.getElementsByClassName('notice');
	var noticesToStore = [];

	Array.prototype.forEach.call(notices, function(notice) {
		noticesToStore.push(notice.innerHTML);
	});

	var titles = document.getElementsByClassName('notice-title');
	var titlesToStore = [];

	Array.prototype.forEach.call(titles, function(title) {
		titlesToStore.push(title.innerHTML);
	});

	localStorage.setItem('notices', JSON.stringify(noticesToStore));
	localStorage.setItem('titles', JSON.stringify(titlesToStore));
}

function clearNotices() {
	localStorage.removeItem('notices');
	localStorage.removeItem('titles');
}
<commit_msg>preview service removed<commit_after>(function() {
	var app = angular.module('noticeListBuilder', []);

	app.controller('NoticeListController', ['$scope', '$sce', 'noticeListService',
		function($scope, $sce, noticeListService, previewService) {
			$scope.notices = noticeListService.notices;

			$scope.addNotice = function() {
				noticeListService.addNotice();
			};
		}
	]);

	app.factory('noticeListService', function() {
		var notices = [];

		var addNotice = function() {
			notices.push({
				title: "",
				body: ""
			});
		};

		return {
			notices: notices,
			addNotice: addNotice
		};
	});

	app.directive('noticeEditor', function() {
		return {
			templateUrl: 'assets/templates/noticeEditor.html'
		}
	});

	app.directive('preview', function() {
		return {
			templateUrl: 'assets/templates/preview.html'
		}
	});

	// based directly on https://fdietz.github.io/recipes-with-angular-js
	app.directive("contenteditable", ['$sce', function($sce) {
		return {
			restrict: "A",
			require: "ngModel",
			link: function(scope, element, attrs, ngModel) {

				function read() {
					ngModel.$setViewValue($sce.trustAsHtml(element.html()));
				}

				ngModel.$render = function() {
					element.html(ngModel.$viewValue || "");
				};

				element.bind("blur keyup change", function() {
					scope.$apply(read);
				});
			}
		};
	}]);
})();

/*******/

function cleanUp() {
	var notices = document.getElementsByClassName("notice");

	Array.prototype.forEach.call(notices, function(notice) {
		cleanChildNodes(notice);
	});

	var titles = document.getElementsByClassName("notice-title");

	Array.prototype.forEach.call(titles, function(title) {
		cleanChildNodes(title);
	});
}

function cleanChildNodes(element) {
	var nodes = element.childNodes;
	for (var i = 0; i < nodes.length; ++i) {
		fixNodeStyle(nodes[i]);
		cleanChildNodes(nodes[i]);
	}
}

function fixNodeStyle(node) {
	// clean up
	if (node.nodeName.toLowerCase() == 'font') {
		node.removeAttribute("face");
		node.removeAttribute("size");
	}

	var classes = ['span', 'p', 'div', 'code', 'pre', 'a', 'font'];

	if (classes.indexOf(node.nodeName.toLowerCase()) > -1) {
		node.style.fontSize = '';
		node.style.fontFamily = '';
		node.style.lineHeight = '';
	}

	if (node.nodeName.toLowerCase() == 'p') {
		node.style.paddingBottom = '5pt';
	}
}

function generate() {
	var resultElement = document.getElementById("result");
	var previewElement = document.getElementById("preview");
	var notices = JSON.parse(localStorage.getItem('notices'));
	var titles = JSON.parse(localStorage.getItem('titles'));

	previewElement.innerHTML = '';

	if (titles !== null) {
		var index = 1;
		Array.prototype.forEach.call(titles, function(title) {
			var span = document.createElement('span');
			span.innerHTML = index + '. ' + title;
			++index;

			previewElement.appendChild(span);
			previewElement.appendChild(document.createElement('br'));
		});

		previewElement.appendChild(document.createElement('br'));
	}

	var table = document.createElement("table");
	table.style.width = '100%';
	previewElement.appendChild(table);

	if (notices !== null) {
		var index = 1;
		Array.prototype.forEach.call(notices, function(notice) {
			var tr = document.createElement("tr");

			var tdIndex = document.createElement("td");
			tdIndex.style.paddingRight = '20pt';
			tdIndex.style.borderTop = '1px solid #777777';
			tdIndex.style.verticalAlign = 'top';
			tdIndex.style.fontSize = '20pt';
			tdIndex.style.color = '#444444';
			tdIndex.style.fontWeight = 'bold';
			tdIndex.style.width = '40pt';

			tdIndex.textContent = index;
			++index;

			var tdContent = document.createElement("td");
			tdContent.style.paddingBottom = '20pt';
			tdContent.style.borderTop = '1px solid #777777';
			tdContent.innerHTML = notice;

			tr.appendChild(tdIndex);
			tr.appendChild(tdContent);

			table.appendChild(tr);
		});
	}

	resultElement.textContent = previewElement.innerHTML;
}

function readNotices() {
	var noticesContainer = document.getElementById('notices');
	noticesContainer.innerHTML = '';

	var storedNotices = JSON.parse(localStorage.getItem('notices'));
	var storedTitles = JSON.parse(localStorage.getItem('titles'));
	if (storedNotices !== null && storedTitles !== null) {
		console.log(storedNotices);
		console.log(storedTitles);

		var numberOfNotices = storedNotices.length;

		for (var i = 0; i < numberOfNotices; ++i) {
			addNotice(storedTitles[i], storedNotices[i]);
		}
	}
}

function saveNotices() {
	var notices = document.getElementsByClassName('notice');
	var noticesToStore = [];

	Array.prototype.forEach.call(notices, function(notice) {
		noticesToStore.push(notice.innerHTML);
	});

	var titles = document.getElementsByClassName('notice-title');
	var titlesToStore = [];

	Array.prototype.forEach.call(titles, function(title) {
		titlesToStore.push(title.innerHTML);
	});

	localStorage.setItem('notices', JSON.stringify(noticesToStore));
	localStorage.setItem('titles', JSON.stringify(titlesToStore));
}

function clearNotices() {
	localStorage.removeItem('notices');
	localStorage.removeItem('titles');
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var spawn  = require('child_process').spawn;
$.del = require('del');
var config = require('./config.js')

var ts           = $.typescript;
var tsProject    = ts.createProject(config.tsConfigFile);
var failOnErrors = false;
$.ts = $.typescript;

// Require and Initialize browser sync with our configurtion
var browserSync  = require('browser-sync').create();

browserSync.init({
        server: {
            baseDir: config.htmlDir,
        },
        port: config.bsPort
});

var handleError = function(err) {
  if (failOnErrors) {
    $.util.log(err.message);
    process.exit(1);
  }
}

gulp.task('transpile-ts2js', function () {
  return tsProject.src()
                  .pipe($.ts(tsProject))
                  .on('error', handleError)
                  .js
                  .pipe(gulp.dest(config.tsOutDir));
});

gulp.task('default', function() {
   gulp.watch(config.tsFilesGlob, ['transpile-ts2js']);
   gulp.watch(config.htmlDir, browserSync.reload);
   gulp.watch(config.cssDir, browserSync.reload);
});<commit_msg>Rearranged gulpfile<commit_after>var gulp   = require('gulp');
var $      = require('gulp-load-plugins')();
var del    = require('del');
var config = require('./config.js')

$.ts  = $.typescript;
$.del = del;

var tsProject = $.ts.createProject(config.tsConfigFile);
var browserSync  = require('browser-sync').create();

var failOnErrors = false;
var handleError = function(err) {
  if (failOnErrors) {
    $.util.log(err.message);
    process.exit(1);
  }
}

gulp.task('transpile-ts2js', function () {
  return tsProject.src()
    .pipe($.ts(tsProject))
    .on('error', handleError)
    .js
    .pipe(gulp.dest(config.tsOutDir));
});

gulp.task('browser-sync', function() {
  browserSync.init({
    'server': {'baseDir': config.htmlDir},
    'port': config.bsPort
  });
});

gulp.task('default', function() {
   gulp.watch(config.tsFilesGlob, ['transpile-ts2js']);
   gulp.watch(config.htmlDir, browserSync.reload);
   gulp.watch(config.cssDir, browserSync.reload);
});
<|endoftext|>


<commit_before>/*!
 * Basic postMessage Support
 *
 * Copyright (c) 2013-2014 Dave Olsen, http://dmolsen.com
 * Licensed under the MIT license
 *
 * Handles the postMessage stuff in the pattern, view-all, and style guide templates.
 *
 */

// alert the iframe parent that the pattern has loaded assuming this view was loaded in an iframe
if (self != top) {

	// handle the options that could be sent to the parent window
	//   - all get path
	//   - pattern & view all get a pattern partial, styleguide gets all
	//   - pattern shares lineage
	var path = window.location.toString();
	var parts = path.split("?");
	var options = { "event": "patternLab.pageLoad", "path": parts[0] };

	options.patternpartial = (patternData.patternPartial !== "") ? patternData.patternPartial : "all";
	if (patternData.lineage !== "") {
		options.lineage = patternData.lineage;
	}

	var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
	parent.postMessage(options, targetOrigin);

	// find all links and add an onclick handler for replacing the iframe address so the history works
	var aTags = document.getElementsByTagName('a');
	for (var i = 0; i < aTags.length; i++) {
		aTags[i].onclick = function(e) {
			var href   = this.getAttribute("href");
			var target = this.getAttribute("target");
			if ((target != undefined) && ((target == "_parent") || (target == "_blank"))) {
				// just do normal stuff
			} else if (href && href !== "#") {
				e.preventDefault();
				window.location.replace(href);
			} else {
				e.preventDefault();
				return false;
			}
		};
	}

	// bind the keyboard shortcuts for various viewport resizings + pattern search
	var keys = [ "s", "m", "l", "d", "h", "f" ];
	for (var i = 0; i < keys.length; i++) {
		jwerty.key('ctrl+shift+'+keys[i],  function (k,t) {
			return function(e) {
				var obj = JSON.stringify({ "event": "patternLab.keyPress", "keyPress": "ctrl+shift+"+k });
				parent.postMessage(obj,t);
				return false;
			}
		}(keys[i],targetOrigin));
	}

	// bind the keyboard shortcuts for mqs
	var i = 0;
	while (i < 10) {
		jwerty.key('ctrl+shift+'+i, function (k,t) {
			return function(e) {
				var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
				var obj = JSON.stringify({ "event": "patternLab.keyPress", "keyPress": "ctrl+shift+"+k });
				parent.postMessage(obj,t);
				return false;
			}
		}(i,targetOrigin));
		i++;
	}

}

// if there are clicks on the iframe make sure the nav in the iframe parent closes
var body = document.getElementsByTagName('body');
body[0].onclick = function() {
	var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
	var obj = JSON.stringify({ "event": "patternLab.bodyClick", "bodyclick": "bodyclick" });
	parent.postMessage(obj,targetOrigin);
};

// watch the iframe source so that it can be sent back to everyone else.
function receiveIframeMessage(event) {

	var path;
	var data = (typeof event.data !== "string") ? event.data : JSON.parse(event.data);

	// does the origin sending the message match the current host? if not dev/null the request
	if ((window.location.protocol != "file:") && (event.origin !== window.location.protocol+"//"+window.location.host)) {
		return;
	}

	// see if it got a path to replace
	if (data.event == "patternLab.updatePath") {

		if (patternData.patternPartial !== "") {

			// handle patterns and the view all page
			var re = /(patterns|snapshots)\/(.*)$/;
			path = window.location.protocol+"//"+window.location.host+window.location.pathname.replace(re,'')+data.path+'?'+Date.now();
			window.location.replace(path);

		} else {

			// handle the style guide
			path = window.location.protocol+"//"+window.location.host+window.location.pathname.replace("styleguide\/html\/styleguide.html","")+data.path+'?'+Date.now();
			window.location.replace(path);

		}

	} else if (data.event == "patternLab.reload") {

		// reload the location if there was a message to do so
		window.location.reload();

	}

}
window.addEventListener("message", receiveIframeMessage, false);
<commit_msg>smarter handling of message data<commit_after>/*!
 * Basic postMessage Support
 *
 * Copyright (c) 2013-2014 Dave Olsen, http://dmolsen.com
 * Licensed under the MIT license
 *
 * Handles the postMessage stuff in the pattern, view-all, and style guide templates.
 *
 */

// alert the iframe parent that the pattern has loaded assuming this view was loaded in an iframe
if (self != top) {

	// handle the options that could be sent to the parent window
	//   - all get path
	//   - pattern & view all get a pattern partial, styleguide gets all
	//   - pattern shares lineage
	var path = window.location.toString();
	var parts = path.split("?");
	var options = { "event": "patternLab.pageLoad", "path": parts[0] };

	options.patternpartial = (patternData.patternPartial !== undefined) ? patternData.patternPartial : "all";
	if (patternData.lineage !== "") {
		options.lineage = patternData.lineage;
	}

	var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
	parent.postMessage(options, targetOrigin);

	// find all links and add an onclick handler for replacing the iframe address so the history works
	var aTags = document.getElementsByTagName('a');
	for (var i = 0; i < aTags.length; i++) {
		aTags[i].onclick = function(e) {
			var href   = this.getAttribute("href");
			var target = this.getAttribute("target");
			if ((target != undefined) && ((target == "_parent") || (target == "_blank"))) {
				// just do normal stuff
			} else if (href && href !== "#") {
				e.preventDefault();
				window.location.replace(href);
			} else {
				e.preventDefault();
				return false;
			}
		};
	}

	// bind the keyboard shortcuts for various viewport resizings + pattern search
	var keys = [ "s", "m", "l", "d", "h", "f" ];
	for (var i = 0; i < keys.length; i++) {
		jwerty.key('ctrl+shift+'+keys[i],  function (k,t) {
			return function(e) {
				var obj = JSON.stringify({ "event": "patternLab.keyPress", "keyPress": "ctrl+shift+"+k });
				parent.postMessage(obj,t);
				return false;
			}
		}(keys[i],targetOrigin));
	}

	// bind the keyboard shortcuts for mqs
	var i = 0;
	while (i < 10) {
		jwerty.key('ctrl+shift+'+i, function (k,t) {
			return function(e) {
				var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
				var obj = JSON.stringify({ "event": "patternLab.keyPress", "keyPress": "ctrl+shift+"+k });
				parent.postMessage(obj,t);
				return false;
			}
		}(i,targetOrigin));
		i++;
	}

}

// if there are clicks on the iframe make sure the nav in the iframe parent closes
var body = document.getElementsByTagName('body');
body[0].onclick = function() {
	var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
	var obj = JSON.stringify({ "event": "patternLab.bodyClick", "bodyclick": "bodyclick" });
	parent.postMessage(obj,targetOrigin);
};

// watch the iframe source so that it can be sent back to everyone else.
function receiveIframeMessage(event) {

	var path;
	var data = (typeof event.data !== "string") ? event.data : JSON.parse(event.data);

	// does the origin sending the message match the current host? if not dev/null the request
	if ((window.location.protocol != "file:") && (event.origin !== window.location.protocol+"//"+window.location.host)) {
		return;
	}

	// see if it got a path to replace
	if (data.event == "patternLab.updatePath") {

		if (patternData.patternPartial !== undefined) {

			// handle patterns and the view all page
			var re = /(patterns|snapshots)\/(.*)$/;
			path = window.location.protocol+"//"+window.location.host+window.location.pathname.replace(re,'')+data.path+'?'+Date.now();
			window.location.replace(path);

		} else {

			// handle the style guide
			path = window.location.protocol+"//"+window.location.host+window.location.pathname.replace("styleguide\/html\/styleguide.html","")+data.path+'?'+Date.now();
			window.location.replace(path);

		}

	} else if (data.event == "patternLab.reload") {

		// reload the location if there was a message to do so
		window.location.reload();

	}

}
window.addEventListener("message", receiveIframeMessage, false);
<|endoftext|>


<commit_before>$(document).ready(function() {
  var start;
  var rate;
  var period;
  var invest;
  var years;

	if(hasKey('start') && hasKey('rate') && hasKey('period') && hasKey('invest')) {

	} else {
		start = 100;
    rate = 0.01;
    period = 12;
    invest = 10;
    years = 2;
	}

  var balance = ['balance', start];
  var interest = ['interest', 0];
  var deposits = ['deposit', 0];
  var time = ['0'];

  var previous = start;

  for(var p = 1; p <= period * years; p++) {
    balance.push(previous);
    interest.push(previous * rate / period);
    deposits.push(invest);
    time.push((p / period).toString());
    previous = previous + previous * rate / period + invest;
  }

  c3.generate({
    bindto: '#interest-chart',
    data: {
        columns: [balance, interest, deposits],
        type: 'bar',
    	groups: [['balance', 'interest', 'deposit']],
	order: null
    },
    axis: {
    	x: {categories: time,
		label: {text: 'time', position: 'outer-center'}},
    	y: {label: {text: 'money', position: 'outer-middle'}}
    }
  });
});
<commit_msg>Update compound-interest.js<commit_after>$(document).ready(function() {
  var start;
  var rate;
  var period;
  var invest;
  var years;

	if(hasKey('start') && hasKey('rate') && hasKey('period') && hasKey('invest')) {

	} else {
		start = 100;
    rate = 0.01;
    period = 12;
    invest = 10;
    years = 2;
	}

  var balance = ['balance', start];
  var interest = ['interest', 0];
  var deposits = ['deposit', 0];
  var time = ['0'];

  var previous = start;

  for(var p = 1; p < period * years; p++) {
    balance.push(previous);
    interest.push(previous * rate / period);
    deposits.push(invest);
    time.push((p / period).toString());
    previous = previous + previous * rate / period + invest;
  }

  c3.generate({
    bindto: '#interest-chart',
    data: {
        columns: [balance, interest, deposits],
        type: 'bar',
    	groups: [['balance', 'interest', 'deposit']],
	order: null
    },
    axis: {
    	x: {type: 'category', categories: time,
		label: {text: 'time', position: 'outer-center'}},
    	y: {label: {text: 'money', position: 'outer-middle'}}
    }
  });
});
<|endoftext|>


<commit_before>/*jshint node:true */
'use strict';

var gulp = require('gulp');

// site
var connect = require('gulp-connect');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var minifyCSS = require('gulp-minify-css');

var del = require('del');
gulp.task('lint', function () {
  gulp.src(['./app/**/*.js', '!./app/bower_components/**']).
    pipe(jshint()).
    pipe(jshint.reporter('default')).
    pipe(jshint.reporter('fail'));
});
gulp.task('clean', function (cb) {
  del(['dist/*', '!dist/data'], cb);
});
gulp.task('minify-css', function () {
  var opts = {comments: true, spare: true};
  gulp.src(['./app/**/*.css', '!./app/bower_components/**']).
    pipe(minifyCSS(opts)).
    pipe(gulp.dest('./dist/'));
});
gulp.task('minify-js', function () {
  gulp.src(['./app/**/*.js', '!./app/bower_components/**']).
    pipe(uglify({
      // inSourceMap:
      // outSourceMap: "app.js.map"
    })).
    pipe(gulp.dest('./dist/'));
});
gulp.task('copy-bower-components', function () {
  gulp.src('./app/bower_components/**').
    pipe(gulp.dest('dist/bower_components'));
});
gulp.task('copy-html-files', function () {
  gulp.src('./app/**/*.html').
    pipe(gulp.dest('dist/'));
});
gulp.task('copy-image-files', function () {
  gulp.src('./app/**/*.{png,svg}').
    pipe(gulp.dest('dist/'));
});
gulp.task('copy-text-files', function () {
  gulp.src('./app/**/*.txt').
    pipe(gulp.dest('dist/'));
});
gulp.task('connect', function () {
  connect.server({
    root: 'app/',
    port: 8888
  });
});
gulp.task('connectDist', function () {
  connect.server({
    root: 'dist/',
    port: 9999
  });
});

gulp.task('default',
  ['lint', 'connect']
);
gulp.task('build',
  ['lint', 'minify-css', 'minify-js', 'copy-bower-components', 'copy-html-files', 'copy-image-files', 'copy-text-files', 'connectDist']
);

// intern
var intern = require('./intern.js');

gulp.task('find:users', function (cb) {
  intern.findUsers(function (err, data) {
    if (err) {
      console.error(err);
      cb(err);
      return;
    }

    cb();
  });
});
gulp.task('find:blocks', function (cb) {
  intern.findBlocks(function (err, data) {
    if (err) {
      console.error(err);
      cb(err);
      return;
    }

    cb();
  });
});
<commit_msg>fix weird require orders<commit_after>/*jshint node:true */
'use strict';

var gulp = require('gulp');

// site
var connect = require('gulp-connect');
var jshint = require('gulp-jshint');
var del = require('del');
var minifyCSS = require('gulp-minify-css');
var uglify = require('gulp-uglify');

gulp.task('lint', function () {
  gulp.src(['./app/**/*.js', '!./app/bower_components/**']).
    pipe(jshint()).
    pipe(jshint.reporter('default')).
    pipe(jshint.reporter('fail'));
});
gulp.task('clean', function (cb) {
  del(['dist/*', '!dist/data'], cb);
});
gulp.task('minify-css', function () {
  var opts = {comments: true, spare: true};
  gulp.src(['./app/**/*.css', '!./app/bower_components/**']).
    pipe(minifyCSS(opts)).
    pipe(gulp.dest('./dist/'));
});
gulp.task('minify-js', function () {
  gulp.src(['./app/**/*.js', '!./app/bower_components/**']).
    pipe(uglify({
      // inSourceMap:
      // outSourceMap: "app.js.map"
    })).
    pipe(gulp.dest('./dist/'));
});
gulp.task('copy-bower-components', function () {
  gulp.src('./app/bower_components/**').
    pipe(gulp.dest('dist/bower_components'));
});
gulp.task('copy-html-files', function () {
  gulp.src('./app/**/*.html').
    pipe(gulp.dest('dist/'));
});
gulp.task('copy-image-files', function () {
  gulp.src('./app/**/*.{png,svg}').
    pipe(gulp.dest('dist/'));
});
gulp.task('copy-text-files', function () {
  gulp.src('./app/**/*.txt').
    pipe(gulp.dest('dist/'));
});
gulp.task('connect', function () {
  connect.server({
    root: 'app/',
    port: 8888
  });
});
gulp.task('connectDist', function () {
  connect.server({
    root: 'dist/',
    port: 9999
  });
});

gulp.task('default',
  ['lint', 'connect']
);
gulp.task('build',
  ['lint', 'minify-css', 'minify-js', 'copy-bower-components', 'copy-html-files', 'copy-image-files', 'copy-text-files', 'connectDist']
);

// intern
var intern = require('./intern.js');

gulp.task('find:users', function (cb) {
  intern.findUsers(function (err, data) {
    if (err) {
      console.error(err);
      cb(err);
      return;
    }

    cb();
  });
});
gulp.task('find:blocks', function (cb) {
  intern.findBlocks(function (err, data) {
    if (err) {
      console.error(err);
      cb(err);
      return;
    }

    cb();
  });
});
<|endoftext|>


<commit_before>var gulp = require("gulp");
var merge = require('merge-stream');
var babel = require("gulp-babel");
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var nodemon = require('gulp-nodemon');
var plumber = require('gulp-plumber');
var zip = require('gulp-zip');
var tar = require('gulp-tar');
var gzip = require('gulp-gzip');
var sass = require('gulp-sass');
var cleanCSS = require('gulp-clean-css');
var include = require("gulp-include");

/**
 * Paths
 *
 * @type       {Object}
 */
var paths = {
	scriptlibs: [
		'./node_modules/socket.io-client/socket.io.js',
		'./node_modules/jquery/dist/jquery.min.js',
		'./node_modules/vue/dist/vue.min.js',
		'./node_modules/jquery-smooth-scroll/jquery.smooth-scroll.min.js',
		'./node_modules/jquery-simple-upload/simpleUpload.min.js',
		'./node_modules/jquery-contextmenu/dist/jquery.contextMenu.min.js',
		'./node_modules/sticky-js/dist/sticky.min.js',
		'./node_modules/simplemde/dist/simplemde.min.js',
		'./node_modules/ace-builds/src-min-noconflict/ace.js',
		'./node_modules/ace-builds/src-min-noconflict/ext-modelist.js',
		'./node_modules/ace-builds/src-min-noconflict/mode-markdown.js',
		'./node_modules/ace-builds/src-min-noconflict/theme-tomorrow_night.js',
		'./node_modules/filesize.js/dist/filesize.min.js',
		'./node_modules/lodash/lodash.min.js'
	],
	scriptlibs_acemodes: [
		'./node_modules/ace-builds/src-min-noconflict/mode-*.js',
		'!./node_modules/ace-builds/src-min-noconflict/mode-markdown.js'
	],
	scriptapps: [
		'./client/js/*.js'
	],
	scriptapps_watch: [
		'./client/js/**/*.js'
	],
	csslibs: [
		'./node_modules/font-awesome/css/font-awesome.min.css',
		'./node_modules/highlight.js/styles/default.css',
		'./node_modules/simplemde/dist/simplemde.min.css'
	],
	cssapps: [
		'./client/scss/*.scss'
	],
	cssapps_watch: [
		'./client/scss/**/*.scss'
	],
	fonts: [
		'./node_modules/font-awesome/fonts/*-webfont.*',
		'!./node_modules/font-awesome/fonts/*-webfont.svg'
	],
	deploypackage: [
		'./**/*',
		'!node_modules', '!node_modules/**',
		'!coverage', '!coverage/**',
		'!client/js', '!client/js/**',
		'!client/scss', '!client/scss/**',
		'!dist', '!dist/**',
		'!tests', '!tests/**',
		'!.babelrc', '!.gitattributes', '!.gitignore', '!.snyk', '!.travis.yml',
		'!gulpfile.js', '!inch.json', '!config.yml', '!wiki.sublime-project'
	]
};

/**
 * TASK - Starts server in development mode
 */
gulp.task('server', ['scripts', 'css'/*, 'fonts'*/], function() {
	nodemon({
		script: './server',
		ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'],
		ext: 'js json',
		env: { 'NODE_ENV': 'development' }
	});
});

/**
 * TASK - Process all scripts processes
 */
gulp.task("scripts", ['scripts-libs', 'scripts-app']);

/**
 * TASK - Combine js libraries
 */
gulp.task("scripts-libs", function () {

	return merge(

		gulp.src(paths.scriptlibs)
		.pipe(concat('libs.js', {newLine: ';\n'}))
		.pipe(uglify({ mangle: false }))
		.pipe(gulp.dest("./assets/js")),

		gulp.src(paths.scriptlibs_acemodes)
		.pipe(gulp.dest("./assets/js/ace"))

	);

});

/**
 * TASK - Combine, make compatible and compress js app scripts
 */
gulp.task("scripts-app", function () {

	return gulp.src(paths.scriptapps)
	.pipe(plumber())
	.pipe(include({ extensions: "js" }))
	.pipe(babel())
	.pipe(uglify())
	.pipe(plumber.stop())
	.pipe(gulp.dest("./assets/js"));

});

/**
 * TASK - Process all css processes
 */
gulp.task("css", ['css-libs', 'css-app']);

/**
 * TASK - Combine css libraries
 */
gulp.task("css-libs", function () {
	return gulp.src(paths.csslibs)
	.pipe(plumber())
	.pipe(concat('libs.css'))
	.pipe(cleanCSS({ keepSpecialComments: 0 }))
	.pipe(plumber.stop())
	.pipe(gulp.dest("./assets/css"));
});

/**
 * TASK - Combine app css
 */
gulp.task("css-app", function () {
	return gulp.src(paths.cssapps)
	.pipe(plumber())
	.pipe(sass())
	.pipe(cleanCSS({ keepSpecialComments: 0 }))
	.pipe(plumber.stop())
	.pipe(gulp.dest("./assets/css"));
});

/**
 * TASK - Copy web fonts
 */
gulp.task("fonts", function () {
	return gulp.src(paths.fonts)
	.pipe(gulp.dest("./assets/fonts"));
});

/**
 * TASK - Start dev watchers
 */
gulp.task('watch', function() {
	gulp.watch([paths.scriptapps_watch], ['scripts-app']);
	gulp.watch([paths.cssapps_watch], ['css-app']);
});

/**
 * TASK - Starts development server with watchers
 */
gulp.task('default', ['watch', 'server']);

/**
 * TASK - Creates deployment packages
 */
gulp.task('deploy', ['scripts', 'css', 'fonts'], function() {
	var zipStream = gulp.src(paths.deploypackage)
		.pipe(zip('requarks-wiki.zip'))
		.pipe(gulp.dest('dist'));

	var targzStream = gulp.src(paths.deploypackage)
		.pipe(tar('requarks-wiki.tar'))
		.pipe(gzip())
		.pipe(gulp.dest('dist'));

	return merge(zipStream, targzStream);
});
<commit_msg>Updated gulpfile.js<commit_after>var gulp = require("gulp");
var merge = require('merge-stream');
var babel = require("gulp-babel");
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var nodemon = require('gulp-nodemon');
var plumber = require('gulp-plumber');
var zip = require('gulp-zip');
var tar = require('gulp-tar');
var gzip = require('gulp-gzip');
var sass = require('gulp-sass');
var cleanCSS = require('gulp-clean-css');
var include = require("gulp-include");

/**
 * Paths
 *
 * @type       {Object}
 */
var paths = {
	scriptlibs: [
		'./node_modules/socket.io-client/socket.io.js',
		'./node_modules/jquery/dist/jquery.min.js',
		'./node_modules/vue/dist/vue.min.js',
		'./node_modules/jquery-smooth-scroll/jquery.smooth-scroll.min.js',
		'./node_modules/jquery-simple-upload/simpleUpload.min.js',
		'./node_modules/jquery-contextmenu/dist/jquery.contextMenu.min.js',
		'./node_modules/sticky-js/dist/sticky.min.js',
		'./node_modules/simplemde/dist/simplemde.min.js',
		'./node_modules/ace-builds/src-min-noconflict/ace.js',
		'./node_modules/ace-builds/src-min-noconflict/ext-modelist.js',
		'./node_modules/ace-builds/src-min-noconflict/mode-markdown.js',
		'./node_modules/ace-builds/src-min-noconflict/theme-tomorrow_night.js',
		'./node_modules/filesize.js/dist/filesize.min.js',
		'./node_modules/lodash/lodash.min.js'
	],
	scriptlibs_acemodes: [
		'./node_modules/ace-builds/src-min-noconflict/mode-*.js',
		'!./node_modules/ace-builds/src-min-noconflict/mode-markdown.js'
	],
	scriptapps: [
		'./client/js/*.js'
	],
	scriptapps_watch: [
		'./client/js/**/*.js'
	],
	csslibs: [
		'./node_modules/font-awesome/css/font-awesome.min.css',
		'./node_modules/highlight.js/styles/default.css',
		'./node_modules/simplemde/dist/simplemde.min.css'
	],
	cssapps: [
		'./client/scss/*.scss'
	],
	cssapps_watch: [
		'./client/scss/**/*.scss'
	],
	fonts: [
		'./node_modules/font-awesome/fonts/*-webfont.*',
		'!./node_modules/font-awesome/fonts/*-webfont.svg'
	],
	deploypackage: [
		'./**/*',
		'!node_modules', '!node_modules/**',
		'!coverage', '!coverage/**',
		'!client/js', '!client/js/**',
		'!client/scss', '!client/scss/**',
		'!dist', '!dist/**',
		'!tests', '!tests/**',
		'!data', '!data/**',
		'!repo', '!repo/**',
		'!.babelrc', '!.gitattributes', '!.gitignore', '!.snyk', '!.travis.yml',
		'!gulpfile.js', '!inch.json', '!config.yml', '!wiki.sublime-project'
	]
};

/**
 * TASK - Starts server in development mode
 */
gulp.task('server', ['scripts', 'css'/*, 'fonts'*/], function() {
	nodemon({
		script: './server',
		ignore: ['assets/', 'client/', 'data/', 'repo/', 'tests/'],
		ext: 'js json',
		env: { 'NODE_ENV': 'development' }
	});
});

/**
 * TASK - Process all scripts processes
 */
gulp.task("scripts", ['scripts-libs', 'scripts-app']);

/**
 * TASK - Combine js libraries
 */
gulp.task("scripts-libs", function () {

	return merge(

		gulp.src(paths.scriptlibs)
		.pipe(concat('libs.js', {newLine: ';\n'}))
		.pipe(uglify({ mangle: false }))
		.pipe(gulp.dest("./assets/js")),

		gulp.src(paths.scriptlibs_acemodes)
		.pipe(gulp.dest("./assets/js/ace"))

	);

});

/**
 * TASK - Combine, make compatible and compress js app scripts
 */
gulp.task("scripts-app", function () {

	return gulp.src(paths.scriptapps)
	.pipe(plumber())
	.pipe(include({ extensions: "js" }))
	.pipe(babel())
	.pipe(uglify())
	.pipe(plumber.stop())
	.pipe(gulp.dest("./assets/js"));

});

/**
 * TASK - Process all css processes
 */
gulp.task("css", ['css-libs', 'css-app']);

/**
 * TASK - Combine css libraries
 */
gulp.task("css-libs", function () {
	return gulp.src(paths.csslibs)
	.pipe(plumber())
	.pipe(concat('libs.css'))
	.pipe(cleanCSS({ keepSpecialComments: 0 }))
	.pipe(plumber.stop())
	.pipe(gulp.dest("./assets/css"));
});

/**
 * TASK - Combine app css
 */
gulp.task("css-app", function () {
	return gulp.src(paths.cssapps)
	.pipe(plumber())
	.pipe(sass())
	.pipe(cleanCSS({ keepSpecialComments: 0 }))
	.pipe(plumber.stop())
	.pipe(gulp.dest("./assets/css"));
});

/**
 * TASK - Copy web fonts
 */
gulp.task("fonts", function () {
	return gulp.src(paths.fonts)
	.pipe(gulp.dest("./assets/fonts"));
});

/**
 * TASK - Start dev watchers
 */
gulp.task('watch', function() {
	gulp.watch([paths.scriptapps_watch], ['scripts-app']);
	gulp.watch([paths.cssapps_watch], ['css-app']);
});

/**
 * TASK - Starts development server with watchers
 */
gulp.task('default', ['watch', 'server']);

/**
 * TASK - Creates deployment packages
 */
gulp.task('deploy', ['scripts', 'css', 'fonts'], function() {
	var zipStream = gulp.src(paths.deploypackage)
		.pipe(zip('requarks-wiki.zip'))
		.pipe(gulp.dest('dist'));

	var targzStream = gulp.src(paths.deploypackage)
		.pipe(tar('requarks-wiki.tar'))
		.pipe(gzip())
		.pipe(gulp.dest('dist'));

	return merge(zipStream, targzStream);
});
<|endoftext|>


<commit_before>var Vis = require('vis');
var remote = require('remote');
var dialog = remote.require('dialog');
var fs = require('fs');

var network;
var inc = 0;

// TODO: add verification when changing node label such that it is different than all other labels
$(document).ready(function () {
    $('#submit-btn').click(function () {
        if (network.body.data.nodes.get().length == 0) {
            createAlert("You have not added any nodes to the graph.");
            return;
        }
        if (network.body.data.edges.get().length == 0) {
            createAlert("You have not added any edges to the graph.");
            return;
        }
        var rootNode = findRootNode(network.body.data.nodes.get());
        if (!rootNode) {
            var nodes = network.body.data.nodes.get();
            rootNode = nodes[0];
            rootNode.root = true;
            network = rebuildNetwork(network, container, options, nodes);
            $("#algo-panel").prepend(alertUserThatNoRoot());
        }
        setupTable(network.body.data.nodes.get());
        setupDistances(network.body.data.nodes.get());
        dijkstraAnimation(rootNode, network.body.data.nodes.get());
    });
    $('#random-btn').click(function () {
        var numberOfNodes = Math.floor((Math.random() * 30) + 10);
        if (network !== null) {
            network.destroy();
            network = null;
        }
        var data = getFreeScaleNetworkWithWeights(numberOfNodes);
        network = new Vis.Network(container, data, options);
    });
});

// create a network
var container = $('#tree-simple')[0];

var options = {
    autoResize: true,
    manipulation: {
        initiallyActive: true,
        addNode: function (nodeData, callback) {
            if (network.body.nodes === {}) {
                inc = 1;
            }
            else {
                inc++;
            }
            nodeData.root = false;
            nodeData.label = inc;
            nodeData.color = '#009688';
            nodeData.font = {
                color: '#fff'
            };
            nodeData.visited = false;
            nodeData.adjacencyList = [];
            nodeData.predecessor = null;
            callback(nodeData);
        },
        editNode: function (nodeData, callback) {
            editNodeCustom(network, nodeData, callback);
        },
        addEdge: function (data, callback) {
            if ($('#directed-chechbox').prop('checked')){
                data.arrows = {};
                data.arrows.to = true;
            }
            if (data.from === data.to) {
                var r = confirm('Do you want to connect the node to itself?');
                if (r === true) {
                    callback(null);
                    return;
                }
            }
            editEdgeCustom(data, callback);
        },
        editEdge: {
            editWithoutDrag: function (data, callback) {
                editEdgeCustom(data, callback);
            }
        }
    },
    interaction: {
        navigationButtons: true
    },
    physics: {
        enabled: false
    }
};

network = new Vis.Network(container, [], options);

function dijkstraAnimation(nodes) {
    var nodeRoot = findRootNode(nodes);
    var distances = [];
    for (var i = 0; i < nodes.length; i++) {
        console.log(nodes[i]);
        if (nodes[i] === nodeRoot) {
            distances[nodes[i]] = 0;
        }
        else if (nodeRoot.adjacencyList.lastIndexOf(nodes[i]) >= 0) {
            var edgeBetweenNodes = network.body.data.edges.filter(function(x) {
                return (x.from === nodeRoot.id && x.to === nodes[i].id);
            });
            distances[nodes[i]] = parseInt(edgeBetweenNodes.label);
            console.log(distances[nodes[i]]);
        }
        else {
            distances[nodes[i]] = Number.POSITIVE_INFINITY;
        }
    }
}

function highlightCodeLine(number) {
    $('#line-' + number).css('color', 'red');
}

function unHighlightCodeLine(number) {
    $('#line-' + number).css('color', '#3f51b5');
}

function unHighlightAllCodeLines() {
    for (var i = 0; i < 10; i++) {
        unHighlightCodeLine(i);
    }
}

function setupTable(nodes) {
   for (var i = 0; i < nodes.length; i++) {
       var tr;
       tr = '
d(' + nodes[i].label + ')
';
       $('#distances-table').append(tr);
   }
}

function setupDistances(nodes) {
    var rootNode = findRootNode(nodes);
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].root) {
            $("#distance-" + nodes[i].label).append(" 0 	");
        }
        else {
            if (rootNode.adjacencyList.lastIndexOf(nodes[i]) >= 0) {
                var edgeBetweenNodes = network.body.data.edges.filter(function(x) {
                    return (x.from === rootNode.id && x.to === nodes[i].id);
                });
                $("#distance-" + nodes[i].label).append(" " + edgeBetweenNodes.label + " 	");
            }
            else {
                $("#distance-" + nodes[i].label).append(" ∞ 	");
            }
        }
    }
}

function markAllNodesAsUnvisited(path) {
    for (var i = 0; i < path.length; i++) {
        path[i].visited = false;
    }
    return path;
}

function findRootNode(path) {
    for (var i = 0; i < path.length; i++) {
        if (path[i].root) {
            return path[i];
        }
    }
}
<commit_msg>removed code line animations duplication in dijkstra<commit_after>var Vis = require('vis');
var remote = require('remote');
var dialog = remote.require('dialog');
var fs = require('fs');

var network;
var inc = 0;

// TODO: add verification when changing node label such that it is different than all other labels
$(document).ready(function () {
    $('#submit-btn').click(function () {
        if (network.body.data.nodes.get().length == 0) {
            createAlert("You have not added any nodes to the graph.");
            return;
        }
        if (network.body.data.edges.get().length == 0) {
            createAlert("You have not added any edges to the graph.");
            return;
        }
        var rootNode = findRootNode(network.body.data.nodes.get());
        if (!rootNode) {
            var nodes = network.body.data.nodes.get();
            rootNode = nodes[0];
            rootNode.root = true;
            network = rebuildNetwork(network, container, options, nodes);
            $("#algo-panel").prepend(alertUserThatNoRoot());
        }
        setupTable(network.body.data.nodes.get());
        setupDistances(network.body.data.nodes.get());
        dijkstraAnimation(rootNode, network.body.data.nodes.get());
    });
    $('#random-btn').click(function () {
        var numberOfNodes = Math.floor((Math.random() * 30) + 10);
        if (network !== null) {
            network.destroy();
            network = null;
        }
        var data = getFreeScaleNetworkWithWeights(numberOfNodes);
        network = new Vis.Network(container, data, options);
    });
});

// create a network
var container = $('#tree-simple')[0];

var options = {
    autoResize: true,
    manipulation: {
        initiallyActive: true,
        addNode: function (nodeData, callback) {
            if (network.body.nodes === {}) {
                inc = 1;
            }
            else {
                inc++;
            }
            nodeData.root = false;
            nodeData.label = inc;
            nodeData.color = '#009688';
            nodeData.font = {
                color: '#fff'
            };
            nodeData.visited = false;
            nodeData.adjacencyList = [];
            nodeData.predecessor = null;
            callback(nodeData);
        },
        editNode: function (nodeData, callback) {
            editNodeCustom(network, nodeData, callback);
        },
        addEdge: function (data, callback) {
            if ($('#directed-chechbox').prop('checked')){
                data.arrows = {};
                data.arrows.to = true;
            }
            if (data.from === data.to) {
                var r = confirm('Do you want to connect the node to itself?');
                if (r === true) {
                    callback(null);
                    return;
                }
            }
            editEdgeCustom(data, callback);
        },
        editEdge: {
            editWithoutDrag: function (data, callback) {
                editEdgeCustom(data, callback);
            }
        }
    },
    interaction: {
        navigationButtons: true
    },
    physics: {
        enabled: false
    }
};

network = new Vis.Network(container, [], options);

function dijkstraAnimation(nodes) {
    var nodeRoot = findRootNode(nodes);
    var distances = [];
    for (var i = 0; i < nodes.length; i++) {
        console.log(nodes[i]);
        if (nodes[i] === nodeRoot) {
            distances[nodes[i]] = 0;
        }
        else if (nodeRoot.adjacencyList.lastIndexOf(nodes[i]) >= 0) {
            var edgeBetweenNodes = network.body.data.edges.filter(function(x) {
                return (x.from === nodeRoot.id && x.to === nodes[i].id);
            });
            distances[nodes[i]] = parseInt(edgeBetweenNodes.label);
            console.log(distances[nodes[i]]);
        }
        else {
            distances[nodes[i]] = Number.POSITIVE_INFINITY;
        }
    }
}

function setupTable(nodes) {
   for (var i = 0; i < nodes.length; i++) {
       var tr;
       tr = '
d(' + nodes[i].label + ')
';
       $('#distances-table').append(tr);
   }
}

function setupDistances(nodes) {
    var rootNode = findRootNode(nodes);
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].root) {
            $("#distance-" + nodes[i].label).append(" 0 	");
        }
        else {
            if (rootNode.adjacencyList.lastIndexOf(nodes[i]) >= 0) {
                var edgeBetweenNodes = network.body.data.edges.filter(function(x) {
                    return (x.from === rootNode.id && x.to === nodes[i].id);
                });
                $("#distance-" + nodes[i].label).append(" " + edgeBetweenNodes.label + " 	");
            }
            else {
                $("#distance-" + nodes[i].label).append(" ∞ 	");
            }
        }
    }
}

function markAllNodesAsUnvisited(path) {
    for (var i = 0; i < path.length; i++) {
        path[i].visited = false;
    }
    return path;
}

function findRootNode(path) {
    for (var i = 0; i < path.length; i++) {
        if (path[i].root) {
            return path[i];
        }
    }
}
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.7.1
(function() {
  var sites, _ref;

  sites = ((_ref = liberator.globalVariables.yaopen) != null ? _ref.sites : void 0) || {
    steamdb: {
      url: 'https://steamdb.info/search/?a=app&q=%ARG%'
    },
    pcgamingwiki: {
      icon: 'http://pcgamingwiki.com/images/WikiFavicon.png',
      url: 'http://pcgamingwiki.com/w/index.php?search=%ARG%'
    },
    '2ch': {
      url: 'http://find.2ch.net/search?q=%ARG%'
    },
    isthereanydeal: {
      icon: 'http://s3-eu-west-1.amazonaws.com/itad/images/favicon.png',
      url: 'http://isthereanydeal.com/#/search:%ARG%;/scroll:#gamelist'
    },
    devdocs: {
      description: 'API Document Browser',
      url: 'http://devdocs.io/#q=%ARG%'
    },
    mdn: {
      description: 'Mozilla Developer Network',
      icon: 'http://developer.cdn.mozilla.net/media/redesign/img/favicon32.png',
      url: 'https://www.google.com/search?q=site:developer.mozilla.org/ja/docs %ARG%'
    },
    wikipedia: {
      url: 'http://ja.wikipedia.org/wiki/Special:Search?search=%ARG%'
    },
    twitter: {
      url: 'https://twitter.com/search?q=%ARG%&src=typd&f=realtime'
    },
    'twitter(lang:ja)': {
      url: 'https://twitter.com/search?q=%ARG% lang:ja&src=typd&f=realtime'
    },
    nicovideo: {
      description: 'ニコニコ動画',
      url: 'http://www.nicovideo.jp/search/%ARG%'
    }
  };

  commands.addUserCommand(['yaopen'], 'Yet another :tabopen', function(args) {
    var url;
    if (sites[args[0]]) {
      url = sites[args[0]].url.replace(/%ARG%/, encodeURIComponent(args[1]));
      return liberator.open(url, liberator.NEW_TAB);
    } else {
      return liberator.echoerr("yaopen: " + args[0] + " is undefined");
    }
  }, {
    literal: 1,
    completer: function(context, args) {
      var key, site;
      if (args.completeArg === 1) {
        return;
      }
      context.completions = (function() {
        var _ref1, _ref2, _results;
        _results = [];
        for (key in sites) {
          site = sites[key];
          _results.push([key, (_ref1 = site.description) != null ? _ref1 : '', (_ref2 = site.icon) != null ? _ref2 : util.createURI(site.url).prePath + '/favicon.ico']);
        }
        return _results;
      })();
      context.keys = {
        text: 0,
        description: 1,
        icon: function(item) {
          return item[2] || DEFAULT_FAVICON;
        }
      };
      return context.compare = CompletionContext.Sort.unsorted;
    }
  }, true);

}).call(this);
<commit_msg>入力が空の時に対応<commit_after>// Generated by CoffeeScript 1.7.1
(function() {
  var sites, _ref;

  sites = ((_ref = liberator.globalVariables.yaopen) != null ? _ref.sites : void 0) || {
    steamdb: {
      url: 'https://steamdb.info/search/?a=app&q=%ARG%'
    },
    pcgamingwiki: {
      icon: 'http://pcgamingwiki.com/images/WikiFavicon.png',
      url: 'http://pcgamingwiki.com/w/index.php?search=%ARG%'
    },
    '2ch': {
      url: 'http://find.2ch.net/search?q=%ARG%'
    },
    isthereanydeal: {
      icon: 'http://s3-eu-west-1.amazonaws.com/itad/images/favicon.png',
      url: 'http://isthereanydeal.com/#/search:%ARG%;/scroll:#gamelist'
    },
    devdocs: {
      description: 'API Document Browser',
      url: 'http://devdocs.io/#q=%ARG%'
    },
    mdn: {
      description: 'Mozilla Developer Network',
      icon: 'http://developer.cdn.mozilla.net/media/redesign/img/favicon32.png',
      url: 'https://www.google.com/search?q=site:developer.mozilla.org/ja/docs %ARG%'
    },
    wikipedia: {
      url: 'http://ja.wikipedia.org/wiki/Special:Search?search=%ARG%'
    },
    twitter: {
      url: 'https://twitter.com/search?q=%ARG%&src=typd&f=realtime'
    },
    'twitter(lang:ja)': {
      url: 'https://twitter.com/search?q=%ARG% lang:ja&src=typd&f=realtime'
    },
    nicovideo: {
      description: 'ニコニコ動画',
      url: 'http://www.nicovideo.jp/search/%ARG%'
    }
  };

  commands.addUserCommand(['yaopen'], 'Yet another :tabopen', function(args) {
    var url;
    if (sites[args[0]]) {
      url = sites[args[0]].url.replace(/%ARG%/, args[1] ? encodeURIComponent(args[1]) : '');
      return liberator.open(url, liberator.NEW_TAB);
    } else {
      return liberator.echoerr("yaopen: " + args[0] + " is undefined");
    }
  }, {
    literal: 1,
    completer: function(context, args) {
      var key, site;
      if (args.completeArg === 1) {
        return;
      }
      context.completions = (function() {
        var _ref1, _ref2, _results;
        _results = [];
        for (key in sites) {
          site = sites[key];
          _results.push([key, (_ref1 = site.description) != null ? _ref1 : '', (_ref2 = site.icon) != null ? _ref2 : util.createURI(site.url).prePath + '/favicon.ico']);
        }
        return _results;
      })();
      context.keys = {
        text: 0,
        description: 1,
        icon: function(item) {
          return item[2] || DEFAULT_FAVICON;
        }
      };
      return context.compare = CompletionContext.Sort.unsorted;
    }
  }, true);

}).call(this);
<|endoftext|>


<commit_before>// Include gulp
var gulp = require('gulp');

// Include Our Plugins
var jshint = require('gulp-jshint');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var git = require('gulp-git');
var bump = require('gulp-bump');
var pkg = require('./package.json');

var paths = {
    scripts: ['js/*.js', 'test/**.*js', '!node_modules/**'],
    tests: 'test/**.*js'
};

gulp.task('clean', function () {
    return gulp.src('./dist', { read: false })
        .pipe(clean());
});

gulp.task('build', ['test', 'clean'], function () {
    return gulp.src('./js/*.js')
        .pipe(concat(pkg.name + '.js'))
        .pipe(gulp.dest('./dist'))
        .pipe(rename(pkg.name + '.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist'));
});

// Lint Task
gulp.task('jshint', function() {
    return gulp.src(paths.scripts)
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(jshint.reporter('fail'));
});

gulp.task('test', ['jshint'], function () {
    return gulp
        .src('tests/index.html')
        .pipe(mochaPhantomJS());
});

gulp.task('bump', function () {
    return gulp.src(['./package.json', './bower.json'])
        .pipe(bump())
        .pipe(gulp.dest('./'));
});

gulp.task('tag', ['bump'], function () {
    var v = pkg.version;
    var message = 'Release ' + v;

    return gulp.src('./')
        .pipe(git.commit(message))
        .pipe(git.tag(v, message))
        .pipe(git.push('origin', 'master', '--tags'))
        .pipe(gulp.dest('./'));
});

gulp.task('npm', ['tag'], function (done) {
    require('child_process').spawn('npm', ['publish'], { stdio: 'inherit' })
        .on('close', done);
});

// Our default task.
// Builds our math game and runs our tests
gulp.task('default', ['test', 'build']);
gulp.task('ci', ['build']);
gulp.task('release', ['npm']);<commit_msg>IssueID#6: gulp task for tagging<commit_after>// Include gulp
var gulp = require('gulp');

// Include Our Plugins
var jshint = require('gulp-jshint');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var git = require('gulp-git');
var bump = require('gulp-bump');
var pkg = require('./package.json');

var paths = {
    scripts: ['js/*.js', 'test/**.*js', '!node_modules/**'],
    tests: 'test/**.*js'
};

gulp.task('clean', function () {
    return gulp.src('./dist', { read: false })
        .pipe(clean());
});

gulp.task('build', ['test', 'clean'], function () {
    return gulp.src('./js/*.js')
        .pipe(concat(pkg.name + '.js'))
        .pipe(gulp.dest('./dist'))
        .pipe(rename(pkg.name + '.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist'));
});

// Lint Task
gulp.task('jshint', function() {
    return gulp.src(paths.scripts)
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(jshint.reporter('fail'));
});

gulp.task('test', ['jshint'], function () {
    return gulp
        .src('tests/index.html')
        .pipe(mochaPhantomJS());
});

gulp.task('bump', ['build'], function () {
    return gulp.src(['./package.json', './bower.json'])
        .pipe(bump())
        .pipe(gulp.dest('./'));
});

gulp.task('tag', ['bump'], function () {
    var v = pkg.version;
    var message = 'Release ' + v;

    return gulp.src('./')
        .pipe(git.commit(message))
        .pipe(git.tag(v, message))
        .pipe(git.push('origin', 'master', '--tags'))
        .pipe(gulp.dest('./'));
});

gulp.task('npm', ['tag'], function (done) {
    require('child_process').spawn('npm', ['publish'], { stdio: 'inherit' })
        .on('close', done);
});

// Our default task.
// Builds our math game and runs our tests
gulp.task('default', ['test', 'build']);
gulp.task('ci', ['build']);
gulp.task('release', ['npm']);<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this.setSuper();
        this.setPlayerTimers();
        this.setAttributes();
        this.type = "PlayerEntity";
        this.setFlags();

        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.addAnimation();

        this.renderable.setCurrentAnimation("idle");
    },

    setSuper: function(x, y){
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 64,
                //the sprite width and height is the size of the image, the width and the height tells the screen how much space to preserve//
                spriteWidth: "64",
                spriteHeight: "64",
                getShape: function() {
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);
    },

    setPlayerTimers: function(){
        this.now = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime(); //haven't used this
    },

    setAttributes: function(){
        this.health = game.data.playerHealth;
        this.body.setVelocity(game.data.playerMoveSpeed, 20);
        this.attack = game.data.playerAttack;
    },

    setFlags: function(){
        //Keeps track of which direction your is going//
        this.facing = "right";
        this.dead = false;
    },

    addAnimation: function(){
        this.renderable.addAnimation("idle", [78]);
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
    },

    update: function(delta){
        this.now = new Date().getTime();

        if(this.health <= 0 ){
            this.dead = true;
            this.pos.x = 10;
            this.pos.y = 0;
            this.health = game.data.playerHealth;
        }

        if (me.input.isKeyPressed("right")) {
            //adds to the postition of my x by the velocity defined above in
            //setVelocity() and multiplying it by me.timer.tick.
            //me.timer.tick the movement look smooth
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
        }else if(me.input.isKeyPressed("left")){
            this.facing = "left";
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else{
            this.body.vel.x = 0;
        }

        if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.falling){
            this.body.jumping = true;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
        }

        if(me.input.isKeyPressed("attack")){
            if(!this.renderable.isCurrentAnimation("attack")){
                //Sets the current Animation to attack and once that is over
                //goes back to the idle animation//
                this.renderable.setCurrentAnimation("attack", "idle");
                //Makes it so that the next time we start this sequence we begin
                //from the first animation, not wherever we left off when we switched to another animation//
                this.renderable.setAnimationFrame();
            }
        }
        else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){
            if(!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
            }
        }else if (!this.renderable.isCurrentAnimation("attack")){
            this.renderable.setCurrentAnimation("idle");
        }

        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);
        return true;
    },

    loseHealth: function(damage){
        this.health = this.health - damage;
    },

    collideHandler: function(response){
        if(response.b.type==='EnemyBaseEntity'){
            var ydif = this.pos.y - response.b.pos.y;
            var xdif = this.pos.x -response.b.pos.x;

             if(ydif<-40 && xdif< 70 && xdif>-35){
                this.body.falling = false;
                this.body.vel.y = -1;
            }
            else if(xdif>-35 && this.facing==='right' && (xdif<0)){
               this.body.vel.x = 0;
               //this.pos.x = this.pos.x -1;
            }else if(xdif<70 && this.facing==='left' && xdif>0){
                this.body.vel.x = 0;
                //this.pos.x = this.pos.x +1;

            }

            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){
                this.lastHit = this.now;
                response.b.loseHealth(game.data.playerAttack);
            }
        }else if(response.b.type==='EnemyCreep'){
            var xdif = this.pos.x - response.b.pos.x;
            var ydif = this.pos.y - response.b.pos.y;

            if (xdif>0){
                //this.pos.x = this.pos.x + 1;
                if(this.facing==="left"){
                    this.body.vel.x = 0;
                }
            }else{
                //this.pos.x = this.pos.x - 1;
                if(this.facing==="right"){
                    this.body.vel.x = 0;
                }
            }
            if(this.renderable.isCurrentAnimation("attack") && (this.now-this.lastHit) >= game.data.playerAttackTimer
                    && (Math.abs(ydif)  <=40) &&
                    (((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
                    ){
                this.lastHit = this.now;
                response.b.loseHealth(game.data.playerAttack);
            }
        }
    }
});<commit_msg>16th push<commit_after>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this.setSuper(x, y);
        this.setPlayerTimers();
        this.setAttributes();
        this.type = "PlayerEntity";
        this.setFlags();

        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.addAnimation();

        this.renderable.setCurrentAnimation("idle");
    },

    setSuper: function(x, y){
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 64,
                //the sprite width and height is the size of the image, the width and the height tells the screen how much space to preserve//
                spriteWidth: "64",
                spriteHeight: "64",
                getShape: function() {
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);
    },

    setPlayerTimers: function(){
        this.now = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime(); //haven't used this
    },

    setAttributes: function(){
        this.health = game.data.playerHealth;
        this.body.setVelocity(game.data.playerMoveSpeed, 20);
        this.attack = game.data.playerAttack;
    },

    setFlags: function(){
        //Keeps track of which direction your is going//
        this.facing = "right";
        this.dead = false;
        this.attacking = false;
    },

    addAnimation: function(){
        this.renderable.addAnimation("idle", [78]);
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
    },

    update: function(delta){
        this.now = new Date().getTime();
        this.dead = this.checkIfDead();
        this.checkKeyPressesAndMove();
        this.setAnimation();
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },

    checkIfDead: function(){
      if(this.health <= 0 ){
            return true;
            this.pos.x = 10;
            this.pos.y = 0;
            this.health = game.data.playerHealth;
        }
        return false;
    },

    checkKeyPressesAndMove: function(){
      if (me.input.isKeyPressed("right")) {
            this.moveRight();
        }else if(me.input.isKeyPressed("left")){
            this.moveLeft();
        }else{
            this.body.vel.x = 0;
        }

        if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.falling){
            this.jump();
        }

      this.attacking = me.input.isKeyPressed("attack");
    },

    moveRight: function(){
      //adds to the postition of my x by the velocity defined above in
            //setVelocity() and multiplying it by me.timer.tick.
            //me.timer.tick the movement look smooth
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
    },

    jump: function(){
      this.body.jumping = true;
      this.body.vel.y -= this.body.accel.y * me.timer.tick;
    },

    moveLeft: function(){
        this.facing = "left";
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.flipX(false);
    },

    setAnimation: function(){
        if(this.attacking){
            if(!this.renderable.isCurrentAnimation("attack")){
                //Sets the current Animation to attack and once that is over
                //goes back to the idle animation//
                this.renderable.setCurrentAnimation("attack", "idle");
                //Makes it so that the next time we start this sequence we begin
                //from the first animation, not wherever we left off when we switched to another animation//
                this.renderable.setAnimationFrame();
            }
        }
        else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){
            if(!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
            }
        }else if (!this.renderable.isCurrentAnimation("attack")){
            this.renderable.setCurrentAnimation("idle");
        }
    },

    loseHealth: function(damage){
        this.health = this.health - damage;
    },

    collideHandler: function(response){
        if(response.b.type==='EnemyBaseEntity'){
            this.collideWithEnemyBase(response);
        }else if(response.b.type==='EnemyCreep'){
                this.collideWithEnemyCreep(response);
        }
    },

    collideWithEnemyBase: function(response){
            var ydif = this.pos.y - response.b.pos.y;
            var xdif = this.pos.x -response.b.pos.x;

             if(ydif<-40 && xdif< 70 && xdif>-35){
                this.body.falling = false;
                this.body.vel.y = -1;
            }
            else if(xdif>-35 && this.facing==='right' && (xdif<0)){
               this.body.vel.x = 0;
            }else if(xdif<70 && this.facing==='left' && xdif>0){
                this.body.vel.x = 0;

            }
            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){
                this.lastHit = this.now;
                response.b.loseHealth(game.data.playerAttack);
            }
    },

    collideWithEnemyCreep: function(response){
            var xdif = this.pos.x - response.b.pos.x;
            var ydif = this.pos.y - response.b.pos.y;

            this.stopMovement(response);

            if(this.checkAttack(xdif, ydif)){
               this.hitCreep(response);
            };

    },

    stopMovement: function(xdif){
          if (xdif>0){
                if(this.facing==="left"){
                    this.body.vel.x = 0;
                }
            }else{
                if(this.facing==="right"){
                    this.body.vel.x = 0;
                }
            }
    },

    checkAttack: function(xdif, ydif){
         if(this.renderable.isCurrentAnimation("attack") && (this.now-this.lastHit) >= game.data.playerAttackTimer
                    && (Math.abs(ydif)  <=40) &&
                    (((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
                    ){
                this.lastHit = this.now;
                //if the creeps health is less than our attack, execute code in this if statemaent
                 return true;
        }
        return false;
    },

    hitCreep: function(response){
        if(response.b.health <= game.data.playerAttack){
                    //adds one gold for a creep kill//
                    game.data.gold += 1;
                    console.log("Current gold: " + game.data.gold);
                }

                response.b.loseHealth(game.data.playerAttack);
    }
});<|endoftext|>


<commit_before>const JS_SRC    = './resources/js/src/';
const JS_DIST   = './resources/js/dist/';
const SCSS_SRC  = './resources/scss/';
const SCSS_DIST = './resources/css/';
const OUTPUT_PREFIX = 'plugin-callisto';

// import gulp
var fs = require('fs');
var Q = require('q');
var path = require('path');
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var del = require('del');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var browserify = require('browserify');
var glob = require('glob');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var addSrc = require('gulp-add-src');
var ignore = require('gulp-ignore');
var minifyCSS = require('gulp-minify-css');
var eslint = require('gulp-eslint');
var props = require('gulp-props');
var tap = require('gulp-tap');

// import sass tools
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');

gulp.task('watch:js', ['build:vendor'], function() {
    return gulp
        .watch( JS_SRC + '**/*.js', ['build:app']);
});

gulp.task('watch:sass', function() {
    return gulp
        .watch( SCSS_SRC + '**/*.scss', ['build:sass']);
});

gulp.task('build', ['build:bundle', 'build:sass-min']);

gulp.task('build:bundle', ['build:app', 'build:vendor', 'build:lang'], function() {
    return gulp.src( [
            JS_DIST + OUTPUT_PREFIX + '-vendor.js',
            JS_SRC + 'app.config.js',
            JS_DIST + OUTPUT_PREFIX + '-app.js'
            ] )
        .pipe( sourcemaps.init({ loadMaps: true }) )
        .pipe( concat( OUTPUT_PREFIX + '.js' ) )
        .pipe( gulp.dest( JS_DIST ) )
        .pipe( rename( OUTPUT_PREFIX + '.min.js') )
        .pipe( uglify().on('error', gutil.log) )
        .pipe( sourcemaps.write('.') )
        .pipe( gulp.dest( JS_DIST ) );
});

gulp.task('build:app', /*['build:lint'],*/ function() {

    var builder = browserify({
        entries: glob.sync("app/!(services)/**/*.js", {cwd: JS_SRC}),
        debug: true,
        basedir: JS_SRC,
        paths: [ 'app/' ]
    });

    return builder.bundle()
        .pipe( source( OUTPUT_PREFIX + '-app.js' ) )
        .pipe( buffer() )
        .pipe( sourcemaps.init({ loadMaps: true }) )
        .pipe( addSrc.append(JS_SRC + 'app/main.js') )
        .pipe( concat( OUTPUT_PREFIX + '-app.js') )
        .pipe( sourcemaps.write('.', {includeContent: false, sourceRoot: '../src'}) )
        .pipe( gulp.dest( JS_DIST ) );
});

gulp.task('build:lang', function() {
    var defered = Q.defer();
    var translations = {};

    try {
        fs.accessSync( './resources/js/lang' );
    }
    catch(e)
    {
        fs.mkdir( './resources/js/lang' );
    }
    glob.sync('./resources/lang/*').forEach( function( filePath ) {
        if( fs.statSync( filePath ).isDirectory() )
        {
            var lang = path.basename( filePath );
            translations[lang] = {};
            gulp.src( filePath + '/*.properties')
                .pipe( props({ namespace: '' }) )
                .pipe(
                    tap(function(file, t) {
                        var group = path.basename( file.path, '.json' );
                        translations[lang][group] = JSON.parse( String(file.contents) );
                    }).on('end', function() {
                        defered.resolve();
                        fs.writeFileSync('./resources/js/lang/' + lang + '.js', "var Translations = " + JSON.stringify( translations[lang] ) + ";" );
                    })
                );
        }
    });

    return defered.promise;
});

gulp.task('build:vendor', function() {
    var libraries = require(JS_SRC + 'vendor.json');
    return gulp.src( libraries )
        .pipe( sourcemaps.init() )
        .pipe( concat( OUTPUT_PREFIX + '-vendor.js' ) )
        .pipe( sourcemaps.write('.', {sourceRoot: '../src/libraries'}) )
        .pipe( gulp.dest( JS_DIST ) );
});

gulp.task('build:lint', function() {
    // ESLint ignores files with "node_modules" paths.
    // So, it's best to have gulp ignore the directory as well.
    // Also, Be sure to return the stream from the task;
    // Otherwise, the task may end before the stream has finished.
    return gulp.src(['resources/js/src/**/*.js', '!node_modules/**'])
        .pipe(eslint({
            "configFile": "./.eslintrc.json",
            "fix": true
        }))
        .pipe(gulp.dest("resources/js/src/"))
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format("table"))
        .pipe(eslint.failAfterError());
});

gulp.task('build:sass-min', ['build:sass'], function() {
    return buildSass( OUTPUT_PREFIX+'.min.css', 'compressed' );
});

gulp.task('build:sass', function() {
    return buildSass( OUTPUT_PREFIX+'.css', 'expanded' );
});

function buildSass( outputFile, outputStyle )
{
    var config = {
        scssOptions : {
            errLogToConsole : true,
            outputStyle     : outputStyle
        },
        prefixOptions: {
            browsers: ['last 2 versions', '> 5%', 'Firefox ESR']
        }
    };

    return gulp
        .src( SCSS_SRC + 'PluginCallisto.scss' )
        .pipe( sourcemaps.init() )
        .pipe( sass( config.scssOptions ).on( 'error', sass.logError ) )
        .pipe( rename( outputFile ) )
        .pipe( autoprefixer( config.prefixOptions ) )
        .pipe( minifyCSS() )
        .pipe( sourcemaps.write( '.' ) )
        .pipe( gulp.dest( SCSS_DIST ) );
}
<commit_msg>arm eslint<commit_after>const JS_SRC    = './resources/js/src/';
const JS_DIST   = './resources/js/dist/';
const SCSS_SRC  = './resources/scss/';
const SCSS_DIST = './resources/css/';
const OUTPUT_PREFIX = 'plugin-callisto';

// import gulp
var fs = require('fs');
var Q = require('q');
var path = require('path');
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var del = require('del');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var browserify = require('browserify');
var glob = require('glob');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var addSrc = require('gulp-add-src');
var ignore = require('gulp-ignore');
var minifyCSS = require('gulp-minify-css');
var eslint = require('gulp-eslint');
var props = require('gulp-props');
var tap = require('gulp-tap');

// import sass tools
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');

gulp.task('watch:js', ['build:vendor'], function() {
    return gulp
        .watch( JS_SRC + '**/*.js', ['build:app']);
});

gulp.task('watch:sass', function() {
    return gulp
        .watch( SCSS_SRC + '**/*.scss', ['build:sass']);
});

gulp.task('build', ['build:bundle', 'build:sass-min']);

gulp.task('build:bundle', ['build:app', 'build:vendor', 'build:lang'], function() {
    return gulp.src( [
            JS_DIST + OUTPUT_PREFIX + '-vendor.js',
            JS_SRC + 'app.config.js',
            JS_DIST + OUTPUT_PREFIX + '-app.js'
            ] )
        .pipe( sourcemaps.init({ loadMaps: true }) )
        .pipe( concat( OUTPUT_PREFIX + '.js' ) )
        .pipe( gulp.dest( JS_DIST ) )
        .pipe( rename( OUTPUT_PREFIX + '.min.js') )
        .pipe( uglify().on('error', gutil.log) )
        .pipe( sourcemaps.write('.') )
        .pipe( gulp.dest( JS_DIST ) );
});

gulp.task('build:app', ['build:lint'], function() {

    var builder = browserify({
        entries: glob.sync("app/!(services)/**/*.js", {cwd: JS_SRC}),
        debug: true,
        basedir: JS_SRC,
        paths: [ 'app/' ]
    });

    return builder.bundle()
        .pipe( source( OUTPUT_PREFIX + '-app.js' ) )
        .pipe( buffer() )
        .pipe( sourcemaps.init({ loadMaps: true }) )
        .pipe( addSrc.append(JS_SRC + 'app/main.js') )
        .pipe( concat( OUTPUT_PREFIX + '-app.js') )
        .pipe( sourcemaps.write('.', {includeContent: false, sourceRoot: '../src'}) )
        .pipe( gulp.dest( JS_DIST ) );
});

gulp.task('build:lang', function() {
    var defered = Q.defer();
    var translations = {};

    try {
        fs.accessSync( './resources/js/lang' );
    }
    catch(e)
    {
        fs.mkdir( './resources/js/lang' );
    }
    glob.sync('./resources/lang/*').forEach( function( filePath ) {
        if( fs.statSync( filePath ).isDirectory() )
        {
            var lang = path.basename( filePath );
            translations[lang] = {};
            gulp.src( filePath + '/*.properties')
                .pipe( props({ namespace: '' }) )
                .pipe(
                    tap(function(file, t) {
                        var group = path.basename( file.path, '.json' );
                        translations[lang][group] = JSON.parse( String(file.contents) );
                    }).on('end', function() {
                        defered.resolve();
                        fs.writeFileSync('./resources/js/lang/' + lang + '.js', "var Translations = " + JSON.stringify( translations[lang] ) + ";" );
                    })
                );
        }
    });

    return defered.promise;
});

gulp.task('build:vendor', function() {
    var libraries = require(JS_SRC + 'vendor.json');
    return gulp.src( libraries )
        .pipe( sourcemaps.init() )
        .pipe( concat( OUTPUT_PREFIX + '-vendor.js' ) )
        .pipe( sourcemaps.write('.', {sourceRoot: '../src/libraries'}) )
        .pipe( gulp.dest( JS_DIST ) );
});

gulp.task('build:lint', function() {
    // ESLint ignores files with "node_modules" paths.
    // So, it's best to have gulp ignore the directory as well.
    // Also, Be sure to return the stream from the task;
    // Otherwise, the task may end before the stream has finished.
    return gulp.src(['resources/js/src/**/*.js', '!node_modules/**'])
        .pipe(eslint({
            "configFile": "./.eslintrc.json",
            "fix": true
        }))
        .pipe(gulp.dest("resources/js/src/"))
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format("table"))
        .pipe(eslint.failAfterError());
});

gulp.task('build:sass-min', ['build:sass'], function() {
    return buildSass( OUTPUT_PREFIX+'.min.css', 'compressed' );
});

gulp.task('build:sass', function() {
    return buildSass( OUTPUT_PREFIX+'.css', 'expanded' );
});

function buildSass( outputFile, outputStyle )
{
    var config = {
        scssOptions : {
            errLogToConsole : true,
            outputStyle     : outputStyle
        },
        prefixOptions: {
            browsers: ['last 2 versions', '> 5%', 'Firefox ESR']
        }
    };

    return gulp
        .src( SCSS_SRC + 'PluginCallisto.scss' )
        .pipe( sourcemaps.init() )
        .pipe( sass( config.scssOptions ).on( 'error', sass.logError ) )
        .pipe( rename( outputFile ) )
        .pipe( autoprefixer( config.prefixOptions ) )
        .pipe( minifyCSS() )
        .pipe( sourcemaps.write( '.' ) )
        .pipe( gulp.dest( SCSS_DIST ) );
}
<|endoftext|>