<commit_before>// Generated by CoffeeScript 1.9.2
(function() {
  var csso, exec, fs, getFileName, nib, opt, path, shell, stylus;

  exec = require('child_process').exec;

  path = require('path');

  fs = require('fs');

  opt = require('optimist');

  stylus = require('stylus');

  nib = require('nib');

  csso = require('csso');

  shell = require('shelljs');

  getFileName = function(filepath) {
    var name, nameArr, pathArr;
    pathArr = filepath.split('/');
    nameArr = pathArr[pathArr.length - 1].split('.');
    nameArr.pop();
    return name = nameArr.join('.');
  };

  exports.complies = function(grunt, compe) {
    var exports;
    exports = {};
    exports.init = function(options) {
      var basePath, deploy, distCss, distIconCss, distStyl, dplPath, getPath, importPath, main, pagePath, processCSSO, processDir, sysPath, tasks, writeFile;
      processCSSO = function(src, isOpt) {
        var min;
        min = '';
        if (isOpt) {
          min = csso.justDoIt(src);
        } else {
          min = csso.justDoIt(src, true);
        }
        return min;
      };
      getPath = function(dir) {
        if (options.onlyStylu) {
          return dir;
        } else {
          return 'tos-styl/' + dir;
        }
      };
      distCss = getPath('dist_css');
      distIconCss = getPath('dist_icon_css');
      distStyl = getPath('dist_styl');
      importPath = getPath('styl/import');
      basePath = getPath('styl/base');
      dplPath = getPath('styl/dpl');
      sysPath = getPath('styl/sys');
      pagePath = getPath('styl/app/page');
      writeFile = function(putfile, results) {
        grunt.log.ok("File " + putfile + ' created');
        return grunt.file.write(putfile, results.join(grunt.util.normalizelf(grunt.util.linefeed)));
      };
      processDir = function(dir, callback) {
        return grunt.file.recurse(dir, function(abspath, rootdir, subdir, filename) {
          return callback(filename, abspath);
        });
      };
      tasks = {
        importDirProcess: function(mod, needimp, currentDir) {
          var content, fargs, filesArr, linesArr, putCss, putfile;
          if (needimp == null) {
            needimp = false;
          }
          putfile = distStyl + '/' + mod + '.styl';
          putCss = distCss + '/' + mod + '.css';
          content = [];
          linesArr = [];
          filesArr = [];
          fargs = [];
          if (needimp === true) {
            fargs.push(function() {
              return content.push(grunt.file.read(distStyl + '/import.styl'));
            });
          }
          fargs.push(function() {
            return processDir(currentDir, function(filename, abspath) {
              linesArr[filename] = {
                path: '@import ' + '"' + abspath + '"'
              };
              return filesArr.push(filename);
            });
          });
          fargs.push(function() {
            var file, i, len, results1;
            filesArr.sort();
            results1 = [];
            for (i = 0, len = filesArr.length; i < len; i++) {
              file = filesArr[i];
              results1.push(content.push(linesArr[file].path));
            }
            return results1;
          });
          fargs.push(function() {
            return writeFile(putfile, content);
          });
          fargs.push(function() {
            return compe(putfile, options, function(css, err) {
              grunt.file.write(putCss, css);
              return console.log('File ' + putCss + ' created');
            });
          });
          return grunt.util.async.parallel(fargs);
        },
        proPage: function(filepath) {
          var content, fargs, importCss, name, nameArr, pathArr, putCss, putCssMin, putfile, regImport;
          pathArr = filepath.split('/');
          putfile = distStyl + '/' + pathArr[pathArr.length - 1];
          nameArr = pathArr[pathArr.length - 1].split('.');
          nameArr.pop();
          name = nameArr.join('.');
          putCss = distCss + '/' + name + '.css';
          putCssMin = distCss + '/' + name + '.min.css';
          importCss = "";
          regImport = /@import\s+"([a-zA-Z0-9._\/-]+\.css)";?\n/gm;
          content = [];
          fargs = [];
          fargs.push(function() {
            return content.push(grunt.file.read(distStyl + '/import.styl'));
          });
          fargs.push(function() {
            return content.push(grunt.file.read(filepath));
          });
          fargs.push(function() {
            return writeFile(putfile, content);
          });
          fargs.push(function() {
            return compe(putfile, options, function(css, err) {
              var e, iconFiles, patt, strArr, tempCss;
              strArr = putCss.slice(putCss.lastIndexOf('/') + 1, putCss.length - 4);
              patt = new RegExp("(icon|i)-" + strArr + "[0-9]*[-.]");
              iconFiles = shell.find(distIconCss).filter(function(file) {
                return file.match(patt);
              });
              if (iconFiles.length) {
                iconFiles.forEach(function(item) {
                  css = grunt.file.read(item) + "\r\n" + css;
                  return grunt.log.ok('File ' + putCss + ' prepended file ' + item);
                });
              }
              css.replace(regImport, function(m, s1) {
                importCss = importCss + grunt.file.read(s1);
                return grunt.log.ok('Import ' + s1 + ' success.');
              });
              css = importCss + css.replace(regImport, '');
              grunt.file.write(putCss, css);
              if (options.isCompress) {
                try {
                  tempCss = processCSSO(css);
                  css = tempCss;
                  grunt.file.write(putCssMin, css);
                  grunt.log.ok('File ' + putCss + ' minified.');
                } catch (_error) {
                  e = _error;
                  grunt.file.write(putCssMin, css);
                  grunt.log.error('minify ' + putCss + ' failed.');
                }
              }
              return grunt.log.ok('File ' + putCss + ' created');
            });
          });
          return grunt.util.async.parallel(fargs);
        },
        proModule: function(filepath) {
          var fargs;
          fargs = [];
          grunt.file.recurse(pagePath, function(abspath, rootdir, subdir, filename) {
            var matchPath;
            matchPath = new RegExp('/module/' + getFileName(filepath));
            return fargs.push(function() {
              return matchPath.test(fs.readFileSync(abspath).toString()) && tasks.proPage(abspath);
            });
          });
          return grunt.util.async.parallel(fargs);
        }
      };
      main = function(mod, filepath) {
        var currentDir, fargs;
        if (mod === 'base' || mod === 'dpl' || mod === 'sys') {
          currentDir = path.dirname(filepath);
          fargs = [];
          fargs.push(function() {
            return tasks.importDirProcess(mod, true, currentDir);
          });
          return grunt.util.async.parallel(fargs);
        } else if (mod === 'import') {
          currentDir = path.dirname(filepath);
          fargs = [];
          fargs.push(function() {
            return tasks.importDirProcess(mod, false, currentDir);
          });
          fargs.push(function() {
            return tasks.importDirProcess('base', true, basePath);
          });
          fargs.push(function() {
            return tasks.importDirProcess('dpl', true, dplPath);
          });
          fargs.push(function() {
            return tasks.importDirProcess('sys', true, sysPath);
          });
          fargs.push(function() {
            return grunt.file.recurse(pagePath, function(abspath, rootdir, subdir, filename) {
              return tasks.proPage(abspath);
            });
          });
          return grunt.util.async.parallel(fargs);
        } else if (mod === 'page') {
          return tasks.proPage(filepath);
        } else if (mod === 'module') {
          return tasks.proModule(filepath);
        }
      };
      deploy = function() {
        var currentVersion, execute, lastReleaseVersion, versionCacheFile;
        execute = function(command, callback) {
          return callback(shell.exec(command, {
            silent: true
          }).output);
        };
        lastReleaseVersion = null;
        versionCacheFile = 'versioncache.log';
        currentVersion = shell.exec("git log -1 --pretty=format:'%H'", {
          silent: true
        }).output;
        if (grunt.file.exists(versionCacheFile)) {
          lastReleaseVersion = grunt.file.read(versionCacheFile);
        }
        if (lastReleaseVersion) {
          execute("git diff " + currentVersion + ".." + lastReleaseVersion + " --raw", function(raw) {
            var rawArr;
            if (!raw) {
              return;
            }
            rawArr = raw.split("\n");
            console.log(raw);
            return rawArr.forEach(function(line) {
              var fileArr, filename, filenameArr, lineArr;
              if (line) {
                lineArr = line.split(' ');
                fileArr = lineArr[4].split("\t");
                if (fileArr[0] !== 'D' && fileArr[1].indexOf(".styl") !== -1) {
                  filename = fileArr[1];
                  filenameArr = filename.split("/");
                  return main(filenameArr[filenameArr.length - 2], fileArr[1]);
                }
              }
            });
          });
        } else {
          main('import', 'styl/import/effect.styl');
        }
        return grunt.file.write(versionCacheFile, currentVersion);
      };
      if (!options.deploy) {
        return main(options.mod, options.filepath);
      } else {
        return deploy();
      }
    };
    return exports;
  };

}).call(this);
<commit_msg>fix icon reg bug<commit_after>// Generated by CoffeeScript 1.9.2
(function() {
  var csso, exec, fs, getFileName, nib, opt, path, shell, stylus;

  exec = require('child_process').exec;

  path = require('path');

  fs = require('fs');

  opt = require('optimist');

  stylus = require('stylus');

  nib = require('nib');

  csso = require('csso');

  shell = require('shelljs');

  getFileName = function(filepath) {
    var name, nameArr, pathArr;
    pathArr = filepath.split('/');
    nameArr = pathArr[pathArr.length - 1].split('.');
    nameArr.pop();
    return name = nameArr.join('.');
  };

  exports.complies = function(grunt, compe) {
    var exports;
    exports = {};
    exports.init = function(options) {
      var basePath, deploy, distCss, distIconCss, distStyl, dplPath, getPath, importPath, main, pagePath, processCSSO, processDir, sysPath, tasks, writeFile;
      processCSSO = function(src, isOpt) {
        var min;
        min = '';
        if (isOpt) {
          min = csso.justDoIt(src);
        } else {
          min = csso.justDoIt(src, true);
        }
        return min;
      };
      getPath = function(dir) {
        if (options.onlyStylu) {
          return dir;
        } else {
          return 'tos-styl/' + dir;
        }
      };
      distCss = getPath('dist_css');
      distIconCss = getPath('dist_icon_css');
      distStyl = getPath('dist_styl');
      importPath = getPath('styl/import');
      basePath = getPath('styl/base');
      dplPath = getPath('styl/dpl');
      sysPath = getPath('styl/sys');
      pagePath = getPath('styl/app/page');
      writeFile = function(putfile, results) {
        grunt.log.ok("File " + putfile + ' created');
        return grunt.file.write(putfile, results.join(grunt.util.normalizelf(grunt.util.linefeed)));
      };
      processDir = function(dir, callback) {
        return grunt.file.recurse(dir, function(abspath, rootdir, subdir, filename) {
          return callback(filename, abspath);
        });
      };
      tasks = {
        importDirProcess: function(mod, needimp, currentDir) {
          var content, fargs, filesArr, linesArr, putCss, putfile;
          if (needimp == null) {
            needimp = false;
          }
          putfile = distStyl + '/' + mod + '.styl';
          putCss = distCss + '/' + mod + '.css';
          content = [];
          linesArr = [];
          filesArr = [];
          fargs = [];
          if (needimp === true) {
            fargs.push(function() {
              return content.push(grunt.file.read(distStyl + '/import.styl'));
            });
          }
          fargs.push(function() {
            return processDir(currentDir, function(filename, abspath) {
              linesArr[filename] = {
                path: '@import ' + '"' + abspath + '"'
              };
              return filesArr.push(filename);
            });
          });
          fargs.push(function() {
            var file, i, len, results1;
            filesArr.sort();
            results1 = [];
            for (i = 0, len = filesArr.length; i < len; i++) {
              file = filesArr[i];
              results1.push(content.push(linesArr[file].path));
            }
            return results1;
          });
          fargs.push(function() {
            return writeFile(putfile, content);
          });
          fargs.push(function() {
            return compe(putfile, options, function(css, err) {
              grunt.file.write(putCss, css);
              return console.log('File ' + putCss + ' created');
            });
          });
          return grunt.util.async.parallel(fargs);
        },
        proPage: function(filepath) {
          var content, fargs, importCss, name, nameArr, pathArr, putCss, putCssMin, putfile, regImport;
          pathArr = filepath.split('/');
          putfile = distStyl + '/' + pathArr[pathArr.length - 1];
          nameArr = pathArr[pathArr.length - 1].split('.');
          nameArr.pop();
          name = nameArr.join('.');
          putCss = distCss + '/' + name + '.css';
          putCssMin = distCss + '/' + name + '.min.css';
          importCss = "";
          regImport = /@import\s+"([a-zA-Z0-9._\/-]+\.css)";?\n/gm;
          content = [];
          fargs = [];
          fargs.push(function() {
            return content.push(grunt.file.read(distStyl + '/import.styl'));
          });
          fargs.push(function() {
            return content.push(grunt.file.read(filepath));
          });
          fargs.push(function() {
            return writeFile(putfile, content);
          });
          fargs.push(function() {
            return compe(putfile, options, function(css, err) {
              var e, iconFiles, patt, strArr, tempCss;
              strArr = putCss.slice(putCss.lastIndexOf('/') + 1, putCss.length - 4);
              patt = new RegExp("(icon|i)-" + strArr + "[0-9]*\.");
              iconFiles = shell.find(distIconCss).filter(function(file) {
                return file.match(patt);
              });
              if (iconFiles.length) {
                iconFiles.forEach(function(item) {
                  css = grunt.file.read(item) + "\r\n" + css;
                  return grunt.log.ok('File ' + putCss + ' prepended file ' + item);
                });
              }
              css.replace(regImport, function(m, s1) {
                importCss = importCss + grunt.file.read(s1);
                return grunt.log.ok('Import ' + s1 + ' success.');
              });
              css = importCss + css.replace(regImport, '');
              grunt.file.write(putCss, css);
              if (options.isCompress) {
                try {
                  tempCss = processCSSO(css);
                  css = tempCss;
                  grunt.file.write(putCssMin, css);
                  grunt.log.ok('File ' + putCss + ' minified.');
                } catch (_error) {
                  e = _error;
                  grunt.file.write(putCssMin, css);
                  grunt.log.error('minify ' + putCss + ' failed.');
                }
              }
              return grunt.log.ok('File ' + putCss + ' created');
            });
          });
          return grunt.util.async.parallel(fargs);
        },
        proModule: function(filepath) {
          var fargs;
          fargs = [];
          grunt.file.recurse(pagePath, function(abspath, rootdir, subdir, filename) {
            var matchPath;
            matchPath = new RegExp('/module/' + getFileName(filepath));
            return fargs.push(function() {
              return matchPath.test(fs.readFileSync(abspath).toString()) && tasks.proPage(abspath);
            });
          });
          return grunt.util.async.parallel(fargs);
        }
      };
      main = function(mod, filepath) {
        var currentDir, fargs;
        if (mod === 'base' || mod === 'dpl' || mod === 'sys') {
          currentDir = path.dirname(filepath);
          fargs = [];
          fargs.push(function() {
            return tasks.importDirProcess(mod, true, currentDir);
          });
          return grunt.util.async.parallel(fargs);
        } else if (mod === 'import') {
          currentDir = path.dirname(filepath);
          fargs = [];
          fargs.push(function() {
            return tasks.importDirProcess(mod, false, currentDir);
          });
          fargs.push(function() {
            return tasks.importDirProcess('base', true, basePath);
          });
          fargs.push(function() {
            return tasks.importDirProcess('dpl', true, dplPath);
          });
          fargs.push(function() {
            return tasks.importDirProcess('sys', true, sysPath);
          });
          fargs.push(function() {
            return grunt.file.recurse(pagePath, function(abspath, rootdir, subdir, filename) {
              return tasks.proPage(abspath);
            });
          });
          return grunt.util.async.parallel(fargs);
        } else if (mod === 'page') {
          return tasks.proPage(filepath);
        } else if (mod === 'module') {
          return tasks.proModule(filepath);
        }
      };
      deploy = function() {
        var currentVersion, execute, lastReleaseVersion, versionCacheFile;
        execute = function(command, callback) {
          return callback(shell.exec(command, {
            silent: true
          }).output);
        };
        lastReleaseVersion = null;
        versionCacheFile = 'versioncache.log';
        currentVersion = shell.exec("git log -1 --pretty=format:'%H'", {
          silent: true
        }).output;
        if (grunt.file.exists(versionCacheFile)) {
          lastReleaseVersion = grunt.file.read(versionCacheFile);
        }
        if (lastReleaseVersion) {
          execute("git diff " + currentVersion + ".." + lastReleaseVersion + " --raw", function(raw) {
            var rawArr;
            if (!raw) {
              return;
            }
            rawArr = raw.split("\n");
            console.log(raw);
            return rawArr.forEach(function(line) {
              var fileArr, filename, filenameArr, lineArr;
              if (line) {
                lineArr = line.split(' ');
                fileArr = lineArr[4].split("\t");
                if (fileArr[0] !== 'D' && fileArr[1].indexOf(".styl") !== -1) {
                  filename = fileArr[1];
                  filenameArr = filename.split("/");
                  return main(filenameArr[filenameArr.length - 2], fileArr[1]);
                }
              }
            });
          });
        } else {
          main('import', 'styl/import/effect.styl');
        }
        return grunt.file.write(versionCacheFile, currentVersion);
      };
      if (!options.deploy) {
        return main(options.mod, options.filepath);
      } else {
        return deploy();
      }
    };
    return exports;
  };

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


<commit_before>var pkg = require('../package.json')
var gulp = require('gulp')
var browser = require('browser-sync')

<commit_msg>synching browser execution function<commit_after>var pkg = require('../package.json')
var gulp = require('gulp')
var browser = require('browser-sync')

gulp.task('sync', function () {
  browser.init(pkg.folders.dist + '/**', {
    server: {
      baseDir: ''
    }
  })
})
<|endoftext|>


<commit_before>var task = function(gulp, config) {
  'use strict';

  var mocha = require('gulp-mocha');
  var notify = require('gulp-notify');

  gulp.task('test', function () {
    return gulp.src(config.tests, {read: false})
      // gulp-mocha needs filepaths so you can't have any plugins before it
      .pipe(mocha({
        reporter: 'dot'
        }))
      .on('error', notify.onError({message: '<%= error.message %>', title: 'Gulp mocha'}));
  });
};

module.exports = task;
<commit_msg>Failed tests are not plugin errors. Closes #7<commit_after>var task = function(gulp, config) {
  'use strict';

  var mocha = require('gulp-mocha');
  var notify = require('gulp-notify');

  gulp.task('test', function () {
    return gulp.src(config.tests, {read: false})
      // gulp-mocha needs filepaths so you can't have any plugins before it
      .pipe(mocha({
        reporter: 'dot'
        }))
      .on('error', function (error) {
        notify({message: '<%= error.message %>', title: 'Gulp mocha'});
        this.emit('end');
      });
  });
};

module.exports = task;
<|endoftext|>


<commit_before>/*    _____                    _____
     /\    \                  /\    \
    /::\    \                /::\    \
    \:::\    \              /::::\    \
     \:::\    \            /::::::\    \
      \:::\    \          /:::/\:::\    \
       \:::\    \        /:::/  \:::\    \
       /::::\    \      /:::/    \:::\    \
      /::::::\    \    /:::/    / \:::\    \
     /:::/\:::\    \  /:::/    /   \:::\    \
    /:::/  \:::\____\/:::/____/     \:::\____\
   /:::/    \::/    /\:::\    \      \::/    /
  /:::/    / \/____/  \:::\    \      \/____/
 /:::/    /            \:::\    \
/:::/    /              \:::\    \
\::/    /                \:::\    \
 \/____/                  \:::\    \
                           \:::\    \
                            \:::\____\
                             \::/    /
                              \/____/
                             TYPE/CODE
                         From 2010 till ∞     */

(function(window, $) {

	var NI = window.NI;

	function Overlay(options) {
		var o, $c, $m, open, $elements;

		o = $.extend({
			context: "body", // Selector to element where overlay will be inserted.
			autoflush: true, // If true, the Overlay automatically flushes its content when it is closed.
			flavor: null, // Additional classnames for Mask and Overlay.
			maskClick: true, // Hide Overlay if Mask is Clicked.
			maskFadeOutSpeed: 100, // Delay for mask Fade Out Animation.
			escape: true, //ESC Keypress closes Overlay.
			closeBtn: false, // Appends Close Button to Overlay.
			onClose: function(instance) {} // Callback After Overlay is hidden and content removed.
		}, options);

		function init(me){
			var $pane;

			$c = generate.overlay().hide().appendTo(o.context);
			$m = generate.mask().hide();
			$c.before($m);

			if (typeof o.flavor === "string") {
				$c.addClass(o.flavor);
				$m.addClass(o.flavor);
			} else if ($.isArray(o.flavor)) {
				$.each(o.flavor, function(i, flavor) {
					$c.addClass(flavor);
					$m.addClass(flavor);
				});
			}

			$pane = $c.find(">.tier > .tier > .pane");
			$elements = {
				pane: $pane,
				hd: $pane.children(".hd"),
				bd: $pane.children(".bd"),
				ft: $pane.children(".ft")
			};

			if (o.maskClick) {
				$c.bind("click", {instance:me, $pane:$elements.pane, allowPaneClick: true}, events.clickClose);
			}

			$c.bind("focus", {instance:me, escape:o.escape, $c:$c}, function(e) {
				$(window.document).bind("keydown.overlay", {instance:e.data.instance, escape:e.data.escape, $c:e.data.$c}, events.keydown);
			}).bind("blur", {instance:me}, function(e) {
				$(window.document).unbind("keydown.overlay", events.keydown);
			});

			open = false;
		}

		var events = {
			keydown: function(e) {
				var key;
				key = e.keyCode || e.which;
				switch (key) {
					case NI.co.keyboard.ESCAPE:
						if (e.data.escape === true) {
							e.data.instance.close();
						}
						break;
					case NI.co.keyboard.ENTER:
						e.data.$c.find(".button.ca").click();
						break;
				}
			},
			clickClose: function(e) {
				e.preventDefault();
				if (e.data.$pane && e.data.allowPaneClick) {
					if (!$.contains(e.data.$pane[0], e.target)) {
						e.data.instance.close();
					}
				} else {
					e.data.instance.close();
				}
			}
		};

		var generate = {
			overlay:function(){
				return $( '
\

\

\

\

\

\

\

\

\

\

\

' );
			},
			mask:function(){
				return $( '
\

' );
			},
			closeBtn:function(instance){
				var $btn;
				$btn = $( "Close" );
				if (instance) {
					$btn.bind("click", {instance:instance}, events.clickClose);
				}
				return $btn;
			}
		};

		this.flush = function() {
			$elements.hd.empty();
			$elements.bd.empty();
			$elements.ft.empty();
		};

		this.open = function(options) {
			var _o;
			_o = $.extend({
				hd:null,
				bd:null,
				ft:null
			},options);

			if (_o.hd) { $elements.hd.empty().append(_o.hd); }
			if (_o.bd) { $elements.bd.empty().append(_o.bd); }
			if (_o.ft) { $elements.ft.empty().append(_o.ft); }

			if (o.closeBtn && !($elements.hd.find(".btn-close").length)) {
				$elements.hd.append(generate.closeBtn(this));
			}

			$m.show();
			$c.show().scrollTop(0).focus();

			open = true;

			return this;
		};

		this.close = function() {
			if (!open) { return this; }
			$m.fadeOut();
			$c.hide().blur();
			if (o.autoflush === true) {
				this.flush();
			}
			open = false;
			if ($.isFunction(o.onClose)) {
				o.onClose(this);
			}
			return this;
		};

		this.destroy = function() {
			$c.blur().remove();
			$m.remove();
		};

		init(this);
	}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	NI.Overlay = Overlay;

}(this, this.jQuery));<commit_msg>fix in overlay click close handler<commit_after>/*    _____                    _____
     /\    \                  /\    \
    /::\    \                /::\    \
    \:::\    \              /::::\    \
     \:::\    \            /::::::\    \
      \:::\    \          /:::/\:::\    \
       \:::\    \        /:::/  \:::\    \
       /::::\    \      /:::/    \:::\    \
      /::::::\    \    /:::/    / \:::\    \
     /:::/\:::\    \  /:::/    /   \:::\    \
    /:::/  \:::\____\/:::/____/     \:::\____\
   /:::/    \::/    /\:::\    \      \::/    /
  /:::/    / \/____/  \:::\    \      \/____/
 /:::/    /            \:::\    \
/:::/    /              \:::\    \
\::/    /                \:::\    \
 \/____/                  \:::\    \
                           \:::\    \
                            \:::\____\
                             \::/    /
                              \/____/
                             TYPE/CODE
                         From 2010 till ∞     */

(function(window, $) {

	var NI = window.NI;

	function Overlay(options) {
		var o, $c, $m, open, $elements;

		o = $.extend({
			context: "body", // Selector to element where overlay will be inserted.
			autoflush: true, // If true, the Overlay automatically flushes its content when it is closed.
			flavor: null, // Additional classnames for Mask and Overlay.
			maskClick: true, // Hide Overlay if Mask is Clicked.
			maskFadeOutSpeed: 100, // Delay for mask Fade Out Animation.
			escape: true, //ESC Keypress closes Overlay.
			closeBtn: false, // Appends Close Button to Overlay.
			onClose: function(instance) {} // Callback After Overlay is hidden and content removed.
		}, options);

		function init(me){
			var $pane;

			$c = generate.overlay().hide().appendTo(o.context);
			$m = generate.mask().hide();
			$c.before($m);

			if (typeof o.flavor === "string") {
				$c.addClass(o.flavor);
				$m.addClass(o.flavor);
			} else if ($.isArray(o.flavor)) {
				$.each(o.flavor, function(i, flavor) {
					$c.addClass(flavor);
					$m.addClass(flavor);
				});
			}

			$pane = $c.find(">.tier > .tier > .pane");
			$elements = {
				pane: $pane,
				hd: $pane.children(".hd"),
				bd: $pane.children(".bd"),
				ft: $pane.children(".ft")
			};

			if (o.maskClick) {
				$c.bind("click", {instance:me, $pane:$elements.pane, allowPaneClick: true}, events.clickClose);
			}

			$c.bind("focus", {instance:me, escape:o.escape, $c:$c}, function(e) {
				$(window.document).bind("keydown.overlay", {instance:e.data.instance, escape:e.data.escape, $c:e.data.$c}, events.keydown);
			}).bind("blur", {instance:me}, function(e) {
				$(window.document).unbind("keydown.overlay", events.keydown);
			});

			open = false;
		}

		var events = {
			keydown: function(e) {
				var key;
				key = e.keyCode || e.which;
				switch (key) {
					case NI.co.keyboard.ESCAPE:
						if (e.data.escape === true) {
							e.data.instance.close();
						}
						break;
					case NI.co.keyboard.ENTER:
						e.data.$c.find(".button.ca").click();
						break;
				}
			},
			clickClose: function(e) {
				var pane;
				e.preventDefault();
				if (e.data.$pane && e.data.allowPaneClick) {
					pane = e.data.$pane[0];
					if (!$.contains(pane, e.target) && (pane != e.target)) {
						e.data.instance.close();
					}
				} else {
					e.data.instance.close();
				}
			}
		};

		var generate = {
			overlay:function(){
				return $( '
\

\

\

\

\

\

\

\

\

\

\

' );
			},
			mask:function(){
				return $( '
\

' );
			},
			closeBtn:function(instance){
				var $btn;
				$btn = $( "Close" );
				if (instance) {
					$btn.bind("click", {instance:instance}, events.clickClose);
				}
				return $btn;
			}
		};

		this.flush = function() {
			$elements.hd.empty();
			$elements.bd.empty();
			$elements.ft.empty();
		};

		this.open = function(options) {
			var _o;
			_o = $.extend({
				hd:null,
				bd:null,
				ft:null
			},options);

			if (_o.hd) { $elements.hd.empty().append(_o.hd); }
			if (_o.bd) { $elements.bd.empty().append(_o.bd); }
			if (_o.ft) { $elements.ft.empty().append(_o.ft); }

			if (o.closeBtn && !($elements.hd.find(".btn-close").length)) {
				$elements.hd.append(generate.closeBtn(this));
			}

			$m.show();
			$c.show().scrollTop(0).focus();

			open = true;

			return this;
		};

		this.close = function() {
			if (!open) { return this; }
			$m.fadeOut();
			$c.hide().blur();
			if (o.autoflush === true) {
				this.flush();
			}
			open = false;
			if ($.isFunction(o.onClose)) {
				o.onClose(this);
			}
			return this;
		};

		this.destroy = function() {
			$c.blur().remove();
			$m.remove();
		};

		init(this);
	}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	NI.Overlay = Overlay;

}(this, this.jQuery));<|endoftext|>


<commit_before>(function(module) {
    'use strict';

    module.controller('AppCtrl', ['$scope', '$location', '$window', 'angularPiwik', 'backendService', 'playerService',
        function($scope, $location, $window, angularPiwik, backendService, playerService) {
            $scope.goToView = function(view) {
                $scope.menuShown = false;
                $location.path(view);
            };

            // Expose some backend states and methods
            $scope.isLoggedIn = backendService.isLoggedIn;
            $scope.canViewGraph = backendService.canViewGraph;
            $scope.logout = backendService.logout;

            $scope.menuShown = false;

            // Reload the whole app when the session gets destroyed to clear all data
            $scope.$onRootScope('veganaut.session.destroyed', function() {
                $window.location.reload();
            });

            // Listen to route changes to track page views
            $scope.$onRootScope('$routeChangeSuccess', function() {
                angularPiwik.trackPageView();
            });

            // Get the logged in user data
            playerService.getMe().then(function(me) {
                $scope.me = me;
            });

            // Expose the activity verb method
            $scope.getActivityVerb = playerService.getActivityVerb;
        }
    ]);
})(window.veganaut.mainModule);
<commit_msg>Fixing exposed backendService methods on AppCtrl.<commit_after>(function(module) {
    'use strict';

    module.controller('AppCtrl', ['$scope', '$location', '$window', 'angularPiwik', 'backendService', 'playerService',
        function($scope, $location, $window, angularPiwik, backendService, playerService) {
            $scope.goToView = function(view) {
                $scope.menuShown = false;
                $location.path(view);
            };

            // Expose some backend states and methods
            $scope.isLoggedIn = backendService.isLoggedIn.bind(backendService);
            $scope.canViewGraph = backendService.canViewGraph.bind(backendService);
            $scope.logout = backendService.logout.bind(backendService);

            $scope.menuShown = false;

            // Reload the whole app when the session gets destroyed to clear all data
            $scope.$onRootScope('veganaut.session.destroyed', function() {
                $window.location.reload();
            });

            // Listen to route changes to track page views
            $scope.$onRootScope('$routeChangeSuccess', function() {
                angularPiwik.trackPageView();
            });

            // Get the logged in user data
            playerService.getMe().then(function(me) {
                $scope.me = me;
            });

            // Expose the activity verb method
            $scope.getActivityVerb = playerService.getActivityVerb;
        }
    ]);
})(window.veganaut.mainModule);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import Page from '../../containers/Page';
import TitleBar from '../../components/TitleBar';
import h from '../../utils/helpers';
import './Home.scss';

export default class Home extends Component {
  static propTypes = {
    entries: PropTypes.object.isRequired,
    sections: PropTypes.object.isRequired,
  };

  render() {
    const { entries } = this.props.entries;
    const { sections } = this.props.sections;
    const newEntries = [...entries].reverse().slice(0, 3);

    return (
      <Page name="home">
        <TitleBar title="Home" />

Recent Entries

                {newEntries.map(e =>

<Link to={`/admin/entries/${h.getSlugFromId(sections, e.section)}/${e._id}`}>{e.title}</Link>

                )}

      </Page>
    );
  }
}
<commit_msg>:wrench: Fix .isRequired errors<commit_after>import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import Page from '../../containers/Page';
import TitleBar from '../../components/TitleBar';
import h from '../../utils/helpers';
import './Home.scss';

export default class Home extends Component {
  static propTypes = {
    entries: PropTypes.object,
    sections: PropTypes.object,
  };

  static defaultTypes = {
    entries: null,
    sections: null,
  };

  render() {
    const { entries } = this.props.entries;
    const { sections } = this.props.sections;
    const newEntries = [...entries].reverse().slice(0, 3);

    return (
      <Page name="home">
        <TitleBar title="Home" />

Recent Entries

                {newEntries.map(e =>

<Link to={`/admin/entries/${h.getSlugFromId(sections, e.section)}/${e._id}`}>{e.title}</Link>

                )}

      </Page>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

class NeoCrawlError extends Error {

    constructor(data) {
        super();
        for (key of data) {
            this[key] = data;
        }
    }
}

module.exports = NeoCrawlError;<commit_msg>fix NeoCrawl to pass on error<commit_after>'use strict';

class NeoCrawlError extends Error {

    constructor(data) {
        super();
        const keys = Object.getOwnPropertyNames(data);

        keys.forEach((key) => {
            this[key] = data;
        });
    }
}

module.exports = NeoCrawlError;<|endoftext|>


<commit_before>var request = require('request');

return function (context, callback) {
    var required_params = ['twilio_auth_token', 'twilio_account_sid', 'to', 'from', 'message'];
    for (var p in required_params)
        if (!context.data[required_params[p]])
            return callback(new Error('The `' + required_params[p] + '` parameter must be provided.'));

    request({
        url: 'https://api.twilio.com/2010-04-01/Accounts/' + context.data.twilio_account_sid + '/Messages',
        method: 'POST',
        auth: {
            user: context.data.twilio_account_sid,
            pass: context.data.twilio_auth_token
        },
        form: {
            From: context.data.from,
            To: context.data.to,
            Body: context.data.message
        }
    }, function (error, res, body) {
        callback(error, body);
    });
}
<commit_msg>Update send_sms.js<commit_after>var request = require('request');

return function (context, callback) {
    var required_params = ['TWILIO_AUTH_TOKEN', 'TWILIO_ACCOUNT_SID', 'to', 'TWILIO_NUMBER', 'message'];
    for (var p in required_params)
        if (!context.data[required_params[p]])
            return callback(new Error('The `' + required_params[p] + '` parameter must be provided.'));

    request({
        url: 'https://api.twilio.com/2010-04-01/Accounts/' + context.data.TWILIO_ACCOUNT_SID + '/Messages',
        method: 'POST',
        auth: {
            user: context.data.TWILIO_ACCOUNT_SID,
            pass: context.data.TWILIO_AUTH_TOKEN
        },
        form: {
            From: context.data.TWILIO_NUMBER,
            To: context.data.to,
            Body: context.data.message
        }
    }, function (error, res, body) {
        callback(error, body);
    });
}
<|endoftext|>


<commit_before>/* eslint no-undef: 0 */
/**
  * @flow
 */
type Tuple<A, B> = [A, B];
type Tuple3<A, B, C> = [A, B, C];
type Tuple4<A, B, C, D> = [A, B, C, D];

type GetMemberEvent = '/api_get_member/deck'
                    | '/api_get_member/ship_deck';

// @todo Check if needed: Implement polymorphic type declarations to the incoming API data
// @todo Check if needed: Covariant parameter types for event data handlers
// declare type ApiEvent = GetMemberEvent;

// Declare common types used in the API data

/**
 * Base ship type
 */
declare type kcsapi$BaseShip = {
  api_afterbull: number,
  api_afterfuel: number,
  api_afterlv: number,
  api_aftershipid: string,
  api_backs: number,
  api_broken: Tuple4<number, number, number, number>,
  api_buildtime: number,
  api_bull_max: number,
  api_fuel_max: number,
  api_getmes: string,
  api_houg: Tuple<number, number>,
  api_id: number,
  api_leng: number,
  api_luck: Tuple<number, number>,
  api_maxeq: Array<number>,
  api_name: string,
  api_powup: Tuple4<number, number, number, number>,
  api_raig: Tuple<number, number>,
  api_slot_num: number,
  api_soku: number,
  api_sortno: number,
  api_souk: Tuple<number, number>,
  api_stype: number,
  api_taik: Tuple<number, number>,
  api_tyku: Tuple<number, number>,
  api_voicef: number,
  api_yomi: string
};

// Base equipment type
declare type kcsapi$BaseEquipmentType = {
  api_id: number,
  api_name: string,
  api_show_fig: number
};

// Base equipment
declare type kcsapi$BaseEquipment = {
  api_atap: number,
  api_bakk: number,
  api_baku: number,
  api_broken: Tuple4<number, number, number, number>,
  api_houg: number,
  api_houk: number,
  api_houm: number,
  api_id: number,
  api_info: string,
  api_leng: number,
  api_luck: number,
  api_name: string,
  api_raig: number,
  api_raik: number,
  api_raim: number,
  api_rare: number,
  api_sakb: number,
  api_saku: number,
  api_soku: number,
  api_sortno: number,
  api_souk: number,
  api_taik: number,
  api_tais: number,
  api_tyku: number,
  api_type: Array<number>,
  api_usebull: string
};

// Base ship type
declare type kcsapi$BaseShipType = {
  api_equip_type: { [key: string]: number },
  api_id: number,
  api_kcnt: number,
  api_name: string,
  api_scnt: number,
  api_sortno: number
};

declare type kcsapi$BaseMapArea = {
  api_id: number,
  api_name: string,
  api_type: number
};

// Player data
declare type kcsapi$Deck = {
  api_flagship: string,
  api_id: number,
  api_member_id: number,
  api_mission: Tuple4<number, number, number, number>,
  api_name: string,
  api_name_id: string,
  api_ship: Array<number>
};

declare type kcsapi$Ship = {
  api_backs: number,
  api_bull: number,
  api_cond: number,
  api_exp: Tuple3<number, number, number>,
  api_fuel: number,
  api_id: number,
  api_kaihi: Tuple<number, number>,
  api_karyoku: Tuple<number, number>,
  api_kyouka: Array<number>,
  api_leng: number,
  api_locked: number,
  api_locked_equip: number,
  api_lucky: Tuple<number, number>,
  api_lv: number,
  api_maxhp: number,
  api_ndock_item: Array<number>,
  api_ndock_time: number,
  api_nowhp: number,
  api_onslot: Array<number>,
  api_raisou: Tuple<number, number>,
  api_sakuteki: Tuple<number, number>,
  api_ship_id: number,
  api_slot: Array<number>,
  api_slot_ex: number,
  api_slotnum: number,
  api_soku: number,
  api_sortno: number,
  api_soukou: Tuple<number, number>,
  api_srate: number,
  api_taiku: Tuple<number, number>,
  api_taisen: Tuple<number, number>
};

// GetMemberEvents

// /api_get_member/ship_deck
declare type kcsapi$GetMember$ShipDeck = {
  api_deck_data: Array<kcsapi$Deck>,
  api_ship_data: Array<kcsapi$Ship>
};
<commit_msg>Add map area typedefs<commit_after>/* eslint no-undef: 0 */
/**
  * @flow
 */
type Tuple<A, B> = [A, B];
type Tuple3<A, B, C> = [A, B, C];
type Tuple4<A, B, C, D> = [A, B, C, D];

type GetMemberEvent = '/api_get_member/deck'
                    | '/api_get_member/ship_deck';

// @todo Check if needed: Implement polymorphic type declarations to the incoming API data
// @todo Check if needed: Covariant parameter types for event data handlers
// declare type ApiEvent = GetMemberEvent;

// Declare common types used in the API data

// Map area
declare type kcsapi$MapArea = {
  api_id: number,
  api_name: string,
  api_type: number
};

// Map info
declare type kcsapi$MapInfo = {
  api_id: number,
  api_infotext: string,
  api_item: Array<number>,
  api_level: number,
  api_maparea_id: number,
  api_max_maphp: *,
  api_name: string,
  api_no: number,
  api_opetext: string,
  api_required_defeat_count?: number,
  api_sally_flag: Tuple<number, number>
};

// Base ship type
declare type kcsapi$BaseShip = {
  api_afterbull: number,
  api_afterfuel: number,
  api_afterlv: number,
  api_aftershipid: string,
  api_backs: number,
  api_broken: Tuple4<number, number, number, number>,
  api_buildtime: number,
  api_bull_max: number,
  api_fuel_max: number,
  api_getmes: string,
  api_houg: Tuple<number, number>,
  api_id: number,
  api_leng: number,
  api_luck: Tuple<number, number>,
  api_maxeq: Array<number>,
  api_name: string,
  api_powup: Tuple4<number, number, number, number>,
  api_raig: Tuple<number, number>,
  api_slot_num: number,
  api_soku: number,
  api_sortno: number,
  api_souk: Tuple<number, number>,
  api_stype: number,
  api_taik: Tuple<number, number>,
  api_tyku: Tuple<number, number>,
  api_voicef: number,
  api_yomi: string
};

// Base equipment type
declare type kcsapi$BaseEquipmentType = {
  api_id: number,
  api_name: string,
  api_show_fig: number
};

// Base equipment
declare type kcsapi$BaseEquipment = {
  api_atap: number,
  api_bakk: number,
  api_baku: number,
  api_broken: Tuple4<number, number, number, number>,
  api_houg: number,
  api_houk: number,
  api_houm: number,
  api_id: number,
  api_info: string,
  api_leng: number,
  api_luck: number,
  api_name: string,
  api_raig: number,
  api_raik: number,
  api_raim: number,
  api_rare: number,
  api_sakb: number,
  api_saku: number,
  api_soku: number,
  api_sortno: number,
  api_souk: number,
  api_taik: number,
  api_tais: number,
  api_tyku: number,
  api_type: Array<number>,
  api_usebull: string
};

// Base ship type
declare type kcsapi$BaseShipType = {
  api_equip_type: { [key: string]: number },
  api_id: number,
  api_kcnt: number,
  api_name: string,
  api_scnt: number,
  api_sortno: number
};

declare type kcsapi$BaseMapArea = {
  api_id: number,
  api_name: string,
  api_type: number
};

// Player data
declare type kcsapi$Deck = {
  api_flagship: string,
  api_id: number,
  api_member_id: number,
  api_mission: Tuple4<number, number, number, number>,
  api_name: string,
  api_name_id: string,
  api_ship: Array<number>
};

declare type kcsapi$Ship = {
  api_backs: number,
  api_bull: number,
  api_cond: number,
  api_exp: Tuple3<number, number, number>,
  api_fuel: number,
  api_id: number,
  api_kaihi: Tuple<number, number>,
  api_karyoku: Tuple<number, number>,
  api_kyouka: Array<number>,
  api_leng: number,
  api_locked: number,
  api_locked_equip: number,
  api_lucky: Tuple<number, number>,
  api_lv: number,
  api_maxhp: number,
  api_ndock_item: Array<number>,
  api_ndock_time: number,
  api_nowhp: number,
  api_onslot: Array<number>,
  api_raisou: Tuple<number, number>,
  api_sakuteki: Tuple<number, number>,
  api_ship_id: number,
  api_slot: Array<number>,
  api_slot_ex: number,
  api_slotnum: number,
  api_soku: number,
  api_sortno: number,
  api_soukou: Tuple<number, number>,
  api_srate: number,
  api_taiku: Tuple<number, number>,
  api_taisen: Tuple<number, number>
};

// GetMemberEvents

// /api_get_member/ship_deck
declare type kcsapi$GetMember$ShipDeck = {
  api_deck_data: Array<kcsapi$Deck>,
  api_ship_data: Array<kcsapi$Ship>
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var app = require('commander')
var async = require('async')
var stdin = require('get-stdin')
var truncate = require('truncate')
var moment = require('moment')
var api = require('./util/api')
var getInbox = require('./util/get-inbox')

function parseDueDate(value) {
  if (/\d{4}\-\d{2}\-\d{2}/.test(value) === true) {
    return value
  }
  return false
}

app
  .description('Add a task to your inbox')
  .usage('[task]')
  .option('-l, --list [name]', 'Specify a list other than your inbox')
  .option('--today', 'Set the due date to today')
  .option('--tomorrow', 'Set the due date to tomorrow')
  .option('--due [date]', 'Set a specific due date', parseDueDate)
  .option('-s, --stdin', 'Create tasks from stdin')
  .parse(process.argv)

var due_date

if (app.today) {
  due_date = moment().format('YYYY-MM-DD')
}

if (app.tomorrow) {
  due_date = moment().add(1, 'day').format('YYYY-MM-DD')
}

if (app.due) {
  due_date = app.due
}

function truncateTitle (title) {
  return truncate(title.trim(), 254, {ellipsis: '…'})
}

function getListId (cb) {
  if (!app.list) {
    return getInbox(function (inbox) {
      cb(inbox.id)
    })
  }

  var list = {
    title: app.list.trim()
  }

  api.get('/lists', function (err, res, body) {
    if (err) process.exit(1)

    var existing = body.filter(function (item) {
      return item.title.toLowerCase().trim() === list.title.toLowerCase()
    })
    if (existing.length > 0) {
      return cb(existing[0].id)
    }
    api.post({url: '/lists', body: list}, function (err, res, body) {
      if (err) process.exit(1)

      cb(body.id)
    })
  })
}

if (typeof app.stdin === 'undefined') {
  var title = app.args.join(' ')

  if (!title) {
    process.exit(1)
  }

  async.waterfall([
    function (cb) {
      getListId(function (inbox_id) {
        cb(null, inbox_id)
      })
    },
    function (inbox_id, cb) {
      cb(null, {
        title: truncateTitle(title),
        list_id: inbox_id,
        due_date: due_date
      })
    },
    function (task, cb) {
      api.post({url: '/tasks', body: task}, function (err, res, body) {
        if (err || body.error) {
          console.log(err || body.error)
          process.exit(1)
        }
        cb(null, body)
      })
    }
  ], function (err, res) {
    if (err) {
      process.exit(1)
    }
    process.exit()
  })
}

if (app.stdin === true) {
  async.waterfall([
    function (cb) {
      stdin(function (data) {
        var sep = data.indexOf('\r\n') !== -1 ? '\r\n' : '\n'
        var lines = data.trim().split(sep)
        cb(null, lines)
      })
    },
    function (lines, cb) {
      getListId(function (list_id) {
        cb(null, list_id, lines)
      })
    },
    function (list_id, lines, cb) {
      var tasks = lines
        .filter(function (line) {
          return line.trim().length > 0
        })
        .map(function (line) {
          return {
            title: truncateTitle(line),
            due_date: due_date,
            list_id: list_id
          }
        })
      cb(null, tasks)
    }
  ], function (err, tasks) {
    if (err) {
      process.exit(1)
    }

    async.each(tasks, function (task, finished) {
      api.post({url: '/tasks', body: task}, function (err, res, body) {
        if (err || body.error) {
          console.log(err || body.error)
          process.exit(1)
        }
        process.stderr.write('.')
        finished()
      })
    }, function () {
      process.exit()
    })
  })
}
<commit_msg>adds --open option for adding tasks<commit_after>#!/usr/bin/env node

var app = require('commander')
var async = require('async')
var stdin = require('get-stdin')
var truncate = require('truncate')
var moment = require('moment')
var api = require('./util/api')
var getInbox = require('./util/get-inbox')
var opn = require('opn')
var config = require('./util/config')

function parseDueDate (value) {
  if (/\d{4}\-\d{2}\-\d{2}/.test(value) === true) {
    return value
  }
  return false
}

function openTask (task) {
  var web = 'https://www.wunderlist.com/#/tasks/' + task.id
  var mac = 'wunderlist://tasks/' + task.id
  if (config.platform === 'mac') return opn(mac)
  opn(web)
}

function openList (list) {
  var web = 'https://www.wunderlist.com/#/lists/' + list.id
  var mac = 'wunderlist://lists/' + list.id
  if (config.platform === 'mac') return opn(mac)
  opn(web)
}

app
  .description('Add a task to your inbox')
  .usage('[task]')
  .option('-l, --list [name]', 'Specify a list other than your inbox')
  .option('--today', 'Set the due date to today')
  .option('--tomorrow', 'Set the due date to tomorrow')
  .option('--due [date]', 'Set a specific due date', parseDueDate)
  .option('-o, --open', 'Open Wunderlist on completion')
  .option('-s, --stdin', 'Create tasks from stdin')
  .parse(process.argv)

var due_date

if (app.today) {
  due_date = moment().format('YYYY-MM-DD')
}

if (app.tomorrow) {
  due_date = moment().add(1, 'day').format('YYYY-MM-DD')
}

if (app.due) {
  due_date = app.due
}

function truncateTitle (title) {
  return truncate(title.trim(), 254, {ellipsis: '…'})
}

function getListId (cb) {
  if (!app.list) {
    return getInbox(function (inbox) {
      cb(inbox.id)
    })
  }

  var list = {
    title: app.list.trim()
  }

  api.get('/lists', function (err, res, body) {
    if (err) process.exit(1)

    var existing = body.filter(function (item) {
      return item.title.toLowerCase().trim() === list.title.toLowerCase()
    })
    if (existing.length > 0) {
      return cb(existing[0].id)
    }
    api.post({url: '/lists', body: list}, function (err, res, body) {
      if (err) process.exit(1)

      cb(body.id)
    })
  })
}

if (typeof app.stdin === 'undefined') {
  var title = app.args.join(' ')

  if (!title) {
    process.exit(1)
  }

  async.waterfall([
    function (cb) {
      getListId(function (inbox_id) {
        cb(null, inbox_id)
      })
    },
    function (inbox_id, cb) {
      cb(null, {
        title: truncateTitle(title),
        list_id: inbox_id,
        due_date: due_date
      })
    },
    function (task, cb) {
      api.post({url: '/tasks', body: task}, function (err, res, body) {
        if (err || body.error) {
          console.log(err || body.error)
          process.exit(1)
        }
        cb(null, body)
      })
    }
  ], function (err, res) {
    if (err) {
      process.exit(1)
    }
    if (app.open) {
      openTask(res)
    }
    process.exit()
  })
}

if (app.stdin === true) {
  async.waterfall([
    function (cb) {
      stdin(function (data) {
        var sep = data.indexOf('\r\n') !== -1 ? '\r\n' : '\n'
        var lines = data.trim().split(sep)
        cb(null, lines)
      })
    },
    function (lines, cb) {
      getListId(function (list_id) {
        cb(null, list_id, lines)
      })
    },
    function (list_id, lines, cb) {
      var tasks = lines
        .filter(function (line) {
          return line.trim().length > 0
        })
        .map(function (line) {
          return {
            title: truncateTitle(line),
            due_date: due_date,
            list_id: list_id
          }
        })
      cb(null, tasks)
    }
  ], function (err, tasks) {
    if (err) {
      process.exit(1)
    }

    async.each(tasks, function (task, finished) {
      api.post({url: '/tasks', body: task}, function (err, res, body) {
        if (err || body.error) {
          console.log(err || body.error)
          process.exit(1)
        }
        process.stderr.write('.')
        finished()
      })
    }, function () {
      if (app.open && tasks.length > 0) {
        openList({id: tasks[0].list_id})
      }

      process.exit()
    })
  })
}
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var fs = require('node-fs');
var log = require('../../lib/util/log.js');
var reportError = require('../util/reportError');
var gulp = require('gulp');
var exec = require('child_process').exec;
var Q = require('q');

function system(cmd) {
  var deferred = Q.defer();
  log('system: ' + cmd);
  exec(cmd, function (error, stdout, stderr) {

    if ((stdout || '').indexOf('nothing to commit, working directory clean') >= 0) {
      error = null;
    }

    if ((stderr || '').indexOf('remote origin already exists') >= 0) {
      error = null;
    }
    if ((stderr || '').indexOf('Couldn\'t find remote ref master') >= 0) {
      error = null;
    }
    if ((stderr || '').indexOf('ambiguous argument \'origin/master\': unknown revision or path not in the working tree.') >= 0) {
      error = null;
    }
    if ((stderr || '').indexOf('pathspec \'\' did not match any files') >= 0) {
      error = null;
    }

    if (error) {
      deferred.reject(new Error(error));
    } else {
      deferred.resolve();
    }
  });

  return deferred.promise;
}

module.exports = function (program, env) {

  /*
   * TODO: document what env has that may be useful to a plugin develoepr.
   *
   * toggle leverages https://www.npmjs.org/package/commander for it's commands
   * You can review it's API https://github.com/visionmedia/commander.js to extend toggle with your own commands.
   *
   */

  program
    .command('deploy')
    .description('TODO: fill in command description')
    .option('-p, --nopush', 'Do everything except push to the remote')
    .option('-c, --nocommit', 'Do everything except commit & push to the remote')
    .action(function (options) {

      var nocommit = options.nocommit;
      var nopush = options.nopush || nocommit;

      var deployDir = path.resolve(env.toggleConfig.paths.deploy);
      var sourceDir = env.toggleConfig.paths.source;
      var deployType = env.toggleConfig.deployType;
      var deployGit = env.toggleConfig.deployGitUrl;

      if (deployType === 'githubpages') {

        // var returnError = function () {
        //     process.chdir(cwd);
        // };

        var copyFiles = function () {
          var deferred = Q.defer();

          gulp.src(path.join(sourceDir, '**/*'))
            .pipe(gulp.dest(deployDir))
            .on('error', function (error) {
              deferred.reject(new Error(error));
            })
            .on('end', function () {
              deferred.resolve();
            });

          return deferred.promise;
        };

        // setup deploy folder.
        if (!fs.existsSync(deployDir)) {
          log('Deploy directory [' + deployDir + '] did not exist. Creating it...');
          fs.mkdirSync(deployDir, parseInt(777, 8), true);
        }

        var cwd = process.cwd();
        process.chdir(deployDir);

        // setup git.
        var promise;
        if (!fs.existsSync(path.join(deployDir, '.git'))) {
          promise = system('git init');
        } else {
          promise = Q.resolve();
        }

        promise
          .then(function () {
            return system('git remote add origin ' + deployGit);
          }).then(function () {
            return system('git fetch origin');
          }).then(function () {
            return system('git reset origin/master --hard');
          }).then(function () {
            return system('git rm --cached -r .');
          }).then(function () {
            return system('git clean -fd');
          }).then(function () {
            process.chdir(cwd);
            return copyFiles();
          }).then(function () {
            process.chdir(deployDir);
            return system('git add -A');
          }).then(function () {
            if (nocommit) {
              return Q.resolve();
            }
            return system('git commit -m \'Updated site: ' + (new Date()).toUTCString() + '\'');
          }).then(function () {
            if (nopush) {
              return Q.resolve();
            }
            return system('git push origin master');
          }).then(function () {
            process.chdir(cwd);
          }).fail(function (error) {
            process.chdir(cwd);
            reportError(error);
          });

      } else {
        throw 'Unknown deploy type [' + deployType + ']';
      }
    });
};
<commit_msg>fixed an issue deploying on a windows machine<commit_after>'use strict';
var path = require('path');
var fs = require('node-fs');
var log = require('../../lib/util/log.js');
var reportError = require('../util/reportError');
var gulp = require('gulp');
var exec = require('child_process').exec;
var Q = require('q');

function system(cmd) {
  var deferred = Q.defer();
  log('system: ' + cmd);
  exec(cmd, function (error, stdout, stderr) {

    if ((stdout || '').indexOf('nothing to commit, working directory clean') >= 0) {
      error = null;
    }

    if ((stderr || '').indexOf('remote origin already exists') >= 0) {
      error = null;
    }
    if ((stderr || '').indexOf('Couldn\'t find remote ref master') >= 0) {
      error = null;
    }
    if ((stderr || '').indexOf('ambiguous argument \'origin/master\': unknown revision or path not in the working tree.') >= 0) {
      error = null;
    }
    if ((stderr || '').indexOf('pathspec \'\' did not match any files') >= 0) {
      error = null;
    }

    if (error) {
      deferred.reject(new Error(error));
    } else {
      deferred.resolve();
    }
  });

  return deferred.promise;
}

module.exports = function (program, env) {

  /*
   * TODO: document what env has that may be useful to a plugin develoepr.
   *
   * toggle leverages https://www.npmjs.org/package/commander for it's commands
   * You can review it's API https://github.com/visionmedia/commander.js to extend toggle with your own commands.
   *
   */

  program
    .command('deploy')
    .description('TODO: fill in command description')
    .option('-p, --nopush', 'Do everything except push to the remote')
    .option('-c, --nocommit', 'Do everything except commit & push to the remote')
    .action(function (options) {

      var nocommit = options.nocommit;
      var nopush = options.nopush || nocommit;

      var deployDir = path.resolve(env.toggleConfig.paths.deploy);
      var sourceDir = env.toggleConfig.paths.source;
      var deployType = env.toggleConfig.deployType;
      var deployGit = env.toggleConfig.deployGitUrl;

      if (deployType === 'githubpages') {

        // var returnError = function () {
        //     process.chdir(cwd);
        // };

        var copyFiles = function () {
          var deferred = Q.defer();

          gulp.src(path.join(sourceDir, '**/*'))
            .pipe(gulp.dest(deployDir))
            .on('error', function (error) {
              deferred.reject(new Error(error));
            })
            .on('end', function () {
              deferred.resolve();
            });

          return deferred.promise;
        };

        // setup deploy folder.
        if (!fs.existsSync(deployDir)) {
          log('Deploy directory [' + deployDir + '] did not exist. Creating it...');
          fs.mkdirSync(deployDir, parseInt(777, 8), true);
        }

        var cwd = process.cwd();
        process.chdir(deployDir);

        // setup git.
        var promise;
        if (!fs.existsSync(path.join(deployDir, '.git'))) {
          promise = system('git init');
        } else {
          promise = Q.resolve();
        }

        promise
          .then(function () {
            return system('git remote add origin ' + deployGit);
          }).then(function () {
            return system('git fetch origin');
          }).then(function () {
            return system('git reset origin/master --hard');
          }).then(function () {
            return system('git rm --cached -r .');
          }).then(function () {
            return system('git clean -fd');
          }).then(function () {
            process.chdir(cwd);
            return copyFiles();
          }).then(function () {
            process.chdir(deployDir);
            return system('git add -A');
          }).then(function () {
            if (nocommit) {
              return Q.resolve();
            }
            if( /^win/.test(process.platform)) {
              return system('git commit -m "Updated site: ' + (new Date()).toUTCString() + '"');
            }
            return system('git commit -m \'Updated site: ' + (new Date()).toUTCString() + '\'');
          }).then(function () {
            if (nopush) {
              return Q.resolve();
            }
            return system('git push origin master');
          }).then(function () {
            process.chdir(cwd);
          }).fail(function (error) {
            process.chdir(cwd);
            reportError(error);
          });

      } else {
        throw 'Unknown deploy type [' + deployType + ']';
      }
    });
};
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'default',
      bower: {
        devDependencies: {}
      }
    },
    {
      name: 'ember-ember-data-2.11',
      npm: {
        devDependencies: {
          'ember-source': '2.11',
          'ember-data': '2.11',
          'ember-data-model-fragments': '2.11'
        }
      }
    },
    {
      name: 'ember-ember-data-release',
      bower: {
        devDependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'release'
        }
      }
    },
    {
      name: 'ember-ember-data-beta',
      bower: {
        devDependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'beta'
        }
      }
    },
    {
      name: 'ember-ember-data-canary',
      bower: {
        devDependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'canary'
        }
      }
    }
  ]
};
<commit_msg>fixing ci for 2.11<commit_after>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'default',
      bower: {
        devDependencies: {}
      }
    },
    {
      name: 'ember-ember-data-2.11',
      npm: {
        devDependencies: {
          'ember-source': '2.11',
          'ember-data': '2.11',
          'ember-data-model-fragments': '2.11',
          'ember-inflector': '1.9.4'
        }
      }
    },
    {
      name: 'ember-ember-data-release',
      bower: {
        devDependencies: {
          'ember': 'components/ember#release'
        },
        resolutions: {
          'ember': 'release'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'release'
        }
      }
    },
    {
      name: 'ember-ember-data-beta',
      bower: {
        devDependencies: {
          'ember': 'components/ember#beta'
        },
        resolutions: {
          'ember': 'beta'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'beta'
        }
      }
    },
    {
      name: 'ember-ember-data-canary',
      bower: {
        devDependencies: {
          'ember': 'components/ember#canary'
        },
        resolutions: {
          'ember': 'canary'
        }
      },
      npm: {
        devDependencies: {
          'ember-data': 'canary'
        }
      }
    }
  ]
};
<|endoftext|>


<commit_before><commit_msg>V3A19F8<commit_after><|endoftext|>


<commit_before>function drawAdventure(character) {
    var adventurer = character.adventurer;
    var context = mainContext;
    var cameraX = character.cameraX;
    context.clearRect(0, 0, mainCanvas.width, mainCanvas.height);
    var area = editingLevelInstance ? editingLevelInstance : character.area;
    var background = ifdefor(backgrounds[area.background], backgrounds.field);
    var cloudX = cameraX + character.time * .5;
    var fullDrawingWidth = Math.ceil(mainCanvas.width / 64) * 64 + 64;
    background.forEach(function(section) {
        var source = section.source;
        var y = ifdefor(section.y, 0);
        var height = ifdefor(section.height, 240 - y);
        var width = ifdefor(section.width, 64);
        var parallax = ifdefor(section.parallax, 1);
        var spacing = ifdefor(section.spacing, 1);
        var velocity = ifdefor(section.velocity, 0);
        var alpha = ifdefor(section.alpha, 1);
        context.globalAlpha = alpha;
        for (var i = 0; i <= fullDrawingWidth; i += 64 * spacing) {
            var x = (fullDrawingWidth + (i - (cameraX - character.time * velocity) * parallax) % fullDrawingWidth) % fullDrawingWidth - 64;
            context.drawImage(source.image, source.x, source.y, source.width, source.height,
                                  x, y, width, height);
        }
        context.globalAlpha = 1;
    });
    ifdefor(character.objects, []).forEach(function (object, index) {
        object.draw(context, object.x - cameraX, 240 - 128);
    });
    ifdefor(character.enemies, []).forEach(function (actor, index) {
        drawActor(character, actor, 1 + character.enemies.length - index)
    });
    drawActor(character, adventurer, 0);
    ifdefor(character.allies, []).forEach(function (actor, index) {
        if (actor == adventurer) return;
        drawActor(character, actor, -index)
    });
    // Draw text popups such as damage dealt, item points gained, and so on.
    context.fillStyle = 'red';
    for (var i = 0; i < ifdefor(character.treasurePopups, []).length; i++) {
        character.treasurePopups[i].draw(character);
    }
    for (var i = 0; i < ifdefor(character.projectiles, []).length; i++) {
        character.projectiles[i].draw(character);
    }
    for (var i = 0; i < ifdefor(character.effects, []).length; i++) {
        character.effects[i].draw(character);
    }
    for (var i = 0; i < ifdefor(character.textPopups, []).length; i++) {
        var textPopup = character.textPopups[i];
        context.fillStyle = ifdefor(textPopup.color, "red");
        context.font = ifdefor(textPopup.font, "20px sans-serif");
        context.textAlign = 'center'
        context.fillText(textPopup.value, textPopup.x - cameraX, textPopup.y);
    }
    drawMinimap(character);
}
function drawActor(character, actor, index) {
    mainContext.save();
    if (actor.personCanvas) {
        if (actor.isDead) {
            actor.animationTime = actor.timeOfDeath;
            mainContext.globalAlpha = 1 - (actor.time - actor.timeOfDeath);
        }
        drawAdventurer(character, actor, index);
    } else drawMonster(character, actor, index);
    mainContext.restore();
}
function drawMonster(character, monster, index) {
    if (!monster.image) {
        console.log("Found monster without an image. Last time this happened was because the -enchanged/-imbued version of the image was not being created at load time.");
        console.log(monster);
        return;
    }
    var cameraX = character.cameraX;
    var context = mainContext;
    var source = monster.base.source;
    var frame;
    context.save();
    if (monster.cloaked) {
        context.globalAlpha = .2;
    }
    monster.width = ifdefor(monster.width, source.width * 2 * ifdefor(monster.scale, 1));
    monster.height = ifdefor(monster.height, ifdefor(source.height, 64) * 2 * ifdefor(monster.scale, 1));
    monster.left = monster.x - cameraX;
    monster.top = 240 - monster.height - 72 - ifdefor(source.y, 0) * 2 * ifdefor(monster.scale, 1) - 2 * index;
    context.translate(monster.left + monster.width / 2, 0);
    if ((source.flipped && monster.direction < 0) || (!source.flipped && monster.direction > 0)) {
        context.scale(-1, 1);
    }

    if (monster.isDead && !ifdefor(source.deathFrames)) {
        monster.animationTime = monster.timeOfDeath;
        mainContext.globalAlpha = 1 - (monster.time - monster.timeOfDeath);
    }
    if (monster.pull) {
        frame = 0;
    } else if (monster.isDead && ifdefor(source.deathFrames)) {
        var deathFps = 1.5 * source.deathFrames.length;
        frame = Math.min(source.deathFrames.length - 1, Math.floor((monster.time - monster.timeOfDeath) * deathFps));
        frame = arrMod(source.deathFrames, frame);
    } else if (ifdefor(source.attackFrames) && monster.target && monster.lastAction && monster.lastAction.attackSpeed) { // attacking loop
        var attackFps = 1 / ((1 / monster.lastAction.attackSpeed) / source.attackFrames.length);
        var frame = Math.floor(Math.abs(monster.animationTime - monster.attackCooldown) * attackFps);
        frame = arrMod(source.attackFrames, frame);
    } else {
        var walkFps = ifdefor(monster.base.fpsMultiplier, 1) * 3 * monster.speed / 100;
        frame = Math.floor(monster.animationTime * walkFps);
        if (ifdefor(source.walkFrames)) frame = arrMod(source.walkFrames, frame);
        else frame = frame % source.frames;
    }
    var xFrame = frame;
    var yFrame = 0;
    // Some images wrap every N frames and will have framesPerRow set on the source.
    if (ifdefor(source.framesPerRow)) {
        xFrame = frame % source.framesPerRow;
        yFrame = Math.floor(frame / source.framesPerRow);
    }
    var frameSource = {'left': xFrame * source.width + source.offset, 'top': yFrame * ifdefor(source.height, 64), 'width': source.width, 'height': ifdefor(source.height, 64)};
    var target = {'left': -monster.width / 2, 'top': monster.top, 'width': monster.width, 'height': monster.height};
    if (ifdefor(monster.tint) && !(monster.slow > .3)) {
        drawTintedImage(context, monster.image, monster.tint, .2 + Math.cos(monster.animationTime * 5) / 10, frameSource, target);
    } else if (monster.slow > 0) {
        drawTintedImage(context, monster.image, '#fff', Math.min(1, monster.slow), frameSource, target);
    } else {
        context.drawImage(monster.image, frameSource.left, frameSource.top, frameSource.width, frameSource.height,
                                         target.left, target.top, target.width, target.height);
    }
    context.restore();
    // Uncomment to draw a reference of the character to show where left side of monster should be
    // context.drawImage(character.personCanvas, 0 * 32, 0 , 32, 64, monster.x - cameraX, 240 - 128 - 72, 64, 128);
    //context.fillRect(monster.x - cameraX, 240 - 128 - 72, 64, 128);
    // life bar
    if (monster.isDead) return;
    drawBar(context, monster.x - cameraX + monster.width / 2 - 32, 240 - 128 - 36 - 2 * index - ifdefor(source.y, 0) * 2, 64, 4, 'white', ifdefor(monster.color, 'red'), monster.health / monster.maxHealth);
    if (ifdefor(monster.reflectBarrier, 0)) {
        drawBar(context, monster.x - cameraX + monster.width / 2 - 32, 240 - 128 - 36 - 2 * index - 2 - ifdefor(source.y, 0) * 2, 64, 4, 'white', 'blue', monster.reflectBarrier / monster.maxReflectBarrier);
    }
}
function drawAdventurer(character, adventurer, index) {
    var cameraX = character.cameraX;
    adventurer.left = adventurer.x - cameraX;
    adventurer.top = 240 - 128 - 72 - 2 * index;
    adventurer.width = 64;
    adventurer.height = 128;
    //draw character
    if (adventurer.target && adventurer.lastAction && adventurer.lastAction.attackSpeed) { // attacking loop
        var attackSpeed = adventurer.lastAction.attackSpeed;
        var attackFps = 1 / ((1 / attackSpeed) / fightLoop.length);
        var frame = Math.floor(Math.abs(adventurer.animationTime - adventurer.attackCooldown) * attackFps) % fightLoop.length;
        if (adventurer.slow > 0) {
            drawTintedImage(mainContext, adventurer.personCanvas, '#fff', Math.min(1, adventurer.slow),
                        {'left': fightLoop[frame] * 32, 'top': 0 , 'width': 32, 'height': 64},
                        {'left': adventurer.x - cameraX, 'top': 240 - 128 - 72, 'width': 64, 'height': 128});
        } else {
            mainContext.drawImage(adventurer.personCanvas, fightLoop[frame] * 32, 0 , 32, 64,
                            adventurer.x - cameraX, 240 - 128 - 72, 64, 128);
        }
    } else { // walking loop
        if (adventurer.cloaked) {
            mainContext.globalAlpha = .2;
        }
        var fps = Math.floor(3 * adventurer.speed / 100);
        var frame = Math.floor(adventurer.animationTime * fps) % walkLoop.length;
        if (adventurer.pull || adventurer.stunned) {
            frame = 0;
        }
        if (adventurer.slow > 0) {
            drawTintedImage(mainContext, adventurer.personCanvas, '#fff', Math.min(1, adventurer.slow),
                        {'left': walkLoop[frame] * 32, 'top': 0 , 'width': 32, 'height': 64},
                        {'left': adventurer.x - cameraX, 'top': 240 - 128 - 72, 'width': 64, 'height': 128});
        } else {
            mainContext.drawImage(adventurer.personCanvas, walkLoop[frame] * 32, 0 , 32, 64,
                        adventurer.x - cameraX, 240 - 128 - 72, 64, 128);
        }
    }
    //mainContext.fillRect(adventurer.x - cameraX, 240 - 128 - 72, 64, 128);
    // life bar
    if (adventurer.isDead) return;
    drawBar(mainContext, adventurer.x - cameraX, 240 - 128 - 36 - 2 * index, 64, 4, 'white', 'red', adventurer.health / adventurer.maxHealth);
    if (ifdefor(adventurer.reflectBarrier, 0)) {
        drawBar(mainContext, adventurer.x - cameraX, 240 - 128 - 36 - 2 * index - 2, 64, 4, 'white', 'blue', adventurer.reflectBarrier / adventurer.maxReflectBarrier);
    }
}
function drawMinimap(character) {
    var y = 270 - 20;
    var height = 6;
    var x = 10;
    var width = 750;
    var context = mainContext;
    var area = editingLevelInstance ? editingLevelInstance : character.area;
    context.fillStyle = 'black';
    context.fillRect(0, 240, mainCanvas.width, 30);
    drawBar(context, x, y, width, height, 'white', 'white', character.waveIndex / area.waves.length);
    for (var i = 0; i < area.waves.length; i++) {
        var centerX = x + (i + 1) * width / area.waves.length;
        var centerY = y + height / 2;
        context.fillStyle = 'white';
        context.beginPath();
            context.arc(centerX, centerY, 11, 0, 2 * Math.PI);
        context.fill();
    }
    context.fillStyle = 'orange';
    context.fillRect(x + 1, y + 1, (width - 2) * (character.waveIndex / area.waves.length) - 10, height - 2);
    for (var i = 0; i < area.waves.length; i++) {
        var centerX = x + (i + 1) * width / area.waves.length;
        var centerY = y + height / 2;
        if (i < character.waveIndex) {
            context.fillStyle = 'orange';
            context.beginPath();
            context.arc(centerX, centerY, 10, 0, 2 * Math.PI);
            context.fill();
        }
        var waveCompleted = (i < character.waveIndex - 1)  || (i <= character.waveIndex - 1 && (ifdefor(character.enemies, []).length + ifdefor(character.objects, []).length) === 0);
        area.waves[i].draw(context, waveCompleted, centerX, centerY);
    }
}<commit_msg>Don't allow units to use index higher than 9. Just let enemies overlap in that case.<commit_after>var maxIndex = 9;
function drawAdventure(character) {
    var adventurer = character.adventurer;
    var context = mainContext;
    var cameraX = character.cameraX;
    context.clearRect(0, 0, mainCanvas.width, mainCanvas.height);
    var area = editingLevelInstance ? editingLevelInstance : character.area;
    var background = ifdefor(backgrounds[area.background], backgrounds.field);
    var cloudX = cameraX + character.time * .5;
    var fullDrawingWidth = Math.ceil(mainCanvas.width / 64) * 64 + 64;
    background.forEach(function(section) {
        var source = section.source;
        var y = ifdefor(section.y, 0);
        var height = ifdefor(section.height, 240 - y);
        var width = ifdefor(section.width, 64);
        var parallax = ifdefor(section.parallax, 1);
        var spacing = ifdefor(section.spacing, 1);
        var velocity = ifdefor(section.velocity, 0);
        var alpha = ifdefor(section.alpha, 1);
        context.globalAlpha = alpha;
        for (var i = 0; i <= fullDrawingWidth; i += 64 * spacing) {
            var x = (fullDrawingWidth + (i - (cameraX - character.time * velocity) * parallax) % fullDrawingWidth) % fullDrawingWidth - 64;
            context.drawImage(source.image, source.x, source.y, source.width, source.height,
                                  x, y, width, height);
        }
        context.globalAlpha = 1;
    });
    ifdefor(character.objects, []).forEach(function (object, index) {
        object.draw(context, object.x - cameraX, 240 - 128);
    });
    ifdefor(character.enemies, []).forEach(function (actor, index) {
        drawActor(character, actor, 1 + character.enemies.length - index)
    });
    drawActor(character, adventurer, 0);
    ifdefor(character.allies, []).forEach(function (actor, index) {
        if (actor == adventurer) return;
        drawActor(character, actor, -index)
    });
    // Draw text popups such as damage dealt, item points gained, and so on.
    context.fillStyle = 'red';
    for (var i = 0; i < ifdefor(character.treasurePopups, []).length; i++) {
        character.treasurePopups[i].draw(character);
    }
    for (var i = 0; i < ifdefor(character.projectiles, []).length; i++) {
        character.projectiles[i].draw(character);
    }
    for (var i = 0; i < ifdefor(character.effects, []).length; i++) {
        character.effects[i].draw(character);
    }
    for (var i = 0; i < ifdefor(character.textPopups, []).length; i++) {
        var textPopup = character.textPopups[i];
        context.fillStyle = ifdefor(textPopup.color, "red");
        context.font = ifdefor(textPopup.font, "20px sans-serif");
        context.textAlign = 'center'
        context.fillText(textPopup.value, textPopup.x - cameraX, textPopup.y);
    }
    drawMinimap(character);
}
function drawActor(character, actor, index) {
    mainContext.save();
    if (actor.personCanvas) {
        if (actor.isDead) {
            actor.animationTime = actor.timeOfDeath;
            mainContext.globalAlpha = 1 - (actor.time - actor.timeOfDeath);
        }
        drawAdventurer(character, actor, index);
    } else drawMonster(character, actor, index);
    mainContext.restore();
}
function drawMonster(character, monster, index) {
    if (!monster.image) {
        console.log("Found monster without an image. Last time this happened was because the -enchanged/-imbued version of the image was not being created at load time.");
        console.log(monster);
        return;
    }
    var cameraX = character.cameraX;
    var context = mainContext;
    var source = monster.base.source;
    var frame;
    context.save();
    if (monster.cloaked) {
        context.globalAlpha = .2;
    }
    monster.width = ifdefor(monster.width, source.width * 2 * ifdefor(monster.scale, 1));
    monster.height = ifdefor(monster.height, ifdefor(source.height, 64) * 2 * ifdefor(monster.scale, 1));
    monster.left = monster.x - cameraX;
    monster.top = 240 - monster.height - 72 - ifdefor(source.y, 0) * 2 * ifdefor(monster.scale, 1) - 2 * (index % maxIndex);
    context.translate(monster.left + monster.width / 2, 0);
    if ((source.flipped && monster.direction < 0) || (!source.flipped && monster.direction > 0)) {
        context.scale(-1, 1);
    }

    if (monster.isDead && !ifdefor(source.deathFrames)) {
        monster.animationTime = monster.timeOfDeath;
        mainContext.globalAlpha = 1 - (monster.time - monster.timeOfDeath);
    }
    if (monster.pull) {
        frame = 0;
    } else if (monster.isDead && ifdefor(source.deathFrames)) {
        var deathFps = 1.5 * source.deathFrames.length;
        frame = Math.min(source.deathFrames.length - 1, Math.floor((monster.time - monster.timeOfDeath) * deathFps));
        frame = arrMod(source.deathFrames, frame);
    } else if (ifdefor(source.attackFrames) && monster.target && monster.lastAction && monster.lastAction.attackSpeed) { // attacking loop
        var attackFps = 1 / ((1 / monster.lastAction.attackSpeed) / source.attackFrames.length);
        var frame = Math.floor(Math.abs(monster.animationTime - monster.attackCooldown) * attackFps);
        frame = arrMod(source.attackFrames, frame);
    } else {
        var walkFps = ifdefor(monster.base.fpsMultiplier, 1) * 3 * monster.speed / 100;
        frame = Math.floor(monster.animationTime * walkFps);
        if (ifdefor(source.walkFrames)) frame = arrMod(source.walkFrames, frame);
        else frame = frame % source.frames;
    }
    var xFrame = frame;
    var yFrame = 0;
    // Some images wrap every N frames and will have framesPerRow set on the source.
    if (ifdefor(source.framesPerRow)) {
        xFrame = frame % source.framesPerRow;
        yFrame = Math.floor(frame / source.framesPerRow);
    }
    var frameSource = {'left': xFrame * source.width + source.offset, 'top': yFrame * ifdefor(source.height, 64), 'width': source.width, 'height': ifdefor(source.height, 64)};
    var target = {'left': -monster.width / 2, 'top': monster.top, 'width': monster.width, 'height': monster.height};
    if (ifdefor(monster.tint) && !(monster.slow > .3)) {
        drawTintedImage(context, monster.image, monster.tint, .2 + Math.cos(monster.animationTime * 5) / 10, frameSource, target);
    } else if (monster.slow > 0) {
        drawTintedImage(context, monster.image, '#fff', Math.min(1, monster.slow), frameSource, target);
    } else {
        context.drawImage(monster.image, frameSource.left, frameSource.top, frameSource.width, frameSource.height,
                                         target.left, target.top, target.width, target.height);
    }
    context.restore();
    // Uncomment to draw a reference of the character to show where left side of monster should be
    // context.drawImage(character.personCanvas, 0 * 32, 0 , 32, 64, monster.x - cameraX, 240 - 128 - 72, 64, 128);
    //context.fillRect(monster.x - cameraX, 240 - 128 - 72, 64, 128);
    // life bar
    if (monster.isDead) return;
    drawBar(context, monster.x - cameraX + monster.width / 2 - 32, 240 - 128 - 36 - 2 * (index % maxIndex) - ifdefor(source.y, 0) * 2, 64, 4, 'white', ifdefor(monster.color, 'red'), monster.health / monster.maxHealth);
    if (ifdefor(monster.reflectBarrier, 0)) {
        drawBar(context, monster.x - cameraX + monster.width / 2 - 32, 240 - 128 - 36 - 2 * (index % maxIndex) - 2 - ifdefor(source.y, 0) * 2, 64, 4, 'white', 'blue', monster.reflectBarrier / monster.maxReflectBarrier);
    }
}
function drawAdventurer(character, adventurer, index) {
    var cameraX = character.cameraX;
    adventurer.left = adventurer.x - cameraX;
    adventurer.top = 240 - 128 - 72 - 2 * (index % maxIndex);
    adventurer.width = 64;
    adventurer.height = 128;
    //draw character
    if (adventurer.target && adventurer.lastAction && adventurer.lastAction.attackSpeed) { // attacking loop
        var attackSpeed = adventurer.lastAction.attackSpeed;
        var attackFps = 1 / ((1 / attackSpeed) / fightLoop.length);
        var frame = Math.floor(Math.abs(adventurer.animationTime - adventurer.attackCooldown) * attackFps) % fightLoop.length;
        if (adventurer.slow > 0) {
            drawTintedImage(mainContext, adventurer.personCanvas, '#fff', Math.min(1, adventurer.slow),
                        {'left': fightLoop[frame] * 32, 'top': 0 , 'width': 32, 'height': 64},
                        {'left': adventurer.x - cameraX, 'top': 240 - 128 - 72, 'width': 64, 'height': 128});
        } else {
            mainContext.drawImage(adventurer.personCanvas, fightLoop[frame] * 32, 0 , 32, 64,
                            adventurer.x - cameraX, 240 - 128 - 72, 64, 128);
        }
    } else { // walking loop
        if (adventurer.cloaked) {
            mainContext.globalAlpha = .2;
        }
        var fps = Math.floor(3 * adventurer.speed / 100);
        var frame = Math.floor(adventurer.animationTime * fps) % walkLoop.length;
        if (adventurer.pull || adventurer.stunned) {
            frame = 0;
        }
        if (adventurer.slow > 0) {
            drawTintedImage(mainContext, adventurer.personCanvas, '#fff', Math.min(1, adventurer.slow),
                        {'left': walkLoop[frame] * 32, 'top': 0 , 'width': 32, 'height': 64},
                        {'left': adventurer.x - cameraX, 'top': 240 - 128 - 72, 'width': 64, 'height': 128});
        } else {
            mainContext.drawImage(adventurer.personCanvas, walkLoop[frame] * 32, 0 , 32, 64,
                        adventurer.x - cameraX, 240 - 128 - 72, 64, 128);
        }
    }
    //mainContext.fillRect(adventurer.x - cameraX, 240 - 128 - 72, 64, 128);
    // life bar
    if (adventurer.isDead) return;
    drawBar(mainContext, adventurer.x - cameraX, 240 - 128 - 36 - 2 * (index % maxIndex), 64, 4, 'white', 'red', adventurer.health / adventurer.maxHealth);
    if (ifdefor(adventurer.reflectBarrier, 0)) {
        drawBar(mainContext, adventurer.x - cameraX, 240 - 128 - 36 - 2 * (index % maxIndex) - 2, 64, 4, 'white', 'blue', adventurer.reflectBarrier / adventurer.maxReflectBarrier);
    }
}
function drawMinimap(character) {
    var y = 270 - 20;
    var height = 6;
    var x = 10;
    var width = 750;
    var context = mainContext;
    var area = editingLevelInstance ? editingLevelInstance : character.area;
    context.fillStyle = 'black';
    context.fillRect(0, 240, mainCanvas.width, 30);
    drawBar(context, x, y, width, height, 'white', 'white', character.waveIndex / area.waves.length);
    for (var i = 0; i < area.waves.length; i++) {
        var centerX = x + (i + 1) * width / area.waves.length;
        var centerY = y + height / 2;
        context.fillStyle = 'white';
        context.beginPath();
            context.arc(centerX, centerY, 11, 0, 2 * Math.PI);
        context.fill();
    }
    context.fillStyle = 'orange';
    context.fillRect(x + 1, y + 1, (width - 2) * (character.waveIndex / area.waves.length) - 10, height - 2);
    for (var i = 0; i < area.waves.length; i++) {
        var centerX = x + (i + 1) * width / area.waves.length;
        var centerY = y + height / 2;
        if (i < character.waveIndex) {
            context.fillStyle = 'orange';
            context.beginPath();
            context.arc(centerX, centerY, 10, 0, 2 * Math.PI);
            context.fill();
        }
        var waveCompleted = (i < character.waveIndex - 1)  || (i <= character.waveIndex - 1 && (ifdefor(character.enemies, []).length + ifdefor(character.objects, []).length) === 0);
        area.waves[i].draw(context, waveCompleted, centerX, centerY);
    }
}<|endoftext|>


<commit_before>'use strict'
require('./check-versions')()

const config = require('../config')
if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}

const opn = require('opn')
const path = require('path')
const express = require('express')
const webpack = require('webpack')
const proxyMiddleware = require('http-proxy-middleware')
const webpackConfig = require('./webpack.dev.conf')

// default port where dev server listens for incoming traffic
const port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
const autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
const proxyTable = config.dev.proxyTable

const app = express()
const compiler = webpack(webpackConfig)

const devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  quiet: true
})

const hotMiddleware = require('webpack-hot-middleware')(compiler, {
  log: false,
  heartbeat: 2000
})
// force page reload when html-webpack-plugin template changes
// currently disabled until this is resolved:
// https://github.com/jantimon/html-webpack-plugin/issues/680
// compiler.plugin('compilation', function (compilation) {
//   compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
//     hotMiddleware.publish({ action: 'reload' })
//     cb()
//   })
// })

// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)

// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
  let options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(options.filter || context, options))
})

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
app.use(devMiddleware)

// serve pure static assets
const staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static'))

const uri = 'http://localhost:' + port

var _resolve
var _reject
var readyPromise = new Promise((resolve, reject) => {
  _resolve = resolve
  _reject = reject
})

var server
var portfinder = require('portfinder')
portfinder.basePort = port

console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
  portfinder.getPort((err, port) => {
    if (err) {
      _reject(err)
    }
    process.env.PORT = port
    var uri = 'http://localhost:' + port
    console.log('> Listening at ' + uri + '\n')
    // when env is testing, don't need open it
    if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
      opn(uri)
    }
    server = app.listen(port)
    _resolve()
  })
})

module.exports = {
  ready: readyPromise,
  close: () => {
    server.close()
  }
}
<commit_msg>Load the favicon<commit_after>'use strict'
require('./check-versions')()

const config = require('../config')
if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}

const opn = require('opn')
const path = require('path')
const express = require('express')
const webpack = require('webpack')
const proxyMiddleware = require('http-proxy-middleware')
const webpackConfig = require('./webpack.dev.conf')

// default port where dev server listens for incoming traffic
const port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
const autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
const proxyTable = config.dev.proxyTable

const app = express()
const compiler = webpack(webpackConfig)

const devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  quiet: true
})

const hotMiddleware = require('webpack-hot-middleware')(compiler, {
  log: false,
  heartbeat: 2000
})
// force page reload when html-webpack-plugin template changes
// currently disabled until this is resolved:
// https://github.com/jantimon/html-webpack-plugin/issues/680
// compiler.plugin('compilation', function (compilation) {
//   compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
//     hotMiddleware.publish({ action: 'reload' })
//     cb()
//   })
// })

// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)

// load the favicon
app.use('/favicon.ico', express.static(__dirname + '/../favicon.ico'));

// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
  let options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(options.filter || context, options))
})

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
app.use(devMiddleware)

// serve pure static assets
const staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static'))

const uri = 'http://localhost:' + port

var _resolve
var _reject
var readyPromise = new Promise((resolve, reject) => {
  _resolve = resolve
  _reject = reject
})

var server
var portfinder = require('portfinder')
portfinder.basePort = port

console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
  portfinder.getPort((err, port) => {
    if (err) {
      _reject(err)
    }
    process.env.PORT = port
    var uri = 'http://localhost:' + port
    console.log('> Listening at ' + uri + '\n')
    // when env is testing, don't need open it
    if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
      opn(uri)
    }
    server = app.listen(port)
    _resolve()
  })
})

module.exports = {
  ready: readyPromise,
  close: () => {
    server.close()
  }
}
<|endoftext|>