<commit_before>/*global workbox:true*/
/*eslint no-undef: "error"*/
"use strict";

/**
 * Configuration & setup
 * - Set name for precache & runtime cache
 * - Skip waiting and claim clients so we take over from any old workers
 * - Also make sure that if we are an old worker, we force reload the page to get freshest stuff
 */
const staticCacheName = "static",
	imageCacheName = "images",
	offlinePage = "/offline.html";

workbox.core.setCacheNameDetails({
	precache: "precache",
	prefix: "dg",
	suffix: "prod",
	runtime: "site",
});
workbox.skipWaiting();
workbox.clientsClaim();

var isRefreshing = false;

var refreshWindow = function() {
	if (isRefreshing) {
		return;
	}
	isRefreshing = true;
	window.location.reload();
};

self.addEventListener("controllerchange", refreshWindow);

/**
 * Enables navigation preload which we use in our default handler
 */
workbox.navigationPreload.enable();

/**
 * Precaching all the things!
 * - All data is specified in _config.yml
 * - This empty array will be filled out via jekyll
 */
workbox.precaching.precacheAndRoute([]);

/**
 * Routing for different filetypes & endpoints
 * - Stale while revalidate for js, css, and json
 * - Make sure we force all analytics calls to network only
 * - State while revalidate for fonts stylesheets
 * - Cache up to 60 images for 30 days
 */
workbox.routing.registerRoute(
	/.*\.(?:js|css|json)$/,
	workbox.strategies.staleWhileRevalidate({
		cacheName: staticCacheName
	})
);
workbox.routing.registerRoute(
	/^https?:\/\/www\.google-analytics\.com/,
	workbox.strategies.networkOnly()
);
workbox.routing.registerRoute(
	/^https?:\/\/*google*\.com/,
	workbox.strategies.networkOnly()
);
workbox.routing.registerRoute(
	/^https?:\/\/use\.typekit\.net/,
	workbox.strategies.staleWhileRevalidate({
		cacheName: staticCacheName,
		plugins: [
			new workbox.cacheableResponse.Plugin({
				statuses: [0, 200],
			}),
		],
	})
);
workbox.routing.registerRoute(
	/^https?:\/\/p\.typekit\.net/,
	workbox.strategies.cacheFirst({
		cacheName: staticCacheName,
		plugins: [
			new workbox.cacheableResponse.Plugin({
				statuses: [0, 200],
			}),
			new workbox.expiration.Plugin({
				maxAgeSeconds: 60 * 60 * 24 * 120,
			}),
		],
	})
);
workbox.routing.registerRoute(
	/\.(?:png|gif|jpg|jpeg|svg|webp)$/,
	workbox.strategies.cacheFirst({
		cacheName: imageCacheName,
		plugins: [
			new workbox.expiration.Plugin({
				maxEntries: 60,
				maxAgeSeconds: 60 * 60 * 24 * 30,
			}),
		],
	}),
);

/**
 * Default handler & catch handler
 * - There's a default handler here that will fetch using networkFirst, but
 *   if offline, will try to return an offline page
 * - The regular catch handler is set up to return an offline page if we can't find something that matches.
 *   Otherwise, we'll return an error response
 */
const fetchWithOfflineFallback = async (args) => {
	try {
		// Use the preloaded response, if it's there
		const preloadResponse = await args.preloadResponse;

		if (preloadResponse) {
			return preloadResponse;
		}

		// Otherwise, try network first with a fallback to the offline page
		const response = await workbox.strategies.networkFirst().handle(args);

		return response || await caches.match(offlinePage);
	} catch (error) {
		return await caches.match(offlinePage);
	}
};

workbox.routing.setDefaultHandler(fetchWithOfflineFallback);
workbox.routing.setCatchHandler(({event}) => {
	if (event.request.cache === "only-if-cached" &&
		event.request.mode !== "same-origin") {
		return new Response();
	}
	switch (event.request.destination) {
	case "document":
		return caches.match(offlinePage);
	default:
		return Response.error();
	}
});
<commit_msg>Cache font files for 120 days, 404 not cached<commit_after>/*global workbox:true*/
/*eslint no-undef: "error"*/
"use strict";

/**
 * Configuration & setup
 * - Set name for precache & runtime cache
 * - Skip waiting and claim clients so we take over from any old workers
 * - Also make sure that if we are an old worker, we force reload the page to get freshest stuff
 */
const staticCacheName = "static",
	vendorCacheName = "vendor-static",
	imageCacheName = "images",
	offlinePage = "/offline.html";

workbox.core.setCacheNameDetails({
	precache: "precache",
	prefix: "dg",
	suffix: "prod",
	runtime: "site",
});
workbox.skipWaiting();
workbox.clientsClaim();

var isRefreshing = false;

var refreshWindow = function() {
	if (isRefreshing) {
		return;
	}
	isRefreshing = true;
	window.location.reload();
};

self.addEventListener("controllerchange", refreshWindow);

/**
 * Enables navigation preload which we use in our default handler
 */
workbox.navigationPreload.enable();

/**
 * Precaching all the things!
 * - All data is specified in _config.yml
 * - This empty array will be filled out via jekyll
 */
workbox.precaching.precacheAndRoute([]);

/**
 * Routing for different filetypes & endpoints
 * - Force 404 page to network only since we don't need it offline
 * - Force all analytics calls to network only
 * - Cache the actual font files (use.typekit.net/af) for 120 days
 * - State while revalidate for fonts stylesheets
 * - Stale while revalidate for js, css, and json
 * - Cache up to 60 images for 30 days
 */
workbox.routing.registerRoute(
	/404.html/,
	workbox.strategies.networkOnly()
);
workbox.routing.registerRoute(
	/^https?:\/\/www\.google-analytics\.com/,
	workbox.strategies.networkOnly()
);
workbox.routing.registerRoute(
	/^https?:\/\/*google*\.com/,
	workbox.strategies.networkOnly()
);
workbox.routing.registerRoute(
	/^https?:\/\/.*.typekit\.net\/af/,
	workbox.strategies.cacheFirst({
		cacheName: vendorCacheName,
		plugins: [
			new workbox.cacheableResponse.Plugin({
				statuses: [0, 200],
			}),
			new workbox.expiration.Plugin({
				maxAgeSeconds: 60 * 60 * 24 * 120,
			}),
		],
	})
);
workbox.routing.registerRoute(
	/^https?:\/\/.*.typekit\.net/,
	workbox.strategies.staleWhileRevalidate({
		cacheName: vendorCacheName,
		plugins: [
			new workbox.cacheableResponse.Plugin({
				statuses: [0, 200],
			}),
		],
	})
);
workbox.routing.registerRoute(
	/.*\.(?:js|css|json)$/,
	workbox.strategies.staleWhileRevalidate({
		cacheName: staticCacheName
	})
);
workbox.routing.registerRoute(
	/\.(?:png|gif|jpg|jpeg|svg|webp)$/,
	workbox.strategies.cacheFirst({
		cacheName: imageCacheName,
		plugins: [
			new workbox.expiration.Plugin({
				maxEntries: 60,
				maxAgeSeconds: 60 * 60 * 24 * 30,
			}),
		],
	}),
);

/**
 * Default handler & catch handler
 * - There's a default handler here that will fetch using networkFirst, but
 *   if offline, will try to return an offline page
 * - The regular catch handler is set up to return an offline page if we can't find something that matches.
 *   Otherwise, we'll return an error response
 */
const fetchWithOfflineFallback = async (args) => {
	try {
		// Use the preloaded response, if it's there
		const preloadResponse = await args.preloadResponse;

		if (preloadResponse) {
			return preloadResponse;
		}

		// Otherwise, try network first with a fallback to the offline page
		const response = await workbox.strategies.networkFirst().handle(args);

		return response || await caches.match(offlinePage);
	} catch (error) {
		return await caches.match(offlinePage);
	}
};

workbox.routing.setDefaultHandler(fetchWithOfflineFallback);
workbox.routing.setCatchHandler(({event}) => {
	if (event.request.cache === "only-if-cached" &&
		event.request.mode !== "same-origin") {
		return new Response();
	}
	switch (event.request.destination) {
	case "document":
		return caches.match(offlinePage);
	default:
		return Response.error();
	}
});
<|endoftext|>


<commit_before>/*
 *  Large join() needs a valstack check.  Even larger joins run
 *  out of valstack unless the join is done in stages.
 *
 *  These were broken at some point.
 */

/*===
100
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
===*/

/* 100 elements */
tmp = [
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9
];

print(tmp.length);

print(tmp.join(''));

/*===
building
joining
1000000
===*/

/* This was broken at some point: joining happened naively through the
 * valstack whose size topped out for large joins.
 */

tmp = [];
var i;

print('building');
for (i = 1000000; i; i -= 1) {  // funny syntax; current version does not support comparisons yet
	tmp[tmp.length] = 'x';
}

print('joining');
print(tmp.join('').length);

<commit_msg>improve large join testcase<commit_after>/*
 *  Large join() needs a valstack check.  Even larger joins run
 *  out of valstack unless the join is done in stages.
 *
 *  These were broken at some point.
 */

/*===
100
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
===*/

/* 100 elements */
tmp = [
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9,
    0,1,2,3,4,5,6,7,8,9
];

print(tmp.length);
print(tmp.join(''));

/*===
building
1000000
joining
1000000
checking
ok
===*/

/* This was broken at some point: joining happened naively through the
 * valstack whose size topped out for large joins.
 */

tmp = [];
var i;
var res;

print('building');
for (i = 0; i < 1000000; i++) {
	tmp[tmp.length] = String.fromCharCode(i % 65536);
}
print(tmp.length);

print('joining');
res = tmp.join('');
print(res.length);

print('checking');
for (i = 0; i < 1000000; i++) {
    if (res.charCodeAt(i) !== (i % 65536)) {
        throw new Error('invalid char at offset ' + i);
    }
}

print('ok');
<|endoftext|>


<commit_before>function Ui(ui_container) {
    this.container(ui_container);
    this.board(null);
    this.displayed_board(null);
    this.row(0);
    this.column(0);
    this.displayed_row(null);
}

accessor(Ui, "container");
accessor(Ui, "board");
accessor(Ui, "displayed_board");
accessor(Ui, "row");
accessor(Ui, "column");
accessor(Ui, "displayed_row");

Ui.prototype.cell_class= function() {
    return this.board().cell_color(this.row(), this.column()) + "-cell";
}

Ui.prototype.cell_contents= function() {
    if (this.board().is_ant_at(this.row(), this.column()))
	return "";
    return "";
};

Ui.prototype.start_row= function() {
    this.displayed_row($("

").appendTo(this.displayed_board()));
};

Ui.prototype.done= function() {
    return this.row() >= this.board().height();
};

Ui.prototype.display= function(a_board) {
    this.board(a_board);
    this.displayed_board($("

").appendTo(this.container()));
    while (!this.done()) {
	this.start_row();
	while (this.column() < this.board().width()) {
	    $("" + this.cell_contents() + "	").appendTo(this.displayed_row());
	    this.column(this.column() + 1);
	}
	this.column(0);
	this.row(this.row() + 1);
    }
};
<commit_msg>Refactoring: flattened nested loops in Ui.display()<commit_after>function Ui(ui_container) {
    this.container(ui_container);
    this.board(null);
    this.displayed_board(null);
    this.row(0);
    this.column(0);
    this.displayed_row(null);
}

accessor(Ui, "container");
accessor(Ui, "board");
accessor(Ui, "displayed_board");
accessor(Ui, "row");
accessor(Ui, "column");
accessor(Ui, "displayed_row");

Ui.prototype.cell_class= function() {
    return this.board().cell_color(this.row(), this.column()) + "-cell";
}

Ui.prototype.cell_contents= function() {
    if (this.board().is_ant_at(this.row(), this.column()))
	return "";
    return "";
};

Ui.prototype.start_row= function() {
    this.displayed_row($("

").appendTo(this.displayed_board()));
};

Ui.prototype.done= function() {
    return this.row() >= this.board().height();
};

Ui.prototype.display= function(a_board) {
    this.board(a_board);
    this.displayed_board($("

").appendTo(this.container()));
    while (!this.done()) {
	if (this.column() === 0)
	    this.start_row();

	$("" + this.cell_contents() + "	").appendTo(this.displayed_row());
	this.column(this.column() + 1);

	if (this.column() >= this.board().width()) {
	    this.column(0);
	    this.row(this.row() + 1);
	}
    }
};
<|endoftext|>


<commit_before>(function() {
  /**
   * The CPU of the emulator, responsible for processing memory opcodes.
   *
   * @class Chip8.VM
   * @constructor
   */
  var VM = function VM() {
    this.pc = 0x200;
    this.stack = new Array;
    this.screen = { clear: function() {}, render: function() {}, setPixel: function() {} };
    this.input = { isKeyPressed: function(key) {} };
    this.v = new Uint8Array(16);
    this.i = 0;
    this.memory = new Uint8Array(4096);
    this.delayTimer = 0;
    this.soundTimer = 0;
    this.paused = false;
    this.speed = 10;

    /**
     * Loads the CHIP8 fonts into memory.
     * Detailed information can be found at: http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#font
     * @method loadFonts
     * @private
     */
    var loadFonts = function() {
      var fonts = [
        0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
        0x20, 0x60, 0x20, 0x20, 0x70, // 1
        0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
        0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
        0x90, 0x90, 0xF0, 0x10, 0x10, // 4
        0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
        0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
        0xF0, 0x10, 0x20, 0x40, 0x40, // 7
        0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
        0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
        0xF0, 0x90, 0xF0, 0x90, 0x90, // A
        0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
        0xF0, 0x80, 0x80, 0x80, 0xF0, // C
        0xE0, 0x90, 0x90, 0x90, 0xE0, // D
        0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
        0xF0, 0x80, 0xF0, 0x80, 0x80  // F
      ];

      for (var i = 0, length = fonts.length; i < length; i++) {
        this.memory[i] = fonts[i];
      }
    }

    /**
     * Reset the VM with the default values.
     * @method reset
     */
    this.reset = function() {
      this.pc = 0x200;
      this.stack = new Array;
      this.v = new Uint8Array(16);
      this.i = 0;
      this.memory = new Uint8Array(4096);
      this.delayTimer = 0;
      this.soundTimer = 0;
      this.screen.clear();
      this.input.clear();
      loadFonts();
      this.paused = false;
    }

    /**
     * Loads a program into the memory.
     * @method loadProgram
     * @param {Array} program array of bytes of a CHIP8 program
     */
    this.loadProgram = function(program) {
      for (var i = 0, length = program.length; i < length; i++) {
        this.memory[0x200 + i] = program[i];
      }
    }

    /**
     * The main CPU cycle.
     * @method cycle
     */
    this.cycle = function() {
      for (var i = 0; i < this.speed; i++) {
        if (!this.paused) {
          var opcode = this.memory[this.pc] << 8 | this.memory[this.pc + 1];
          this.perform(opcode);
          this.updateTimers();
        }
      }

      this.render();
    }

    /**
     * Process a given opcode.
     * @method perform
     * @param {Integer} opcode
     */
    this.perform = function(opcode) {
      this.pc += 2;

      var x = (opcode & 0x0F00) >> 8;
      var y = (opcode & 0x00F0) >> 4;

      switch (opcode & 0xF000) {
        case 0x000:
          switch(opcode) {
            case 0x00E0:
              this.screen.clear();
              break;

            case 0x00EE:
              this.pc = this.stack.pop();
              break;
          }
          break;

        case 0xA000:
          this.i = opcode & 0x0FFF;
          break;

        case 0xB000:
          this.pc = (opcode & 0x0FFF) + this.v[0];
          break;

        case 0x1000:
          this.pc = opcode & 0x0FFF;
          break;

        case 0x2000:
          this.stack.push(this.pc);
          this.pc = opcode & 0x0FFF;
          break;

        case 0x3000:
          if (this.v[x] == (opcode & 0x00FF)) {
            this.pc += 2;
          }
          break;

        case 0x4000:
          if (this.v[x] != (opcode & 0x00FF)) {
            this.pc += 2;
          }
          break;

        case 0x5000:
          if (this.v[x] == this.v[y]) {
            this.pc += 2;
          }
          break;

        case 0x6000:
          this.v[x] = opcode & 0x00FF;
          break;

        case 0x7000:
          this.v[x] += opcode & 0x00FF;
          break;

        case 0x8000:
          switch (opcode & 0x000F) {
            case 0x0000:
              this.v[x] = this.v[y];
              break;

            case 0x0001:
              this.v[x] = this.v[x] | this.v[y];
              break;

            case 0x0002:
              this.v[x] = this.v[x] & this.v[y];
              break;

            case 0x0003:
              this.v[x] = this.v[x] ^ this.v[y];
              break;

            case 0x0004:
              var sum = this.v[x] + this.v[y];

              if (sum > 0xFF) {
                this.v[0xF] = 1;
              } else {
                this.v[0xF] = 0;
              }

              this.v[x] = sum;
              break;

            case 0x0005:
              if(this.v[x] > this.v[y]) {
                this.v[0xF] = 1;
              } else {
                this.v[0xF] = 0;
              }

              this.v[x] = this.v[x] - this.v[y];
              break;

            case 0x0006:
              this.v[0xF] = this.v[x] & 0x01;
              this.v[x] = this.v[x] >> 1;
              break;

            case 0x0007:
              if (this.v[x] > this.v[y]) {
                this.v[0xF] = 0;
              } else {
                this.v[0xF] = 1;
              }

              this.v[x] = this.v[y] - this.v[x];
              break;

            case 0x000E:
              this.v[0xF] = this.v[x] & 0x80;
              this.v[x] = this.v[x] << 1;
              break;
          }
          break;

        case 0x9000:
          if (this.v[x] != this.v[y]) this.pc += 2;
          break;

        case 0xC000:
          this.v[x] = Math.floor(Math.random() * 0xFF) & (opcode & 0x00FF);
          break;

        case 0xD000:
          var row, col, sprite
            , width = 8
            , height = opcode & 0x000F;

          this.v[0xF] = 0;

          for (row = 0; row < height; row++) {
            sprite = this.memory[this.i + row];

            for (col = 0; col < width; col++) {
              if ((sprite & 0x80) > 0) {
                if (this.screen.setPixel(this.v[x] + col, this.v[y] + row)) {
                  this.v[0xF] = 1;
                }
              }

              sprite = sprite << 1;
            }
          }

          break;

        case 0xE000:
          switch (opcode & 0x00FF) {
            case 0x009E:
              if (this.input.isKeyPressed(this.v[x])) {
                this.pc += 2;
              }
              break;

            case 0x00A1:
              if (!this.input.isKeyPressed(this.v[x])) {
                this.pc += 2;
              }
              break;
          }
          break;

        case 0xF000:
          switch (opcode & 0x00FF) {
            case 0x0007:
              this.v[x] = this.delayTimer;
              break;

            case 0x000A:
              this.paused = true;

              this.input.onKeyPress = function(key) {
                this.v[x] = key;
                this.paused = false;
                this.input.onKeyPress = function() {}
              }.bind(this);

            case 0x0015:
              this.delayTimer = this.v[x];
              break;

            case 0x0018:
              this.soundTimer = this.v[x];
              break;

            case 0x0029:
              this.i = this.v[x] * 5;
              break;

            case 0x0033:
              this.memory[this.i]     = parseInt(this.v[x] / 100);
              this.memory[this.i + 1] = parseInt(this.v[x] % 100 / 10);
              this.memory[this.i + 2] = this.v[x] % 10;
              break;

            case 0x0055:
              for (var i = 0; i <= x; i++) {
                this.memory[this.i + i] = this.v[i];
              }
              break;

            case 0x0065:
              for (var i = 0; i <= x; i++) {
                this.v[i] = this.memory[this.i + i];
              }
              break;

            case 0x001E:
              this.i += this.v[x];
              break;
          }

          break;

        default:
          throw new Error("Unknow opcode " + opcode.toString(16) + " informed.");
      }
    }

    /**
     * Renders the screen.
     * @method render
     */
    this.render = function() {
      this.screen.render();
    }

    /**
     * Updates the CPU delay and sound timers.
     * More info at: http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.5
     * @method updateTimers
     */
    this.updateTimers = function() {
      if (this.delayTimer > 0) this.delayTimer -= 1;
      if (this.soundTimer > 0) this.soundTimer -= 1;
    }
  }

  if (typeof module != "undefined") {
    module.exports = VM;
  } else {
    window.Chip8.VM = VM;
  }
})();
<commit_msg>Fixing the opcodes ordering.<commit_after>(function() {
  /**
   * The CPU of the emulator, responsible for processing memory opcodes.
   *
   * @class Chip8.VM
   * @constructor
   */
  var VM = function VM() {
    this.pc = 0x200;
    this.stack = new Array;
    this.screen = { clear: function() {}, render: function() {}, setPixel: function() {} };
    this.input = { isKeyPressed: function(key) {} };
    this.v = new Uint8Array(16);
    this.i = 0;
    this.memory = new Uint8Array(4096);
    this.delayTimer = 0;
    this.soundTimer = 0;
    this.paused = false;
    this.speed = 10;

    /**
     * Loads the CHIP8 fonts into memory.
     * Detailed information can be found at: http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#font
     * @method loadFonts
     * @private
     */
    var loadFonts = function() {
      var fonts = [
        0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
        0x20, 0x60, 0x20, 0x20, 0x70, // 1
        0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
        0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
        0x90, 0x90, 0xF0, 0x10, 0x10, // 4
        0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
        0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
        0xF0, 0x10, 0x20, 0x40, 0x40, // 7
        0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
        0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
        0xF0, 0x90, 0xF0, 0x90, 0x90, // A
        0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
        0xF0, 0x80, 0x80, 0x80, 0xF0, // C
        0xE0, 0x90, 0x90, 0x90, 0xE0, // D
        0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
        0xF0, 0x80, 0xF0, 0x80, 0x80  // F
      ];

      for (var i = 0, length = fonts.length; i < length; i++) {
        this.memory[i] = fonts[i];
      }
    }

    /**
     * Reset the VM with the default values.
     * @method reset
     */
    this.reset = function() {
      this.pc = 0x200;
      this.stack = new Array;
      this.v = new Uint8Array(16);
      this.i = 0;
      this.memory = new Uint8Array(4096);
      this.delayTimer = 0;
      this.soundTimer = 0;
      this.screen.clear();
      this.input.clear();
      loadFonts();
      this.paused = false;
    }

    /**
     * Loads a program into the memory.
     * @method loadProgram
     * @param {Array} program array of bytes of a CHIP8 program
     */
    this.loadProgram = function(program) {
      for (var i = 0, length = program.length; i < length; i++) {
        this.memory[0x200 + i] = program[i];
      }
    }

    /**
     * The main CPU cycle.
     * @method cycle
     */
    this.cycle = function() {
      for (var i = 0; i < this.speed; i++) {
        if (!this.paused) {
          var opcode = this.memory[this.pc] << 8 | this.memory[this.pc + 1];
          this.perform(opcode);
          this.updateTimers();
        }
      }

      this.render();
    }

    /**
     * Process a given opcode.
     * @method perform
     * @param {Integer} opcode
     */
    this.perform = function(opcode) {
      this.pc += 2;

      var x = (opcode & 0x0F00) >> 8;
      var y = (opcode & 0x00F0) >> 4;

      switch (opcode & 0xF000) {
        case 0x000:
          switch(opcode) {
            case 0x00E0:
              this.screen.clear();
              break;

            case 0x00EE:
              this.pc = this.stack.pop();
              break;
          }
          break;

        case 0x1000:
          this.pc = opcode & 0x0FFF;
          break;

        case 0x2000:
          this.stack.push(this.pc);
          this.pc = opcode & 0x0FFF;
          break;

        case 0x3000:
          if (this.v[x] == (opcode & 0x00FF)) {
            this.pc += 2;
          }
          break;

        case 0x4000:
          if (this.v[x] != (opcode & 0x00FF)) {
            this.pc += 2;
          }
          break;

        case 0x5000:
          if (this.v[x] == this.v[y]) {
            this.pc += 2;
          }
          break;

        case 0x6000:
          this.v[x] = opcode & 0x00FF;
          break;

        case 0x7000:
          this.v[x] += opcode & 0x00FF;
          break;

        case 0x8000:
          switch (opcode & 0x000F) {
            case 0x0000:
              this.v[x] = this.v[y];
              break;

            case 0x0001:
              this.v[x] = this.v[x] | this.v[y];
              break;

            case 0x0002:
              this.v[x] = this.v[x] & this.v[y];
              break;

            case 0x0003:
              this.v[x] = this.v[x] ^ this.v[y];
              break;

            case 0x0004:
              var sum = this.v[x] + this.v[y];

              if (sum > 0xFF) {
                this.v[0xF] = 1;
              } else {
                this.v[0xF] = 0;
              }

              this.v[x] = sum;
              break;

            case 0x0005:
              if(this.v[x] > this.v[y]) {
                this.v[0xF] = 1;
              } else {
                this.v[0xF] = 0;
              }

              this.v[x] = this.v[x] - this.v[y];
              break;

            case 0x0006:
              this.v[0xF] = this.v[x] & 0x01;
              this.v[x] = this.v[x] >> 1;
              break;

            case 0x0007:
              if (this.v[x] > this.v[y]) {
                this.v[0xF] = 0;
              } else {
                this.v[0xF] = 1;
              }

              this.v[x] = this.v[y] - this.v[x];
              break;

            case 0x000E:
              this.v[0xF] = this.v[x] & 0x80;
              this.v[x] = this.v[x] << 1;
              break;
          }
          break;

        case 0x9000:
          if (this.v[x] != this.v[y]) this.pc += 2;
          break;

        case 0xA000:
          this.i = opcode & 0x0FFF;
          break;

        case 0xB000:
          this.pc = (opcode & 0x0FFF) + this.v[0];
          break;

        case 0xC000:
          this.v[x] = Math.floor(Math.random() * 0xFF) & (opcode & 0x00FF);
          break;

        case 0xD000:
          var row, col, sprite
            , width = 8
            , height = opcode & 0x000F;

          this.v[0xF] = 0;

          for (row = 0; row < height; row++) {
            sprite = this.memory[this.i + row];

            for (col = 0; col < width; col++) {
              if ((sprite & 0x80) > 0) {
                if (this.screen.setPixel(this.v[x] + col, this.v[y] + row)) {
                  this.v[0xF] = 1;
                }
              }

              sprite = sprite << 1;
            }
          }

          break;

        case 0xE000:
          switch (opcode & 0x00FF) {
            case 0x009E:
              if (this.input.isKeyPressed(this.v[x])) {
                this.pc += 2;
              }
              break;

            case 0x00A1:
              if (!this.input.isKeyPressed(this.v[x])) {
                this.pc += 2;
              }
              break;
          }
          break;

        case 0xF000:
          switch (opcode & 0x00FF) {
            case 0x0007:
              this.v[x] = this.delayTimer;
              break;

            case 0x000A:
              this.paused = true;

              this.input.onKeyPress = function(key) {
                this.v[x] = key;
                this.paused = false;
                this.input.onKeyPress = function() {}
              }.bind(this);

            case 0x0015:
              this.delayTimer = this.v[x];
              break;

            case 0x0018:
              this.soundTimer = this.v[x];
              break;

            case 0x0029:
              this.i = this.v[x] * 5;
              break;

            case 0x0033:
              this.memory[this.i]     = parseInt(this.v[x] / 100);
              this.memory[this.i + 1] = parseInt(this.v[x] % 100 / 10);
              this.memory[this.i + 2] = this.v[x] % 10;
              break;

            case 0x0055:
              for (var i = 0; i <= x; i++) {
                this.memory[this.i + i] = this.v[i];
              }
              break;

            case 0x0065:
              for (var i = 0; i <= x; i++) {
                this.v[i] = this.memory[this.i + i];
              }
              break;

            case 0x001E:
              this.i += this.v[x];
              break;
          }

          break;

        default:
          throw new Error("Unknow opcode " + opcode.toString(16) + " informed.");
      }
    }

    /**
     * Renders the screen.
     * @method render
     */
    this.render = function() {
      this.screen.render();
    }

    /**
     * Updates the CPU delay and sound timers.
     * More info at: http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.5
     * @method updateTimers
     */
    this.updateTimers = function() {
      if (this.delayTimer > 0) this.delayTimer -= 1;
      if (this.soundTimer > 0) this.soundTimer -= 1;
    }
  }

  if (typeof module != "undefined") {
    module.exports = VM;
  } else {
    window.Chip8.VM = VM;
  }
})();
<|endoftext|>


<commit_before>require.config({
  // make bower_components more sensible
  // expose jquery
  paths: {
    "bower_components": "../bower_components",
    "jquery": "../bower_components/jquery/jquery",
    "knockout": "../bower_components/knockout.js"
  }
});

// Use the debug version of knockout it development only
// When compiling with grunt require js will only look at the first
// require.config({}) found in this file
require.config({
  paths: {
    "knockout": "../bower_components/knockout.js/knockout-2.3.0.debug"
  }
});

if (!window.requireTestMode) {
  require(['main'], function(){ });
}

<commit_msg>fix config.js knockout path<commit_after>require.config({
  // make bower_components more sensible
  // expose jquery
  paths: {
    "bower_components": "../bower_components",
    "jquery": "../bower_components/jquery/jquery",
    "knockout": "../bower_components/knockout.js/knockout"
  }
});

// Use the debug version of knockout it development only
// When compiling with grunt require js will only look at the first
// require.config({}) found in this file
require.config({
  paths: {
    "knockout": "../bower_components/knockout.js/knockout-2.3.0.debug"
  }
});

if (!window.requireTestMode) {
  require(['main'], function(){ });
}

<|endoftext|>


<commit_before>(function () {
  "use strict";
  var root = this,
    previous_xo = root.xo,
    xo;
  /**
   * @module xo
   * @version 0.3.1
  */
  xo = {
    VERSION: '0.3.1',
    noConflict: noConflict,
    memoize: memoize,
    flatten: flatten,
    compact: compact,
    partial: partial,
    findIndex: findIndex,
    filter: filter,
    isBoolean: is('Boolean'),
    isNumber: is('Number'),
    isString: is('String'),
    isObject: is('Object'),
    isArray: is('Array'),
    isFunction: is('Function'),
    maybe: maybe
  };

  /**
   * Allows users to avoid conflicts over the xo name
   *
   * @example
   * var ox = xo.noConflict();
   *
   * @alias module:xo.noConflict
   * @return {Object}
  */
  function noConflict() {
    root.xo = previous_xo;
    return xo;
  }

  /**
   * Takes a function with zero or more arguments.
   * Returns a function that can be invoked with remaining arguments at a later time
   *
   * @example
   * var greet = function(greeting, name) {
   *   return [greeting, name].join(' ');
   * };
   *
   * var sayHi = xo.partial(greet, 'Hi');
   * sayHi('Bob'); // "Hi Bob"
   *
   * @alias module:xo.partial
   * @param {Function} fn
   * @return {Function}
  */
  function partial(fn) {
    var initialArgs = Array.prototype.slice.call(arguments, 1);
    return function() {
      var remainingArgs = Array.prototype.slice.call(arguments);
      return fn.apply(this, initialArgs.concat(remainingArgs));
    };
  }

  /**
   * Takes an n-dimensional nested array.
   * Returns a flattened 1-dimensional array.
   *
   * @example
   * var test = [0, 1, [2, 3], [4, [5, 6]], 7, [8, [9]]];
   * xo.flatten(test); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   *
   * @alias module:xo.flatten
   * @param {Array} arr
   * @return {Array}
  */
  function flatten(arr) {
    var output = [];
    arr.forEach(function(val) {
      output = output.concat(Array.isArray(val) ? flatten(val) : val);
    });
    return output;
  }

  /**
   * Takes an array and a predicate function.
   * Returns an array with only those terms that pass the predicate
   *
   * @example
   * function compare(id, obj) {
   *   return id === obj.id;
   * }
   * var objArr = [
   *   { name: 'a', id: '001' },
   *   { name: 'b', id: '003' },
   *   { name: 'c', id: '003' },
   *   { name: 'd', id: '004' }
   * ];
   * xo.filter(objArr, xo.partial(compare, '003')); // [{ name: 'b', id: '003'},{name: 'c', id: '003'}]
   *
   * @alias module:xo.filter
   * @param {Array} arr
   * @param {Function} predicate
   * @return {Array}
  */
  function filter(arr, predicate) {
    var result = [],
      idx,
      len;
    for (idx = 0, len = arr.length; idx < len; idx += 1) {
      if (predicate(arr[idx])) {
        result.push(arr[idx]);
      }
    }
    return result;
  }

  /**
   * Takes an array.
   * Returns an array with all falsy values removed
   *
   * @example
   * var test = [1, , false, 2, 3, false];
   * xo.compact(test); // [1, 2, 3]
   *
   * @alias module:xo.compact
   * @param {Array} arr
   * @return {Array}
  */
  function compact(arr) {
    return arr.reduce(function(memo, val) {
      return val ? memo.concat(val) : memo;
    }, []);
  }

  /**
   * Takes an array and a predicate function.
   * Returns the index of the first term that passes the predicate
   *
   * @example
   * function compare(id, obj) {
   *   return id === obj.id;
   * }
   * var objArr = [
   *   { name: 'a', id: '001' },
   *   { name: 'b', id: '002' },
   *   { name: 'c', id: '003' },
   *   { name: 'd', id: '004' }
   * ];
   * xo.findIndex(objArr, xo.partial(compare, '003')); // 2
   *
   * @alias module:xo.findIndex
   * @param {Array} arr
   * @param {Function} predicate
   * @return {Number}
  */
  function findIndex(arr, predicate) {
    var idx,
      len;
    for (idx = 0, len = arr.length; idx < len; idx += 1) {
      if (predicate(arr[idx])) {
        return idx;
      }
    }
    return -1;
  }

  /**
   * Takes a function and returns a function.
   * Invoking the returned function will return cached results if the same
   * arguments have been provided during previous invocations.
   *
   * @example
   * var upper = function(str) {
   *   return str.toUpperCase();
   * };
   * var memoUpper = xo.memoize(upper);
   * memoUpper('foo'); // "FOO"
   * memoUpper('foo'); // "FOO" (cached version)
   *
   * @alias module:xo.memoize
   * @param {Function} fn
   * @return {Function}
  */
  function memoize(fn) {
    var cache = {};
    return function() {
      var key = JSON.stringify(arguments);
      return cache[key] || (cache[key] = fn.apply(this, arguments));
    };
  }

  function is(type) {
    var fastTypes = ['undefined', 'boolean', 'number', 'string', 'symbol', 'function'];
    if (fastTypes.indexOf(type.toLowerCase()) >= 0) {
      type = type.toLowerCase();
      return function(test) {
        return typeof test === type;
      };
    }
    type = '[object ' + type + ']';
    return function(test) {
      return Object.prototype.toString.call(test) === type;
    };
  }

  /**
   * Takes a function and returns a function.
   * The returned function will not be called if supplied with null
   * or undefined arguments
   *
   * @alias module:xo.maybe
   * @param {Function} fn
   * @return {Function}
  */
  function maybe(fn) {
    return function() {
      var args = Array.prototype.slice.call(arguments);
      if (!args.length || args.some(function(val) { return val == null; })) {
        return;
      }
      return fn.apply(this, args);
    };
  }

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = xo; // jshint ignore:line
    }
    exports.xo = xo;
  } else {
    root.xo = xo;
  }

}).call(this);
<commit_msg>added jsdoc example for maybe function<commit_after>(function () {
  "use strict";
  var root = this,
    previous_xo = root.xo,
    xo;
  /**
   * @module xo
   * @version 0.3.1
  */
  xo = {
    VERSION: '0.3.1',
    noConflict: noConflict,
    memoize: memoize,
    flatten: flatten,
    compact: compact,
    partial: partial,
    findIndex: findIndex,
    filter: filter,
    isBoolean: is('Boolean'),
    isNumber: is('Number'),
    isString: is('String'),
    isObject: is('Object'),
    isArray: is('Array'),
    isFunction: is('Function'),
    maybe: maybe
  };

  /**
   * Allows users to avoid conflicts over the xo name
   *
   * @example
   * var ox = xo.noConflict();
   *
   * @alias module:xo.noConflict
   * @return {Object}
  */
  function noConflict() {
    root.xo = previous_xo;
    return xo;
  }

  /**
   * Takes a function with zero or more arguments.
   * Returns a function that can be invoked with remaining arguments at a later time
   *
   * @example
   * var greet = function(greeting, name) {
   *   return [greeting, name].join(' ');
   * };
   *
   * var sayHi = xo.partial(greet, 'Hi');
   * sayHi('Bob'); // "Hi Bob"
   *
   * @alias module:xo.partial
   * @param {Function} fn
   * @return {Function}
  */
  function partial(fn) {
    var initialArgs = Array.prototype.slice.call(arguments, 1);
    return function() {
      var remainingArgs = Array.prototype.slice.call(arguments);
      return fn.apply(this, initialArgs.concat(remainingArgs));
    };
  }

  /**
   * Takes an n-dimensional nested array.
   * Returns a flattened 1-dimensional array.
   *
   * @example
   * var test = [0, 1, [2, 3], [4, [5, 6]], 7, [8, [9]]];
   * xo.flatten(test); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   *
   * @alias module:xo.flatten
   * @param {Array} arr
   * @return {Array}
  */
  function flatten(arr) {
    var output = [];
    arr.forEach(function(val) {
      output = output.concat(Array.isArray(val) ? flatten(val) : val);
    });
    return output;
  }

  /**
   * Takes an array and a predicate function.
   * Returns an array with only those terms that pass the predicate
   *
   * @example
   * function compare(id, obj) {
   *   return id === obj.id;
   * }
   * var objArr = [
   *   { name: 'a', id: '001' },
   *   { name: 'b', id: '003' },
   *   { name: 'c', id: '003' },
   *   { name: 'd', id: '004' }
   * ];
   * xo.filter(objArr, xo.partial(compare, '003')); // [{ name: 'b', id: '003'},{name: 'c', id: '003'}]
   *
   * @alias module:xo.filter
   * @param {Array} arr
   * @param {Function} predicate
   * @return {Array}
  */
  function filter(arr, predicate) {
    var result = [],
      idx,
      len;
    for (idx = 0, len = arr.length; idx < len; idx += 1) {
      if (predicate(arr[idx])) {
        result.push(arr[idx]);
      }
    }
    return result;
  }

  /**
   * Takes an array.
   * Returns an array with all falsy values removed
   *
   * @example
   * var test = [1, , false, 2, 3, false];
   * xo.compact(test); // [1, 2, 3]
   *
   * @alias module:xo.compact
   * @param {Array} arr
   * @return {Array}
  */
  function compact(arr) {
    return arr.reduce(function(memo, val) {
      return val ? memo.concat(val) : memo;
    }, []);
  }

  /**
   * Takes an array and a predicate function.
   * Returns the index of the first term that passes the predicate
   *
   * @example
   * function compare(id, obj) {
   *   return id === obj.id;
   * }
   * var objArr = [
   *   { name: 'a', id: '001' },
   *   { name: 'b', id: '002' },
   *   { name: 'c', id: '003' },
   *   { name: 'd', id: '004' }
   * ];
   * xo.findIndex(objArr, xo.partial(compare, '003')); // 2
   *
   * @alias module:xo.findIndex
   * @param {Array} arr
   * @param {Function} predicate
   * @return {Number}
  */
  function findIndex(arr, predicate) {
    var idx,
      len;
    for (idx = 0, len = arr.length; idx < len; idx += 1) {
      if (predicate(arr[idx])) {
        return idx;
      }
    }
    return -1;
  }

  /**
   * Takes a function and returns a function.
   * Invoking the returned function will return cached results if the same
   * arguments have been provided during previous invocations.
   *
   * @example
   * var upper = function(str) {
   *   return str.toUpperCase();
   * };
   * var memoUpper = xo.memoize(upper);
   * memoUpper('foo'); // "FOO"
   * memoUpper('foo'); // "FOO" (cached version)
   *
   * @alias module:xo.memoize
   * @param {Function} fn
   * @return {Function}
  */
  function memoize(fn) {
    var cache = {};
    return function() {
      var key = JSON.stringify(arguments);
      return cache[key] || (cache[key] = fn.apply(this, arguments));
    };
  }

  function is(type) {
    var fastTypes = ['undefined', 'boolean', 'number', 'string', 'symbol', 'function'];
    if (fastTypes.indexOf(type.toLowerCase()) >= 0) {
      type = type.toLowerCase();
      return function(test) {
        return typeof test === type;
      };
    }
    type = '[object ' + type + ']';
    return function(test) {
      return Object.prototype.toString.call(test) === type;
    };
  }

  /**
   * Takes a function and returns a function.
   * The returned function will not be called if supplied with null
   * or undefined arguments
   *
   * @example
   * var sum = function(a, b) {
   *   return a + b;
   * }
   * var maybeSum = xo.maybe(sum);
   * maybeSum(2, 3); // 5
   * maybeSum(null, 3); // doesn't invoke sum
   *
   * @alias module:xo.maybe
   * @param {Function} fn
   * @return {Function}
  */
  function maybe(fn) {
    return function() {
      var args = Array.prototype.slice.call(arguments);
      if (!args.length || args.some(function(val) { return val == null; })) {
        return;
      }
      return fn.apply(this, args);
    };
  }

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = xo; // jshint ignore:line
    }
    exports.xo = xo;
  } else {
    root.xo = xo;
  }

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


<commit_before>import component from "./index.vue";
import assert from "assert";
import {WebGLRenderer} from "three";

const {computed} = component;

describe("canvasコンポーネントのテスト", function() {
    describe("computedのテスト", function() {
        describe("_rendererのテスト", function() {
            it("_rendererメソッドの存在確認", function() {
                assert.equal(typeof computed._renderer, "function");
            });
            it("_rendererメソッドはWebGLRendererのインスタンスを返す", function() {
                const _this = {
                    $refs: {}
                };
                const result = computed._renderer.apply(_this);
                assert(result instanceof WebGLRenderer);
            });
        });
    });
});
<commit_msg>テスト用のthisにcanvas要素を定義。<commit_after>import component from "./index.vue";
import assert from "assert";
import {WebGLRenderer} from "three";

const {computed} = component;

describe("canvasコンポーネントのテスト", function() {
    describe("computedのテスト", function() {
        describe("_rendererのテスト", function() {
            it("_rendererメソッドの存在確認", function() {
                assert.equal(typeof computed._renderer, "function");
            });
            it("_rendererメソッドはWebGLRendererのインスタンスを返す", function() {
                const _this = {
                    $refs: {
                        canvas: document.createElement("canvas")
                    }
                };
                const result = computed._renderer.apply(_this);
                assert(result instanceof WebGLRenderer);
            });
        });
    });
});
<|endoftext|>


<commit_before>(function( $, undefined ) {
    $.KBWidget({
        name: "KBaseGenomeGeneTable",
        parent: "kbaseAuthenticatedWidget",
        version: "1.0.0",
        genome_id: null,
        ws_name: null,
        kbCache: null,
        width: 1150,
        options: {
            genome_id: null,
            ws_name: null,
            kbCache: null,
            loadingImage: "assets/img/ajax-loader.gif"
        },
        wsUrl: "https://kbase.us/services/ws/",

        init: function(options) {
            this._super(options);

            this.ws_name = this.options.ws_name;
            this.genome_id = this.options.genome_id;
            this.kbCache = this.options.kbCache;
            this.render();
            return this;
        },

        render: function() {
            var self = this;
        	var pref = this.uuid();

            var container = this.$elem;

        	container.append("
  loading genes data...
");

        	var genomeRef = "" + this.options.ws_name + "/" + this.options.genome_id;

            var objId = {ref: genomeRef};
            if (this.options.kbCache)
                prom = this.options.kbCache.req('ws', 'get_objects', [objId]);
            else
                prom = kb.ws.get_objects([objId]);

            var self = this;

            $.when(prom).done($.proxy(function(data) {
            		container.empty();
            		var gnm = data[0].data;
            		////////////////////////////// Genes Tab //////////////////////////////
            		container.append($('
').css("overflow","auto").append('
'));
            		var genesData = [];
            		var geneMap = {};
            		var contigMap = {};

            		if (gnm.contig_ids && gnm.contig_lengths && gnm.contig_ids.length == gnm.contig_lengths.length) {
            			for (var pos in gnm.contig_ids) {
            				var contigId = gnm.contig_ids[pos];
            				var contigLen = gnm.contig_lengths[pos];
            				contigMap[contigId] = {name: contigId, length: contigLen, genes: []};
            			}
            		}

            		function geneEvents() {
            			$('.'+pref+'gene-click').unbind('click');
            			$('.'+pref+'gene-click').click(function() {
            				var geneId = [$(this).data('geneid')];
            				window.open("#/genes/" + genomeRef + "/" + geneId, "_blank");
            			});
            		}

            		for (var genePos in gnm.features) {
            			var gene = gnm.features[genePos];
            			var geneId = gene.id;
            			var contigName = null;
            			var geneStart = null;
            			var geneDir = null;
            			var geneLen = null;
            			if (gene.location && gene.location.length > 0) {
            				contigName = gene.location[0][0];
            				geneStart = gene.location[0][1];
            				geneDir = gene.location[0][2];
            				geneLen = gene.location[0][3];
            			}
            			var geneType = gene.type;
            			var geneFunc = gene['function'];
            			if (!geneFunc)
            				geneFunc = '-';
            			genesData[genesData.length] = {id: ''+geneId+'',
            					contig: contigName, start: geneStart, dir: geneDir, len: geneLen, type: geneType, func: geneFunc};
            			geneMap[geneId] = gene;
            			var contig = contigMap[contigName];
            			if (contigName != null && !contig) {
            				contig = {name: contigName, length: 0, genes: []};
            				contigMap[contigName] = contig;
            			}
            			if (contig) {
            				var geneStop = Number(geneStart);
            				if (geneDir == '+')
            					geneStop += Number(geneLen);
            				if (contig.length < geneStop) {
            					contig.length = geneStop;
            				}
            				contig.genes.push(gene);
            			}
            		}
            		var genesSettings = {
            				"sPaginationType": "full_numbers",
            				"iDisplayLength": 10,
            				"aoColumns": [
            				              {sTitle: "Gene ID", mData: "id"},
            				              {sTitle: "Contig", mData: "contig"},
            				              {sTitle: "Start", mData: "start"},
            				              {sTitle: "Strand", mData: "dir"},
            				              {sTitle: "Length", mData: "len"},
            				              {sTitle: "Type", mData: "type"},
            				              {sTitle: "Function", mData: "func"}
            				              ],
            				              "aaData": [],
            				              "oLanguage": {
            				            	  "sSearch": "Search gene:",
            				            	  "sEmptyTable": "No genes found."
            				              },
            				              "fnDrawCallback": geneEvents
            		};
            		var genesTable = $('#'+pref+'genes-table').dataTable(genesSettings);
            		genesTable.fnAddData(genesData);
            }, this));
            $.when(prom).fail($.proxy(function(data) {
            		container.empty();
            		container.append('
[Error] ' + data.error.message + '
');
            }, this));
            return this;
        },

        getData: function() {
        	return {
        		type: "KBaseGenomeGeneTable",
        		id: this.options.ws_name + "." + this.options.genome_id,
        		workspace: this.options.ws_name,
        		title: "Gene list"
        	};
        },

        uuid: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
                function(c) {
                    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                    return v.toString(16);
                });
        }
    });
})( jQuery );
<commit_msg>tidied up table<commit_after>(function( $, undefined ) {
    $.KBWidget({
        name: "KBaseGenomeGeneTable",
        parent: "kbaseAuthenticatedWidget",
        version: "1.0.0",
        genome_id: null,
        ws_name: null,
        kbCache: null,
        width: 1150,
        options: {
            genome_id: null,
            ws_name: null,
            kbCache: null,
            loadingImage: "assets/img/ajax-loader.gif"
        },
        wsUrl: "https://kbase.us/services/ws/",

        init: function(options) {
            this._super(options);

            this.ws_name = this.options.ws_name;
            this.genome_id = this.options.genome_id;
            this.kbCache = this.options.kbCache;
            this.render();
            return this;
        },

        render: function() {
            var self = this;
        	var pref = this.uuid();

            var container = this.$elem;

        	container.append("
  loading genes data...
");

        	var genomeRef = "" + this.options.ws_name + "/" + this.options.genome_id;

            var objId = {ref: genomeRef};
            if (this.options.kbCache)
                prom = this.options.kbCache.req('ws', 'get_objects', [objId]);
            else
                prom = kb.ws.get_objects([objId]);

            var self = this;

            $.when(prom).done($.proxy(function(data) {
            		container.empty();
            		var gnm = data[0].data;
            		////////////////////////////// Genes Tab //////////////////////////////
            		container.append($('
').css("overflow","auto").append('
'));
            		var genesData = [];
            		var geneMap = {};
            		var contigMap = {};

            		if (gnm.contig_ids && gnm.contig_lengths && gnm.contig_ids.length == gnm.contig_lengths.length) {
            			for (var pos in gnm.contig_ids) {
            				var contigId = gnm.contig_ids[pos];
            				var contigLen = gnm.contig_lengths[pos];
            				contigMap[contigId] = {name: contigId, length: contigLen, genes: []};
            			}
            		}

            		function geneEvents() {
            			$('.'+pref+'gene-click').unbind('click');
            			$('.'+pref+'gene-click').click(function() {
            				var geneId = [$(this).data('geneid')];
            				window.open("#/genes/" + genomeRef + "/" + geneId, "_blank");
            			});
            		}

            		for (var genePos in gnm.features) {
            			var gene = gnm.features[genePos];
            			var geneId = gene.id;
            			var contigName = null;
            			var geneStart = null;
            			var geneDir = null;
            			var geneLen = null;
            			if (gene.location && gene.location.length > 0) {
            				contigName = gene.location[0][0];
            				geneStart = gene.location[0][1];
            				geneDir = gene.location[0][2];
            				geneLen = gene.location[0][3];
            			}
            			var geneType = gene.type;
            			var geneFunc = gene['function'];
            			if (!geneFunc)
            				geneFunc = '-';
            			genesData[genesData.length] = {id: ''+geneId+'',
            					contig: contigName, start: geneStart, dir: geneDir, len: geneLen, type: geneType, func: geneFunc};
            			geneMap[geneId] = gene;
            			var contig = contigMap[contigName];
            			if (contigName != null && !contig) {
            				contig = {name: contigName, length: 0, genes: []};
            				contigMap[contigName] = contig;
            			}
            			if (contig) {
            				var geneStop = Number(geneStart);
            				if (geneDir == '+')
            					geneStop += Number(geneLen);
            				if (contig.length < geneStop) {
            					contig.length = geneStop;
            				}
            				contig.genes.push(gene);
            			}
            		}
            		var genesSettings = {
            				"sPaginationType": "full_numbers",
            				"iDisplayLength": 10,
					"aaSorting" : [[1,'asc'],[2,'asc']],
            				"aoColumns": [
            				              {sTitle: "Gene ID", mData: "id"},
            				              {sTitle: "Contig", mData: "contig"},
			                              {sTitle: "Start", mData: "start", sWidth:"7%"},
			                              {sTitle: "Strand", mData: "dir", sWidth:"7%"},
			                              {sTitle: "Length", mData: "len", sWidth:"7%"},
			                              {sTitle: "Type", mData: "type", sWidth:"10%"},
			                              {sTitle: "Function", mData: "func", sWidth:"45%"}
            				              ],
            				              "aaData": [],
            				              "oLanguage": {
            				            	  "sSearch": "Search gene:",
            				            	  "sEmptyTable": "No genes found."
            				              },
            				              "fnDrawCallback": geneEvents
            		};
            		var genesTable = $('#'+pref+'genes-table').dataTable(genesSettings);
            		genesTable.fnAddData(genesData);
            }, this));
            $.when(prom).fail($.proxy(function(data) {
            		container.empty();
            		container.append('
[Error] ' + data.error.message + '
');
            }, this));
            return this;
        },

        getData: function() {
        	return {
        		type: "KBaseGenomeGeneTable",
        		id: this.options.ws_name + "." + this.options.genome_id,
        		workspace: this.options.ws_name,
        		title: "Gene list"
        	};
        },

        uuid: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
                function(c) {
                    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                    return v.toString(16);
                });
        }
    });
})( jQuery );
<|endoftext|>


<commit_before>QB.init(QBApp.appId, QBApp.authKey, QBApp.authSecret, true);

// Create session
	var filter = {sort_asc: 'created_at'};
QB.createSession(QBUser, function(err, result){
	if (err) {
		console.log('Something went wrong: ' + err);
	} else {
		console.log('Session created with id ' + result.id);
		// Get all posts
		getAllPosts();

		$('#send_post').click(function(e) {
			e.preventDefault();

			var textTitle = $('#title_post')[0].value;
					textBody = $('#body_post').val();
			// Adds a new post
			if (textTitle && textBody) {
				$("#load-img").show(0);
				addNewPost(textTitle, textBody);
			} else {
				alert('Please complete all required fields')
			}
		});
	}
});

function getAllPosts() {

	QB.data.list("Blog", filter, function(err, result){
		if (err) {
			console.log(err);
		} else {
			console.log(result);

			var containerElement = $('#posts-container');

			for (var i=0; i < result.items.length; i++) {
				var postElement = $('

').addClass('starter-template');
				var postTitle = $('

').html(result.items[result.items.length-i-1].title);
						postElement.append(postTitle);
				var postBody = $('

').addClass('lead').html(result.items[result.items.length-i-1].body);
						postElement.append(postBody);

					containerElement.append(postElement);
			}
		}
	});
}

function addNewPost(textTitle, textBody) {
	QB.data.create("Blog", {title: textTitle, body: textBody}, function(err, res){
		if (err) {
			console.log(err);
		} else {
			console.log(res);

			$("#load-img").delay(1000).fadeOut(1000);
			$('#myModal').modal('hide');
			$('#title_post').val('');
			$('#body_post').val('');

			var containerElement = $('#posts-container');
			var postElement = $('

').addClass('starter-template');
			var postTitle = $('

').html(textTitle);
					postElement.append(postTitle);
			var postBody = $('

').addClass('lead').html(textBody);
					postElement.append(postBody);

				containerElement.prepend(postElement);
		}
	});
}<commit_msg>simplification<commit_after>QB.init(QBApp.appId, QBApp.authKey, QBApp.authSecret, true);

// Create session
	var filter = {sort_asc: 'created_at'};
QB.createSession(QBUser, function(err, result){
	if (err) {
		console.log('Something went wrong: ' + err);
	} else {
		console.log('Session created with id ' + result.id);
		// Get all posts
		getAllPosts();

		$('#send_post').click(function(e) {
			e.preventDefault();

			var textTitle = $('#title_post')[0].value;
					textBody = $('#body_post').val();
			// Adds a new post
			if (textTitle && textBody) {
				$("#load-img").show(0);
				addNewPost(textTitle, textBody);
			} else {
				alert('Please complete all required fields')
			}
		});
	}
});

function getAllPosts() {
	QB.data.list("Blog", filter, function(err, result){
		if (err) {
			console.log(err);
		} else {
			console.log(result);

			for (var i=0; i < result.items.length; i++) {
				var item = result.items[result.items.length-i-1];
				showPost(item.title, item.body, false);
			}
		}
	});
}

function addNewPost(textTitle, textBody) {
	QB.data.create("Blog", {title: textTitle, body: textBody}, function(err, res){
		if (err) {
			console.log(err);
		} else {
			console.log(res);

			$("#load-img").delay(1000).fadeOut(1000);
			$('#myModal').modal('hide');
			$('#title_post').val('');
			$('#body_post').val('');

			QB.data.list("Blog", filter, function(err, result){
				if (err) {
					console.log(err);
				} else {
					console.log(result);

					showPost(textTitle, textBody, true);
				}
			});
		}
	});
}

function showPost(textTitle, textBody, lastPost) {
	var containerElement = $('#posts-container');
	var postElement = $('

').addClass('starter-template');
	var postTitle = $('

').html(textTitle);
			postElement.append(postTitle);
	var postBody = $('

').addClass('lead').html(textBody);
			postElement.append(postBody);

	if (lastPost) {
				containerElement.prepend(postElement);
	} else {
				containerElement.append(postElement);
	}
}<|endoftext|>


<commit_before>// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Initialization
var undoStack = [];

// Finds folder at the specified level of the tree.
function findFolder(folderName, level, fn){
	chrome.bookmarks.getTree(function(tree){
		var children = tree[level].children;
		for (i =0; i < children.length; i++) {
			if(children[i].title==folderName){
				fn(children[i]);
			}
		}
	});
}

function replicateTree(treefromId, bMark){
    chrome.bookmarks.create(bMark, function(currentNode){
        treeToId = currentNode.id;
        console.log(treefromId);
        console.log(treeToId);
        chrome.bookmarks.getSubTree(treefromId, function(tree){
            var children = tree[0].children;
            for (i =0; i < children.length; i++) {
                var bMark ={};
                if (children[i].url!=undefined){
                    bMark={'parentId':treeToId, 'title':children[i].title, 'url':children[i].url};
                    chrome.bookmarks.create(bMark);
                }
                else{
                    bMark={'parentId':treeToId, 'title':children[i].title};
                    chrome.bookmarks.create(bMark, function(currentNode){
                        replicateTree(children[i].id, currentNode.id);
                        console.log(currentNode.id);
                    });
                }
            }
        });
    });

}

//Loads the folders present in other bookmarks.
init = function() {
	findFolder('Other bookmarks',0,function(btNode){
		var folderList=[];
		var children=btNode.children;
		for (i =0; i < children.length; i++) {
			if(!children[i].url){
				folderList.push(children[i]);
			}
		}

        var selectS = document.getElementById("selectSFolder");
        var selectR = document.getElementById("selectRFolder");
		var newFolder = document.createElement("option");

        selectS.innerHTML ='';
        selectR.innerHTML ='';
		newFolder.textContent = "New Folder...";
		newFolder.value= -1;
		selectS.appendChild(newFolder);

		for(var i = 0; i < folderList.length; i++) {
		    var opt = folderList[i];

            var el1 = document.createElement("option");
            el1.textContent = opt.title;
            el1.value = opt.id;

            selectS.appendChild(el1);

            var el2 = document.createElement("option");
		    el2.textContent = opt.title;
            el2.value = opt.id;
		    selectR.appendChild(el2);
		}
	});
}
document.addEventListener('DOMContentLoaded', init());

// Delete Folder
document.getElementById("selectSFolder").addEventListener("click", function(){
    var a = document.getElementById("selectSFolder");
    var title = a.options[a.selectedIndex].innerHTML;
    var selId=a.options[a.selectedIndex].value;
    if (selId!=-1){
        document.getElementById("save-footer").innerHTML = "";
    }
    else{
        document.getElementById("save-footer").innerHTML = "Double Click to save to Folder";
    }
    document.getElementById('delYes').addEventListener('click', function(){
    var a = document.getElementById("selectSFolder");
    var title = a.options[a.selectedIndex].innerHTML;
    var selId=a.options[a.selectedIndex].value;
    if(selId!=-1){
        document.getElementById("save-footer").innerHTML = "Are you sure you want to delete \""+title+"\"?
Yes No";
    }

    document.getElementById('del').addEventListener('click', function(){
        document.getElementById("save-footer").innerHTML = "
 Deleted";
        chrome.bookmarks.removeTree(selId);
        init();
    });
        document.getElementById("nodel").addEventListener("click", function(){
            document.getElementById("save-footer").innerHTML = "
 Cancelled";
            init();
        });

    });

});

// Functionality of Save
document.getElementById("selectSFolder").addEventListener("dblclick", function(){
    var a = document.getElementById("selectSFolder");
    var title = a.options[a.selectedIndex].innerHTML;
    var selId=a.options[a.selectedIndex].value;
    if(selId!=-1){
        document.getElementById("save-footer").innerHTML = "Are you sure you wanna overwrite \""+title+"\"?
Yes No";
        document.getElementById("yes").addEventListener("click", function(){
           findFolder('Bookmarks bar',0,function(bBar){
            bchildren=bBar.children;
            bBarId = bBar.id;
            //console.log(a.options[a.selectedIndex].value);

            var id;
            id=selId;
            chrome.bookmarks.getSubTree(id, function(treeNode){
                undoStack.push(treeNode);
            });
            chrome.bookmarks.getChildren(id, function(children){
                for (var i = 0; i < bchildren.length; i++){
                    var bMark ={};
                    if (bchildren[i].url!=undefined && bchildren[i].url!=''){
                        bMark={'parentId':id, 'title':bchildren[i].title, 'url':bchildren[i].url};
                        chrome.bookmarks.create(bMark);
                    }
                    else {
                        bMark={'parentId':id, 'title':bchildren[i].title};
                        replicateTree(bchildren[i].id, bMark)
                    }

                        if(children[i]!=undefined && children[i]!=''){
                            if(children[i].url!=undefined && children[i].url!='')
                                chrome.bookmarks.remove(children[i].id);
                            else
                                chrome.bookmarks.removeTree(children[i].id);
                        }
                }
                document.getElementById("save-footer").innerHTML = "
 Saved
";
            });
           });
        });

        document.getElementById("no").addEventListener("click", function(){
            document.getElementById("save-footer").innerHTML = "
 Cancelled
";
        });
    }
    else{
        document.getElementById("save-footer").innerHTML = "<input id=\"newFolder\" type=\"text\">
 Create
";
        document.getElementById("newFButton").addEventListener("click",function(){
            var folderName = document.getElementById("newFolder").value;
            var otherBId;
            var id;
            findFolder('Other bookmarks',0,function(otherBookmarks){
                otherBId = otherBookmarks.id;
                console.log(otherBId);
                findFolder('Bookmarks bar',0,function(bBar){
                    bchildren=bBar.children;
                    bBarId = bBar.id;
                    bMark={'parentId':otherBId, 'title':folderName};
                    replicateTree(bBarId,bMark);
                    document.getElementById("save-footer").innerHTML = "
 Saved
";
                    init();
                });
           });
        });
    }

});

// Functionality of Replace
document.getElementById("selectRFolder").addEventListener("dblclick", function(){
		var a = document.getElementById("selectRFolder");
		findFolder('Bookmarks bar',0,function(bBar){
			bchildren=bBar.children;
			bBarId = bBar.id;
			for (var i = 0; i < bchildren.length; i++){
                if(bchildren[i].url!=undefined)
				    chrome.bookmarks.remove(bchildren[i].id);
                else
                    chrome.bookmarks.removeTree(bchildren[i].id);
			}
			//console.log(a.options[a.selectedIndex].value);
			var id=a.options[a.selectedIndex].value;
			chrome.bookmarks.getChildren(id, function(children){
				//children=node.children;
				for (var i = 0; i < children.length; i++){
					var bMark ={};
					if (children[i].url!=undefined){
						bMark={'parentId':bBarId, 'title':children[i].title, 'url':children[i].url};
                        chrome.bookmarks.create(bMark);
                    }
                    else{
                        bMark={'parentId':bBarId, 'title':children[i].title};
                        replicateTree(children[i].id, bMark)
                    }

				}
			});
		});

});
<commit_msg>testing<commit_after>// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Initialization
var undoStack = [];

// Finds folder at the specified level of the tree.
function findFolder(folderName, level, fn){
	chrome.bookmarks.getTree(function(tree){
		var children = tree[level].children;
		for (i =0; i < children.length; i++) {
			if(children[i].title==folderName){
				fn(children[i]);
			}
		}
	});
}

function replicateTree(treefromId, bMark){
    chrome.bookmarks.create(bMark, function(currentNode){
        treeToId = currentNode.id;
        console.log(currentNode.id);
        console.log(treefromId);
        console.log(treeToId);
        chrome.bookmarks.getSubTree(treefromId, function(tree){
            var children = tree[0].children;
            for (i =0; i < children.length; i++) {
                var bMark ={};
                if (children[i].url!=undefined){
                    bMark={'parentId':treeToId, 'title':children[i].title, 'url':children[i].url};
                    chrome.bookmarks.create(bMark);
                }
                else{
                    bMark={'parentId':treeToId, 'title':children[i].title};
                    chrome.bookmarks.create(bMark, function(currentNode){
                        replicateTree(children[i].id, currentNode.id);
                        console.log(currentNode.id);
                    });
                }
            }
        });
    });

}

//Loads the folders present in other bookmarks.
init = function() {
	findFolder('Other bookmarks',0,function(btNode){
		var folderList=[];
		var children=btNode.children;
		for (i =0; i < children.length; i++) {
			if(!children[i].url){
				folderList.push(children[i]);
			}
		}

        var selectS = document.getElementById("selectSFolder");
        var selectR = document.getElementById("selectRFolder");
		var newFolder = document.createElement("option");

        selectS.innerHTML ='';
        selectR.innerHTML ='';
		newFolder.textContent = "New Folder...";
		newFolder.value= -1;
		selectS.appendChild(newFolder);

		for(var i = 0; i < folderList.length; i++) {
		    var opt = folderList[i];

            var el1 = document.createElement("option");
            el1.textContent = opt.title;
            el1.value = opt.id;

            selectS.appendChild(el1);

            var el2 = document.createElement("option");
		    el2.textContent = opt.title;
            el2.value = opt.id;
		    selectR.appendChild(el2);
		}
	});
}
document.addEventListener('DOMContentLoaded', init());

// Delete Folder
document.getElementById("selectSFolder").addEventListener("click", function(){
    var a = document.getElementById("selectSFolder");
    var title = a.options[a.selectedIndex].innerHTML;
    var selId=a.options[a.selectedIndex].value;
    if (selId!=-1){
        document.getElementById("save-footer").innerHTML = "";
    }
    else{
        document.getElementById("save-footer").innerHTML = "Double Click to save to Folder";
    }
    document.getElementById('delYes').addEventListener('click', function(){
    var a = document.getElementById("selectSFolder");
    var title = a.options[a.selectedIndex].innerHTML;
    var selId=a.options[a.selectedIndex].value;
    if(selId!=-1){
        document.getElementById("save-footer").innerHTML = "Are you sure you want to delete \""+title+"\"?
Yes No";
    }

    document.getElementById('del').addEventListener('click', function(){
        document.getElementById("save-footer").innerHTML = "
 Deleted";
        chrome.bookmarks.removeTree(selId);
        init();
    });
        document.getElementById("nodel").addEventListener("click", function(){
            document.getElementById("save-footer").innerHTML = "
 Cancelled";
            init();
        });

    });

});

// Functionality of Save
document.getElementById("selectSFolder").addEventListener("dblclick", function(){
    var a = document.getElementById("selectSFolder");
    var title = a.options[a.selectedIndex].innerHTML;
    var selId=a.options[a.selectedIndex].value;
    if(selId!=-1){// Not trying to create a folder
        document.getElementById("save-footer").innerHTML = "Are you sure you wanna overwrite \""+title+"\"?
Yes No";
        document.getElementById("yes").addEventListener("click", function(){
           findFolder('Bookmarks bar',0,function(bBar){
            bchildren=bBar.children;
            bBarId = bBar.id;
            //console.log(a.options[a.selectedIndex].value);

            var id;
            id=selId;
            chrome.bookmarks.getSubTree(id, function(treeNode){
                undoStack.push(treeNode);
            });//Future for undo functionality..!

            chrome.bookmarks.getChildren(id, function(children){
                for (var i = 0; i < bchildren.length; i++){
                    var bMark ={};
                    if (bchildren[i].url!=undefined && bchildren[i].url!=''){
                        bMark={'parentId':id, 'title':bchildren[i].title, 'url':bchildren[i].url};
                        chrome.bookmarks.create(bMark);
                    }
                    else {// Make the folder with all the shit inside
                        bMark={'parentId':id, 'title':bchildren[i].title};
                        replicateTree(bchildren[i].id, bMark)
                    }

                        if(children[i]!=undefined && children[i]!=''){
                            if(children[i].url!=undefined && children[i].url!='')
                                chrome.bookmarks.remove(children[i].id);
                            else
                                chrome.bookmarks.removeTree(children[i].id);
                        }
                }
                document.getElementById("save-footer").innerHTML = "
 Saved
";
            });
           });
        });

        document.getElementById("no").addEventListener("click", function(){
            document.getElementById("save-footer").innerHTML = "
 Cancelled
";
        });
    }
    else{
        document.getElementById("save-footer").innerHTML = "<input id=\"newFolder\" type=\"text\">
 Create
";
        document.getElementById("newFButton").addEventListener("click",function(){
            var folderName = document.getElementById("newFolder").value;
            var otherBId;
            var id;
            findFolder('Other bookmarks',0,function(otherBookmarks){
                otherBId = otherBookmarks.id;
                console.log(otherBId);
                findFolder('Bookmarks bar',0,function(bBar){
                    bchildren=bBar.children;
                    bBarId = bBar.id;
                    bMark={'parentId':otherBId, 'title':folderName};
                    replicateTree(bBarId,bMark);
                    document.getElementById("save-footer").innerHTML = "
 Saved
";
                    init();
                });
           });
        });
    }

});

// Functionality of Replace
document.getElementById("selectRFolder").addEventListener("dblclick", function(){
		var a = document.getElementById("selectRFolder");
		findFolder('Bookmarks bar',0,function(bBar){
			bchildren=bBar.children;
			bBarId = bBar.id;
			for (var i = 0; i < bchildren.length; i++){
                if(bchildren[i].url!=undefined)
				    chrome.bookmarks.remove(bchildren[i].id);
                else
                    chrome.bookmarks.removeTree(bchildren[i].id);
			}
			//console.log(a.options[a.selectedIndex].value);
			var id=a.options[a.selectedIndex].value;
			chrome.bookmarks.getChildren(id, function(children){
				//children=node.children;
				for (var i = 0; i < children.length; i++){
					var bMark ={};
					if (children[i].url!=undefined){
						bMark={'parentId':bBarId, 'title':children[i].title, 'url':children[i].url};
                        chrome.bookmarks.create(bMark);
                    }
                    else{
                        bMark={'parentId':bBarId, 'title':children[i].title};
                        replicateTree(children[i].id, bMark)
                    }

				}
			});
		});

});
<|endoftext|>


<commit_before>var packageName = document.title;

var runkitLinkNode = document.querySelector('[href*=runkit]');
runkitLinkNode.innerText = 'Test ' + packageName + ' on 2runkit';

var replitLinkListNode = document.createElement('li');
replitLinkListNode.className = 'replit';
var replitLinkNode = document.createElement('a');
var pageUrl = chrome.extension.getURL("index.html");
var requireCode = 'const ' + packageName + " = require('" + packageName + "');";
var href = pageUrl;
replitLinkNode.setAttribute('href', href);
replitLinkNode.innerText = 'Test ' + packageName + ' on repl.it';
replitLinkListNode.append(replitLinkNode);

var tryItBoxNode = runkitLinkNode.parentElement.parentElement;
tryItBoxNode.insertBefore(replitLinkListNode, tryItBoxNode.childNodes[0]);
<commit_msg>Fix packageName not being added to query params<commit_after>var packageName = document.title;

var runkitLinkNode = document.querySelector('[href*=runkit]');
runkitLinkNode.innerText = 'Test ' + packageName + ' on 2runkit';

var replitLinkListNode = document.createElement('li');
replitLinkListNode.className = 'replit';
var replitLinkNode = document.createElement('a');
var pageHref = chrome.extension.getURL("index.html") + '?packageName=' + packageName;
replitLinkNode.setAttribute('href', pageHref);
replitLinkNode.innerText = 'Test ' + packageName + ' on repl.it';
replitLinkListNode.append(replitLinkNode);

var tryItBoxNode = runkitLinkNode.parentElement.parentElement;
tryItBoxNode.insertBefore(replitLinkListNode, tryItBoxNode.childNodes[0]);
<|endoftext|>


<commit_before>(function(Ember) {
  /**
  * The main namespace for `Ember.Responsive`.
  *
  * @module  ember-responsive
  * @main    ember-responsive
  */
  Ember.Responsive = {};

 /**
  * This is the main entry point to `Ember.Responsive`, and all it does
  * is take care of configuring this library to your specifications before
  * spinning up your Ember app.
  *
  * **Setting media for your application**
  *
  * Presently, you can easily configure your application's breakpoints
  * using media queries.
  *
  * ```javascript
  * var App = Ember.Application.extend();
  *
  * // Declare the media that we care about.
  * App.responsive({
  *   media: {
  *     mobile:  '(max-width: 768px)',
  *     tablet:  '(min-width: 769px) and (max-width: 992px)',
  *     desktop: '(min-width: 993px) and (max-width: 1200px)',
  *     jumbo:   '(min-width: 1201px)',
  *   }
  * });
  * ```
  *
  * After you've gone through this process, you'll be able to access
  * the media queries in a few different places of your application:
  *
  *   - All controllers, under the name `media`.
  *   - All components, under the name `media`.
  *   - All views, under the name `media`.
  *   - All routes, under the name `media`.
  *   - In the container, under the name `responsive:media`.
  *
  * **Binding media classes to your application view**
  *
  * `Ember.Responsive` makes it very easy to bind the active media queries as
  * class names on your app view (or any view, for that matter). This helps you
  * avoid having to duplicate media queries in your CSS and Ember code, and
  * makes writing responsive CSS much simpler.
  *
  * ```javascript
  * App.ApplicationView = Ember.View.extend({
  *   classNameBindings: ['media.classNames']
  * });
  * ```
  *
  * **Referencing media queries in your app**
  *
  * `Ember.Responsive` also allows access to its API in controllers, components,
  * routes, and views, making it dead simple to only perform certain types of
  * work for certain devices.
  *
  * ```javascript
  * App.PostsRoute = Ember.Router.extend({
  *   model: function() {
  *     if (this.get('media.isMobile')) {
  *       // Return a smaller, less data-hungry result
  *     }
  *   }
  * });
  * ```
  *
  * **Referencing media queries in your templates**
  *
  * Since media queries are available in your controllers, components,
  * and views, they'll also be accessible in your templates.
  *
  * ```handlebars
  * \{{#if media.isMobile}}
  *    Mobile view!
  * \{{/if}}
  * ```
  *
  * **Mocking a particular media type in test**
  *
  * It's very easy to fake a particular view when testing as well. This
  * is useful when you want to be able to test different behaviours
  * for different types of devices.
  *
  * If you're writing an integration test, you'll probably want to mock
  * out the media type at the application level.
  *
  * ```javascript
  * App.responsive({
  *   media: {
  *     mobile: 'all' // The 'all' media query will always match
  *   }
  * });
  * ```
  *
  * But in unit tests, you can simply override the property that you're
  * referencing.
  *
  * ```javascript
  * controller.set('media.isMobile', true);
  * ```
  *
  * Refer to the {{#crossLink "Ember.Responsive.Media"}}{{/crossLink}}
  * documentation for more examples of how to interact with the
  * aforementioned `media` object.
  *
  * @static
  * @module            ember-responsive
  * @namespace         Ember.Application
  * @class             responsive
  * @param   {object}  config
  */
  Ember.Application.reopenClass({
    responsive: function(config) {
      var media = config.media;

      if (!this.responsive.media) {
        this.responsive.media = Ember.Responsive.Media.create();
      }

      if (media) {
        for (var name in media) {
          if (media.hasOwnProperty(name)) {
            this.responsive.media.match(name, media[name]);
          }
        }
      }

      return this;
    }
  });
})(window.Ember);

(function(Ember) {
 /**
  * An initializer that sets up `Ember.Responsive`.
  *
  * Refer to {{#crossLink "Ember.Application.responsive"}}{{/crossLink}}
  * for examples of how to configure this library before the initializer
  * before it's run by Ember.
  *
  * @static
  * @constructor
  * @module            ember-responsive
  * @namespace         Ember.Application
  * @class             initializer
  * @param   {object}  matchers  A hash of media queries to test.
  * @return  {object}            An Ember initializer.
  */
  Ember.Application.initializer({
     /**
      * @property  name
      * @type      string
      * @default   responsive
      */
    name: 'responsive',

     /**
      * @method  initialize
      * @param   Ember.Container   container
      * @param   Ember.Application app
      */
    initialize: function(container, app) {
      var responsive = app.constructor.responsive;

      if (responsive.media) {
        app.register('responsive:media', responsive.media, { instantiate: false });
        app.inject('controller', 'media', 'responsive:media');
        app.inject('component', 'media', 'responsive:media');
        app.inject('route', 'media', 'responsive:media');
        app.inject('view', 'media', 'responsive:media');
      }
    }
  });
})(window.Ember);

(function(Ember) {
 /**
  * Handles detecting and responding to media queries.
  *
  * Generally speaking, you won't ever need to create an instance of this class
  * yourself, since `Ember.Responsive` takes care of creating and configuring it
  * for you. However, it is important to document how to interact with this
  * class—which can become important during test time in particular. With that
  * said, let's take a look at how to work with it.
  *
  * **Adding media query matchers**
  *
  * The first step to using the class is to add media queries that you
  * want it to listen to. Each media query has a name that you can
  * use to reference it by.
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('mobile', '(max-width: 768px)');
  * media.match('desktop', '(min-width: 769px)');
  * ```
  *
  * **Testing the media query matchers**
  *
  * Now that you've added a few matchers, you can access those media queries as
  * if they were properties on your object. The nice thing is that whenever the
  * media queries change, this class will automatically update the relevant
  * properties (and so will the rest of your application, thanks to the power
  * of two-way data-binding).
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('mobile', '(max-width: 768px)');
  * media.match('desktop', '(min-width: 769px)');
  *
  * // There are convenient "isser" properties defined...
  * if (media.get('isMobile')) {
  *   console.log('mobile!');
  * }
  *
  * // As well as access to the matchMedia API...
  * if (media.get('desktop.matches')) {
  *   console.log('desktop!');
  * }
  * ```
  *
  * **Retrieving a list of matching media queries**
  *
  * It's also nice to be able to see which media queries are matching, since
  * some applications might have many matches at the same time.
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('desktop', 'all');
  * media.match('mobile', 'all');
  *
  * console.log(media.get('matches'));
  * // => Ember.Set(['desktop', 'mobile']);
  * ```
  *
  * This class can also return that list as a string of dasherized class names,
  * which is useful for placing on your app's rootElement. By default, these
  * class names are prefixed with `media-`, so as not to clash with any other
  * classes your app might use.
  *
  * ```javascript
  * App.ApplicationView = Ember.View.extend({
  *   classNameBindings: ['media.classNames']
  * });
  * ```
  *
  * @module    ember-responsive
  * @namespace Ember.Responsive
  * @class     Media
  * @extends   Ember.Object
  */
  Ember.Responsive.Media = Ember.Object.extend({
   /**
    * A set of matching matchers.
    *
    * @property  matches
    * @type      Ember.Set
    * @default   Ember.Set
    */
    matches: function() {
      return new Ember.Set();
    }.property(),

   /**
    * The matcher to use for testing media queries.
    *
    * @property  matcher
    * @type      matchMedia
    * @default   window.matchMedia
    * @private
    */
    mql: window.matchMedia,

   /**
    * A string composed of all the matching matchers' names, turned into
    * friendly, dasherized class-names that are prefixed with `media-`.
    *
    * @property  classNames
    * @type      string
    */
    classNames: function() {
      return this.get('matches').map(function(name) {
        return 'media-' + name.dasherize();
      }).join(' ');
    }.property('matches.[]'),

   /**
    * Adds a new matcher to the list.
    *
    * After this method is called, you will be able to access the result
    * of the matcher as a property on this object.
    *
    * **Adding a new matcher**
    *
    * ```javascript
    * media = Ember.Responsive.Media.create();
    * media.match('all', 'all');
    * media.get('all');
    *   // => instanceof window.matchMedia
    * media.get('all.matches');
    *   // => true
    * ```
    *
    * @param   string  name   The name of the matcher
    * @param   string  query  The media query to match against
    * @method  match
    */
    match: function(name, query) {
      var matcher = this.get('mql')(query),
          isser = 'is' + name.classify(),
          _this = this;

      var listener = function(matcher) {
        _this.set(name, matcher);

        if (matcher.matches) {
          _this.get('matches').add(name);
        } else {
          _this.get('matches').remove(name);
        }
      };

      matcher.addListener(listener);
      listener(matcher);

      // Define a corresponding "isser" which is prettier to look at and type
      Ember.defineProperty(this, isser, Ember.computed(function() {
        return this.get(name).matches;
      }).property(name));
    }
  });
})(window.Ember);
<commit_msg>Build dist file<commit_after>(function(Ember) {
  /**
  * The main namespace for `Ember.Responsive`.
  *
  * @module  ember-responsive
  * @main    ember-responsive
  */
  Ember.Responsive = {};

 /**
  * This is the main entry point to `Ember.Responsive`, and all it does
  * is take care of configuring this library to your specifications before
  * spinning up your Ember app.
  *
  * **Setting media for your application**
  *
  * Presently, you can easily configure your application's breakpoints
  * using media queries.
  *
  * ```javascript
  * var App = Ember.Application.extend();
  *
  * // Declare the media that we care about.
  * App.responsive({
  *   media: {
  *     mobile:  '(max-width: 768px)',
  *     tablet:  '(min-width: 769px) and (max-width: 992px)',
  *     desktop: '(min-width: 993px) and (max-width: 1200px)',
  *     jumbo:   '(min-width: 1201px)',
  *   }
  * });
  * ```
  *
  * After you've gone through this process, you'll be able to access
  * the media queries in a few different places of your application:
  *
  *   - All controllers, under the name `media`.
  *   - All components, under the name `media`.
  *   - All views, under the name `media`.
  *   - All routes, under the name `media`.
  *   - In the container, under the name `responsive:media`.
  *
  * **Binding media classes to your application view**
  *
  * `Ember.Responsive` makes it very easy to bind the active media queries as
  * class names on your app view (or any view, for that matter). This helps you
  * avoid having to duplicate media queries in your CSS and Ember code, and
  * makes writing responsive CSS much simpler.
  *
  * ```javascript
  * App.ApplicationView = Ember.View.extend({
  *   classNameBindings: ['media.classNames']
  * });
  * ```
  *
  * **Referencing media queries in your app**
  *
  * `Ember.Responsive` also allows access to its API in controllers, components,
  * routes, and views, making it dead simple to only perform certain types of
  * work for certain devices.
  *
  * ```javascript
  * App.PostsRoute = Ember.Router.extend({
  *   model: function() {
  *     if (this.get('media.isMobile')) {
  *       // Return a smaller, less data-hungry result
  *     }
  *   }
  * });
  * ```
  *
  * **Referencing media queries in your templates**
  *
  * Since media queries are available in your controllers, components,
  * and views, they'll also be accessible in your templates.
  *
  * ```handlebars
  * \{{#if media.isMobile}}
  *    Mobile view!
  * \{{/if}}
  * ```
  *
  * **Mocking a particular media type in test**
  *
  * It's very easy to fake a particular view when testing as well. This
  * is useful when you want to be able to test different behaviours
  * for different types of devices.
  *
  * If you're writing an integration test, you'll probably want to mock
  * out the media type at the application level.
  *
  * ```javascript
  * App.responsive({
  *   media: {
  *     mobile: 'all' // The 'all' media query will always match
  *   }
  * });
  * ```
  *
  * But in unit tests, you can simply override the property that you're
  * referencing.
  *
  * ```javascript
  * controller.set('media.isMobile', true);
  * ```
  *
  * Refer to the {{#crossLink "Ember.Responsive.Media"}}{{/crossLink}}
  * documentation for more examples of how to interact with the
  * aforementioned `media` object.
  *
  * @static
  * @module            ember-responsive
  * @namespace         Ember.Application
  * @class             responsive
  * @param   {object}  config
  */
  Ember.Application.reopenClass({
    responsive: function(config) {
      var media = config.media;

      if (!this.responsive.media) {
        this.responsive.media = Ember.Responsive.Media.create();
      }

      if (media) {
        for (var name in media) {
          if (media.hasOwnProperty(name)) {
            this.responsive.media.match(name, media[name]);
          }
        }
      }

      return this;
    }
  });
})(window.Ember);

(function(Ember) {
 /**
  * An initializer that sets up `Ember.Responsive`.
  *
  * Refer to {{#crossLink "Ember.Application.responsive"}}{{/crossLink}}
  * for examples of how to configure this library before the initializer
  * before it's run by Ember.
  *
  * @static
  * @constructor
  * @module            ember-responsive
  * @namespace         Ember.Application
  * @class             initializer
  * @param   {object}  matchers  A hash of media queries to test.
  * @return  {object}            An Ember initializer.
  */
  Ember.Application.initializer({
     /**
      * @property  name
      * @type      string
      * @default   responsive
      */
    name: 'responsive',

     /**
      * @method  initialize
      * @param   Ember.Container   container
      * @param   Ember.Application app
      */
    initialize: function(container, app) {
      var responsive = app.constructor.responsive;

      if (responsive.media) {
        app.register('responsive:media', responsive.media, { instantiate: false });
        app.inject('controller', 'media', 'responsive:media');
        app.inject('component', 'media', 'responsive:media');
        app.inject('route', 'media', 'responsive:media');
        app.inject('view', 'media', 'responsive:media');
      }
    }
  });
})(window.Ember);

(function(Ember) {
 /**
  * Handles detecting and responding to media queries.
  *
  * Generally speaking, you won't ever need to create an instance of this class
  * yourself, since `Ember.Responsive` takes care of creating and configuring it
  * for you. However, it is important to document how to interact with this
  * class—which can become important during test time in particular. With that
  * said, let's take a look at how to work with it.
  *
  * **Adding media query matchers**
  *
  * The first step to using the class is to add media queries that you
  * want it to listen to. Each media query has a name that you can
  * use to reference it by.
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('mobile', '(max-width: 768px)');
  * media.match('desktop', '(min-width: 769px)');
  * ```
  *
  * **Testing the media query matchers**
  *
  * Now that you've added a few matchers, you can access those media queries as
  * if they were properties on your object. The nice thing is that whenever the
  * media queries change, this class will automatically update the relevant
  * properties (and so will the rest of your application, thanks to the power
  * of two-way data-binding).
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('mobile', '(max-width: 768px)');
  * media.match('desktop', '(min-width: 769px)');
  *
  * // There are convenient "isser" properties defined...
  * if (media.get('isMobile')) {
  *   console.log('mobile!');
  * }
  *
  * // As well as access to the matchMedia API...
  * if (media.get('desktop.matches')) {
  *   console.log('desktop!');
  * }
  * ```
  *
  * **Retrieving a list of matching media queries**
  *
  * It's also nice to be able to see which media queries are matching, since
  * some applications might have many matches at the same time.
  *
  * ```javascript
  * media = Ember.Responsive.Media.create();
  * media.match('desktop', 'all');
  * media.match('mobile', 'all');
  *
  * console.log(media.get('matches'));
  * // => Ember.Set(['desktop', 'mobile']);
  * ```
  *
  * This class can also return that list as a string of dasherized class names,
  * which is useful for placing on your app's rootElement. By default, these
  * class names are prefixed with `media-`, so as not to clash with any other
  * classes your app might use.
  *
  * ```javascript
  * App.ApplicationView = Ember.View.extend({
  *   classNameBindings: ['media.classNames']
  * });
  * ```
  *
  * @module    ember-responsive
  * @namespace Ember.Responsive
  * @class     Media
  * @extends   Ember.Object
  */
  Ember.Responsive.Media = Ember.Object.extend({
   /**
    * A set of matching matchers.
    *
    * @property  matches
    * @type      Ember.Set
    * @default   Ember.Set
    */
    matches: function() {
      return new Ember.Set();
    }.property(),

   /**
    * The matcher to use for testing media queries.
    *
    * @property  matcher
    * @type      matchMedia
    * @default   window.matchMedia
    * @private
    */
    mql: window.matchMedia,

   /**
    * A string composed of all the matching matchers' names, turned into
    * friendly, dasherized class-names that are prefixed with `media-`.
    *
    * @property  classNames
    * @type      string
    */
    classNames: function() {
      return this.get('matches').map(function(name) {
        return 'media-' + name.dasherize();
      }).join(' ');
    }.property('matches.[]'),

   /**
    * Adds a new matcher to the list.
    *
    * After this method is called, you will be able to access the result
    * of the matcher as a property on this object.
    *
    * **Adding a new matcher**
    *
    * ```javascript
    * media = Ember.Responsive.Media.create();
    * media.match('all', 'all');
    * media.get('all');
    *   // => instanceof window.matchMedia
    * media.get('all.matches');
    *   // => true
    * ```
    *
    * @param   string  name   The name of the matcher
    * @param   string  query  The media query to match against
    * @method  match
    */
    match: function(name, query) {
      var matcher = this.get('mql')(query),
          isser = 'is' + name.classify(),
          _this = this;

      var listener = function(matcher) {
        _this.set(name, matcher);
        _this.set(isser, matcher.matches);

        if (matcher.matches) {
          _this.get('matches').add(name);
        } else {
          _this.get('matches').remove(name);
        }
      };

      matcher.addListener(listener);
      listener(matcher);
    }
  });
})(window.Ember);
<|endoftext|>