<commit_before>var assert = require('assert');
var fs = require('fs-extra');
var Tree = require('./utils/builder');
var watch = require('../');

var tree = Tree();
var watcher;

beforeEach(function(done) {
  tree = Tree();
  if (watcher) watcher.close();
  setTimeout(done, 500);
});

after(function() {
  tree && tree.cleanup()
});

describe('watch for files', function() {
  it('should watch a single file and keep watching', function(done) {
    this.timeout(3000);
    var times = 1;
    var file = 'home/a/file1';
    var fpath = tree.getPath(file);
    watcher = watch(fpath, function(evt, name) {
      assert.equal(fpath, name)
      if (times++ >= 3) {
        done();
      }
    });
    tree.modify(file, 100);
    tree.modify(file, 500);
    tree.modify(file, 900);
  });

  it('should watch files inside a directory', function(done) {
    var dir = 'home/a';
    var fpath = tree.getPath('home/a');
    var stack = [
      tree.getPath('home/a/file1'),
      tree.getPath('home/a/file2')
    ];
    watcher = watch(fpath, function(evt, name) {
      stack.splice(stack.indexOf(name), 1);
      if (!stack.length) done();
    });

    tree.modify('home/a/file1', 200);
    tree.modify('home/a/file2', 300);
  });

  it('should ignore duplicate changes', function(done) {
    var file = 'home/a/file2';
    var fpath = tree.getPath(file);
    var times = 0;
    watcher = watch(fpath, function(evt, name) {
      if (fpath == name) times++;
      setTimeout(function() {
        assert(times == 1)
        done();
      }, 200);
    });
    tree.modify(file);
    tree.modify(file);
    tree.modify(file);
  });

});

describe('watch for directoies', function() {

  it('should watch directories inside a directory', function(done) {
    var home = tree.getPath('home');
    var dir = tree.getPath('home/c');

    watcher = watch(home, { recursive: true }, function(evt, name) {
      assert.equal(dir, name);
      done();
    });

    tree.remove('home/c', 300);
  });

  it('should watch new created directories', function(done) {
    var home = tree.getPath('home');
    watcher = watch(home, { recursive: true }, function(evt, name) {
      if (name == tree.getPath('home/new/file1')) {
        done();
      }
    });
    tree.newFile('home/new/file1', 100);
    tree.modify('home/new/file1', 400);
  });
});

describe('events', function() {
  it('should identify `remove` event', function(done) {
    var file = 'home/a/file1';
    var fpath = tree.getPath(file);
    watcher = watch(fpath, function(evt, name) {
      if (evt == 'remove' && name == fpath) done();
    });
    tree.remove(file, 100);
  });

  it('should identify `update` event', function(done) {
    var file = 'home/a/file1';
    var fpath = tree.getPath(file);
    watcher = watch(fpath, function(evt, name) {
      if (evt == 'update' && name == fpath) done();
    });
    tree.modify(file, 100);
  });

  it('should report `update` on new files', function(done) {
    var dir = tree.getPath('home/a');
    var file = 'home/a/newfile' + Date.now();
    var fpath = tree.getPath(file);
    watcher = watch(dir, function(evt, name) {
      if (evt == 'update' && name == fpath) done();
    });
    tree.newFile(file);
  });

});

describe('options', function() {
  describe('recursive', function() {
    it('should watch recursively with `recursive: true` option', function(done) {
      var dir = tree.getPath('home');
      var file = tree.getPath('home/bb/file1');
      watcher = watch(dir, { recursive: true }, function(evt, name) {
        assert.equal(file, name);
        done();
      });
      tree.modify('home/bb/file1', 200);
    });
  });

  describe('encoding', function() {
    it('should throw on invalid encoding', function(done) {
      var dir = tree.getPath('home/a');
      try {
        watcher = watch(dir, 'unknown');
      } catch (e) {
        done();
      }
    });

    it('should accept options as an encoding string', function(done) {
      var dir = tree.getPath('home/a');
      var file = 'home/a/file1';
      var fpath = tree.getPath(file);
      watcher = watch(dir, 'utf8', function(evt, name) {
        assert(name.toString() === fpath);
        done();
      });
      tree.modify(file, 200);
    });

    it('should support buffer encoding', function(done) {
      var dir = tree.getPath('home/a');
      var file = 'home/a/file1';
      var fpath = tree.getPath(file);
      watcher = watch(dir, 'buffer', function(evt, name) {
        assert(Buffer.isBuffer(name), 'not a Buffer')
        assert(name.toString() === fpath);
        done();
      });
      tree.modify(file, 200);
    });

    it('should support base64 encoding', function(done) {
      var dir = tree.getPath('home/a');
      var file = 'home/a/file1';
      var fpath = tree.getPath(file);
      watcher = watch(dir, 'base64', function(evt, name) {
        assert(
          name === (Buffer.from ? Buffer.from(fpath) : new Buffer(fpath)).toString('base64'),
          'wrong base64 encoding'
        );
        done();
      });
      tree.modify(file, 200);
    });

    it('should support hex encoding', function(done) {
      var dir = tree.getPath('home/a');
      var file = 'home/a/file1';
      var fpath = tree.getPath(file);
      watcher = watch(dir, 'hex', function(evt, name) {
        assert(
          name === (Buffer.from ? Buffer.from(fpath) : new Buffer(fpath)).toString('hex'),
          'wrong hex encoding'
        );
        done();
      });
      tree.modify(file, 200);
    });
  });

  describe('filter', function() {
    it('should only watch filtered directories', function(done) {
      var shouldModify = true;
      var shouldNotModify = false;

      var option = {
        recursive: true,
        filter: function(name) {
          return !/node_modules/.test(name);
        }
      };

      watcher = watch(tree.getPath('home'), option, function(evt, name) {
        if (/node_modules/.test(name)) {
          shouldNotModify = true;
        } else {
          shouldModify = false;
        }
      });

      tree.modify('home/b/file1', 200);
      tree.modify('home/node_modules/ma/file1', 500);

      setTimeout(function() {
        assert(!shouldModify, 'watch failed');
        assert(!shouldNotModify, 'fail to ingore path `node_modules`');
        done();
      }, 900);
    });

    it('should only report filtered files', function(done) {
      var dir = tree.getPath('home/a');
      var file1 = 'home/a/file1';
      var file2 = 'home/a/file2';

      var options = {
        filter: function(name) {
          return !/file1/.test(name);
        }
      }

      var times = 0;
      watcher = watch(dir, options, function(evt, name) {
        times++;
        if (name == tree.getPath(file2)) {
          assert(times, 1, 'home/a/file1 should be ignored.');
          done();
        }
      });

      tree.modify(file1, 200);
      tree.modify(file2, 400);
    });

    it('should be able to filter with regexp', function(done) {
      var dir = tree.getPath('home/a');
      var file1 = 'home/a/file1';
      var file2 = 'home/a/file2';

      var options = {
        filter:  /file2/
      }

      var times = 0;
      watcher = watch(dir, options, function(evt, name) {
        times++;
        if (name == tree.getPath(file2)) {
          assert(times, 1, 'home/a/file1 should be ignored.');
          done();
        }
      });

      tree.modify(file1, 200);
      tree.modify(file2, 400);
    });

  });
});

describe('parameters', function() {

  it('should throw error on non-existed file', function(done) {
    var somedir = tree.getPath('home/somedir');
    try {
      watcher = watch(somedir);
    } catch(err) {
      done();
    }
  });

  it('should accept filename as Buffer', function(done) {
    var fpath = tree.getPath('home/a/file1');
    watcher = watch(new Buffer(fpath), function(evt, name) {
      assert(name == fpath);
      done();
    });
    tree.modify('home/a/file1', 100);
  });

  it('should compose array of files or directories', function(done) {
    var file1 = 'home/a/file1';
    var file2 = 'home/a/file2';
    var fpaths = [
      tree.getPath(file1),
      tree.getPath(file2)
    ];

    times = 0;
    watcher = watch(fpaths, function(evt, name) {
      if (fpaths.indexOf(name) !== -1) times++;
      if (times >= 2) done();
    });

    tree.modify(file1);
    tree.modify(file2);
  });

});

describe('watcher object', function() {

  it('should using watcher object to watch', function(done) {
    var dir = tree.getPath('home/a');
    var file = 'home/a/file1';
    var fpath = tree.getPath(file);

    watcher = watch(dir);
    watcher.on('change', function(evt, name) {
      assert(evt == 'update');
      assert(name == fpath);
      done();
    });

    tree.modify(file);
  });

  it('should close a watcher using .close()', function(done) {
    var dir = tree.getPath('home/a');
    var file = 'home/a/file1';
    var times = 0;
    watcher = watch(dir);
    watcher.on('change', function(evt, name) {
      times++;
    });
    watcher.close();

    tree.modify(file);
    tree.modify(file, 300);
    setTimeout(function() {
      assert(watcher.isClosed(), 'watcher should be closed');
      assert(times === 0, 'failed to close the watcher');
      done();
    }, 400);
  });

});
<commit_msg>increase interval<commit_after>var assert = require('assert');
var fs = require('fs-extra');
var Tree = require('./utils/builder');
var watch = require('../');

var tree = Tree();
var watcher;

beforeEach(function(done) {
  tree = Tree();
  if (watcher) watcher.close();
  setTimeout(done, 500);
});

after(function() {
  tree && tree.cleanup()
});

describe('watch for files', function() {
  it('should watch a single file and keep watching', function(done) {
    this.timeout(3000);
    var times = 1;
    var file = 'home/a/file1';
    var fpath = tree.getPath(file);
    watcher = watch(fpath, function(evt, name) {
      assert.equal(fpath, name)
      if (times++ >= 3) {
        done();
      }
    });
    tree.modify(file, 100);
    tree.modify(file, 500);
    tree.modify(file, 900);
  });

  it('should watch files inside a directory', function(done) {
    var dir = 'home/a';
    var fpath = tree.getPath('home/a');
    var stack = [
      tree.getPath('home/a/file1'),
      tree.getPath('home/a/file2')
    ];
    watcher = watch(fpath, function(evt, name) {
      stack.splice(stack.indexOf(name), 1);
      if (!stack.length) done();
    });

    tree.modify('home/a/file1', 200);
    tree.modify('home/a/file2', 300);
  });

  it('should ignore duplicate changes', function(done) {
    var file = 'home/a/file2';
    var fpath = tree.getPath(file);
    var times = 0;
    watcher = watch(fpath, function(evt, name) {
      if (fpath == name) times++;
      setTimeout(function() {
        assert(times == 1)
        done();
      }, 200);
    });
    tree.modify(file);
    tree.modify(file);
    tree.modify(file);
  });

});

describe('watch for directoies', function() {

  it('should watch directories inside a directory', function(done) {
    var home = tree.getPath('home');
    var dir = tree.getPath('home/c');

    watcher = watch(home, { recursive: true }, function(evt, name) {
      assert.equal(dir, name);
      done();
    });

    tree.remove('home/c', 300);
  });

  it('should watch new created directories', function(done) {
    var home = tree.getPath('home');
    watcher = watch(home, { recursive: true }, function(evt, name) {
      if (name == tree.getPath('home/new/file1')) {
        done();
      }
    });
    tree.newFile('home/new/file1', 200);
    tree.modify('home/new/file1', 500);
  });
});

describe('events', function() {
  it('should identify `remove` event', function(done) {
    var file = 'home/a/file1';
    var fpath = tree.getPath(file);
    watcher = watch(fpath, function(evt, name) {
      if (evt == 'remove' && name == fpath) done();
    });
    tree.remove(file, 100);
  });

  it('should identify `update` event', function(done) {
    var file = 'home/a/file1';
    var fpath = tree.getPath(file);
    watcher = watch(fpath, function(evt, name) {
      if (evt == 'update' && name == fpath) done();
    });
    tree.modify(file, 100);
  });

  it('should report `update` on new files', function(done) {
    var dir = tree.getPath('home/a');
    var file = 'home/a/newfile' + Date.now();
    var fpath = tree.getPath(file);
    watcher = watch(dir, function(evt, name) {
      if (evt == 'update' && name == fpath) done();
    });
    tree.newFile(file);
  });

});

describe('options', function() {
  describe('recursive', function() {
    it('should watch recursively with `recursive: true` option', function(done) {
      var dir = tree.getPath('home');
      var file = tree.getPath('home/bb/file1');
      watcher = watch(dir, { recursive: true }, function(evt, name) {
        assert.equal(file, name);
        done();
      });
      tree.modify('home/bb/file1', 200);
    });
  });

  describe('encoding', function() {
    it('should throw on invalid encoding', function(done) {
      var dir = tree.getPath('home/a');
      try {
        watcher = watch(dir, 'unknown');
      } catch (e) {
        done();
      }
    });

    it('should accept options as an encoding string', function(done) {
      var dir = tree.getPath('home/a');
      var file = 'home/a/file1';
      var fpath = tree.getPath(file);
      watcher = watch(dir, 'utf8', function(evt, name) {
        assert(name.toString() === fpath);
        done();
      });
      tree.modify(file, 200);
    });

    it('should support buffer encoding', function(done) {
      var dir = tree.getPath('home/a');
      var file = 'home/a/file1';
      var fpath = tree.getPath(file);
      watcher = watch(dir, 'buffer', function(evt, name) {
        assert(Buffer.isBuffer(name), 'not a Buffer')
        assert(name.toString() === fpath);
        done();
      });
      tree.modify(file, 200);
    });

    it('should support base64 encoding', function(done) {
      var dir = tree.getPath('home/a');
      var file = 'home/a/file1';
      var fpath = tree.getPath(file);
      watcher = watch(dir, 'base64', function(evt, name) {
        assert(
          name === (Buffer.from ? Buffer.from(fpath) : new Buffer(fpath)).toString('base64'),
          'wrong base64 encoding'
        );
        done();
      });
      tree.modify(file, 200);
    });

    it('should support hex encoding', function(done) {
      var dir = tree.getPath('home/a');
      var file = 'home/a/file1';
      var fpath = tree.getPath(file);
      watcher = watch(dir, 'hex', function(evt, name) {
        assert(
          name === (Buffer.from ? Buffer.from(fpath) : new Buffer(fpath)).toString('hex'),
          'wrong hex encoding'
        );
        done();
      });
      tree.modify(file, 200);
    });
  });

  describe('filter', function() {
    it('should only watch filtered directories', function(done) {
      var shouldModify = true;
      var shouldNotModify = false;

      var option = {
        recursive: true,
        filter: function(name) {
          return !/node_modules/.test(name);
        }
      };

      watcher = watch(tree.getPath('home'), option, function(evt, name) {
        if (/node_modules/.test(name)) {
          shouldNotModify = true;
        } else {
          shouldModify = false;
        }
      });

      tree.modify('home/b/file1', 200);
      tree.modify('home/node_modules/ma/file1', 500);

      setTimeout(function() {
        assert(!shouldModify, 'watch failed');
        assert(!shouldNotModify, 'fail to ingore path `node_modules`');
        done();
      }, 900);
    });

    it('should only report filtered files', function(done) {
      var dir = tree.getPath('home/a');
      var file1 = 'home/a/file1';
      var file2 = 'home/a/file2';

      var options = {
        filter: function(name) {
          return !/file1/.test(name);
        }
      }

      var times = 0;
      watcher = watch(dir, options, function(evt, name) {
        times++;
        if (name == tree.getPath(file2)) {
          assert(times, 1, 'home/a/file1 should be ignored.');
          done();
        }
      });

      tree.modify(file1, 200);
      tree.modify(file2, 400);
    });

    it('should be able to filter with regexp', function(done) {
      var dir = tree.getPath('home/a');
      var file1 = 'home/a/file1';
      var file2 = 'home/a/file2';

      var options = {
        filter:  /file2/
      }

      var times = 0;
      watcher = watch(dir, options, function(evt, name) {
        times++;
        if (name == tree.getPath(file2)) {
          assert(times, 1, 'home/a/file1 should be ignored.');
          done();
        }
      });

      tree.modify(file1, 200);
      tree.modify(file2, 400);
    });

  });
});

describe('parameters', function() {

  it('should throw error on non-existed file', function(done) {
    var somedir = tree.getPath('home/somedir');
    try {
      watcher = watch(somedir);
    } catch(err) {
      done();
    }
  });

  it('should accept filename as Buffer', function(done) {
    var fpath = tree.getPath('home/a/file1');
    watcher = watch(new Buffer(fpath), function(evt, name) {
      assert(name == fpath);
      done();
    });
    tree.modify('home/a/file1', 100);
  });

  it('should compose array of files or directories', function(done) {
    var file1 = 'home/a/file1';
    var file2 = 'home/a/file2';
    var fpaths = [
      tree.getPath(file1),
      tree.getPath(file2)
    ];

    times = 0;
    watcher = watch(fpaths, function(evt, name) {
      if (fpaths.indexOf(name) !== -1) times++;
      if (times >= 2) done();
    });

    tree.modify(file1);
    tree.modify(file2);
  });

});

describe('watcher object', function() {

  it('should using watcher object to watch', function(done) {
    var dir = tree.getPath('home/a');
    var file = 'home/a/file1';
    var fpath = tree.getPath(file);

    watcher = watch(dir);
    watcher.on('change', function(evt, name) {
      assert(evt == 'update');
      assert(name == fpath);
      done();
    });

    tree.modify(file);
  });

  it('should close a watcher using .close()', function(done) {
    var dir = tree.getPath('home/a');
    var file = 'home/a/file1';
    var times = 0;
    watcher = watch(dir);
    watcher.on('change', function(evt, name) {
      times++;
    });
    watcher.close();

    tree.modify(file);
    tree.modify(file, 300);
    setTimeout(function() {
      assert(watcher.isClosed(), 'watcher should be closed');
      assert(times === 0, 'failed to close the watcher');
      done();
    }, 400);
  });

});
<|endoftext|>


<commit_before>import Ember from "ember";
import layout from "../templates/components/em-flickity";

const { computed, get, getProperties, set } = Ember;

export default Ember.Component.extend({
  layout,
  classNames: ["flickity-wrapper"],
  eventHandlers: [],
  showSlides: false,
  widget: null,

  // some default flickity settings
  cellAlign: "center",
  contain: true,
  friction: 0.8,
  pageDots: false,
  selectedAttraction: 0.125,
  setGallerySize: false,

  optionKeys: computed(function getOptionKeys() {
    return [
      "accessibility",
      "adaptiveHeight",
      "arrowShape",
      "asNavFor",
      "autoPlay",
      "bgLazyLoad",
      "draggable",
      "gragThreshold",
      "cellAlign",
      "cellSelector",
      "contain",
      "freeScroll",
      "freeScrollFriction",
      "friction",
      "groupCells",
      "imagesLoaded",
      "initialIndex",
      "lazyLoad",
      "pageDots",
      "percentPosition",
      "prevNextButtons",
      "resize",
      "rightToLeft",
      "selectedAttraction",
      "setGallerySize",
      "watchCSS",
      "wrapAround"
    ];
  }),

  eventKeys: computed(function getEventKeys() {
    return [
      "cellSelect",
      "select",
      "settle",
      "scroll",
      "dragStart",
      "dragMove",
      "dragEnd",
      "pointerDown",
      "pointerMove",
      "pointerUp",
      "staticClick",
      "lazyLoad",
      "bgLazyLoad"
    ];
  }),

  didInsertElement() {
    if (get(this, "showSlides")) {
      set(this, "widget", this.$().flickity(this._getOptions()));
      this._setupEvents();
    }
  },

  willDestroyElement() {
    const $widget = get(this, "widget");

    if ($widget) {
      get(this, "eventHandlers").forEach(evt => evt.off());
      $widget.flickity("destroy");
    }
  },

  _setupEvents() {
    const $widget = get(this, "widget");

    const handler = key => (event, pointer, cellElement, cellIndex) => {
      if (this.attrs[key]) {
        this.attrs[key](
          cellIndex || $widget.data("flickity").selectedIndex,
          $widget.data("flickity")
        );
      }
    };

    const eventHandlers = get(this, "eventKeys")
      .map(key => $widget.on(`${key}.flickity`, handler(key)));

    set(this, "eventHandlers", eventHandlers);
  },

  _getOptions() {
    const propKeys = get(this, "optionKeys");
    const props = getProperties(this, ...propKeys);

    Object.keys(props).forEach(prop => {
      if (!props[prop] && typeof props[prop] !== "boolean") {
        delete props[prop];
      }
    });

    return props;
  }
});
<commit_msg>Update em-flickity.js<commit_after>import Ember from "ember";
import layout from "../templates/components/em-flickity";

const { computed, get, getProperties, set } = Ember;

export default Ember.Component.extend({
  layout,
  classNames: ["flickity-wrapper"],
  eventHandlers: [],
  showSlides: false,
  widget: null,

  // some default flickity settings
  cellAlign: "center",
  contain: true,
  friction: 0.8,
  pageDots: false,
  selectedAttraction: 0.125,
  setGallerySize: false,

  optionKeys: computed(function getOptionKeys() {
    return [
      "accessibility",
      "adaptiveHeight",
      "arrowShape",
      "asNavFor",
      "autoPlay",
      "bgLazyLoad",
      "draggable",
      "gragThreshold",
      "cellAlign",
      "cellSelector",
      "contain",
      "freeScroll",
      "freeScrollFriction",
      "friction",
      "groupCells",
      "imagesLoaded",
      "initialIndex",
      "lazyLoad",
      "pageDots",
      "percentPosition",
      "prevNextButtons",
      "resize",
      "rightToLeft",
      "selectedAttraction",
      "setGallerySize",
      "watchCSS",
      "wrapAround"
    ];
  }),

  eventKeys: computed(function getEventKeys() {
    return [
      "cellSelect",
      "select",
      "settle",
      "scroll",
      "dragStart",
      "dragMove",
      "dragEnd",
      "pointerDown",
      "pointerMove",
      "pointerUp",
      "staticClick",
      "lazyLoad",
      "bgLazyLoad",
      "ready"
    ];
  }),

  didInsertElement() {
    if (get(this, "showSlides")) {
      set(this, "widget", this.$().flickity(this._getOptions()));
      this._setupEvents();
    }
  },

  willDestroyElement() {
    const $widget = get(this, "widget");

    if ($widget) {
      get(this, "eventHandlers").forEach(evt => evt.off());
      $widget.flickity("destroy");
    }
  },

  _setupEvents() {
    const $widget = get(this, "widget");

    const handler = key => (event, pointer, cellElement, cellIndex) => {
      if (this.attrs[key]) {
        this.attrs[key](
          cellIndex || $widget.data("flickity").selectedIndex,
          $widget.data("flickity")
        );
      }
    };

    const eventHandlers = get(this, "eventKeys")
      .map(key => $widget.on(`${key}.flickity`, handler(key)));

    set(this, "eventHandlers", eventHandlers);
  },

  _getOptions() {
    const propKeys = get(this, "optionKeys");
    const props = getProperties(this, ...propKeys);

    Object.keys(props).forEach(prop => {
      if (!props[prop] && typeof props[prop] !== "boolean") {
        delete props[prop];
      }
    });

    return props;
  }
});
<|endoftext|>


<commit_before>var fsExtra = require('fs-extra');
var fs = require('fs');

var mkdir = module.exports

//create folder

mkdir.createFolder = function(nameFolder){
  if(typeof nameFolder == 'array'){
    for(i in nameFolder){
      if(!fs.existsSync(i)){
        fs.mkdirSync(i);
      }
    }
  }
  else{
    if(!fs.existsSync(nameFolder)){
      fs.mkdirSync(nameFolder);
    }
  }
}

//explorer function
mkdir.explorer = function(nameFolder){
    var jsonFileList = fs.readdirSync(nameFolder);
    return fileList;
}

//delete function
mkdir.deleteFiles = function(nameFolder, listOfFile){
  var jsonFileList = fs.readdirSync(nameFolder);
  for(i in jsonFileList ){
    fsExtra.remove(i, function(err) {
      if (err) return console.error(err);
    });
  }
}

//delete all function
mkdir.deleteFiles = function(nameFolder){
  var jsonFileList = fs.readdirSync(nameFolder);
  for(i in jsonFileList ){
    fsExtra.remove(i, function(err) {
      if (err) return console.error(err)

      });
    }
}

//rename files
mkdir.renameFiles = function(folder, newName){
    var fileList = fs.readdirSync(folder);
    for(var i=0 ;i<fileList.length; i++){
      var extension = '.'+fileList[i].split('.').pop();
      var newName = folder+fileList[i]+i+extension;
      fs.renameSync(folder+fileList[i], newName);
    }
}

mkdir.renameFiles= function(folder,list1, list2){
  var fileList = fs.readdirSync(folder);
  for(i in fileList){
    for(var j = 0 ;i<list1.length ; j++){
      if(j == list1[i]){
        var extension = '.'+list1[i].split('.').pop();
        var newName = folder+list2[i]+extension;
        fs.renameSync(folder+list1[i], newName);
      }
    }
  }
}
<commit_msg>Update mkdir.js<commit_after>var fsExtra = require('fs-extra');
var fs = require('fs');

var mkdir = module.exports

//create folder

mkdir.createFolder = function(nameFolder){
  if(typeof nameFolder == 'array'){
    for(i in nameFolder){
      if(!fs.existsSync(i)){
        fs.mkdirSync(i);
      }
    }
  }
  else{
    if(!fs.existsSync(nameFolder)){
      fs.mkdirSync(nameFolder);
    }
  }
}

//explorer function
mkdir.explorer = function(nameFolder){
    var jsonFileList = fs.readdirSync(nameFolder);
    return fileList;
}

//delete function
mkdir.deleteFiles = function(nameFolder, listOfFile){
  var jsonFileList = fs.readdirSync(nameFolder);
  for(i in jsonFileList ){
    for( i in listOfFile){
      if(i==listOfFile[i])
        fsExtra.remove(i, function(err) {
          if (err) return console.error(err);
        }
      }
    );
  }
}

//delete all function
mkdir.deleteFiles = function(nameFolder){
  var jsonFileList = fs.readdirSync(nameFolder);
  for(i in jsonFileList ){
    fsExtra.remove(i, function(err) {
      if (err) return console.error(err);

      });
    }
}

//rename files
mkdir.renameFiles = function(folder, newName){
    var fileList = fs.readdirSync(folder);
    for(var i=0 ;i<fileList.length; i++){
      var extension = '.'+fileList[i].split('.').pop();
      var newName = folder+fileList[i]+i+extension;
      fs.renameSync(folder+fileList[i], newName);
    }
}

mkdir.renameFiles= function(folder,list1, list2){
  var fileList = fs.readdirSync(folder);
  for(i in fileList){
    for(var j = 0 ;i<list1.length ; j++){
      if(j == list1[i]){
        var extension = '.'+list1[i].split('.').pop();
        var newName = folder+list2[i]+extension;
        fs.renameSync(folder+list1[i], newName);
      }
    }
  }
}
<|endoftext|>


<commit_before>import sinon from 'sinon';
import _ from 'underscore';
import { expect } from 'chai';
import * as utils from '../build/utils';
import ApifyClient from '../build';
import { BASE_PATH } from '../build/key-value-stores';

const options = {
    protocol: 'http',
    host: 'myhost',
    basePath: '/mypath',
    port: 80,
};

describe('Key value store', () => {
    const requestPromiseMock = sinon.mock(utils, 'requestPromise');

    const requestExpectCall = (requestOpts, response) => {
        if (!_.isObject(requestOpts)) throw new Error('"requestOpts" parameter must be an object!');
        if (!requestOpts.method) throw new Error('"requestOpts.method" parameter is not set!');

        requestPromiseMock
            .expects('requestPromise')
            .once()
            .withArgs(Promise, requestOpts)
            .returns(Promise.resolve(response));
    };

    after(() => {
        requestPromiseMock.verify();
        requestPromiseMock.restore();
    });

    describe('indentification', () => {
        it('should work with ENV variable', () => {
            const storeId = 'some-id';

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            }, {
                id: storeId,
            });

            process.env.APIFY_ACT_RUN_ID = storeId;

            const apifyClient = new ApifyClient(options);

            return apifyClient
                .keyValueStores
                .getStore()
                .then((store) => {
                    expect(store.id).to.be.eql(storeId);
                    delete process.env.APIFY_ACT_RUN_ID;
                });
        });

        it('should work with storeId in default params', () => {
            const storeId = 'some-id-2';
            const apifyClient = new ApifyClient(Object.assign({}, options, { storeId }));

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            }, {
                id: storeId,
            });

            return apifyClient
                .keyValueStores
                .getStore()
                .then((store) => {
                    expect(store.id).to.be.eql(storeId);
                    delete process.env.APIFY_ACT_RUN_ID;
                });
        });

        it('should work with storeId in method call params', () => {
            const storeId = 'some-id-3';
            const apifyClient = new ApifyClient(options);

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            }, {
                id: storeId,
            });

            return apifyClient
                .keyValueStores
                .getStore({ storeId })
                .then((store) => {
                    expect(store.id).to.be.eql(storeId);
                    delete process.env.APIFY_ACT_RUN_ID;
                });
        });

        it('should work with user ID and credentials', () => {
            const storeId = 'some-id-4';
            const apifyClient = new ApifyClient(Object.assign({}, options, { storeId }));

            const storeOptions = {
                userId: 'someid',
                token: 'sometoken',
                storeName: 'somename',
            };

            requestExpectCall({
                body: storeOptions,
                json: true,
                method: 'POST',
                url: `http://myhost:80/mypath${BASE_PATH}`,
            }, {
                id: storeId,
            });

            return apifyClient
                .keyValueStores
                .getOrCreateStore(storeOptions)
                .then(store => expect(store.id).to.be.eql(storeId));
        });

        it('should work with username and credentials', () => {
            const storeId = 'some-id-5';
            const apifyClient = new ApifyClient(Object.assign({}, options, { storeId }));

            const storeOptions = {
                username: 'someusername',
                token: 'sometoken',
                storeName: 'somename',
            };

            requestExpectCall({
                body: storeOptions,
                json: true,
                method: 'POST',
                url: `http://myhost:80/mypath${BASE_PATH}`,
            }, {
                id: storeId,
            });

            return apifyClient
                .keyValueStores
                .getOrCreateStore(storeOptions)
                .then(store => expect(store.id).to.be.eql(storeId));
        });
    });

    describe('Key value store REST methods work', () => {
        it('getStore() works', () => {
            const storeId = 'some-id';
            const apifyClient = new ApifyClient(options);
            const expected = { _id: 'some-id', aaa: 'bbb' };

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            }, expected);

            return apifyClient
                .keyValueStores
                .getStore({ storeId })
                .then(given => expect(given).to.be.eql(expected));
        });

        it('deleteStore() works', () => {
            const storeId = 'some-id';
            const apifyClient = new ApifyClient(options);

            requestExpectCall({
                json: true,
                method: 'DELETE',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            });

            return apifyClient
                .keyValueStores
                .deleteStore({ storeId });
        });

        it('getRecord() works', () => {
            const recordKey = 'some-key';
            const storeId = 'some-id';
            const apifyClient = new ApifyClient(options);
            const expected = 'sometext';

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}/records/${recordKey}`,
            }, expected);

            return apifyClient
                .keyValueStores
                .getRecord({ storeId, recordKey })
                .then(given => expect(given).to.be.eql(expected));
        });

        it('put() works', () => {
            const recordKey = 'some-key';
            const storeId = 'some-id';
            const contentType = 'application/json';
            const body = 'someValue';
            const apifyClient = new ApifyClient(options);

            requestExpectCall({
                body: 'someValue',
                headers: { 'Content-Type': 'application/json' },
                json: true,
                method: 'PUT',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}/records/${recordKey}`,
            });

            return apifyClient
                .keyValueStores
                .putRecord({ storeId, recordKey, contentType, body });
        });

        it('delete() works', () => {
            const recordKey = 'some-key';
            const storeId = 'some-id';
            const apifyClient = new ApifyClient(options);

            requestExpectCall({
                json: true,
                method: 'DELETE',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}/records/${recordKey}`,
            });

            return apifyClient
                .keyValueStores
                .deleteRecord({ storeId, recordKey });
        });

        it('keys() works', () => {
            const storeId = 'some-id';
            const exclusiveStartKey = 'fromKey';
            const count = 10;
            const apifyClient = new ApifyClient(options);
            const expected = ['key1', 'key2', 'key3'];

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}/records?exclusiveStartKey=${exclusiveStartKey}&count=${count}`,
            }, expected);

            return apifyClient
                .keyValueStores
                .getRecordsKeys({ storeId, exclusiveStartKey, count })
                .then(keys => expect(keys).to.be.eql({ items: expected }));
        });
    });
});
<commit_msg>Fixed broken unit test for getRecord()<commit_after>import sinon from 'sinon';
import _ from 'underscore';
import { expect } from 'chai';
import * as utils from '../build/utils';
import ApifyClient from '../build';
import { BASE_PATH } from '../build/key-value-stores';

const options = {
    protocol: 'http',
    host: 'myhost',
    basePath: '/mypath',
    port: 80,
};

describe('Key value store', () => {
    const requestPromiseMock = sinon.mock(utils, 'requestPromise');

    const requestExpectCall = (requestOpts, response) => {
        if (!_.isObject(requestOpts)) throw new Error('"requestOpts" parameter must be an object!');
        if (!requestOpts.method) throw new Error('"requestOpts.method" parameter is not set!');

        requestPromiseMock
            .expects('requestPromise')
            .once()
            .withArgs(Promise, requestOpts)
            .returns(Promise.resolve(response));
    };

    after(() => {
        requestPromiseMock.verify();
        requestPromiseMock.restore();
    });

    describe('indentification', () => {
        it('should work with ENV variable', () => {
            const storeId = 'some-id';

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            }, {
                id: storeId,
            });

            process.env.APIFY_ACT_RUN_ID = storeId;

            const apifyClient = new ApifyClient(options);

            return apifyClient
                .keyValueStores
                .getStore()
                .then((store) => {
                    expect(store.id).to.be.eql(storeId);
                    delete process.env.APIFY_ACT_RUN_ID;
                });
        });

        it('should work with storeId in default params', () => {
            const storeId = 'some-id-2';
            const apifyClient = new ApifyClient(Object.assign({}, options, { storeId }));

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            }, {
                id: storeId,
            });

            return apifyClient
                .keyValueStores
                .getStore()
                .then((store) => {
                    expect(store.id).to.be.eql(storeId);
                    delete process.env.APIFY_ACT_RUN_ID;
                });
        });

        it('should work with storeId in method call params', () => {
            const storeId = 'some-id-3';
            const apifyClient = new ApifyClient(options);

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            }, {
                id: storeId,
            });

            return apifyClient
                .keyValueStores
                .getStore({ storeId })
                .then((store) => {
                    expect(store.id).to.be.eql(storeId);
                    delete process.env.APIFY_ACT_RUN_ID;
                });
        });

        it('should work with user ID and credentials', () => {
            const storeId = 'some-id-4';
            const apifyClient = new ApifyClient(Object.assign({}, options, { storeId }));

            const storeOptions = {
                userId: 'someid',
                token: 'sometoken',
                storeName: 'somename',
            };

            requestExpectCall({
                body: storeOptions,
                json: true,
                method: 'POST',
                url: `http://myhost:80/mypath${BASE_PATH}`,
            }, {
                id: storeId,
            });

            return apifyClient
                .keyValueStores
                .getOrCreateStore(storeOptions)
                .then(store => expect(store.id).to.be.eql(storeId));
        });

        it('should work with username and credentials', () => {
            const storeId = 'some-id-5';
            const apifyClient = new ApifyClient(Object.assign({}, options, { storeId }));

            const storeOptions = {
                username: 'someusername',
                token: 'sometoken',
                storeName: 'somename',
            };

            requestExpectCall({
                body: storeOptions,
                json: true,
                method: 'POST',
                url: `http://myhost:80/mypath${BASE_PATH}`,
            }, {
                id: storeId,
            });

            return apifyClient
                .keyValueStores
                .getOrCreateStore(storeOptions)
                .then(store => expect(store.id).to.be.eql(storeId));
        });
    });

    describe('Key value store REST methods work', () => {
        it('getStore() works', () => {
            const storeId = 'some-id';
            const apifyClient = new ApifyClient(options);
            const expected = { _id: 'some-id', aaa: 'bbb' };

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            }, expected);

            return apifyClient
                .keyValueStores
                .getStore({ storeId })
                .then(given => expect(given).to.be.eql(expected));
        });

        it('deleteStore() works', () => {
            const storeId = 'some-id';
            const apifyClient = new ApifyClient(options);

            requestExpectCall({
                json: true,
                method: 'DELETE',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}`,
            });

            return apifyClient
                .keyValueStores
                .deleteStore({ storeId });
        });

        it('getRecord() works', () => {
            const recordKey = 'some-key';
            const storeId = 'some-id';
            const apifyClient = new ApifyClient(options);
            const body = 'sometext';
            const expected = {
                body,
                contentType: 'text/plain', // TODO: finish this !!!!
            };

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}/records/${recordKey}`,
            }, body);

            return apifyClient
                .keyValueStores
                .getRecord({ storeId, recordKey })
                .then(given => expect(given).to.be.eql(expected));
        });

        it('put() works', () => {
            const recordKey = 'some-key';
            const storeId = 'some-id';
            const contentType = 'application/json';
            const body = 'someValue';
            const apifyClient = new ApifyClient(options);

            requestExpectCall({
                body: 'someValue',
                headers: { 'Content-Type': 'application/json' },
                json: true,
                method: 'PUT',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}/records/${recordKey}`,
            });

            return apifyClient
                .keyValueStores
                .putRecord({ storeId, recordKey, contentType, body });
        });

        it('delete() works', () => {
            const recordKey = 'some-key';
            const storeId = 'some-id';
            const apifyClient = new ApifyClient(options);

            requestExpectCall({
                json: true,
                method: 'DELETE',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}/records/${recordKey}`,
            });

            return apifyClient
                .keyValueStores
                .deleteRecord({ storeId, recordKey });
        });

        it('keys() works', () => {
            const storeId = 'some-id';
            const exclusiveStartKey = 'fromKey';
            const count = 10;
            const apifyClient = new ApifyClient(options);
            const expected = ['key1', 'key2', 'key3'];

            requestExpectCall({
                json: true,
                method: 'GET',
                url: `http://myhost:80/mypath${BASE_PATH}/${storeId}/records?exclusiveStartKey=${exclusiveStartKey}&count=${count}`,
            }, expected);

            return apifyClient
                .keyValueStores
                .getRecordsKeys({ storeId, exclusiveStartKey, count })
                .then(keys => expect(keys).to.be.eql({ items: expected }));
        });
    });
});
<|endoftext|>


<commit_before>(function() {
  "use strict";
  var states = {
    MAIN: 0,
    VIEW: 1
  };

  var sequenceTypes = {
    ALPHABETICAL: 0,
    NUMERIC: 1
  };

  var casings = {
    LOWERCASE: 0,
    UPPERCASE: 1,
    MIXED: 2
  };

  var state = null;
  var baseUrl = null;
  var sequences = [];

  function byId(input) {
    return document.getElementById(input);
  }

  function byClass(input) {
    return document.getElementsByClassName(input);
  }

  function byTag(input) {
    return document.getElementsByTagName(input);
  }

  Element.prototype.byId = function(input) {
    return this.getElementById(input);
  };

  Element.prototype.byClass = function(input) {
    return this.getElementsByClassName(input);
  };

  Element.prototype.byTag = function(input) {
    return this.getElementsByTagName(input);
  };

  var casingHtml = '<select class="config"><option value="0">Lowercase</option><option value="1">Uppercase</option><option value="1">Mixed</option></select>';
  var paddingHtml = '<input class="config" type="number" value="PAD">';

  function addSequence(type, padding, casing, start) {
    var element = document.createElement("div");
    element.className = "sequence";
    element.innerHTML = '<select class="type"><option value="0">Alphabetical</option><option value="1">Numeric</option></select>
' +
      ' ' + (type === sequenceTypes.ALPHABETICAL ? casingHtml : paddingHtml.replace("PAD", padding)) +
      'Start at: <input type="text" class="start" value="' + (type === sequenceTypes.ALPHABETICAL ? "a" : "1") + '">';
    byId("sequences").appendChild(element);
    var sel = element.byClass("type")[0];
    sel.selectedIndex = type;
    sel.addEventListener("change", onTypeChange);
  }

  function addNewSequence() {
    addSequence(sequenceTypes.NUMERIC, 3, casings.LOWERCASE, 1);
  }

  function onTypeChange(e) {
      let elem = this.parentElement.byClass("config")[0];
      if (this.selectedIndex === sequenceTypes.ALPHABETICAL) {
        elem.outerHTML = casingHtml;
        this.parentElement.byClass("start")[0].value = "a";
      }
      else if (this.selectedIndex === sequenceTypes.NUMERIC) {
        elem.outerHTML = paddingHtml;
        this.parentElement.byClass("start")[0].value = "1";
      }
  }

  function removeSequence(index) {
    if (index > -1 && index < sequences.length) {
      sequences.splice(index, 1);
    }
  }

  function doNextSequence() {
    doSequence(++seqIndex);
  }

  function doPrevSequence() {
    doSequence(--seqIndex);
  }

  function doSequence() {
    if (sequences.length < 1) {
      alert("Error!");
    }
    if (seqIndex < 0) {
      seqIndex = 0;
    }
    var seq = sequences[0];
    var image = byId("image");
    var src = baseUrl;
    var name = seqIndex.toString();
    while (name.length < seq.padding) {
      name = "0" + name;
    }
    src += name + ".jpg";
    image.src = src;
    image.alt = src;
    setImageSize();
  }

  function onImageClick(e) {
    if (this.classList.contains("fit")) {
      this.classList.remove("fit");
      this.classList.add("full");
      this.removeAttribute("height");
      this.removeAttribute("width");
    }
    else {
      this.classList.add("fit");
      this.classList.remove("full");
      setImageSize();
    }
  }

  function start() {
    state = states.VIEW;
    buildSequences();
    byId("main").classList.add("hidden");
    byId("view").classList.remove("hidden");
    document.addEventListener("keydown", keyCheck);
    document.body.classList.add("view");
    window.addEventListener("resize", setImageSize);
    byId("image").addEventListener("click", onImageClick);
    doSequence();
  }

  function setImageSize() {
    var image = byId("image");
    if (image.classList.contains("fit")) {
      let height = image.height;
      let width = image.width;
      if (height > width) {
        width = Math.floor(width * (window.innerHeight / height));
        height = window.innerHeight;
      }
      else {
        height = Math.floor(height * (window.innerWidth / width));
        width = window.innerWidth;
      }
      image.setAttribute("height", height);
      image.setAttribute("width", width);
    }
  }

  function keyCheck(e) {
    if (e.keyCode === 39) {
      doNextSequence();
    }
    else if (e.keyCode === 37) {
      doPrevSequence();
    }
  }

  var seqIndex = 0;

  function buildSequences() {
    baseUrl = byId("base-url").value;
    sequences = [];
    var elems = byClass("sequence");
    for (let i = elems.length - 1; i >= 0; i--) {
      let elem = elems[i];
      let seq = { };
      let type = elem.byClass("type")[0].selectedIndex;
      seq.type = type;
      seq.start = elem.byClass("start")[0].value;
      if (type === sequenceTypes.ALPHABETICAL) {
        seq.padding = 0;
        seq.casing = elem.byClass("config")[0].selectedIndex;
      }
      else if (type === sequenceTypes.NUMERIC) {
        seq.padding = elem.byClass("config")[0].value;
        seq.casing = casings.LOWERCASE;
        seq.start = +seq.start;
      }
      sequences.push(seq);
    }
    seqIndex = sequences[0].start;
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    state = states.MAIN;
    byId("add-sequence").addEventListener("click", addNewSequence);
    byId("start").addEventListener("click", start);
    addNewSequence();
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<commit_msg>Update img.js<commit_after>(function() {
  "use strict";
  var states = {
    MAIN: 0,
    VIEW: 1
  };

  var sequenceTypes = {
    ALPHABETICAL: 0,
    NUMERIC: 1
  };

  var casings = {
    LOWERCASE: 0,
    UPPERCASE: 1,
    MIXED: 2
  };

  var state = null;
  var baseUrl = null;
  var sequences = [];

  function byId(input) {
    return document.getElementById(input);
  }

  function byClass(input) {
    return document.getElementsByClassName(input);
  }

  function byTag(input) {
    return document.getElementsByTagName(input);
  }

  Element.prototype.byId = function(input) {
    return this.getElementById(input);
  };

  Element.prototype.byClass = function(input) {
    return this.getElementsByClassName(input);
  };

  Element.prototype.byTag = function(input) {
    return this.getElementsByTagName(input);
  };

  var casingHtml = '<select class="config"><option value="0">Lowercase</option><option value="1">Uppercase</option><option value="1">Mixed</option></select>';
  var paddingHtml = '<input class="config" type="number" value="PAD">';

  function addSequence(type, padding, casing, start) {
    var element = document.createElement("div");
    element.className = "sequence";
    element.innerHTML = '<select class="type"><option value="0">Alphabetical</option><option value="1">Numeric</option></select>
' +
      ' ' + (type === sequenceTypes.ALPHABETICAL ? casingHtml : paddingHtml.replace("PAD", padding)) +
      'Start at: <input type="text" class="start" value="' + (type === sequenceTypes.ALPHABETICAL ? "a" : "1") + '">';
    byId("sequences").appendChild(element);
    var sel = element.byClass("type")[0];
    sel.selectedIndex = type;
    sel.addEventListener("change", onTypeChange);
  }

  function addNewSequence() {
    addSequence(sequenceTypes.NUMERIC, 3, casings.LOWERCASE, 1);
  }

  function onTypeChange(e) {
      let elem = this.parentElement.byClass("config")[0];
      if (this.selectedIndex === sequenceTypes.ALPHABETICAL) {
        elem.outerHTML = casingHtml;
        this.parentElement.byClass("start")[0].value = "a";
      }
      else if (this.selectedIndex === sequenceTypes.NUMERIC) {
        elem.outerHTML = paddingHtml;
        this.parentElement.byClass("start")[0].value = "1";
      }
  }

  function removeSequence(index) {
    if (index > -1 && index < sequences.length) {
      sequences.splice(index, 1);
    }
  }

  function doNextSequence() {
    doSequence(++seqIndex);
  }

  function doPrevSequence() {
    doSequence(--seqIndex);
  }

  function doSequence() {
    if (sequences.length < 1) {
      alert("Error!");
    }
    if (seqIndex < 0) {
      seqIndex = 0;
    }
    var seq = sequences[0];
    var image = byId("image");
    var src = baseUrl;
    var name = seqIndex.toString();
    while (name.length < seq.padding) {
      name = "0" + name;
    }
    src += name + ".jpg";
    image.src = src;
    image.alt = src;
    setImageSize();
  }

  function onImageClick(e) {
    if (this.classList.contains("fit")) {
      this.classList.remove("fit");
      this.classList.add("full");
      this.removeAttribute("height");
      this.removeAttribute("width");
    }
    else {
      this.classList.add("fit");
      this.classList.remove("full");
      setImageSize();
    }
  }

  function start() {
    state = states.VIEW;
    buildSequences();
    byId("main").classList.add("hidden");
    byId("view").classList.remove("hidden");
    document.addEventListener("keydown", keyCheck);
    document.body.classList.add("view");
    window.addEventListener("resize", setImageSize);
    byId("image").addEventListener("click", onImageClick);
    doSequence();
  }

  function setImageSize() {
    var image = byId("image");
    image.removeAttribute("height");
    image.removeAttribute("width");
    if (image.classList.contains("fit")) {
      let height = image.height;
      let width = image.width;
      if (height > width) {
        if (height > window.innerHeight) {
          constrainByHeight();
        }
        else if (width > window.innerWidth) {
          constrainByWidth();
        }
      }
      else {
        if (width > window.innerWidth) {
          constrainByWidth();
        }
        else if (height > window.innerHeight) {
          constrainByHeight();
        }
      }
    }
  }

  function constrainByWidth(image) {
    let height = image.height;
    let width = image.width;
    height = Math.floor(height * (window.innerWidth / width));
    width = window.innerWidth;
    image.setAttribute("height", height);
    image.setAttribute("width", width);
  }

  function constrainByHeight(image) {
    let height = image.height;
    let width = image.width;
    width = Math.floor(width * (window.innerHeight / height));
    height = window.innerHeight;
    image.setAttribute("height", height);
    image.setAttribute("width", width);
  }

  function keyCheck(e) {
    if (e.keyCode === 39) {
      doNextSequence();
    }
    else if (e.keyCode === 37) {
      doPrevSequence();
    }
  }

  var seqIndex = 0;

  function buildSequences() {
    baseUrl = byId("base-url").value;
    sequences = [];
    var elems = byClass("sequence");
    for (let i = elems.length - 1; i >= 0; i--) {
      let elem = elems[i];
      let seq = { };
      let type = elem.byClass("type")[0].selectedIndex;
      seq.type = type;
      seq.start = elem.byClass("start")[0].value;
      if (type === sequenceTypes.ALPHABETICAL) {
        seq.padding = 0;
        seq.casing = elem.byClass("config")[0].selectedIndex;
      }
      else if (type === sequenceTypes.NUMERIC) {
        seq.padding = elem.byClass("config")[0].value;
        seq.casing = casings.LOWERCASE;
        seq.start = +seq.start;
      }
      sequences.push(seq);
    }
    seqIndex = sequences[0].start;
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    state = states.MAIN;
    byId("add-sequence").addEventListener("click", addNewSequence);
    byId("start").addEventListener("click", start);
    addNewSequence();
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<|endoftext|>


<commit_before>'use strict';

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

var _ = require('lodash');
var async = require('async');
var debug = require('debug')('strider-simple-runner');
var EventEmitter2 = require('eventemitter2').EventEmitter2;
var Loader = require('strider-extension-loader');

var core = require('strider-runner-core');

var cachier = require('./cachier');
var keeper = require('dirkeeper');
var JobData = require('./jobdata');
var JobQueue = require('./jobqueue');
var branchFromJob = require('./utils').branchFromJob;

// timeout for callbacks. Helps to kill misbehaving plugins, etc
function t(time, done) {
  if (arguments.length === 1) {
    done = time;
    time = 2000;
  }
  var error = new Error(`Callback took too long (max: ${time})`);
  var waiting = true;

  var timeout = setTimeout(function () {
    if (!waiting) return;
    waiting = false;
    done(error);
  }, time);

  function handler() {
    if (!waiting) return;
    clearTimeout(timeout);
    waiting = false;
    done.apply(this, arguments);
  }

  return handler;
}

module.exports = Runner;

/*
 * Options:
 *    pty: use 'pty'
 *    io: the means of communication with the job worker
 *    pluginDir: the directory in which to look for plugins
 *    dataDir: the directory in which to clone/test/etc
 */
function Runner(emitter, config) {
  debug('RUNNER INIT');
  var dotStrider = path.join(process.env.HOME || '/', '.strider');
  this.config = _.extend({
    pty: false,
    io: new EventEmitter2({
      wildcard: true
    }),
    processJob: core.process,
    pluginDir: path.join(__dirname, '../node_modules'),
    dataDir: process.env.STRIDER_CLONE_DEST || dotStrider,
    concurrentJobs: parseInt(process.env.CONCURRENT_JOBS || '1', 10) || 1,
    defaultRecentBuilds: parseInt(process.env.DEFAULT_RECENT_BUILDS || '1', 10) || 1
  }, config);
  this.emitter = emitter;
  this.queue = new JobQueue(this.processJob.bind(this), this.config.concurrentJobs);
  this.io = this.config.io;
  this.callbackMap = {};
  this.hooks = [];
  this.jobdata = new JobData(this.io);
  this.attach();
}

// base: the base directory where all jobs data for this project and branch is stored
// the job object.
// done(err, {base:, data:, cache:})
function initJobDirs(branchBase, job, cache, done) {
  var dirs = {
    base: branchBase,
    data: path.join(branchBase, `job-${job._id.toString()}`),
    cache: cache
  };

  async.series([
    function checkData(next) {
      fs.exists(dirs.data, function (exists) {
        if (!exists) return next();
        fs.remove(dirs.data, function () {
          next();
        });
      });
    },
    fs.mkdirp.bind(null, dirs.data),
    fs.mkdirp.bind(null, dirs.cache)
  ], function (err) {
    done(err, dirs);
  });
}

Runner.prototype = {
  id: 'simple-runner',

  // public API
  loadExtensions: function (dirs, done) {
    var self = this;
    var loader = new Loader();
    loader.collectExtensions(dirs, function (err) {
      if (err) return done(err);
      loader.initWorkerExtensions({}, function (err, extensions) {
        if (err) return done(err);
        self.extensions = extensions;
        done(null);
      });
    });
  },

  getJobData: function (id) {
    return this.jobdata.get(id);
  },

  // Determine which jobs are zombies. This is called when strider
  // starts up.
  //
  // jobs: unfinished jobs that belong to this runner
  // done(err, zombies)
  findZombies: function (jobs, done) {
    done(null, jobs);
  },

  // private API
  attach: function () {
    var self = this;
    this.emitter.on('job.new', this.queueJob.bind(this));
    this.emitter.on('job.cancel', this.cancelJob.bind(this));
    this.emitter.on('job.info', function (id, respond) {
      var job = self.jobdata.get(id);
      if (job) respond(job);
    });
    function proxy(id) {
      // proxy up job.status.* updates as browser events
      var job = self.jobdata.get(id);
      var project = job && job.data.project.name;
      if (!job) return;
      self.emitter.emit('browser.update', project, this.event, [].slice.call(arguments));
    }

    this.io.on('job.status.**', proxy);
    this.io.on('job.cancelled', function (id) {
      // our running job was cancelled, so we need to start the next one
      var jobdata = self.jobdata.pop(id);
      self.emitter.emit('job.cancelled', id, jobdata);
      if (!jobdata) {
        jobdata = {
          _id: id
        };
        debug('Job cancelled, but no data!', id);
      }
      jobdata.errored = true;
      jobdata.error = {
        message: 'Cancelled by the user'
      };
      // self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error])
      delete jobdata.data;
      jobdata.finished = new Date();
      self.emitter.emit('job.done', jobdata);
      if (!self.callbackMap[id]) {
        debug('Job cancelled, but no callback found. The queue is probably broken.');
        return self.queue.process();
      }
      self.callbackMap[id]();
      delete self.callbackMap[id];
    });
    // proxy up plugin events
    this.io.on('plugin.**', function () {
      self.emitter.emit.apply(self.emitter, [this.event].concat([].slice.call(arguments)));
    });
  },

  queueJob: function (job, config) {
    if (config.runner.id !== this.id) return;
    var now = new Date();
    this.jobdata.add(job);
    this.queue.push(job, config);
    this.emitter.emit('browser.update', job.project.name, 'job.status.queued', [job._id, now]);
    debug(`[runner:${this.id}] Queued new job. Project: ${job.project.name} Job ID: ${job._id}`);
  },

  cancelJob: function (id) {
    var jobdata;
    for (var i = 0; i < this.queue.tasks.length; i++) {
      if (this.queue.tasks[i].job._id.toString() === id.toString()) {
        this.queue.tasks.splice(i, 1);
        debug(`[runner:${this.id}] Cancelled job. Job ID: ${id}`);
        jobdata = this.jobdata.pop(id);
        jobdata.errored = true;
        jobdata.error = {
          message: 'Cancelled by the user'
        };
        // self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error])
        delete jobdata.data;
        jobdata.started = new Date();
        jobdata.finished = new Date();
        this.emitter.emit('job.done', jobdata);
        return;
      }
    }
    // if it wasn't found in the queue, fire to the worker in case it is in process
    this.io.emit('job.cancel', id);
  },

  // initialize the provider and job plugins for a job
  // dirs = {base:, data:, cache:}
  plugins: function (user, config, job, dirs, done) {
    var self = this;
    var tasks = [function (next) {
      var plugin = self.extensions.provider[job.project.provider.id];
      if (!plugin) {
        var msg = `Provider plugin '${job.project.provider.id}' not found in this environment!`;
        return next(new Error(msg));
      }
      var finished = t(function (err, provider) {
        if (provider) provider.id = job.project.provider.id;
        next(err, provider);
      });
      if (!plugin.hosted) {
        return plugin.init(dirs, job.providerConfig, job, finished);
      }
      plugin.init(dirs, user.account(job.project.provider).config, job.providerConfig, job, finished);
    }];
    // XXX: do we want/need more things in the context? See
    // extension-loader readme for what gets passed in to the
    // individual phase functions as "Phase context"
    var context = {
      baseDir: dirs.base,
      dataDir: dirs.data,
      cacheDir: dirs.cache
    };
    var anyPluginFailed = config.plugins.some(function (plugin) {
      if (false === plugin.enabled) {
        debug(`[runner:${self.id}] Found a disabled plugin: ${plugin.id} Project: ${job.project.name} Job ID: ${job._id}`);
        return;
      }
      if (!self.extensions.job[plugin.id]) {
        debug(`[runner:${self.id}] Error: Plugin not found ${plugin.id} Project: ${job.project.name} Job ID: ${job._id}`);
        debug('Plugin not found', plugin.id);
        done(new Error(`Plugin required but not found: ${plugin.id}`));
        return true;
      }
      debug(`Initializing plugin '${plugin.id}'...`);
      tasks.push(function (next) {
        var fn = self.extensions.job[plugin.id].init;
        var cb = t(function (err, obj) {
          if (obj) obj.id = plugin.id;
          next(err, obj);
        });
        switch (fn.length) {
          case 1:
            return fn(cb);
          case 2:
            return fn(plugin.config, cb);
          case 3:
            return fn(plugin.config, context, cb);
          case 4:
            return fn(plugin.config, job, context, cb);
          default:
            return fn(user.jobplugins && user.jobplugins[plugin.id], plugin.config, job, context, cb)
        }
      });
    });
    if (anyPluginFailed) return;
    async.parallel(tasks, function (err, results) {
      if (err) return done(err);
      done(null, {
        provider: results.shift(),
        jobplugins: results
      });
    });
  },

  cacheDir: function (project) {
    return path.join(this.config.dataDir, 'cache', project.name);
  },

  getCache: function (project) {
    return cachier(this.cacheDir(project));
  },

  clearCache: function (project, done) {
    fs.remove(this.cacheDir(project), function (err) {
      done(err && new Error(`Failed to clear the cache. Error code: ${err}`));
    });
  },

  processJob: function (job, config, next) {
    var cache = this.getCache(job.project);
    var now = new Date();
    var self = this;
    var oldnext = next;
    next = function () {
      delete self.callbackMap[job._id];
      oldnext();
    };
    this.callbackMap[job._id] = next;

    var projectName = job.project.name.replace('/', '-');
    var branchName = branchFromJob(job).replace('/', '-');
    var branchBase = path.join(self.config.dataDir, 'data', `${projectName}-${branchName}`);
    var recentBuilds = _.get(config, 'runner.config.recentBuilds');

    if (typeof recentBuilds === 'undefined') {
      recentBuilds = self.config.defaultRecentBuilds;
    }

    recentBuilds = Math.max(recentBuilds, 1);

    if (recentBuilds > 1) {
      debug(`Preserving the most recent ${recentBuilds} builds within ${branchBase}.`);
    }

    // Keep around N most recent build directories for this branch.
    // The default is 0, ie wipe at start of each run.
    // Later, this can be configurable in the UI.
    keeper({baseDir: branchBase, count: recentBuilds - 1}, function (err) {
      if (err) return next(err);

      initJobDirs(branchBase, job, cache.base, jobDirsReady);
    });

    function jobDirsReady(err, dirs) {
      if (err) {
        var jobdata = self.jobdata.pop(job._id);
        if (!jobdata) return next(null);
        jobdata.errored = true;
        jobdata.error = {
          message: err.message,
          stack: err.stack
        };
        // self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error])
        delete jobdata.data;
        jobdata.finished = new Date();
        self.emitter.emit('job.done', jobdata);
        next(null);
        return;
      }
      self.jobdata.get(job._id).started = now;
      self.emitter.emit('browser.update', job.project.name, 'job.status.started', [job._id, now]);
      debug(`[runner:${self.id}] Job started. Project: ${job.project.name} Job ID: ${job._id}`);
      debug('Initializing plugins...');
      self.plugins(job.project.creator, config, job, dirs, function (err, workers) {
        if (err) {
          var jobdata = self.jobdata.pop(job._id);
          if (!jobdata) return next(null);
          jobdata.errored = true;
          jobdata.error = {
            message: err.message,
            stack: err.stack
          };
          // self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error])
          delete jobdata.data;
          jobdata.finished = new Date();
          self.emitter.emit('job.done', jobdata);
          debug(`[runner:${self.id}] Job done with error. Project: ${job.project.name} Job ID: ${job._id}`);
          next(null);
          return;
        }
        var env = {};
        if (config.envKeys) {
          env.STRIDER_SSH_PUB = config.pubkey;
          env.STRIDER_SSH_PRIV = config.privkey;
        }
        self.config.processJob(job, workers.provider, workers.jobplugins, {
          cachier: cache,
          baseDir: dirs.base,
          dataDir: dirs.data,
          cacheDir: dirs.cache,
          io: self.config.io,
          branchConfig: config,
          env: env
        }, function (err) {
          var jobdata = self.jobdata.pop(job._id);
          if (!jobdata) return next(null);

          if (err) {
            jobdata.errored = true;
            jobdata.error = {
              message: err.message,
              stack: err.stack
            };
            self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error]);
            debug(`[runner:${self.id}] Job done with error. Project: ${job.project.name} Job ID: ${job._id}`);
          }

          delete jobdata.data;
          jobdata.finished = new Date();
          self.emitter.emit('job.done', jobdata);
          debug(`[runner:${self.id}] Job done without error. Project: ${job.project.name} Job ID: ${job._id}`);
          next(null);
        });
      });
    }
  }
};
<commit_msg>Fix lint<commit_after>'use strict';

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

var _ = require('lodash');
var async = require('async');
var debug = require('debug')('strider-simple-runner');
var EventEmitter2 = require('eventemitter2').EventEmitter2;
var Loader = require('strider-extension-loader');

var core = require('strider-runner-core');

var cachier = require('./cachier');
var keeper = require('dirkeeper');
var JobData = require('./jobdata');
var JobQueue = require('./jobqueue');
var branchFromJob = require('./utils').branchFromJob;

// timeout for callbacks. Helps to kill misbehaving plugins, etc
function t(time, done) {
  if (arguments.length === 1) {
    done = time;
    time = 2000;
  }
  var error = new Error(`Callback took too long (max: ${time})`);
  var waiting = true;

  var timeout = setTimeout(function () {
    if (!waiting) return;
    waiting = false;
    done(error);
  }, time);

  function handler() {
    if (!waiting) return;
    clearTimeout(timeout);
    waiting = false;
    done.apply(this, arguments);
  }

  return handler;
}

module.exports = Runner;

/*
 * Options:
 *    pty: use 'pty'
 *    io: the means of communication with the job worker
 *    pluginDir: the directory in which to look for plugins
 *    dataDir: the directory in which to clone/test/etc
 */
function Runner(emitter, config) {
  debug('RUNNER INIT');
  var dotStrider = path.join(process.env.HOME || '/', '.strider');
  this.config = _.extend({
    pty: false,
    io: new EventEmitter2({
      wildcard: true
    }),
    processJob: core.process,
    pluginDir: path.join(__dirname, '../node_modules'),
    dataDir: process.env.STRIDER_CLONE_DEST || dotStrider,
    concurrentJobs: parseInt(process.env.CONCURRENT_JOBS || '1', 10) || 1,
    defaultRecentBuilds: parseInt(process.env.DEFAULT_RECENT_BUILDS || '1', 10) || 1
  }, config);
  this.emitter = emitter;
  this.queue = new JobQueue(this.processJob.bind(this), this.config.concurrentJobs);
  this.io = this.config.io;
  this.callbackMap = {};
  this.hooks = [];
  this.jobdata = new JobData(this.io);
  this.attach();
}

// base: the base directory where all jobs data for this project and branch is stored
// the job object.
// done(err, {base:, data:, cache:})
function initJobDirs(branchBase, job, cache, done) {
  var dirs = {
    base: branchBase,
    data: path.join(branchBase, `job-${job._id.toString()}`),
    cache: cache
  };

  async.series([
    function checkData(next) {
      fs.exists(dirs.data, function (exists) {
        if (!exists) return next();
        fs.remove(dirs.data, function () {
          next();
        });
      });
    },
    fs.mkdirp.bind(null, dirs.data),
    fs.mkdirp.bind(null, dirs.cache)
  ], function (err) {
    done(err, dirs);
  });
}

Runner.prototype = {
  id: 'simple-runner',

  // public API
  loadExtensions: function (dirs, done) {
    var self = this;
    var loader = new Loader();
    loader.collectExtensions(dirs, function (err) {
      if (err) return done(err);
      loader.initWorkerExtensions({}, function (err, extensions) {
        if (err) return done(err);
        self.extensions = extensions;
        done(null);
      });
    });
  },

  getJobData: function (id) {
    return this.jobdata.get(id);
  },

  // Determine which jobs are zombies. This is called when strider
  // starts up.
  //
  // jobs: unfinished jobs that belong to this runner
  // done(err, zombies)
  findZombies: function (jobs, done) {
    done(null, jobs);
  },

  // private API
  attach: function () {
    var self = this;
    this.emitter.on('job.new', this.queueJob.bind(this));
    this.emitter.on('job.cancel', this.cancelJob.bind(this));
    this.emitter.on('job.info', function (id, respond) {
      var job = self.jobdata.get(id);
      if (job) respond(job);
    });
    function proxy(id) {
      // proxy up job.status.* updates as browser events
      var job = self.jobdata.get(id);
      var project = job && job.data.project.name;
      if (!job) return;
      self.emitter.emit('browser.update', project, this.event, [].slice.call(arguments));
    }

    this.io.on('job.status.**', proxy);
    this.io.on('job.cancelled', function (id) {
      // our running job was cancelled, so we need to start the next one
      var jobdata = self.jobdata.pop(id);
      self.emitter.emit('job.cancelled', id, jobdata);
      if (!jobdata) {
        jobdata = {
          _id: id
        };
        debug('Job cancelled, but no data!', id);
      }
      jobdata.errored = true;
      jobdata.error = {
        message: 'Cancelled by the user'
      };
      // self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error])
      delete jobdata.data;
      jobdata.finished = new Date();
      self.emitter.emit('job.done', jobdata);
      if (!self.callbackMap[id]) {
        debug('Job cancelled, but no callback found. The queue is probably broken.');
        return self.queue.process();
      }
      self.callbackMap[id]();
      delete self.callbackMap[id];
    });
    // proxy up plugin events
    this.io.on('plugin.**', function () {
      self.emitter.emit.apply(self.emitter, [this.event].concat([].slice.call(arguments)));
    });
  },

  queueJob: function (job, config) {
    if (config.runner.id !== this.id) return;
    var now = new Date();
    this.jobdata.add(job);
    this.queue.push(job, config);
    this.emitter.emit('browser.update', job.project.name, 'job.status.queued', [job._id, now]);
    debug(`[runner:${this.id}] Queued new job. Project: ${job.project.name} Job ID: ${job._id}`);
  },

  cancelJob: function (id) {
    var jobdata;
    for (var i = 0; i < this.queue.tasks.length; i++) {
      if (this.queue.tasks[i].job._id.toString() === id.toString()) {
        this.queue.tasks.splice(i, 1);
        debug(`[runner:${this.id}] Cancelled job. Job ID: ${id}`);
        jobdata = this.jobdata.pop(id);
        jobdata.errored = true;
        jobdata.error = {
          message: 'Cancelled by the user'
        };
        // self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error])
        delete jobdata.data;
        jobdata.started = new Date();
        jobdata.finished = new Date();
        this.emitter.emit('job.done', jobdata);
        return;
      }
    }
    // if it wasn't found in the queue, fire to the worker in case it is in process
    this.io.emit('job.cancel', id);
  },

  // initialize the provider and job plugins for a job
  // dirs = {base:, data:, cache:}
  plugins: function (user, config, job, dirs, done) {
    var self = this;
    var tasks = [function (next) {
      var plugin = self.extensions.provider[job.project.provider.id];
      if (!plugin) {
        var msg = `Provider plugin '${job.project.provider.id}' not found in this environment!`;
        return next(new Error(msg));
      }
      var finished = t(function (err, provider) {
        if (provider) provider.id = job.project.provider.id;
        next(err, provider);
      });
      if (!plugin.hosted) {
        return plugin.init(dirs, job.providerConfig, job, finished);
      }
      plugin.init(dirs, user.account(job.project.provider).config, job.providerConfig, job, finished);
    }];
    // XXX: do we want/need more things in the context? See
    // extension-loader readme for what gets passed in to the
    // individual phase functions as "Phase context"
    var context = {
      baseDir: dirs.base,
      dataDir: dirs.data,
      cacheDir: dirs.cache
    };
    var anyPluginFailed = config.plugins.some(function (plugin) {
      if (false === plugin.enabled) {
        debug(`[runner:${self.id}] Found a disabled plugin: ${plugin.id} Project: ${job.project.name} Job ID: ${job._id}`);
        return;
      }
      if (!self.extensions.job[plugin.id]) {
        debug(`[runner:${self.id}] Error: Plugin not found ${plugin.id} Project: ${job.project.name} Job ID: ${job._id}`);
        debug('Plugin not found', plugin.id);
        done(new Error(`Plugin required but not found: ${plugin.id}`));
        return true;
      }
      debug(`Initializing plugin '${plugin.id}'...`);
      tasks.push(function (next) {
        var fn = self.extensions.job[plugin.id].init;
        var cb = t(function (err, obj) {
          if (obj) obj.id = plugin.id;
          next(err, obj);
        });
        switch (fn.length) {
        case 1:
          return fn(cb);
        case 2:
          return fn(plugin.config, cb);
        case 3:
          return fn(plugin.config, context, cb);
        case 4:
          return fn(plugin.config, job, context, cb);
        default:
          return fn(user.jobplugins && user.jobplugins[plugin.id], plugin.config, job, context, cb);
        }
      });
    });
    if (anyPluginFailed) return;
    async.parallel(tasks, function (err, results) {
      if (err) return done(err);
      done(null, {
        provider: results.shift(),
        jobplugins: results
      });
    });
  },

  cacheDir: function (project) {
    return path.join(this.config.dataDir, 'cache', project.name);
  },

  getCache: function (project) {
    return cachier(this.cacheDir(project));
  },

  clearCache: function (project, done) {
    fs.remove(this.cacheDir(project), function (err) {
      done(err && new Error(`Failed to clear the cache. Error code: ${err}`));
    });
  },

  processJob: function (job, config, next) {
    var cache = this.getCache(job.project);
    var now = new Date();
    var self = this;
    var oldnext = next;
    next = function () {
      delete self.callbackMap[job._id];
      oldnext();
    };
    this.callbackMap[job._id] = next;

    var projectName = job.project.name.replace('/', '-');
    var branchName = branchFromJob(job).replace('/', '-');
    var branchBase = path.join(self.config.dataDir, 'data', `${projectName}-${branchName}`);
    var recentBuilds = _.get(config, 'runner.config.recentBuilds');

    if (typeof recentBuilds === 'undefined') {
      recentBuilds = self.config.defaultRecentBuilds;
    }

    recentBuilds = Math.max(recentBuilds, 1);

    if (recentBuilds > 1) {
      debug(`Preserving the most recent ${recentBuilds} builds within ${branchBase}.`);
    }

    // Keep around N most recent build directories for this branch.
    // The default is 0, ie wipe at start of each run.
    // Later, this can be configurable in the UI.
    keeper({baseDir: branchBase, count: recentBuilds - 1}, function (err) {
      if (err) return next(err);

      initJobDirs(branchBase, job, cache.base, jobDirsReady);
    });

    function jobDirsReady(err, dirs) {
      if (err) {
        var jobdata = self.jobdata.pop(job._id);
        if (!jobdata) return next(null);
        jobdata.errored = true;
        jobdata.error = {
          message: err.message,
          stack: err.stack
        };
        // self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error])
        delete jobdata.data;
        jobdata.finished = new Date();
        self.emitter.emit('job.done', jobdata);
        next(null);
        return;
      }
      self.jobdata.get(job._id).started = now;
      self.emitter.emit('browser.update', job.project.name, 'job.status.started', [job._id, now]);
      debug(`[runner:${self.id}] Job started. Project: ${job.project.name} Job ID: ${job._id}`);
      debug('Initializing plugins...');
      self.plugins(job.project.creator, config, job, dirs, function (err, workers) {
        if (err) {
          var jobdata = self.jobdata.pop(job._id);
          if (!jobdata) return next(null);
          jobdata.errored = true;
          jobdata.error = {
            message: err.message,
            stack: err.stack
          };
          // self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error])
          delete jobdata.data;
          jobdata.finished = new Date();
          self.emitter.emit('job.done', jobdata);
          debug(`[runner:${self.id}] Job done with error. Project: ${job.project.name} Job ID: ${job._id}`);
          next(null);
          return;
        }
        var env = {};
        if (config.envKeys) {
          env.STRIDER_SSH_PUB = config.pubkey;
          env.STRIDER_SSH_PRIV = config.privkey;
        }
        self.config.processJob(job, workers.provider, workers.jobplugins, {
          cachier: cache,
          baseDir: dirs.base,
          dataDir: dirs.data,
          cacheDir: dirs.cache,
          io: self.config.io,
          branchConfig: config,
          env: env
        }, function (err) {
          var jobdata = self.jobdata.pop(job._id);
          if (!jobdata) return next(null);

          if (err) {
            jobdata.errored = true;
            jobdata.error = {
              message: err.message,
              stack: err.stack
            };
            self.emitter.emit('browser.update', job.project.name, 'job.status.errored', [job._id, jobdata.error]);
            debug(`[runner:${self.id}] Job done with error. Project: ${job.project.name} Job ID: ${job._id}`);
          }

          delete jobdata.data;
          jobdata.finished = new Date();
          self.emitter.emit('job.done', jobdata);
          debug(`[runner:${self.id}] Job done without error. Project: ${job.project.name} Job ID: ${job._id}`);
          next(null);
        });
      });
    }
  }
};
<|endoftext|>


<commit_before>$( "#nav-toggle" ).on('click', function() {
  $( "#nav-menu" ).slideToggle( "slow" );
  $(this).toggleClass( 'is-active' );
});
<commit_msg>Update nav.js<commit_after>$( "#nav-toggle" ).on('click', function() {
  $( "#nav-menu" ).slideToggle( "slow" );
  $(this).toggleClass( 'is-active' );
});

<|endoftext|>


<commit_before>  game.GameTimerManager = Object.extend({
      init:function(x, y, settings){
          this.now = new Date (). getTime();
          this.lastCreep = new Date () . getTime();
          this.paused = false;
          this.alwaysUpdate=true;

    },
    update: function() {
        this.now = new Date().getTime();
        this.goldTimerCheck();
        this.creepTimerCheck();

        return true;
     },

    goldTimerCheck: function (){
            if (Math.round(this.now / 1000) % 20 === 0 && (this.now - this.lastCreep >= 1000)) {
            game.data.gold+= game.data.exp1+1;
            console.log("Current gold: " + game.data.gold);
        }
    },

    creepTimerCheck: function (){

        if (Math.round(this.now / 1000) % 10 === 0 && (this.now - this.lastCreep >= 1000)) {
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
            me.game.world.addChild(creepe, 5);
        }
    }
});

  game.HeroDeathManager = Object.extend({
      init: function(x, y, settings) {
          this.alwaysUpdate= true;

      },
      update: function (){
          if(game.data.player.dead){
              me.game.world.removeChild(game.data.player);
              me.state.current().resetPlayer(10, 0);
          }
      }
  });

  game.ExperienceManager = Object.extend ({
     init: function (x, y, settings) {
         this.alwaysUpdate = true;
         this.gameOver = false;
     },

     update: function() {
         if(game.data.win=== true && !this.gameOver){
            this.gameOver= true;
         }else if(game.data.win=== false && !this.gameOver){
                this.gameOver(false);
         }

         return true;
     },

     gameOver: function (win) {
         if(win) {
           game.data.exp += 10;
         }else{
              game.data.exp += 1;
         }
         console.log(game.data.exp);
         this.gameOver = true;
          me.save.exp = game.data.exp;
     }

  });

  game.SpendGold = Object.extend ({
      init: function (x, y, settings) {
          this.now = new Date (). getTime();
          this.lastBuy= new Date () . getTime();
          this.paused = false;
          this.alwaysUpdate=true;
          this.updateWhenPaused = true;

      },
      update: function () {
          this.now = new Date (). getTime();
          if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >= 1000 ) {
              this.lastBuy = this.now;
              if(!this.buying) {
                  this.startBuying();
              }else{
              this.stopBuying();

              }
          }

          this.checkBuyKeys();
          return true;

      },

      startBuying: function () {
          this.buying = true;
          me.state.pause(me.state.PLAY);
          game.data.pausePos = me.game.viewport.localToWorld(0, 0 );
          game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
          game.data.buyscreen.updateWhenPaused = true;
          game.data.buyscreen.setOpacity(0.8);
          me.game.world.addChild(game.data.buyscreen, 54);
          game.data.player.body.setVelocity(0, 0);
          me.input.bindKey(me.input.KEY.F1, "F1", true);
          me.input.bindKey(me.input.KEY.F2, "F2", true);
          me.input.bindKey(me.input.KEY.F3, "F3", true);
          me.input.bindKey(me.input.KEY.F4, "F4", true);
          me.input.bindKey(me.input.KEY.F5, "F5", true);
          me.input.bindKey(me.input.KEY.F6, "F6", true);
          this.setBuyText();

      },

      setBuyText: function(){
            game.data.buytext = (new (me.Renderable.extend ({
                    init: function () {
                        this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]);
                        this.font = new me.Font ("Arial", 46, "white");
                        this.updateWhenPaused = true;
                        this.alwaysUpdate = true;
                    },

                    draw: function (renderer) {
                        this.font.draw(renderer.getContext(), "PRESS F1-F4 TO BUY, AND B TO EXIT, SCRUB. Current Gold: " + game.data.gold, this.pos.x , this.pos.y); this.font.draw(renderer.getContext(), "CURRENT EXP: " + game.data.exp.toString(), this.pos.x + 100 , this.pos.y - 50);
                        this.font.draw(renderer.getContext(), " Skill 1:Increase Damage. Current Level:" + game.data.skill1 + "Cost: " + ((game.data.skill1+1)*10), this.pos.x ,  this.pos.y + 40);
                        this.font.draw(renderer.getContext(), " Skill 2:Run Faster: Current Level" + game.data.skill2 + "Cost: " + ((game.data.skill2+1)*10), this.pos.x ,  this.pos.y + 80);
                        this.font.draw(renderer.getContext(), " Skill 3:Increase Health. Current Level" + game.data.skill3 + "Cost: " + ((game.data.skill3+1)*10), this.pos.x ,  this.pos.y + 120);
                        this.font.draw(renderer.getContext(), "QSKILL: Speed Burst. Current Level" + game.data.ability1 + "Cost: " + ((game.data.ability1+1)*10), this.pos.x ,  this.pos.y + 160);
                        this.font.draw(renderer.getContext(), "W SKILL: Eat your Creep for Health:" + game.data.ability2 + "Cost: " + ((game.data.abiility2+1)*10), this.pos.x ,  this.pos.y + 200);
                        this.font.draw(renderer.getContext(), "E SKILL: Throw your Spear:" + game.data.ability3 + "Cost: " + ((game.data.ability3+1)*10), this.pos.x ,  this.pos.y + 240);

                    }
                       })), 35);
             me.game.world.addChild(game.data.buytext, 35);
      },

      stopBuying: function () {
          this.buying = false;
          me.state.resume(me.state.PLAY);
          game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
          me.game.world.removeChild(game.data.buyscreen);
          me.input.unbindKey(me.input.KEY.F1, "F1", true);
          me.input.unbindKey(me.input.KEY.F2, "F2", true);
          me.input.unbindKey(me.input.KEY.F3, "F3", true);
          me.input.unbindKey(me.input.KEY.F4, "F4", true);
          me.input.unbindKey(me.input.KEY.F5, "F5", true);
          me.input.unbindKey(me.input.KEY.F6, "F6", true);
          me.game.world.removeChild(game.data.buytext);
      },

      checkBuyKeys: function ()  {
          if(me.input.isKeyPressed("F1")) {
                if(this.checkCost(1)){
             this.makePurchase(1);
          }

          }else if (me.input.isKeyPressed("F2")){
                 if(this.checkCost(2)){
             this.makePurchase(2);
         }
          }else if (me.input.isKeyPressed("F3")){
                 if(this.checkCost(3)){
             this.makePurchase(3);
         }
          }else if (me.input.isKeyPressed("F4")){
                 if(this.checkCost(4)){
             this.makePurchase(4);
         }
          }else if (me.input.isKeyPressed("F5")){
                 if(this.checkCost(5)){
             this.makePurchase(5);
         }
          }else if (me.input.isKeyPressed("F6")){
                 if(this.checkCost(6)){
             this.makePurchase(6);
          }
      }

      },

      checkCost: function (skill) {
          if(skill===1 && ( game.data.gold >= (game.data.skill1+1)*10)){
              return true;
          } else if(skill===1 && ( game.data.gold >= (game.data.skill1+1)*10)){
              return true;
          } else if(skill===1 && ( game.data.gold >= (game.data.skill1+1)*10)){
              return true;

           if(skill===1 && ( game.data.gold >= (game.data.skill1+1)*10)){
              return true;
          }
          } else{
              return false;
          }
      },

      makePurchase: function (skill) {

      }

  });<commit_msg>4.24.14<commit_after>  game.GameTimerManager = Object.extend({
      init:function(x, y, settings){
          this.now = new Date (). getTime();
          this.lastCreep = new Date () . getTime();
          this.paused = false;
          this.alwaysUpdate=true;

    },
    update: function() {
        this.now = new Date().getTime();
        this.goldTimerCheck();
        this.creepTimerCheck();

        return true;
     },

    goldTimerCheck: function (){
            if (Math.round(this.now / 1000) % 20 === 0 && (this.now - this.lastCreep >= 1000)) {
            game.data.gold+= game.data.exp1+1;
            console.log("Current gold: " + game.data.gold);
        }
    },

    creepTimerCheck: function (){

        if (Math.round(this.now / 1000) % 10 === 0 && (this.now - this.lastCreep >= 1000)) {
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
            me.game.world.addChild(creepe, 5);
        }
    }
});

  game.HeroDeathManager = Object.extend({
      init: function(x, y, settings) {
          this.alwaysUpdate= true;

      },
      update: function (){
          if(game.data.player.dead){
              me.game.world.removeChild(game.data.player);
              me.state.current().resetPlayer(10, 0);
          }
      }
  });

  game.ExperienceManager = Object.extend ({
     init: function (x, y, settings) {
         this.alwaysUpdate = true;
         this.gameOver = false;
     },

     update: function() {
         if(game.data.win=== true && !this.gameOver){
            this.gameOver= true;
         }else if(game.data.win=== false && !this.gameOver){
                this.gameOver(false);
         }

         return true;
     },

     gameOver: function (win) {
         if(win) {
           game.data.exp += 10;
         }else{
              game.data.exp += 1;
         }
         console.log(game.data.exp);
         this.gameOver = true;
          me.save.exp = game.data.exp;
     }

  });

  game.SpendGold = Object.extend ({
      init: function (x, y, settings) {
          this.now = new Date (). getTime();
          this.lastBuy= new Date () . getTime();
          this.paused = false;
          this.alwaysUpdate=true;
          this.updateWhenPaused = true;

      },
      update: function () {
          this.now = new Date (). getTime();
          if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >= 1000 ) {
              this.lastBuy = this.now;
              if(!this.buying) {
                  this.startBuying();
              }else{
              this.stopBuying();

              }
          }

          this.checkBuyKeys();
          return true;

      },

      startBuying: function () {
          this.buying = true;
          me.state.pause(me.state.PLAY);
          game.data.pausePos = me.game.viewport.localToWorld(0, 0 );
          game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
          game.data.buyscreen.updateWhenPaused = true;
          game.data.buyscreen.setOpacity(0.8);
          me.game.world.addChild(game.data.buyscreen, 54);
          game.data.player.body.setVelocity(0, 0);
          me.input.bindKey(me.input.KEY.F1, "F1", true);
          me.input.bindKey(me.input.KEY.F2, "F2", true);
          me.input.bindKey(me.input.KEY.F3, "F3", true);
          me.input.bindKey(me.input.KEY.F4, "F4", true);
          me.input.bindKey(me.input.KEY.F5, "F5", true);
          me.input.bindKey(me.input.KEY.F6, "F6", true);
          this.setBuyText();

      },

      setBuyText: function(){
            game.data.buytext = (new (me.Renderable.extend ({
                    init: function () {
                        this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]);
                        this.font = new me.Font ("Arial", 46, "white");
                        this.updateWhenPaused = true;
                        this.alwaysUpdate = true;
                    },

                    draw: function (renderer) {
                        this.font.draw(renderer.getContext(), "PRESS F1-F4 TO BUY, AND B TO EXIT, SCRUB. Current Gold: " + game.data.gold, this.pos.x , this.pos.y); this.font.draw(renderer.getContext(), "CURRENT EXP: " + game.data.exp.toString(), this.pos.x + 100 , this.pos.y - 50);
                        this.font.draw(renderer.getContext(), " Skill 1:Increase Damage. Current Level:" + game.data.skill1 + "Cost: " + ((game.data.skill1+1)*10), this.pos.x ,  this.pos.y + 40);
                        this.font.draw(renderer.getContext(), " Skill 2:Run Faster: Current Level" + game.data.skill2 + "Cost: " + ((game.data.skill2+1)*10), this.pos.x ,  this.pos.y + 80);
                        this.font.draw(renderer.getContext(), " Skill 3:Increase Health. Current Level" + game.data.skill3 + "Cost: " + ((game.data.skill3+1)*10), this.pos.x ,  this.pos.y + 120);
                        this.font.draw(renderer.getContext(), "QSKILL: Speed Burst. Current Level" + game.data.ability1 + "Cost: " + ((game.data.ability1+1)*10), this.pos.x ,  this.pos.y + 160);
                        this.font.draw(renderer.getContext(), "W SKILL: Eat your Creep for Health:" + game.data.ability2 + "Cost: " + ((game.data.abiility2+1)*10), this.pos.x ,  this.pos.y + 200);
                        this.font.draw(renderer.getContext(), "E SKILL: Throw your Spear:" + game.data.ability3 + "Cost: " + ((game.data.ability3+1)*10), this.pos.x ,  this.pos.y + 240);

                    }
                       })), 35);
             me.game.world.addChild(game.data.buytext, 35);
      },

      stopBuying: function () {
          this.buying = false;
          me.state.resume(me.state.PLAY);
          game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
          me.game.world.removeChild(game.data.buyscreen);
          me.input.unbindKey(me.input.KEY.F1, "F1", true);
          me.input.unbindKey(me.input.KEY.F2, "F2", true);
          me.input.unbindKey(me.input.KEY.F3, "F3", true);
          me.input.unbindKey(me.input.KEY.F4, "F4", true);
          me.input.unbindKey(me.input.KEY.F5, "F5", true);
          me.input.unbindKey(me.input.KEY.F6, "F6", true);
          me.game.world.removeChild(game.data.buytext);
      },

      checkBuyKeys: function ()  {
          if(me.input.isKeyPressed("F1")) {
                if(this.checkCost(1)){
             this.makePurchase(1);
          }

          }else if (me.input.isKeyPressed("F2")){
                 if(this.checkCost(2)){
             this.makePurchase(2);
         }
          }else if (me.input.isKeyPressed("F3")){
                 if(this.checkCost(3)){
             this.makePurchase(3);
         }
          }else if (me.input.isKeyPressed("F4")){
                 if(this.checkCost(4)){
             this.makePurchase(4);
         }
          }else if (me.input.isKeyPressed("F5")){
                 if(this.checkCost(5)){
             this.makePurchase(5);
         }
          }else if (me.input.isKeyPressed("F6")){
                 if(this.checkCost(6)){
             this.makePurchase(6);
          }
      }

      },

      checkCost: function (skill) {
          if(skill===1 && ( game.data.gold >= (game.data.skill1+1)*10)){
              return true;
          } else if(skill===2 && ( game.data.gold >= (game.data.skill2+1)*10)){
              return true;
          } else if(skill===3 && ( game.data.gold >= (game.data.skill3+1)*10)){
              return true;
          }else if(skill===4 && ( game.data.gold >= (game.data.skill4+1)*10)){
              return true;
          }  else if(skill===5 && ( game.data.gold >= (game.data.skill5+1)*10)){
              return true;
          } else if(skill===6 && ( game.data.gold >= (game.data.skill6+1)*10)){
              return true;
          }else{
              return false;
          }
      },

      makePurchase: function (skill) {
          if(skill1=== 1) {
           game.data.gold -= ((game.data.skill1 + 1)* 10);
           game.data.skill += 1;
           game.data.player.attack += 1;
     }else if (skill ===2) {
             game.data.gold -= ((game.data.skill2 + 1)* 10);
           game.data.skill2 += 1;
     }else if (skill === 3){
     game.data.gold -= ((game.data.skill3 + 1)* 10);
           game.data.skill3 += 1;
     }else if (skill === 4){
     game.data.gold -= ((game.ability1 + 1)* 10);
           game.data.ability1 += 1;
     }else if (skill === 5){
     game.data.gold -= ((game.data.ability2 + 1)* 10);
           game.data.ability2 += 1;
     }else if (skill === 6){
     game.data.gold -= ((game.data.ability3 + 1)* 10);
           game.data.ability3 += 1;
     }else{

     }

      }

  });<|endoftext|>