<commit_before>import { default as React, Component } from 'react'
var ReactDOM = require('react-dom');
var config = require('./config.js');
import {AppbaseMap} from './app/AppbaseMap';
import {AppbaseList} from './app/AppbaseList';
import {AppbaseSlider} from './app/AppbaseSlider';
import {AppbaseSearch} from './app/AppbaseSearch';

class Main extends Component {
	onIndex(data) {

	}
	onDelete(data) {

	}
	render() {
		var divStyle = {
			height: "100%",
		};
		return (

 Number of guests (Multiple Select)

							<AppbaseList config={config} fieldName="guests" showCount={true} size={20}/>

 Topics (Single Select)

							<AppbaseList config={config} fieldName="group.group_topics.topic_name_raw" multipleSelect={false} showCount={true} />

 Range of guests

						<AppbaseSlider fieldName="guests" config={config} />

 Select Venue

						<AppbaseSearch fieldName="venue_name_ngrams" config={config} />

					<AppbaseMap
						config={config}
						fieldName="location"
						defaultZoom={13}
						defaultCenter={{ lat: 37.74, lng: -122.45 }}
						historicalData={true}
						markerCluster={false}
						onDelete={this.onDelete}
						searchComponent="appbase"
						searchField="venue_name_ngrams"
						onIndex={this.onIndex} />

		);
	}
}

ReactDOM.render(, document.getElementById('map'));<commit_msg>Showing the facets of countries<commit_after>import { default as React, Component } from 'react'
var ReactDOM = require('react-dom');
var config = require('./config.js');
import {AppbaseMap} from './app/AppbaseMap';
import {AppbaseList} from './app/AppbaseList';
import {AppbaseSlider} from './app/AppbaseSlider';
import {AppbaseSearch} from './app/AppbaseSearch';

class Main extends Component {
	onIndex(data) {

	}
	onDelete(data) {

	}
	render() {
		var divStyle = {
			height: "100%",
		};
		return (

 Countries (Multiple Select)

							<AppbaseList config={config} fieldName="country_name" showCount={true} size={20}/>

 Topics (Single Select)

							<AppbaseList config={config} fieldName="group.group_topics.topic_name_raw" multipleSelect={false} showCount={true} />

 Range of guests

						<AppbaseSlider fieldName="guests" config={config} />

 Select Venue

						<AppbaseSearch fieldName="venue_name_ngrams" config={config} />

					<AppbaseMap
						config={config}
						fieldName="location"
						defaultZoom={13}
						defaultCenter={{ lat: 37.74, lng: -122.45 }}
						historicalData={true}
						markerCluster={false}
						onDelete={this.onDelete}
						searchComponent="appbase"
						searchField="venue_name_ngrams"
						onIndex={this.onIndex} />

		);
	}
}

ReactDOM.render(, document.getElementById('map'));<|endoftext|>


<commit_before>/* Copyright (c) 2013-present The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

/* globals marked */
'use strict';

sendMessageToHost({ command: 'loadDefaultTextContent' });

var $htmlEditor;

function initEditor() {
  var toolbar = [
    ['todo', ['checkbox', 'toggleSelectAllButton']],
    ['style', ['style']],
    ['color', ['color']],
    ['font', ['bold', 'italic', 'underline']],
    ['font2', ['superscript', 'subscript', 'strikethrough', 'clear']],
    ['fontname', ['fontname']],
    ['fontsize', ['fontsize']],
    ['para', ['ul', 'ol', 'paragraph']],
    ['height', ['height']],
    ['table', ['table']],
    ['insert', ['link', 'picture', 'hr']], // 'video',
    ['view', ['codeview']], // 'fullscreen',
    ['help', ['help']]
  ];

  if (isCordova) {
    toolbar = [
      ['todo', ['checkbox', 'toggleSelectAllButton']],
      ['color', ['color']],
      ['style', ['style']],
      ['para', ['paragraph', 'ul', 'ol']],
      ['font', ['bold', 'italic', 'underline']],
      //['font2', ['superscript', 'subscript', 'strikethrough', 'clear']],
      ['fontsize', ['fontsize']],
      //['height', ['height']],
      ['insert', ['picture', 'link', 'hr']],
      ['table', ['table']]
      //['view', ['codeview']]
    ];
  }

  var keyMapping = {
    pc: {
      ENTER: 'insertParagraph',
      'CTRL+Z': 'undo',
      'CTRL+Y': 'redo',
      TAB: 'tab',
      'SHIFT+TAB': 'untab',
      'CTRL+B': 'bold',
      'CTRL+I': 'italic',
      'CTRL+U': 'underline',
      'CTRL+SHIFT+S': 'strikethrough',
      'CTRL+BACKSLASH': 'removeFormat',
      'CTRL+SHIFT+L': 'justifyLeft',
      'CTRL+SHIFT+E': 'justifyCenter',
      'CTRL+SHIFT+R': 'justifyRight',
      'CTRL+SHIFT+J': 'justifyFull',
      'CTRL+SHIFT+NUM7': 'insertUnorderedList',
      'CTRL+SHIFT+NUM8': 'insertOrderedList',
      'CTRL+SHIFT+TAB': 'outdent',
      'CTRL+TAB': 'indent',
      'CTRL+NUM0': 'formatPara',
      'CTRL+NUM1': 'formatH1',
      'CTRL+NUM2': 'formatH2',
      'CTRL+NUM3': 'formatH3',
      'CTRL+NUM4': 'formatH4',
      'CTRL+NUM5': 'formatH5',
      'CTRL+NUM6': 'formatH6',
      'CTRL+ENTER': 'insertHorizontalRule',
      'CTRL+K': 'linkDialog.show'
    },

    mac: {
      ENTER: 'insertParagraph',
      'CMD+Z': 'undo',
      'CMD+SHIFT+Z': 'redo',
      TAB: 'tab',
      'SHIFT+TAB': 'untab',
      'CMD+B': 'bold',
      'CMD+I': 'italic',
      'CMD+U': 'underline',
      'CMD+SHIFT+S': 'strikethrough',
      'CMD+BACKSLASH': 'removeFormat',
      'CMD+SHIFT+L': 'justifyLeft',
      'CMD+SHIFT+E': 'justifyCenter',
      'CMD+SHIFT+R': 'justifyRight',
      'CMD+SHIFT+J': 'justifyFull',
      'CMD+SHIFT+NUM7': 'insertUnorderedList',
      'CMD+SHIFT+NUM8': 'insertOrderedList',
      'CMD+SHIFT+TAB': 'outdent',
      'CMD+TAB': 'indent',
      'CMD+NUM0': 'formatPara',
      'CMD+NUM1': 'formatH1',
      'CMD+NUM2': 'formatH2',
      'CMD+NUM3': 'formatH3',
      'CMD+NUM4': 'formatH4',
      'CMD+NUM5': 'formatH5',
      'CMD+NUM6': 'formatH6',
      'CMD+ENTER': 'insertHorizontalRule',
      'CMD+K': 'linkDialog.show'
    }
  };

  $htmlEditor.summernote({
    focus: true,
    height: '200px',
    disableDragAndDrop: true,
    toolbar: toolbar,
    keyMap: keyMapping,
    callbacks: {
      onChange: function(contents, $editable) {
        sendMessageToHost({ command: 'contentChangedInEditor', filepath: '' });
      }
    }
  });

  // set note-editable panel-body to window height initially and on frame resize
  $('.note-editable.panel-body').height(window.innerHeight - 80);
  $(window).on('resize', function() {
    $('.note-editable.panel-body').height(window.innerHeight - 80);
    //console.log(window.innerHeight);
  });
}

$(document).ready(function() {
  var locale = getParameterByName('locale');
  initI18N(locale, 'ns.editorHTML.json');
});

var sourceURL = '';
var currentContent;
var scrappedOn = '';

function getContent() {
  console.log('Getting text content from editor.');
  $(".note-editable .tsCheckBox").each(() => {
    $(this).attr("disabled", "disabled");
  });

  let content = $(".note-editable").html();

/* Clean content
    $("#iframeViewer").contents().find(".note-editable .tsCheckBox").each(function() {
      $(this).removeAttr("disabled");
    });

    // removing all scripts from the document
    var cleanedContent = content.replace(/


<commit_before>//Translated from group.rb using babyruby2js
'use strict';

var Grid = require('./Grid');
var main = require('./main');

var EMPTY = main.EMPTY;

/** @class
 *  A group keeps the list of its stones, the updated number of "lives" (empty intersections around),
 *  and whatever status information we need to decide what happens to a group (e.g. when a
 *  group is killed or merged with another group, etc.).
 *  Note that most of the work here is to keep this status information up to date.
 *    public read-only attribute: goban, stones, lives, color
 *    public read-only attribute: mergedWith, mergedBy, killedBy, ndx
 *    public write attribute: mergedWith, mergedBy, extraLives  *  only used in this file
 *  Create a new group. Always with a single stone.
 *  Do not call this using Group.new but Goban#newGroup instead.
 */
function Group(goban, stone, lives, ndx) {
    this.goban = goban;
    this.stones = [stone];
    this.lives = lives;
    this.color = stone.color;
    this.mergedWith = null; // a group
    this.mergedBy = null; // a stone
    this.killedBy = null; // a stone
    this.ndx = ndx; // unique index

    // populated by analysis:
    this.isAlive = this.isDead = 0;
    this.inRaceWith = null;
}
module.exports = Group;

Group.prototype.recycle = function (stone, lives, ndx) {
    this.stones.clear();
    this.stones.push(stone);
    this.lives = lives;
    this.color = stone.color;
    this.mergedWith = this.mergedBy = this.killedBy = null;
    this.ndx = ndx;

    this.isAlive = this.isDead = 0;
    this.inRaceWith = null;
    return this;
};

Group.prototype.clear = function () {
    for (var i = this.stones.length - 1; i >= 0; i--) {
        this.stones[i].clear();
    }
    this.goban.deleteGroup(this);
};

Group.prototype.toString = function () {
    var s = '{group #' + this.ndx + ' of ' + this.stones.length + ' ' + Grid.colorName(this.color) + ' stones [';
    for (var stone, stone_array = this.stones, stone_ndx = 0; stone=stone_array[stone_ndx], stone_ndx < stone_array.length; stone_ndx++) {
        s += stone.asMove() + ',';
    }
    s = s.chop();
    s += '], lives:' + this.lives;
    if (this.mergedWith) {
        s += ' MERGED with #' + this.mergedWith.ndx;
    }
    if (this.killedBy) {
        s += ' KILLED by ' + this.killedBy.asMove();
    }
    s += '}';
    return s;
};

// debug dump does not have more to display now that stones are simpler
// TODO: remove it unless stones get more state data to display
Group.prototype.debugDump = function () {
    return this.toString();
};

Group.prototype.stonesDump = function () {
    return this.stones.map(function (s) {
        return s.asMove();
    }).sort().join(',');
};

// Builds a list of all lives of the group (empty stones around)
// Costly!
Group.prototype.allLives = function () {
    var lives = [];
    for (var s, s_array = this.stones, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
        for (var life, life_array = s.neighbors, life_ndx = 0; life=life_array[life_ndx], life_ndx < life_array.length; life_ndx++) {
            if (life.color !== EMPTY) continue;

            if (lives.indexOf(life) < 0) lives.push(life);
        }
    }
    if (lives.length !== this.lives) throw new Error('Wrong life count for group');
    return lives;
};

// Builds a list of all enemies of the group
// Costly!
Group.prototype.allEnemies = function () {
    var enemies = [];
    var enemyColor = 1 - this.color;
    for (var s, s_array = this.stones, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
        for (var en, en_array = s.neighbors, en_ndx = 0; en=en_array[en_ndx], en_ndx < en_array.length; en_ndx++) {
            if (en.color !== enemyColor) continue;

            if (enemies.indexOf(en.group) < 0) enemies.push(en.group);
        }
    }
    if (main.debugGroup) main.log.debug(this + ' has ' + enemies.length + ' enemies');
    return enemies;
};

// Counts the lives of a stone that are not already in the group
// (the stone is to be added or removed)
// NB: presupposes that stone.isNextTo(this) is true
Group.prototype.livesAddedByStone = function (stone) {
    var lives = -1; // -1 since the connection itself removes 1
    for (var life, life_array = stone.neighbors, life_ndx = 0; life=life_array[life_ndx], life_ndx < life_array.length; life_ndx++) {
        if (life.color !== EMPTY) continue;

        lives++;
        for (var s, s_array = life.neighbors, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
            if (s.group === this && s !== stone) {
                lives--;
                break;
            }
        }
    }
    if (main.debugGroup) main.log.debug(lives + ' lives added by ' + stone + ' for group ' + this);
    return lives;
};

// Connects a new stone or a merged stone to this group
Group.prototype.connectStone = function (stone) {
    if (main.debugGroup) main.log.debug('Connecting ' + stone + ' to group ' + this);

    this.stones.push(stone);
    this.lives += this.livesAddedByStone(stone);

    if (this.lives < 0) { // can be 0 if suicide-kill
        throw new Error('Unexpected error (lives<0 on connect)');
    }
    if (main.debugGroup) main.log.debug('Final group: ' + this);
};

// Disconnects a stone
Group.prototype.disconnectStone = function (stone) {
    if (main.debugGroup) main.log.debug('Disconnecting ' + stone + ' from group ' + this);

    if (this.stones.length > 1) {
        this.lives -= this.livesAddedByStone(stone);
        if (this.lives < 0) throw new Error('Lives<0 on disconnect'); // =0 if suicide-kill
    } else { // groups of 1 stone become empty groups (->garbage)
        this.goban.deleteGroup(this);
        if (main.debugGroup) main.log.debug('Group going to recycle bin: ' + this);
    }
    // we always remove them in the reverse order they came
    if (this.stones.pop() !== stone) throw new Error('Unexpected error (disconnect order)');
};

// When a new stone appears next to this group
Group.prototype.attackedBy = function (stone) {
    this.lives--;
    if (this.lives <= 0) { // also check <0 so we can raise in die_from method
        return this._dieFrom(stone);
    }
};

// When a group of stones reappears because we undo
// NB: it can never kill anything
Group.prototype._attackedByResuscitated = function (stone) {
    this.lives--;
    if (main.debugGroup) main.log.debug(this + ' attacked by resuscitated ' + stone);

    if (this.lives < 1) throw new Error('Unexpected error (lives<1 on attack by resucitated)');
};

// Stone parameter is just for debug for now
Group.prototype.notAttackedAnymore = function (stone) {
    this.lives++;
    if (main.debugGroup) main.log.debug(this + ' not attacked anymore by ' + stone);
};

// Merges a subgroup with this group
Group.prototype.merge = function (subgroup, byStone) {
    if (subgroup.mergedWith === this || subgroup === this || this.color !== subgroup.color) {
        throw new Error('Invalid merge');
    }
    if (main.debugGroup) main.log.debug('Merging subgroup:' + subgroup + ' to main:' + this);

    this.lives += subgroup.stones.length;
    for (var s, s_array = subgroup.stones, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
        s.setGroupOnMerge(this);
        this.connectStone(s);
    }
    subgroup.mergedWith = this;
    subgroup.mergedBy = byStone;
    this.goban.mergedGroups.push(subgroup);
    if (main.debugGroup) main.log.debug('After merge: subgroup:' + subgroup + ' main:' + this);
};

// Reverse of merge
Group.prototype._unmerge = function (subgroup) {
    if (main.debugGroup) main.log.debug('Unmerging subgroup:' + subgroup + ' from main:' + this);

    for (var s, s_array = subgroup.stones, s_ndx = s_array.length - 1; s=s_array[s_ndx], s_ndx >= 0; s_ndx--) {
        this.disconnectStone(s);
        s.setGroupOnMerge(subgroup);
    }
    this.lives -= subgroup.stones.length;
    subgroup.mergedBy = subgroup.mergedWith = null;
    if (main.debugGroup) main.log.debug('After _unmerge: subgroup:' + subgroup + ' main:' + this);
};

// This must be called on the main group (stone.group)
Group.prototype.unmergeFrom = function (stone) {
    for (;;) {
        var subgroup = this.goban.mergedGroups[this.goban.mergedGroups.length - 1];
        if (subgroup.mergedBy !== stone || subgroup.mergedWith !== this) break;
        this._unmerge(subgroup);
        this.goban.mergedGroups.pop();
    }
};

// Called when the group has no more life left
Group.prototype._dieFrom = function (killerStone) {
    if (main.debugGroup) main.log.debug('Group dying: ' + this);
    if (this.lives < 0) throw new Error('Unexpected error (lives<0)');

    for (var stone, stone_array = this.stones, stone_ndx = 0; stone=stone_array[stone_ndx], stone_ndx < stone_array.length; stone_ndx++) {
        for (var enemy, enemy_array = stone.uniqueAllies(1 - this.color), enemy_ndx = 0; enemy=enemy_array[enemy_ndx], enemy_ndx < enemy_array.length; enemy_ndx++) {
            enemy.notAttackedAnymore(stone);
        }
        stone.die();
    }
    this.killedBy = killerStone;
    this.goban.killedGroups.push(this);
    if (main.debugGroup) main.log.debug('Group dead: ' + this);
};

// Called when "undo" operation removes the killer stone of this group
Group.prototype._resuscitate = function () {
    this.killedBy = null;
    this.lives = 1; // always comes back with a single life
    for (var stone, stone_array = this.stones, stone_ndx = 0; stone=stone_array[stone_ndx], stone_ndx < stone_array.length; stone_ndx++) {
        stone.resuscitateIn(this);
        for (var enemy, enemy_array = stone.uniqueAllies(1 - this.color), enemy_ndx = 0; enemy=enemy_array[enemy_ndx], enemy_ndx < enemy_array.length; enemy_ndx++) {
            enemy._attackedByResuscitated(stone);
        }
    }
};

Group.resuscitateFrom = function (killerStone, goban) {
    for (;;) {
        var group = goban.killedGroups[goban.killedGroups.length - 1];
        if (group.killedBy !== killerStone) break;
        goban.killedGroups.pop();
        if (main.debugGroup) main.log.debug('taking back ' + killerStone + ' so we resuscitate ' + group.debugDump());
        group._resuscitate();
    }
};

// Returns prisoners grouped by color of dead stones
Group.countPrisoners = function (goban) {
    var prisoners = [0, 0];
    for (var i = 1; i <= goban.killedGroups.length - 1; i++) {
        var g = goban.killedGroups[i];
        prisoners[g.color] += g.stones.length;
    }
    return prisoners;
};
<commit_msg>Group#isValid (WIP)<commit_after>//Translated from group.rb using babyruby2js
'use strict';

var Grid = require('./Grid');
var main = require('./main');

var EMPTY = main.EMPTY;

/** @class
 *  A group keeps the list of its stones, the updated number of "lives" (empty intersections around),
 *  and whatever status information we need to decide what happens to a group (e.g. when a
 *  group is killed or merged with another group, etc.).
 *  Note that most of the work here is to keep this status information up to date.
 *    public read-only attribute: goban, stones, lives, color
 *    public read-only attribute: mergedWith, mergedBy, killedBy, ndx
 *    public write attribute: mergedWith, mergedBy, extraLives  *  only used in this file
 *  Create a new group. Always with a single stone.
 *  Do not call this using Group.new but Goban#newGroup instead.
 */
function Group(goban, stone, lives, ndx) {
    this.goban = goban;
    this.stones = [stone];
    this.lives = lives;
    this.color = stone.color;
    this.mergedWith = null; // a group
    this.mergedBy = null; // a stone
    this.killedBy = null; // a stone
    this.ndx = ndx; // unique index

    // populated by analysis:
    this.isAlive = this.isDead = 0;
    this.inRaceWith = null;
}
module.exports = Group;

Group.prototype.recycle = function (stone, lives, ndx) {
    this.stones.clear();
    this.stones.push(stone);
    this.lives = lives;
    this.color = stone.color;
    this.mergedWith = this.mergedBy = this.killedBy = null;
    this.ndx = ndx;

    this.isAlive = this.isDead = 0;
    this.inRaceWith = null;
    return this;
};

Group.prototype.clear = function () {
    for (var i = this.stones.length - 1; i >= 0; i--) {
        this.stones[i].clear();
    }
    this.goban.deleteGroup(this);
};

Group.prototype.toString = function () {
    var s = '{group #' + this.ndx + ' of ' + this.stones.length + ' ' + Grid.colorName(this.color) + ' stones [';
    for (var stone, stone_array = this.stones, stone_ndx = 0; stone=stone_array[stone_ndx], stone_ndx < stone_array.length; stone_ndx++) {
        s += stone.asMove() + ',';
    }
    s = s.chop();
    s += '], lives:' + this.lives;
    if (this.mergedWith) {
        s += ' MERGED with #' + this.mergedWith.ndx;
    }
    if (this.killedBy) {
        s += ' KILLED by ' + this.killedBy.asMove();
    }
    s += '}';
    return s;
};

Group.prototype.isValid = function () {
    return this.stones[0].group === this;
};

// debug dump does not have more to display now that stones are simpler
// TODO: remove it unless stones get more state data to display
Group.prototype.debugDump = function () {
    return this.toString();
};

Group.prototype.stonesDump = function () {
    return this.stones.map(function (s) {
        return s.asMove();
    }).sort().join(',');
};

// Builds a list of all lives of the group (empty stones around)
// Costly!
Group.prototype.allLives = function () {
    var lives = [];
    for (var s, s_array = this.stones, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
        for (var life, life_array = s.neighbors, life_ndx = 0; life=life_array[life_ndx], life_ndx < life_array.length; life_ndx++) {
            if (life.color !== EMPTY) continue;

            if (lives.indexOf(life) < 0) lives.push(life);
        }
    }
    if (lives.length !== this.lives) throw new Error('Wrong life count for group');
    return lives;
};

// Builds a list of all enemies of the group
// Costly!
Group.prototype.allEnemies = function () {
    var enemies = [];
    var enemyColor = 1 - this.color;
    for (var s, s_array = this.stones, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
        for (var en, en_array = s.neighbors, en_ndx = 0; en=en_array[en_ndx], en_ndx < en_array.length; en_ndx++) {
            if (en.color !== enemyColor) continue;

            if (enemies.indexOf(en.group) < 0) enemies.push(en.group);
        }
    }
    if (main.debugGroup) main.log.debug(this + ' has ' + enemies.length + ' enemies');
    return enemies;
};

// Counts the lives of a stone that are not already in the group
// (the stone is to be added or removed)
// NB: presupposes that stone.isNextTo(this) is true
Group.prototype.livesAddedByStone = function (stone) {
    var lives = -1; // -1 since the connection itself removes 1
    for (var life, life_array = stone.neighbors, life_ndx = 0; life=life_array[life_ndx], life_ndx < life_array.length; life_ndx++) {
        if (life.color !== EMPTY) continue;

        lives++;
        for (var s, s_array = life.neighbors, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
            if (s.group === this && s !== stone) {
                lives--;
                break;
            }
        }
    }
    if (main.debugGroup) main.log.debug(lives + ' lives added by ' + stone + ' for group ' + this);
    return lives;
};

// Connects a new stone or a merged stone to this group
Group.prototype.connectStone = function (stone) {
    if (main.debugGroup) main.log.debug('Connecting ' + stone + ' to group ' + this);

    this.stones.push(stone);
    this.lives += this.livesAddedByStone(stone);

    if (this.lives < 0) { // can be 0 if suicide-kill
        throw new Error('Unexpected error (lives<0 on connect)');
    }
    if (main.debugGroup) main.log.debug('Final group: ' + this);
};

// Disconnects a stone
Group.prototype.disconnectStone = function (stone) {
    if (main.debugGroup) main.log.debug('Disconnecting ' + stone + ' from group ' + this);

    if (this.stones.length > 1) {
        this.lives -= this.livesAddedByStone(stone);
        if (this.lives < 0) throw new Error('Lives<0 on disconnect'); // =0 if suicide-kill
    } else { // groups of 1 stone become empty groups (->garbage)
        this.goban.deleteGroup(this);
        if (main.debugGroup) main.log.debug('Group going to recycle bin: ' + this);
    }
    // we always remove them in the reverse order they came
    if (this.stones.pop() !== stone) throw new Error('Unexpected error (disconnect order)');
};

// When a new stone appears next to this group
Group.prototype.attackedBy = function (stone) {
    this.lives--;
    if (this.lives <= 0) { // also check <0 so we can raise in die_from method
        return this._dieFrom(stone);
    }
};

// When a group of stones reappears because we undo
// NB: it can never kill anything
Group.prototype._attackedByResuscitated = function (stone) {
    this.lives--;
    if (main.debugGroup) main.log.debug(this + ' attacked by resuscitated ' + stone);

    if (this.lives < 1) throw new Error('Unexpected error (lives<1 on attack by resucitated)');
};

// Stone parameter is just for debug for now
Group.prototype.notAttackedAnymore = function (stone) {
    this.lives++;
    if (main.debugGroup) main.log.debug(this + ' not attacked anymore by ' + stone);
};

// Merges a subgroup with this group
Group.prototype.merge = function (subgroup, byStone) {
    if (subgroup.mergedWith === this || subgroup === this || this.color !== subgroup.color) {
        throw new Error('Invalid merge');
    }
    if (main.debugGroup) main.log.debug('Merging subgroup:' + subgroup + ' to main:' + this);

    this.lives += subgroup.stones.length;
    for (var s, s_array = subgroup.stones, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
        s.setGroupOnMerge(this);
        this.connectStone(s);
    }
    subgroup.mergedWith = this;
    subgroup.mergedBy = byStone;
    this.goban.mergedGroups.push(subgroup);
    if (main.debugGroup) main.log.debug('After merge: subgroup:' + subgroup + ' main:' + this);
};

// Reverse of merge
Group.prototype._unmerge = function (subgroup) {
    if (main.debugGroup) main.log.debug('Unmerging subgroup:' + subgroup + ' from main:' + this);

    for (var s, s_array = subgroup.stones, s_ndx = s_array.length - 1; s=s_array[s_ndx], s_ndx >= 0; s_ndx--) {
        this.disconnectStone(s);
        s.setGroupOnMerge(subgroup);
    }
    this.lives -= subgroup.stones.length;
    subgroup.mergedBy = subgroup.mergedWith = null;
    if (main.debugGroup) main.log.debug('After _unmerge: subgroup:' + subgroup + ' main:' + this);
};

// This must be called on the main group (stone.group)
Group.prototype.unmergeFrom = function (stone) {
    for (;;) {
        var subgroup = this.goban.mergedGroups[this.goban.mergedGroups.length - 1];
        if (subgroup.mergedBy !== stone || subgroup.mergedWith !== this) break;
        this._unmerge(subgroup);
        this.goban.mergedGroups.pop();
    }
};

// Called when the group has no more life left
Group.prototype._dieFrom = function (killerStone) {
    if (main.debugGroup) main.log.debug('Group dying: ' + this);
    if (this.lives < 0) throw new Error('Unexpected error (lives<0)');

    for (var stone, stone_array = this.stones, stone_ndx = 0; stone=stone_array[stone_ndx], stone_ndx < stone_array.length; stone_ndx++) {
        for (var enemy, enemy_array = stone.uniqueAllies(1 - this.color), enemy_ndx = 0; enemy=enemy_array[enemy_ndx], enemy_ndx < enemy_array.length; enemy_ndx++) {
            enemy.notAttackedAnymore(stone);
        }
        stone.die();
    }
    this.killedBy = killerStone;
    this.goban.killedGroups.push(this);
    if (main.debugGroup) main.log.debug('Group dead: ' + this);
};

// Called when "undo" operation removes the killer stone of this group
Group.prototype._resuscitate = function () {
    this.killedBy = null;
    this.lives = 1; // always comes back with a single life
    for (var stone, stone_array = this.stones, stone_ndx = 0; stone=stone_array[stone_ndx], stone_ndx < stone_array.length; stone_ndx++) {
        stone.resuscitateIn(this);
        for (var enemy, enemy_array = stone.uniqueAllies(1 - this.color), enemy_ndx = 0; enemy=enemy_array[enemy_ndx], enemy_ndx < enemy_array.length; enemy_ndx++) {
            enemy._attackedByResuscitated(stone);
        }
    }
};

Group.resuscitateFrom = function (killerStone, goban) {
    for (;;) {
        var group = goban.killedGroups[goban.killedGroups.length - 1];
        if (group.killedBy !== killerStone) break;
        goban.killedGroups.pop();
        if (main.debugGroup) main.log.debug('taking back ' + killerStone + ' so we resuscitate ' + group.debugDump());
        group._resuscitate();
    }
};

// Returns prisoners grouped by color of dead stones
Group.countPrisoners = function (goban) {
    var prisoners = [0, 0];
    for (var i = 1; i <= goban.killedGroups.length - 1; i++) {
        var g = goban.killedGroups[i];
        prisoners[g.color] += g.stones.length;
    }
    return prisoners;
};
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Control panel around a content node.
 * Dynamically adjusts its size to fit its contents.
 *
 * @author Sam Reid
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );

  /**
   * @param {Node} content
   * @param {Object} [options]
   * @constructor
   */
  function Panel( content, options ) {

    var thisNode = this;

    // default options
    options = _.extend( {
      fill: 'white',
      stroke: 'black',
      lineWidth: 1, // width of the background border
      xMargin: 5,
      yMargin: 5,
      cornerRadius: 10, // radius of the rounded corners on the background
      resize: true, // dynamically resize when content bounds change
      backgroundPickable: false
    }, options );

    Node.call( thisNode );

    // correct size will be set by updateBackground
    var background = new Rectangle( 0, 0, 1, 1, {
      lineWidth: options.lineWidth,
      pickable: options.backgroundPickable,
      lineDash: options.lineDash
    } );
    this.background = background;
    // update the fill and stroke
    this.setStroke( options.stroke );
    this.setFill( options.fill );

    this.addChild( background );
    this.addChild( content );

    // Adjust the background size to match the content.
    var updateBackground = function() {
      background.setRect( 0, 0, content.width + ( 2 * options.xMargin ), content.height + ( 2 * options.yMargin ), options.cornerRadius, options.cornerRadius );

      // Prevent oscillation and stack overflow due to numerical imprecision, see https://github.com/phetsims/sun/issues/110
      if ( background.center.distanceSquared( content.center ) > 1E-6 ) {
        content.center = background.center;
      }
    };
    if ( options.resize ) {
      content.addEventListener( 'bounds', function() {
        updateBackground();
      } );
    }
    updateBackground();

    // Apply options after the layout is done, so that options that use the bounds will work properly.
    this.mutate( options );
  }

  inherit( Node, Panel, {

     // Change the background rectangle's stroke (can be overridden)
    setStroke: function( stroke ) {
      this.background.stroke = stroke;
    },

    // Get the background rectangle's stroke (can be overridden)
    getStroke: function() {
      return this.background.stroke;
    },

    // Getter/setter for background stroke
    set stroke( value ) { this.setStroke( value ); },
    get stroke() { return this.getStroke(); },

    // Change the background rectangle's fill (can be overridden)
    setFill: function( fill ) {
      this.background.fill = fill;
    },

    // Get the background rectangle's fill (can be overridden)
    getFill: function() {
      return this.background.fill;
    },

    // Getter/setter for background fill
    set fill( value ) { this.setFill( value ); },
    get fill() { return this.getFill(); }
  } );

  return Panel;
} );<commit_msg>Panel default options refactoring for https://github.com/phetsims/molecule-shapes/issues/61<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Control panel around a content node.
 * Dynamically adjusts its size to fit its contents.
 *
 * @author Sam Reid
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );

  var defaultOptions = {
    fill: 'white',
    stroke: 'black',
    lineWidth: 1, // width of the background border
    xMargin: 5,
    yMargin: 5,
    cornerRadius: 10, // radius of the rounded corners on the background
    resize: true, // dynamically resize when content bounds change
    backgroundPickable: false
  };

  /**
   * @param {Node} content
   * @param {Object} [options]
   * @constructor
   */
  function Panel( content, options ) {

    var thisNode = this;

    // default options
    options = _.extend( {}, defaultOptions, options );

    Node.call( thisNode );

    // correct size will be set by updateBackground
    var background = new Rectangle( 0, 0, 1, 1, {
      lineWidth: options.lineWidth,
      pickable: options.backgroundPickable,
      lineDash: options.lineDash
    } );
    this.background = background;
    // update the fill and stroke
    this.setStroke( options.stroke );
    this.setFill( options.fill );

    this.addChild( background );
    this.addChild( content );

    // Adjust the background size to match the content.
    var updateBackground = function() {
      background.setRect( 0, 0, content.width + ( 2 * options.xMargin ), content.height + ( 2 * options.yMargin ), options.cornerRadius, options.cornerRadius );

      // Prevent oscillation and stack overflow due to numerical imprecision, see https://github.com/phetsims/sun/issues/110
      if ( background.center.distanceSquared( content.center ) > 1E-6 ) {
        content.center = background.center;
      }
    };
    if ( options.resize ) {
      content.addEventListener( 'bounds', function() {
        updateBackground();
      } );
    }
    updateBackground();

    // Apply options after the layout is done, so that options that use the bounds will work properly.
    this.mutate( options );
  }

  inherit( Node, Panel, {

     // Change the background rectangle's stroke (can be overridden)
    setStroke: function( stroke ) {
      this.background.stroke = stroke;
    },

    // Get the background rectangle's stroke (can be overridden)
    getStroke: function() {
      return this.background.stroke;
    },

    // Getter/setter for background stroke
    set stroke( value ) { this.setStroke( value ); },
    get stroke() { return this.getStroke(); },

    // Change the background rectangle's fill (can be overridden)
    setFill: function( fill ) {
      this.background.fill = fill;
    },

    // Get the background rectangle's fill (can be overridden)
    getFill: function() {
      return this.background.fill;
    },

    // Getter/setter for background fill
    set fill( value ) { this.setFill( value ); },
    get fill() { return this.getFill(); }
  }, {
    defaultOptions: defaultOptions
  } );

  return Panel;
} );<|endoftext|>


<commit_before>var cleanForPublish = require("clean-for-publish");
var path = require("path");

var location = path.join(__dirname, '..');
cleanForPublish(location);
<commit_msg>Fix linter<commit_after>var cleanForPublish = require("clean-for-publish");
var path = require("path");

var location = path.join(__dirname, "..");
cleanForPublish(location);
<|endoftext|>


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

var http = require('http'),
    localtunnel = require('localtunnel'),
    parseArgs = require('minimist'),
    shell = require('shelljs'),
    fs = require('fs'),
    path = require('path');

var tunneledUrl = "";
var PORT = 8008;
var USAGE = "Error missing args. \n Usage: $cordova-paramedic --platform CORDOVA-PLATFORM --plugin PLUGIN-PATH";
var TEMP_PROJECT_PATH = "tmp";
var storedCWD = process.cwd();

var plugin,platformId;

run();

// main program here
function run() {
    init();
    createTempProject();
    installPlugins();
    startServer();
}

function init() {
    var argv = parseArgs(process.argv.slice(2),{
        plugin:".",
        platform:"windows"
    });

    if(!argv.platform || !argv.plugin) {
        console.log(USAGE);
        process.exit(1);
    }

    platformId = argv.platform;
    plugin = argv.plugin;

    var cordovaResult = shell.exec('cordova --version', {silent:true});
    if(cordovaResult.code) {
        console.error(cordovaResult.output);
        process.exit(cordovaResult.code);
    }
}

function createTempProject() {
    console.log("cordova-paramedic :: creating temp project");
    shell.exec('cordova create ' + TEMP_PROJECT_PATH);
    shell.cd(TEMP_PROJECT_PATH);
}

function installPlugins() {
    console.log("cordova-paramedic :: installing " + plugin);
    shell.exec('cordova plugin add ' + plugin);

    console.log("cordova-paramedic :: installing " + path.join(plugin,'tests'));
    shell.exec('cordova plugin add ' + path.join(plugin,'tests'));

    console.log("cordova-paramedic :: installing plugin-test-framework");
    shell.exec('cordova plugin add http://github.com/apache/cordova-plugin-test-framework');
}

function addAndRunPlatform() {
    console.log("cordova-paramedic :: adding platform and running");
    shell.exec('cordova -d platform add ' + platformId);
    shell.exec('cordova -d run ' + platformId.split("@")[0] + " --phone");
}

function cleanUpAndExitWithCode(exitCode) {
    shell.cd(storedCWD);
    process.exit(exitCode);
}

function writeMedicLogUrl(url) {
    console.log("cordova-paramedic :: writing medic log url to project");
    var obj = {logurl:url};
    fs.writeFileSync(path.join("www","medic.json"),JSON.stringify(obj));
}

function setConfigStartPage() {

    console.log("cordova-paramedic :: setting app start page to test page");

    var fileName = 'config.xml';
    var configStr = fs.readFileSync(fileName).toString();
    if(configStr) {
        configStr = configStr.replace("src=\"index.html\"","src=\"cdvtests/index.html\"");
        fs.writeFileSync(fileName, configStr);
    }
    else {
        console.error("Oops, could not find config.xml");

    }
}

function startServer() {
    console.log("cordova-paramedic :: starting local medic server");

    var server = http.createServer(requestListener);
    server.listen(PORT, '127.0.0.1',function onServerConnect() {
        localtunnel(PORT, tunnelCallback);
    });
}

function requestListener(request, response) {
    if (request.method == 'PUT') {
        var body = '';
        request.on('data', function (data) {
            //console.log("data = " + data);
            body += data;
            // Too much POST data, kill the connection!
            if (body.length > 1e6) {
                req.connection.destroy();
            }
        });
        request.on('end', function (res) {
            if(body.indexOf("mobilespec")  == 2){ // {\"mobilespec\":{...}}
                console.log("logging:" + body);
                try {
                    var results = JSON.parse(body);

                    console.log("Results:: ran " +
                        results.mobilespec.specs +
                        " specs with " +
                        results.mobilespec.failures +
                        " failures");

                    cleanUpAndExitWithCode(0);
                }
                catch(err) {
                    console.log("parse error :: " + err);
                    cleanUpAndExitWithCode(1);
                }
            }
            else {
                console.log("console-log:" + body);
            }
        });
    }
    else {
        console.log(request.method);
        response.writeHead(200, { 'Content-Type': 'text/plain'});
        response.write("Hello");
        response.end();
    }
}

function tunnelCallback(err, tunnel) {
    if (err){
        console.log("failed to create tunnel url, check your internet connectivity.")
        cleanUpAndExitWithCode(1);
    }
    else {
        // the assigned public url for your tunnel
        // i.e. https://abcdefgjhij.localtunnel.me
        tunneledUrl = tunnel.url;
        console.log("cordova-paramedic :: tunneledURL = " + tunneledUrl);
        writeMedicLogUrl(tunneledUrl);
        addAndRunPlatform();
    }
}

<commit_msg>ios does not need localtunnel, other platforms are stubbed/wip for now.<commit_after>#!/usr/bin/env node

var http = require('http'),
    localtunnel = require('localtunnel'),
    parseArgs = require('minimist'),
    shell = require('shelljs'),
    fs = require('fs'),
    path = require('path');

var tunneledUrl = "";
var PORT = 8008;
var USAGE = "Error missing args. \n Usage: $cordova-paramedic --platform CORDOVA-PLATFORM --plugin PLUGIN-PATH";
var TEMP_PROJECT_PATH = "tmp";
var storedCWD = process.cwd();

var plugin,platformId;

run();

// main program here
function run() {
    init();
    createTempProject();
    installPlugins();
    startServer();
}

function init() {
    var argv = parseArgs(process.argv.slice(2),{
        plugin:".",
        platform:""
    });

    if(!argv.platform || !argv.plugin) {
        console.log(USAGE);
        process.exit(1);
    }

    platformId = argv.platform;
    plugin = argv.plugin;

    var cordovaResult = shell.exec('cordova --version', {silent:true});
    if(cordovaResult.code) {
        console.error(cordovaResult.output);
        process.exit(cordovaResult.code);
    }
}

function createTempProject() {
    console.log("cordova-paramedic :: creating temp project");
    shell.exec('cordova create ' + TEMP_PROJECT_PATH);
    shell.cd(TEMP_PROJECT_PATH);
}

function installPlugins() {
    console.log("cordova-paramedic :: installing " + plugin);
    shell.exec('cordova plugin add ' + plugin);

    console.log("cordova-paramedic :: installing " + path.join(plugin,'tests'));
    shell.exec('cordova plugin add ' + path.join(plugin,'tests'));

    console.log("cordova-paramedic :: installing plugin-test-framework");
    shell.exec('cordova plugin add ../../cordova-plugin-test-framework/');

    shell.exec('cordova plugin add ../../cordova-plugin-device/');
}

function addAndRunPlatform() {
    setConfigStartPage();
    console.log("cordova-paramedic :: adding platform and running");
    shell.exec('cordova platform add ' + platformId);
    shell.exec('cordova prepare');
    shell.exec('cordova emulate ' + platformId.split("@")[0] + " --phone");
}

function cleanUpAndExitWithCode(exitCode) {
    shell.cd(storedCWD);
    process.exit(exitCode);
}

function writeMedicLogUrl(url) {
    console.log("cordova-paramedic :: writing medic log url to project");
    var obj = {logurl:url};
    fs.writeFileSync(path.join("www","medic.json"),JSON.stringify(obj));
}

function setConfigStartPage() {

    console.log("cordova-paramedic :: setting app start page to test page");

    var fileName = 'config.xml';
    var configStr = fs.readFileSync(fileName).toString();
    if(configStr) {
        configStr = configStr.replace("src=\"index.html\"","src=\"cdvtests/index.html\"");
        fs.writeFileSync(fileName, configStr);
    }
    else {
        console.error("Oops, could not find config.xml");
    }
}

function startServer() {
    console.log("cordova-paramedic :: starting local medic server " + platformId);

    var server = http.createServer(requestListener);
    server.listen(PORT, '127.0.0.1',function onServerConnect() {

        if(platformId == "ios") {
            console.log('platform is ios');
            writeMedicLogUrl("http://127.0.0.1:" + PORT);
            addAndRunPlatform();
        }
        else {
            //localtunnel(PORT, tunnelCallback); // TODO
            console.log("Only ios is currently supported");
            cleanUpAndExitWithCode(1);
        }
    });
}

function requestListener(request, response) {
    if (request.method == 'PUT' || request.method == 'POST') {
        var body = '';
        request.on('data', function (data) {
            body += data;
            // Too much POST data, kill the connection!
            if (body.length > 1e6) {
                req.connection.destroy();
            }
        });
        request.on('end', function (res) {
            if(body.indexOf("mobilespec")  == 2){ // {\"mobilespec\":{...}}
                try {
                    console.log("body = " + body);
                    var results = JSON.parse(body);
                    console.log("Results:: ran " +
                        results.mobilespec.specs +
                        " specs with " +
                        results.mobilespec.failures +
                        " failures");
                    cleanUpAndExitWithCode(0);
                }
                catch(err) {
                    console.log("parse error :: " + err);
                    cleanUpAndExitWithCode(1);
                }
            }
            else {
                console.log("console-log:" + body);
            }
        });
    }
    else {
        console.log(request.method);
        response.writeHead(200, { 'Content-Type': 'text/plain'});
        response.write("Hello"); // sanity check to make sure server is running
        response.end();
    }
}

function tunnelCallback(err, tunnel) {
    if (err){
        console.log("failed to create tunnel url, check your internet connectivity.")
        cleanUpAndExitWithCode(1);
    }
    else {
        // the assigned public url for your tunnel
        // i.e. https://abcdefgjhij.localtunnel.me
        tunneledUrl = tunnel.url;
        console.log("cordova-paramedic :: tunneledURL = " + tunneledUrl);
        writeMedicLogUrl(tunneledUrl);
        addAndRunPlatform();
    }
}

<|endoftext|>


<commit_before>var runInterval;

function assemble() {
	processor.text = [];
	program.data = [];
	program.labels = {};
	processor.reset();

	textarea = document.getElementById("code");
	programCode = program.stripWhiteSpace(textarea.innerText);
	program.readCode(program.splitLines(program.stripComments(programCode)));
	processor.loadProgram(program);
	showInstructions();
	addLineNumbers();
	instructionsList = document.getElementById("instructions");
	instructionsList.children[processor.programCounter].style["backgroundColor"]="hsl(120,27%,90%)";
	codeDiv = document.getElementById("code");
	codeDiv.children[processor.text[processor.programCounter].lineNum].style["backgroundColor"]="hsl(120,27%,90%)";

};

function showInstructions() {
	instructionsList = document.getElementById("instructions");
	while(instructionsList.lastElementChild!=null) {
		instructionsList.lastElementChild.remove();
	}
	for(ii in processor.text) {
		instr = processor.text[ii];
		instructionsList.appendChild(document.createElement("li"));
		instructionsList.lastChild.innerText = instr.op+ " " + instr.params.join(", ") + " (on line " + instr.lineNum.toString()+ ")";
	}
};

function showRegisters() {
	registersList = document.getElementById("registers");
	for(ii in processor.registers) {
		reg = processor.registers[ii];
		registersList.appendChild(document.createElement("tr"));
		registersList.lastChild.appendChild(document.createElement("td"));
		registersList.lastChild.lastChild.innerText = ii;
		registersList.lastChild.appendChild(document.createElement("td"));

		registersList.lastChild.lastChild.innerText = "abd";
		/*if(processor.registerNames[ii]!=undefined) {
			registersList.lastChild.lastChild.innerText = processor.registerNames[ii];
		}*/

		registersList.lastChild.appendChild(document.createElement("td"));
		registersList.lastChild.lastChild.innerText = processor.registers[ii];
	}
};

function updateRegisters () {
	registersList = document.getElementById("registers").lastChild;
	for(ii in registersList.childNodes) {
		if (registersList.children[ii]&&registersList.children[ii].children!=undefined) {
			registersList.children[ii].children[2].innerText = processor.registers[ii];
		}
	}
};

function addLineNumbers() {
	textarea = document.getElementById("code");
	lineNumbers = document.getElementById("lineNumbers");
	lineNumbers.innerText = "";
	for (i = 0; i < textarea.innerText.match(/$/gm).length; i++) {
		lineNumbers.innerText = lineNumbers.innerText+i+"\n";
	}
};

function runStep() {
	if(!processor.running) return;

	instructionsList = document.getElementById("instructions");
	codeDiv = document.getElementById("code");
	instructionsList.children[processor.programCounter].style["backgroundColor"]="white";
	codeDiv.children[processor.text[processor.programCounter].lineNum].style["backgroundColor"]="white";
	processor.runInstr();

	if(!processor.running) return;

	updateRegisters();
	codeDiv.children[processor.text[processor.programCounter].lineNum].style["backgroundColor"]="hsl(120,27%,90%)";
	instructionsList.children[processor.programCounter].style["backgroundColor"]="hsl(120,27%,90%)";
	codeDiv.children[processor.text[processor.programCounter].lineNum].scrollIntoViewIfNeeded();
};

function resume(interval) {
	runInterval = window.setInterval(step, interval);
};

function pause() {
	window.clearInterval(runInterval);
};

updateRegisters();

codeBox = document.getElementById("code");
console.log(codeBox);
codeBox.onkeyup = addLineNumbers;
codeBox.onpaste = function(){console.log("a")};

<commit_msg>fixed typo<commit_after>var runInterval;

function assemble() {
	processor.text = [];
	program.data = [];
	program.labels = {};
	processor.reset();

	textarea = document.getElementById("code");
	programCode = program.stripWhiteSpace(textarea.innerText);
	program.readCode(program.splitLines(program.stripComments(programCode)));
	processor.loadProgram(program);
	showInstructions();
	addLineNumbers();
	instructionsList = document.getElementById("instructions");
	instructionsList.children[processor.programCounter].style["backgroundColor"]="hsl(120,27%,90%)";
	codeDiv = document.getElementById("code");
	codeDiv.children[processor.text[processor.programCounter].lineNum].style["backgroundColor"]="hsl(120,27%,90%)";

};

function showInstructions() {
	instructionsList = document.getElementById("instructions");
	while(instructionsList.lastElementChild!=null) {
		instructionsList.lastElementChild.remove();
	}
	for(ii in processor.text) {
		instr = processor.text[ii];
		instructionsList.appendChild(document.createElement("li"));
		instructionsList.lastChild.innerText = instr.op+ " " + instr.params.join(", ") + " (on line " + instr.lineNum.toString()+ ")";
	}
};

function showRegisters() {
	registersList = document.getElementById("registers");
	for(ii in processor.registers) {
		reg = processor.registers[ii];
		registersList.appendChild(document.createElement("tr"));
		registersList.lastChild.appendChild(document.createElement("td"));
		registersList.lastChild.lastChild.innerText = ii;
		registersList.lastChild.appendChild(document.createElement("td"));

		registersList.lastChild.lastChild.innerText = "abd";
		/*if(processor.registerNames[ii]!=undefined) {
			registersList.lastChild.lastChild.innerText = processor.registerNames[ii];
		}*/

		registersList.lastChild.appendChild(document.createElement("td"));
		registersList.lastChild.lastChild.innerText = processor.registers[ii];
	}
};

function updateRegisters () {
	registersList = document.getElementById("registers").lastChild;
	for(ii in registersList.childNodes) {
		if (registersList.children[ii]&&registersList.children[ii].children!=undefined) {
			registersList.children[ii].children[2].innerText = processor.registers[ii];
		}
	}
};

function addLineNumbers() {
	textarea = document.getElementById("code");
	lineNumbers = document.getElementById("lineNumbers");
	lineNumbers.innerText = "";
	for (i = 0; i < textarea.innerText.match(/$/gm).length; i++) {
		lineNumbers.innerText = lineNumbers.innerText+i+"\n";
	}
};

function runStep() {
	if(!processor.running) return;

	instructionsList = document.getElementById("instructions");
	codeDiv = document.getElementById("code");
	instructionsList.children[processor.programCounter].style["backgroundColor"]="white";
	codeDiv.children[processor.text[processor.programCounter].lineNum].style["backgroundColor"]="white";
	processor.runInstr();

	if(!processor.running) return;

	updateRegisters();
	codeDiv.children[processor.text[processor.programCounter].lineNum].style["backgroundColor"]="hsl(120,27%,90%)";
	instructionsList.children[processor.programCounter].style["backgroundColor"]="hsl(120,27%,90%)";
	codeDiv.children[processor.text[processor.programCounter].lineNum].scrollIntoViewIfNeeded();
};

function resume(interval) {
	runInterval = window.setInterval(runStep, interval);
};

function pause() {
	window.clearInterval(runInterval);
};

updateRegisters();

codeBox = document.getElementById("code");
console.log(codeBox);
codeBox.onkeyup = addLineNumbers;
codeBox.onpaste = function(){console.log("a")};

<|endoftext|>


<commit_before>// Copyright 2013-2015, University of Colorado Boulder

/**
 * Timer so that other modules can run timing related code through the simulation's requestAnimationFrame.
 * Note: this is not specific to the running screen, it is global across all screens.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var cleanArray = require( 'PHET_CORE/cleanArray' );
  var joist = require( 'JOIST/joist' );

  var listeners = [];
  var listenersDefensiveCopy = []; // separated out to prevent garbage collection issues

  var Timer = {

    // @public (joist-internal) - Trigger a step event, called by Sim.js in the animation loop
    step: function( dt ) {
      var length = listeners.length;
      var i;

      // to safely allow listeners to remove themselves while being called (as is explicitly done in setTimeout), we make a copy of the array.
      // we don't use slice(), since that would cause garbage collection issues.
      for ( i = 0; i < length; i++ ) {
        listenersDefensiveCopy[ i ] = listeners[ i ];
      }
      for ( i = 0; i < length; i++ ) {
        listenersDefensiveCopy[ i ]( dt );
      }
      cleanArray( listenersDefensiveCopy );
    },

    // @public - Add a listener to be called back once after the specified time (in milliseconds)
    setTimeout: function( listener, timeout ) {
      var elapsed = 0;
      var timer = this;
      var callback = function( dt ) {
        elapsed += dt;

        //Convert seconds to ms and see if item has timed out
        if ( elapsed * 1000 >= timeout ) {
          listener();
          timer.removeStepListener( callback );
        }
      };
      this.addStepListener( callback );

      //Return the callback so it can be removed with removeStepListener
      return callback;
    },

    // @public - Clear a scheduled timeout. If there was no timeout, nothing is done.
    clearTimeout: function( timeoutID ) {
      if ( this.hasStepListener( timeoutID ) ) {
        this.removeStepListener( timeoutID );
      }
    },

    // @public - Add a listener to be called at specified intervals (in milliseconds)
    setInterval: function( listener, interval ) {
      var elapsed = 0;
      var callback = function( dt ) {
        elapsed += dt;

        //Convert seconds to ms and see if item has timed out
        while ( elapsed * 1000 >= interval && listeners.indexOf( callback ) !== -1 ) {
          listener();
          elapsed = elapsed - interval / 1000.0; //Save the leftover time so it won't accumulate
        }
      };
      this.addStepListener( callback );

      //Return the callback so it can be removed with removeStepListener
      return callback;
    },

    // @public - Clear a scheduled interval. If there was no interval, nothing is done.
    clearInterval: function( intervalID ) {
      if ( this.hasStepListener( intervalID ) ) {
        this.removeStepListener( intervalID );
      }
    },

    // @public - Add a listener to be called back on every animationFrame with a dt value
    addStepListener: function( listener ) {
      listeners.push( listener );
    },

    // @public - Remove a step listener from being called back
    removeStepListener: function( listener ) {
      var index = listeners.indexOf( listener );
      assert && assert( index !== -1, 'An attempt was made to remove a non-existent step listener' );
      if ( index !== -1 ) {
        listeners.splice( index, 1 );
      }
    },

    // @public
    hasStepListener: function( listener ) {
      return listeners.indexOf( listener ) >= 0;
    }
  };

  joist.register( 'Timer', Timer );

  return Timer;
} );
<commit_msg>fix namespace for phet-core.Timer, https://github.com/phetsims/sun/issues/219<commit_after>// Copyright 2013-2015, University of Colorado Boulder

/**
 * Timer so that other modules can run timing related code through the simulation's requestAnimationFrame.
 * Note: this is not specific to the running screen, it is global across all screens.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var cleanArray = require( 'PHET_CORE/cleanArray' );
  var phetCore = require( 'PHET_CORE/phetCore' );

  var listeners = [];
  var listenersDefensiveCopy = []; // separated out to prevent garbage collection issues

  var Timer = {

    // @public (joist-internal) - Trigger a step event, called by Sim.js in the animation loop
    step: function( dt ) {
      var length = listeners.length;
      var i;

      // to safely allow listeners to remove themselves while being called (as is explicitly done in setTimeout), we make a copy of the array.
      // we don't use slice(), since that would cause garbage collection issues.
      for ( i = 0; i < length; i++ ) {
        listenersDefensiveCopy[ i ] = listeners[ i ];
      }
      for ( i = 0; i < length; i++ ) {
        listenersDefensiveCopy[ i ]( dt );
      }
      cleanArray( listenersDefensiveCopy );
    },

    // @public - Add a listener to be called back once after the specified time (in milliseconds)
    setTimeout: function( listener, timeout ) {
      var elapsed = 0;
      var timer = this;
      var callback = function( dt ) {
        elapsed += dt;

        //Convert seconds to ms and see if item has timed out
        if ( elapsed * 1000 >= timeout ) {
          listener();
          timer.removeStepListener( callback );
        }
      };
      this.addStepListener( callback );

      //Return the callback so it can be removed with removeStepListener
      return callback;
    },

    // @public - Clear a scheduled timeout. If there was no timeout, nothing is done.
    clearTimeout: function( timeoutID ) {
      if ( this.hasStepListener( timeoutID ) ) {
        this.removeStepListener( timeoutID );
      }
    },

    // @public - Add a listener to be called at specified intervals (in milliseconds)
    setInterval: function( listener, interval ) {
      var elapsed = 0;
      var callback = function( dt ) {
        elapsed += dt;

        //Convert seconds to ms and see if item has timed out
        while ( elapsed * 1000 >= interval && listeners.indexOf( callback ) !== -1 ) {
          listener();
          elapsed = elapsed - interval / 1000.0; //Save the leftover time so it won't accumulate
        }
      };
      this.addStepListener( callback );

      //Return the callback so it can be removed with removeStepListener
      return callback;
    },

    // @public - Clear a scheduled interval. If there was no interval, nothing is done.
    clearInterval: function( intervalID ) {
      if ( this.hasStepListener( intervalID ) ) {
        this.removeStepListener( intervalID );
      }
    },

    // @public - Add a listener to be called back on every animationFrame with a dt value
    addStepListener: function( listener ) {
      listeners.push( listener );
    },

    // @public - Remove a step listener from being called back
    removeStepListener: function( listener ) {
      var index = listeners.indexOf( listener );
      assert && assert( index !== -1, 'An attempt was made to remove a non-existent step listener' );
      if ( index !== -1 ) {
        listeners.splice( index, 1 );
      }
    },

    // @public
    hasStepListener: function( listener ) {
      return listeners.indexOf( listener ) >= 0;
    }
  };

  phetCore.register( 'Timer', Timer );

  return Timer;
} );
<|endoftext|>


<commit_before>//
// This file is part of ColorZilla
//
// Written by Alex Sirota (alex @ iosart.com)
//
// Copyright (c) iosart labs llc 2011, All Rights Reserved
//
(function() {
    if (!document.body.hasAttribute('cz-shortcut-listen')) {
        document.body.setAttribute('cz-shortcut-listen', 'true');
        document.body.addEventListener('keydown', function(e) {
            var isMac = navigator.userAgent.toLowerCase().indexOf('mac') > -1;
            var keyCode = e.keyCode;
            if ((e.ctrlKey && e.altKey && !isMac ||
                 e.metaKey && e.altKey && isMac) &&
                 keyCode > 64 && keyCode < 91) {
                    chrome.extension.sendRequest({op:'hotkey-pressed', keyCode: keyCode});
            }
        }, false);
    }
})();
// supposed to fix

function init() { // Main function
	// ========== VARIABLE INITIATION v ==========
	var c = document.getElementById("retrovirus"), // Access the canvas
		vImg = document.getElementById("vImg"), // Virus's image
        	abImg1 = document.getElementById("abImg1"),
        	abImg2 = document.getElementById("abImg2"),
        	abImg3 = document.getElementById("abImg3"), // Antibodys are a little redundant, but i can't get around it
        	abImg4 = document.getElementById("abImg4"),
        	abImg5 = document.getElementById("abImg5"),
        	abCount = 5,
        	numbers = [], // Possible array fix
        	abImg = [], // Possible array fix
		ctx = c.getContext("2d"), // 2D Canvas context
		height = window.innerHeight, // Shortcut to window.innerHeight
		width = window.innerWidth, // Shortcut to window.innerWidth
		centerH, // Center of the canvas's height
		centerW, // Center of the canvas's width
		cW, // Shortcut to the canvas's width
		cH, // Shortcut to the canvas's height
		gridH, // For accessing movement distance/grid height
		gridW // For accessing movement distance/grid width

	for (i = 0; i < abCount; i++) {
		var j = i + 1
		numbers.push[j.toString()]
		abImg[i + 1] = document.getElemenById("abImg" + numbers[i])
	}

	// ========== VARIABLE INITIATION ^ ==========

	// ========== GLOBAL FUNCTIONS v =============

	function writeText(text) { // Text writing function
		ctx.textAlign = "center"
		ctx.font = "12pt ABeeZee"
		ctx.fillText(text, centerW, centerH)
	}

	// ========== GLOBAL FUNCTIONS ^ ==========

 	// =============== CLASSES v ==============

	var RetroVirus = function(x, y) { // Virus constructor
		this.x = x
		this.y = y
	}

	RetroVirus.prototype = { // Virus prototype functions
		move : function(newX, newY) {
			ctx.clearRect(0, 0, cW, cH)
			ctx.rect(0, 0, cW, cH) // Set the canvas background to black
			ctx.fillStyle = "black"
			ctx.fill()
			ctx.drawImage(vImg, newX, newY)
			for (i = 0; i < abCount; i++) {
				antibody[i + 1].render(i + 1)
			}
			return this.x * this.y
		}
	}

	var Antibody = function(x, y) {
		this.x = x
		this.y = y
	}

	var virus = new RetroVirus() // Create new virus with constructor
	var antibody = []
	for (i = 0; i < abCount; i++) {
		antibody[i + 1] = new Antibody()
	}

	// ========== CLASSES ^ ==========

   	if (width > height) { // If in landscape mode

   		// ========== SECOND VARIABLE INITIATION v ==========

		c.width = width - 18
		c.height = height - 22
		cW = c.width
		cH = c.height
		centerW = cW / 2
		centerH = cH / 2

		// ========== SECOND VARIABLE INITIATION ^ ==========

		// ========== SPECIAL FUNCTIONS v ==========

		function grid(countX) { // Sections where the virus will be
			var pos; // Position to start/end the line
			for (var i = countX - 1; i > 0; i--) {
				gridW = cW / countX
				pos = gridW * i
				ctx.moveTo(pos, 0)
				ctx.lineTo(pos, cH)
				// ctx.strokeStyle = "white"
				ctx.stroke()
			}

			for (var i = countX - 1; i > 0; i--) {
				gridH = gridW // Ensure a square
				pos = gridH * i
				ctx.moveTo(0, pos)
				ctx.lineTo(cW, pos)
				// ctx.strokeStyle = "white"
				ctx.stroke()
			}
		}

		// ========== SPECIAL FUNCTIONS ^ ==========

		grid(20) // 20 squares across

		virus.x = centerW // Set the virus's starting position
		virus.y = centerH // - gridH / 2 // To offset image for collision

		// We'll let this fly for now

		antibody[1].x = gridW * 3
		antibody[1].y = gridW * 6

		antibody[2].x = gridW * 15
		antibody[2].y = gridW * 4

		antibody[3].x = gridW * 7
		antibody[3].y = gridW * 5

		antibody[4].x = gridW * 9
		antibody[4].y = gridW * 2

		antibody[5].x = gridW * 8
		antibody[5].y = gridW * 9

		antibody.move = function(newX, newY) {
			ctx.clearRect(0, 0, cW, cH)
			ctx.rect(0, 0, cW, cH) // Set the canvas background to black
			ctx.fillStyle = "black"
			ctx.fill()
			for(i = 0; i < abCount; i++) {
				ctx.drawImage(abImg[i + 1], newX, newY)
			}
			virus.render()
			return this.x * this.y
		}

		antibody.render = function(toRender) {
			ctx.drawImage(abImg[toRender], antibody[toRender].x, antibody[toRender].y)
			return abImg[toRender]
		}

		virus.render = function() {
			ctx.drawImage(vImg, virus.x, virus.y)
			return vImg
		}

		ctx.rect(0, 0, cW, cH) // Set the canvas background to black
		ctx.fillStyle = "black"
		ctx.fill()

	} else { // If in portrait mode
		ctx.textAlign = "center"
		ctx.font = "12pt ABeeZee"
		ctx.fillText("Please use landscape mode.", centerW, centerH)
	}

	// ========== CRUCIAL FUNDEMENTALS v ==========

	setInterval(function() {
		for(i = 0; i < abCount; i++) {
			if (antibody[i + 1].x - virus.x > 0 && antibody[i + 1].x - virus.x > antibody[i + 1].y - virus.y)  {
				antibody[i + 1].move(antibody[i + 1].x -= gridW, antibody[i + 1].y)
			}

			else if (antibody[i + 1].y - virus.y < 0 && antibody[i + 1].y - virus.y < antibody[i + 1].x - virus.x) {
				antibody[i + 1].move(antibody[i + 1].x, antibody[i + 1].y += gridW)
			}

			else if (antibody[i + 1].x - virus.x < 0 && antibody[i + 1].x - virus.x < antibody[i + 1].y - virus.y) {
				antibody[i + 1].move(antibody[i + 1].x += gridW, antibody[i + 1].y)
			}

			else if (antibody[i + 1].y - virus.y > 0 && antibody[i + 1].y - virus.y > antibody[i + 1].x - virus.x) {
				antibody[i + 1].move(antibody[I + 1].x, antibody[i + 1].y -= gridW)
			}
		}
	}, 500)

	window.addEventListener("keydown", function(event) { // Key listener
		switch (event.keyCode) {
			case 37: // Left
				if(virus.x < 0) {} // For edge collision
				else { // Print image at new position
					virus.move(virus.x - gridW, virus.y)
					virus.x -= gridW
				}
				break

			case 38: // Up
				if(virus.y - gridH  < 0) {}
				else {
					virus.move(virus.x, virus.y - gridH)
					virus.y -= gridH
				}
				break

			case 39: // Right
				if(virus.x + gridW * 2 > cW) {}
				else {
					virus.move(virus.x + gridW, virus.y)
					virus.x += gridW
				}
				break

			case 40: // Down
				if(virus.y + gridH * 2 > cH) {}
				else {
					virus.move(virus.x, virus.y + gridH)
					virus.y += gridH
				}
				break
			}
	}, false)

	window.addEventListener("load", function () {
		virus.render()
		for(i = 0; i < abCount; i++) {
			antibody[i + 1].render()
		}
	}, false)

	// ========== CRUCIAL FUNDEMENTALS ^ ==========
}

document.addEventListener("DOMContentLoaded", init, false) // Run when the DOM has loaded
<commit_msg>Update main.js<commit_after>//
// This file is part of ColorZilla
//
// Written by Alex Sirota (alex @ iosart.com)
//
// Copyright (c) iosart labs llc 2011, All Rights Reserved
//
(function() {
    if (!document.body.hasAttribute('cz-shortcut-listen')) {
        document.body.setAttribute('cz-shortcut-listen', 'true');
        document.body.addEventListener('keydown', function(e) {
            var isMac = navigator.userAgent.toLowerCase().indexOf('mac') > -1;
            var keyCode = e.keyCode;
            if ((e.ctrlKey && e.altKey && !isMac ||
                 e.metaKey && e.altKey && isMac) &&
                 keyCode > 64 && keyCode < 91) {
                    chrome.extension.sendRequest({op:'hotkey-pressed', keyCode: keyCode});
            }
        }, false);
    }
})();
// supposed to fix

function init() { // Main function
	// ========== VARIABLE INITIATION v ==========
	var c = document.getElementById("retrovirus"), // Access the canvas
		vImg = document.getElementById("vImg"), // Virus's image
        	abImg1 = document.getElementById("abImg1"),
        	abImg2 = document.getElementById("abImg2"),
        	abImg3 = document.getElementById("abImg3"), // Antibodys are a little redundant, but i can't get around it
        	abImg4 = document.getElementById("abImg4"),
        	abImg5 = document.getElementById("abImg5"),
        	abCount = 5,
        	numbers = [], // Possible array fix
        	abImg = [], // Possible array fix
		ctx = c.getContext("2d"), // 2D Canvas context
		height = window.innerHeight, // Shortcut to window.innerHeight
		width = window.innerWidth, // Shortcut to window.innerWidth
		centerH, // Center of the canvas's height
		centerW, // Center of the canvas's width
		cW, // Shortcut to the canvas's width
		cH, // Shortcut to the canvas's height
		gridH, // For accessing movement distance/grid height
		gridW // For accessing movement distance/grid width

		for (i = 0; i < abCount; i++) {
			var j = i + 1
			numbers.push[j.toString()]
			abImg[i + 1] = document.getElementById("abImg" + numbers[i])
		}

	// ========== VARIABLE INITIATION ^ ==========

	// ========== GLOBAL FUNCTIONS v =============

	function writeText(text) { // Text writing function
		ctx.textAlign = "center"
		ctx.font = "12pt ABeeZee"
		ctx.fillText(text, centerW, centerH)
	}

	// ========== GLOBAL FUNCTIONS ^ ==========

 	// =============== CLASSES v ==============

	var RetroVirus = function(x, y) { // Virus constructor
		this.x = x
		this.y = y
	}

	RetroVirus.prototype = { // Virus prototype functions
		move : function(newX, newY) {
			ctx.clearRect(0, 0, cW, cH)
			ctx.rect(0, 0, cW, cH) // Set the canvas background to black
			ctx.fillStyle = "black"
			ctx.fill()
			ctx.drawImage(vImg, newX, newY)
			for (i = 0; i < abCount; i++) {
				antibody[i + 1].render(i + 1)
			}
			return this.x * this.y
		}
	}

	var Antibody = function(x, y) {
		this.x = x
		this.y = y
	}

	var virus = new RetroVirus() // Create new virus with constructor
	var antibody = []
	for (i = 0; i < abCount; i++) {
		antibody[i + 1] = new Antibody()
	}

	// ========== CLASSES ^ ==========

   	if (width > height) { // If in landscape mode

   		// ========== SECOND VARIABLE INITIATION v ==========

		c.width = width - 18
		c.height = height - 22
		cW = c.width
		cH = c.height
		centerW = cW / 2
		centerH = cH / 2

		// ========== SECOND VARIABLE INITIATION ^ ==========

		// ========== SPECIAL FUNCTIONS v ==========

		function grid(countX) { // Sections where the virus will be
			var pos; // Position to start/end the line
			for (var i = countX - 1; i > 0; i--) {
				gridW = cW / countX
				pos = gridW * i
				ctx.moveTo(pos, 0)
				ctx.lineTo(pos, cH)
				// ctx.strokeStyle = "white"
				ctx.stroke()
			}

			for (var i = countX - 1; i > 0; i--) {
				gridH = gridW // Ensure a square
				pos = gridH * i
				ctx.moveTo(0, pos)
				ctx.lineTo(cW, pos)
				// ctx.strokeStyle = "white"
				ctx.stroke()
			}
		}

		// ========== SPECIAL FUNCTIONS ^ ==========

		grid(20) // 20 squares across

		virus.x = centerW // Set the virus's starting position
		virus.y = centerH // - gridH / 2 // To offset image for collision

		// We'll let this fly for now

		antibody[1].x = gridW * 3
		antibody[1].y = gridW * 6

		antibody[2].x = gridW * 15
		antibody[2].y = gridW * 4

		antibody[3].x = gridW * 7
		antibody[3].y = gridW * 5

		antibody[4].x = gridW * 9
		antibody[4].y = gridW * 2

		antibody[5].x = gridW * 8
		antibody[5].y = gridW * 9

		antibody.move = function(newX, newY) {
			ctx.clearRect(0, 0, cW, cH)
			ctx.rect(0, 0, cW, cH) // Set the canvas background to black
			ctx.fillStyle = "black"
			ctx.fill()
			for(i = 0; i < abCount; i++) {
				ctx.drawImage(abImg[i + 1], newX, newY)
			}
			virus.render()
			return this.x * this.y
		}

		antibody.render = function(toRender) {
			ctx.drawImage(abImg[toRender], antibody[toRender].x, antibody[toRender].y)
			return abImg[toRender]
		}

		virus.render = function() {
			ctx.drawImage(vImg, virus.x, virus.y)
			return vImg
		}

		ctx.rect(0, 0, cW, cH) // Set the canvas background to black
		ctx.fillStyle = "black"
		ctx.fill()

	} else { // If in portrait mode
		ctx.textAlign = "center"
		ctx.font = "12pt ABeeZee"
		ctx.fillText("Please use landscape mode.", centerW, centerH)
	}

	// ========== CRUCIAL FUNDEMENTALS v ==========

	setInterval(function() {
		for(i = 0; i < abCount; i++) {
			if (antibody[i + 1].x - virus.x > 0 && antibody[i + 1].x - virus.x > antibody[i + 1].y - virus.y)  {
				antibody[i + 1].move(antibody[i + 1].x -= gridW, antibody[i + 1].y)
			}

			else if (antibody[i + 1].y - virus.y < 0 && antibody[i + 1].y - virus.y < antibody[i + 1].x - virus.x) {
				antibody[i + 1].move(antibody[i + 1].x, antibody[i + 1].y += gridW)
			}

			else if (antibody[i + 1].x - virus.x < 0 && antibody[i + 1].x - virus.x < antibody[i + 1].y - virus.y) {
				antibody[i + 1].move(antibody[i + 1].x += gridW, antibody[i + 1].y)
			}

			else if (antibody[i + 1].y - virus.y > 0 && antibody[i + 1].y - virus.y > antibody[i + 1].x - virus.x) {
				antibody[i + 1].move(antibody[I + 1].x, antibody[i + 1].y -= gridW)
			}
		}
	}, 500)

	window.addEventListener("keydown", function(event) { // Key listener
		switch (event.keyCode) {
			case 37: // Left
				if(virus.x < 0) {} // For edge collision
				else { // Print image at new position
					virus.move(virus.x - gridW, virus.y)
					virus.x -= gridW
				}
				break

			case 38: // Up
				if(virus.y - gridH  < 0) {}
				else {
					virus.move(virus.x, virus.y - gridH)
					virus.y -= gridH
				}
				break

			case 39: // Right
				if(virus.x + gridW * 2 > cW) {}
				else {
					virus.move(virus.x + gridW, virus.y)
					virus.x += gridW
				}
				break

			case 40: // Down
				if(virus.y + gridH * 2 > cH) {}
				else {
					virus.move(virus.x, virus.y + gridH)
					virus.y += gridH
				}
				break
			}
	}, false)

	window.addEventListener("load", function () {
		virus.render()
		for(i = 0; i < abCount; i++) {
			antibody[i + 1].render()
		}
	}, false)

	// ========== CRUCIAL FUNDEMENTALS ^ ==========
}

document.addEventListener("DOMContentLoaded", init, false) // Run when the DOM has loaded
<|endoftext|>


<commit_before>/* Amber package loading
   usage example:
   amber.load({
   files: ['MyCategory1.js', 'MyCategory2.js'],
   ready: function() {smalltalk.Browser._open()}
   })
*/

amber = (function() {
	var that = {};

	var scripts = document.getElementsByTagName("script");
	var src     = scripts[ scripts.length - 1 ].src;
	var home    = resolveViaDOM(src).replace(/[^\/]+\/[^\/]+$/, "");

	var debug;
	var deploy;

	var spec;
	var jsToLoad = [];
	var loadJS;
	var nocache = '';

    function resolveViaDOM(url) {
        var a = document.createElement("a");
        a.href = url;
        return a.href;
    }

	that.load = function(obj) {
		spec = obj || {};

		// In deployment mode, only the compressed version of Kernel
		// and Canvas are loaded
		deploy = spec.deploy || false;
		debug = spec.debug || false;

		// When debug is turned on, logs are written to the console,
		// and the user will be prompted before they leave the page.
		if (debug) {
			window.onbeforeunload = function(){ return 'You will loose all code that you have not committed'; }
		}

		// Allow loading default Amber files from a different location
		// e.g. http://amber-lang.net/amber/
		if (spec.home) home = spec.home;

		// Specify a version string to avoid wrong browser caching
		if (spec.version) {
			nocache = '?' + spec.version;
		}

		loadDependencies();
		addJSToLoad('js/lib/es5-shim-2.0.2/es5-shim.min.js');
		addJSToLoad('js/lib/es5-shim-2.0.2/es5-sham.min.js');
		addJSToLoad('js/boot.js');

		if (deploy) {
			loadPackages([
				'Kernel-Objects.deploy',
				'Kernel-Classes.deploy',
				'Kernel-Methods.deploy',
				'Kernel-Collections.deploy',
				'Kernel-Exceptions.deploy',
				'Kernel-Transcript.deploy',
				'Kernel-Announcements.deploy',
				'Canvas.deploy'
			]);
		} else {
			loadIDEDependencies();
			loadCSS('amber.css');

			loadPackages([
				'Kernel-Objects',
				'Kernel-Classes',
				'Kernel-Methods',
				'Kernel-Collections',
				'Kernel-Exceptions',
				'Kernel-Transcript',
				'Kernel-Announcements',
				'Canvas',
				'SUnit',
				'Importer-Exporter',
				'Compiler-Exceptions',
				'Compiler-Core',
				'Compiler-AST',
				'Compiler-Semantic',
				'Compiler-IR',
				'Compiler-Inlining',
				'Compiler-Interpreter',
				'Compiler-Tests',
				'parser',
				'IDE',
				'Examples',
				'Benchfib',
				'Kernel-Tests',
				'SUnit-Tests'
			]);
		}

		var additionalFiles = spec.packages || spec.files;
		if (additionalFiles) {
			that.commitPath = loadPackages(additionalFiles, spec.prefix, spec.packageHome);
		}

		// Be sure to setup & initialize smalltalk classes
		addJSToLoad('js/init.js');
		initializeSmalltalk();
	};

	function loadPackages(names, prefix, urlHome){
		var name;
		prefix = prefix || 'js';
		urlHome = urlHome || home;

		for (var i=0; i < names.length; i++) {
			name = names[i].split(/\.js$/)[0];
			addJSToLoad(name + '.js', prefix, urlHome);
		}

		return  {
			js: urlHome + prefix,
			st: urlHome + (prefix.match(/\/js$/) ? prefix.replace(/\/js$/, "/st") : "st")
		};
	}

	function addJSToLoad(name, prefix, urlHome) {
		urlHome = urlHome || home;
		jsToLoad.push(buildJSURL(name, prefix, urlHome));
	}

	function resolve(base, path) {
		if (/(^|:)\/\//.test(path)) {
			// path: [http:]//foo.com/bar/; base: whatever/
			// -> http://foo.com/bar/
			return path;
		}
		if (!/^\//.test(path)) {
			// path: relative/; base: whatever/
			// -> whatever/relative/
			return base + path;
		}
		var match = base.match(/^(([^:/]*:|^)\/\/[^/]*)/);
		if (match) {
			// path: /absolute/; base: [http:]//foo.com/whatever/
			// -> [http:]//foo.com/absolute/
			return match[1] + path;
		}
		// path: /absolute/; base: whatever/path/
		// -> /absolute/
		return path;
	}

	function buildJSURL(name, prefix, urlHome) {
		prefix = prefix ? prefix + '/' : '';
		urlHome = urlHome || home;

		var parts = name.match(/^(.*\/)([^/]*)$/);
		if (parts) {
			name = parts[2];
			urlHome = resolve(urlHome, parts[1]);
		}

		if (!deploy) {
			name = name + nocache;
		}

		return urlHome + prefix + name;
	}

	function loadCSS(name, prefix) {
		prefix = prefix || 'css';
		if (!deploy) {
			name = name + nocache;
		}

		var url = home + prefix + '/' + name;

		var link = document.createElement("link");
		link.setAttribute("rel", "stylesheet");
		link.setAttribute("type", "text/css");
		link.setAttribute("href", url);
		document.getElementsByTagName("head")[0].appendChild(link);
	}

	function loadDependencies() {
		if (typeof jQuery == 'undefined') {
			addJSToLoad('js/lib/jQuery/jquery-1.8.2.min.js');
		}

		if ((typeof jQuery == 'undefined') || (typeof jQuery.ui == 'undefined')) {
			addJSToLoad('js/lib/jQuery/jquery-ui-1.8.16.custom.min.js');
		}
	}

	function loadIDEDependencies() {
		addJSToLoad('js/lib/jQuery/jquery.textarea.js');
		addJSToLoad('js/lib/CodeMirror/codemirror.js');
		addJSToLoad('js/lib/CodeMirror/smalltalk.js');
		addJSToLoad('js/lib/CodeMirror/addon/hint/show-hint.js');
		loadCSS('lib/CodeMirror/codemirror.css', 'js');
		loadCSS('lib/CodeMirror/theme/ambiance.css', 'js');
		loadCSS('lib/CodeMirror/addon/hint/show-hint.css', 'js');
		loadCSS('lib/CodeMirror/amber.css', 'js');
	}

	// This will be called after JS files have been loaded
	function initializeSmalltalk() {
		that.smalltalkReady = function() {
            if (spec.ready) {
                spec.ready();
            }
            evaluateSmalltalkScripts();
        };

        loadAllJS();
	}

	/*
	 * When loaded using AJAX, scripts order not guaranteed.
	 * Load JS in the order they have been added using addJSToLoad().
	 * If loaded, will use jQuery's getScript instead of adding a script element
	 */
	function loadAllJS() {
		loadJS = loadJSViaScriptTag;
		if (typeof jQuery != 'undefined') {
			loadJS = loadJSViaJQuery;
		}
		loadNextJS();
	}

	function loadNextJS() {
		loadJS(jsToLoad[0], function(){
			jsToLoad.shift();
			if (jsToLoad.length > 0) {
				loadNextJS();
			}
		});
	}

	function loadJSViaScriptTag(url, callback) {
		writeScriptTag(url);
		callback();
	}

	function loadJSViaJQuery(url, callback) {
		// The order of loading is as specified, but order of execution may get wrong
		// (observed when loading amber in testing environment using zombiejs).
		// jQuery's getScript/get/ajax does not give any guarantee as to the order of execution.
		// The callback is called after the file is fully load, but it may not have been executed.
		// When given a small timeout between ending previous loading and start of next loading,
		// it is very probable that the time window is used to actually start executing the script.
		$.ajax({
			dataType: "script",
			url: url,
			cache: deploy,
			success: function () { setTimeout(callback, 5); }
		});
	}

	function writeScriptTag(src) {
		var scriptString = '';
		document.write(scriptString);
	}

	function evaluateSmalltalkScripts() {
		jQuery(document).ready(function() {
			jQuery('script[type="text/smalltalk"]').each(function(i, elt) {
				smalltalk.Compiler._new()._evaluateExpression_(jQuery(elt).html());
			});
		})
	}

	var localPackages;

	function populateLocalPackages(){
		var localStorageRE = /^smalltalk\.packages\.(.*)$/;
		localPackages = {};

		var match, key;

		for(var i=0; i < localStorage.length; i++) {
			key = localStorage.key(i);

			if (match = key.match(localStorageRE)) {
				localPackages[match[1]] = localStorage[key];
			}
		}

		return localPackages;
	}

	function clearLocalPackages() {
		for (var name in localPackages) {
			log('Removing ' + name + ' from local storage');
			localStorage.removeItem('smalltalk.packages.' + name);
		}
	}

	function log(string) {
		if (debug) {
			console.log(string);
		}
	}

	that.loadHelios = function() {
        loadCSS('helios_frame.css');
        var frame = jQuery('

');

        jQuery('body').append(frame);
        jQuery(frame).resizable({
            handles: 'n',
            start: onResizeStart,
            stop: onResizeStop,
            resize: onResize,

        });

        function onResize() {
            jQuery('#helios')
                .css('top', '')
                .css('width', '100%')
                .css('bottom', '0px');
        }

        function onResizeStart() {
            jQuery('#helios').append('

')
        }

        function onResizeStop() {
            jQuery('#helios').find('.overlay').remove();
        }
    };

	return that;
})();

window.loadAmber  = amber.load;
window.loadHelios = amber.loadHelios;

// Backward compatibility
function toggleAmberIDE () {
    return smalltalk.TabManager._toggleAmberIDE();
}
<commit_msg>Fixed helios loading amber.js home variable<commit_after>/* Amber package loading
   usage example:
   amber.load({
   files: ['MyCategory1.js', 'MyCategory2.js'],
   ready: function() {smalltalk.Browser._open()}
   })
*/

amber = (function() {
	var that = {};

	var scripts = document.getElementsByTagName("script");
	var src     = scripts[ scripts.length - 1 ].src;
	var home    = resolveViaDOM(src).replace(/[^\/]+\/[^\/]+$/, "");

	var debug;
	var deploy;

	var spec;
	var jsToLoad = [];
	var loadJS;
	var nocache = '';

    function resolveViaDOM(url) {
        var a = document.createElement("a");
        a.href = url;
        return a.href;
    }

	that.load = function(obj) {
		spec = obj || {};

		// In deployment mode, only the compressed version of Kernel
		// and Canvas are loaded
		deploy = spec.deploy || false;
		debug = spec.debug || false;

		// When debug is turned on, logs are written to the console,
		// and the user will be prompted before they leave the page.
		if (debug) {
			window.onbeforeunload = function(){ return 'You will loose all code that you have not committed'; }
		}

		// Allow loading default Amber files from a different location
		// e.g. http://amber-lang.net/amber/
		if (spec.home) home = spec.home;

		// Specify a version string to avoid wrong browser caching
		if (spec.version) {
			nocache = '?' + spec.version;
		}

		loadDependencies();
		addJSToLoad('js/lib/es5-shim-2.0.2/es5-shim.min.js');
		addJSToLoad('js/lib/es5-shim-2.0.2/es5-sham.min.js');
		addJSToLoad('js/boot.js');

		if (deploy) {
			loadPackages([
				'Kernel-Objects.deploy',
				'Kernel-Classes.deploy',
				'Kernel-Methods.deploy',
				'Kernel-Collections.deploy',
				'Kernel-Exceptions.deploy',
				'Kernel-Transcript.deploy',
				'Kernel-Announcements.deploy',
				'Canvas.deploy'
			]);
		} else {
			loadIDEDependencies();
			loadCSS('amber.css');

			loadPackages([
				'Kernel-Objects',
				'Kernel-Classes',
				'Kernel-Methods',
				'Kernel-Collections',
				'Kernel-Exceptions',
				'Kernel-Transcript',
				'Kernel-Announcements',
				'Canvas',
				'SUnit',
				'Importer-Exporter',
				'Compiler-Exceptions',
				'Compiler-Core',
				'Compiler-AST',
				'Compiler-Semantic',
				'Compiler-IR',
				'Compiler-Inlining',
				'Compiler-Interpreter',
				'Compiler-Tests',
				'parser',
				'IDE',
				'Examples',
				'Benchfib',
				'Kernel-Tests',
				'SUnit-Tests'
			]);
		}

		var additionalFiles = spec.packages || spec.files;
		if (additionalFiles) {
			that.commitPath = loadPackages(additionalFiles, spec.prefix, spec.packageHome);
		}

		// Be sure to setup & initialize smalltalk classes
		addJSToLoad('js/init.js');
		initializeSmalltalk();
	};

	function loadPackages(names, prefix, urlHome){
		var name;
		prefix = prefix || 'js';
		urlHome = urlHome || home;

		for (var i=0; i < names.length; i++) {
			name = names[i].split(/\.js$/)[0];
			addJSToLoad(name + '.js', prefix, urlHome);
		}

		return  {
			js: urlHome + prefix,
			st: urlHome + (prefix.match(/\/js$/) ? prefix.replace(/\/js$/, "/st") : "st")
		};
	}

	function addJSToLoad(name, prefix, urlHome) {
		urlHome = urlHome || home;
		jsToLoad.push(buildJSURL(name, prefix, urlHome));
	}

	function resolve(base, path) {
		if (/(^|:)\/\//.test(path)) {
			// path: [http:]//foo.com/bar/; base: whatever/
			// -> http://foo.com/bar/
			return path;
		}
		if (!/^\//.test(path)) {
			// path: relative/; base: whatever/
			// -> whatever/relative/
			return base + path;
		}
		var match = base.match(/^(([^:/]*:|^)\/\/[^/]*)/);
		if (match) {
			// path: /absolute/; base: [http:]//foo.com/whatever/
			// -> [http:]//foo.com/absolute/
			return match[1] + path;
		}
		// path: /absolute/; base: whatever/path/
		// -> /absolute/
		return path;
	}

	function buildJSURL(name, prefix, urlHome) {
		prefix = prefix ? prefix + '/' : '';
		urlHome = urlHome || home;

		var parts = name.match(/^(.*\/)([^/]*)$/);
		if (parts) {
			name = parts[2];
			urlHome = resolve(urlHome, parts[1]);
		}

		if (!deploy) {
			name = name + nocache;
		}

		return urlHome + prefix + name;
	}

	function loadCSS(name, prefix) {
		prefix = prefix || 'css';
		if (!deploy) {
			name = name + nocache;
		}

		var url = home + prefix + '/' + name;

		var link = document.createElement("link");
		link.setAttribute("rel", "stylesheet");
		link.setAttribute("type", "text/css");
		link.setAttribute("href", url);
		document.getElementsByTagName("head")[0].appendChild(link);
	}

	function loadDependencies() {
		if (typeof jQuery == 'undefined') {
			addJSToLoad('js/lib/jQuery/jquery-1.8.2.min.js');
		}

		if ((typeof jQuery == 'undefined') || (typeof jQuery.ui == 'undefined')) {
			addJSToLoad('js/lib/jQuery/jquery-ui-1.8.16.custom.min.js');
		}
	}

	function loadIDEDependencies() {
		addJSToLoad('js/lib/jQuery/jquery.textarea.js');
		addJSToLoad('js/lib/CodeMirror/codemirror.js');
		addJSToLoad('js/lib/CodeMirror/smalltalk.js');
		addJSToLoad('js/lib/CodeMirror/addon/hint/show-hint.js');
		loadCSS('lib/CodeMirror/codemirror.css', 'js');
		loadCSS('lib/CodeMirror/theme/ambiance.css', 'js');
		loadCSS('lib/CodeMirror/addon/hint/show-hint.css', 'js');
		loadCSS('lib/CodeMirror/amber.css', 'js');
	}

	// This will be called after JS files have been loaded
	function initializeSmalltalk() {
		that.smalltalkReady = function() {
            if (spec.ready) {
                spec.ready();
            }
            evaluateSmalltalkScripts();
        };

        loadAllJS();
	}

	/*
	 * When loaded using AJAX, scripts order not guaranteed.
	 * Load JS in the order they have been added using addJSToLoad().
	 * If loaded, will use jQuery's getScript instead of adding a script element
	 */
	function loadAllJS() {
		loadJS = loadJSViaScriptTag;
		if (typeof jQuery != 'undefined') {
			loadJS = loadJSViaJQuery;
		}
		loadNextJS();
	}

	function loadNextJS() {
		loadJS(jsToLoad[0], function(){
			jsToLoad.shift();
			if (jsToLoad.length > 0) {
				loadNextJS();
			}
		});
	}

	function loadJSViaScriptTag(url, callback) {
		writeScriptTag(url);
		callback();
	}

	function loadJSViaJQuery(url, callback) {
		// The order of loading is as specified, but order of execution may get wrong
		// (observed when loading amber in testing environment using zombiejs).
		// jQuery's getScript/get/ajax does not give any guarantee as to the order of execution.
		// The callback is called after the file is fully load, but it may not have been executed.
		// When given a small timeout between ending previous loading and start of next loading,
		// it is very probable that the time window is used to actually start executing the script.
		$.ajax({
			dataType: "script",
			url: url,
			cache: deploy,
			success: function () { setTimeout(callback, 5); }
		});
	}

	function writeScriptTag(src) {
		var scriptString = '';
		document.write(scriptString);
	}

	function evaluateSmalltalkScripts() {
		jQuery(document).ready(function() {
			jQuery('script[type="text/smalltalk"]').each(function(i, elt) {
				smalltalk.Compiler._new()._evaluateExpression_(jQuery(elt).html());
			});
		})
	}

	var localPackages;

	function populateLocalPackages(){
		var localStorageRE = /^smalltalk\.packages\.(.*)$/;
		localPackages = {};

		var match, key;

		for(var i=0; i < localStorage.length; i++) {
			key = localStorage.key(i);

			if (match = key.match(localStorageRE)) {
				localPackages[match[1]] = localStorage[key];
			}
		}

		return localPackages;
	}

	function clearLocalPackages() {
		for (var name in localPackages) {
			log('Removing ' + name + ' from local storage');
			localStorage.removeItem('smalltalk.packages.' + name);
		}
	}

	function log(string) {
		if (debug) {
			console.log(string);
		}
	}

	that.loadHelios = function() {
        loadCSS('helios_frame.css');
        var frame = jQuery('

');

        jQuery('body').append(frame);
        jQuery(frame).resizable({
            handles: 'n',
            start: onResizeStart,
            stop: onResizeStop,
            resize: onResize,

        });

        function onResize() {
            jQuery('#helios')
                .css('top', '')
                .css('width', '100%')
                .css('bottom', '0px');
        }

        function onResizeStart() {
            jQuery('#helios').append('

')
        }

        function onResizeStop() {
            jQuery('#helios').find('.overlay').remove();
        }
    };

	return that;
})();

window.loadAmber  = amber.load;
window.loadHelios = amber.loadHelios;

// Backward compatibility
function toggleAmberIDE () {
    return smalltalk.TabManager._toggleAmberIDE();
}
<|endoftext|>


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

var parseArgs       = require('minimist');
var path            = require('path');
var paramedic       = require('./lib/paramedic');
var ParamedicConfig = require('./lib/ParamedicConfig');

var USAGE           = "Error missing args. \n" +
    "cordova-paramedic --platform PLATFORM --plugin PATH [--justbuild --timeout MSECS --startport PORTNUM --endport PORTNUM --browserify]\n" +
    "`PLATFORM` : the platform id. Currently supports 'ios', 'browser', 'windows', 'android', 'wp8'.\n" +
                    "\tPath to platform can be specified as link to git repo like:\n" +
                    "\twindows@https://github.com/apache/cordova-windows.git\n" +
                    "\tor path to local copied git repo like:\n" +
                    "\twindows@../cordova-windows/\n" +
    "`PATH` : the relative or absolute path to a plugin folder\n" +
                    "\texpected to have a 'tests' folder.\n" +
                    "\tYou may specify multiple --plugin flags and they will all\n" +
                    "\tbe installed and tested together.\n" +
    "`MSECS` : (optional) time in millisecs to wait for tests to pass|fail \n" +
              "\t(defaults to 10 minutes) \n" +
    "`PORTNUM` : (optional) ports to find available and use for posting results from emulator back to paramedic server(default is from 8008 to 8009)\n" +
    "--justbuild : (optional) just builds the project, without running the tests \n" +
    "--browserify : (optional) plugins are browserified into cordova.js \n" +
    "--verbose : (optional) verbose mode. Display more information output\n" +
    "--useTunnel : (optional) use tunneling instead of local address. default is false\n" +
    "--config : (optional) read configuration from paramedic configuration file\n" +
    "--outputDir: (optional) path to save Junit results file & Device logs\n" +
    "--cleanUpAfterRun: (optional) cleans up the application after the run\n" +
    "--logMins: (optional) Windows only - specifies number of minutes to get logs\n" +
    "--tccDb: (optional) iOS only - specifies the path for the TCC.db file to be copied." +
    "--shouldUseSauce: (optional) run tests on Saucelabs\n" +
    "--buildName: (optional) Build name to show in Saucelabs dashboard\n" +
    "--sauceUser: (optional) Saucelabs username\n" +
    "--sauceKey: (optional) Saucelabs access key";

var argv = parseArgs(process.argv.slice(2));
var pathToParamedicConfig = argv.config && path.resolve(argv.config);

if (pathToParamedicConfig || // --config
    argv.platform && argv.plugin) { // or --platform and --plugin

    var paramedicConfig = pathToParamedicConfig ?
        ParamedicConfig.parseFromFile(pathToParamedicConfig):
        ParamedicConfig.parseFromArguments(argv);

    if (argv.plugin) {
        paramedicConfig.setPlugins(argv.plugin);
    }

    if (argv.outputDir) {
        paramedicConfig.setOutputDir(argv.outputDir);
    }

    if (argv.logMins) {
        paramedicConfig.setLogMins(argv.logMins);
    }

    if (argv.tccDb){
        paramedicConfig.setTccDb(argv.tccDb);
    }

    if (argv.platform) {
        paramedicConfig.setPlatform(argv.platform);
    }

    if (argv.action) {
        paramedicConfig.setAction(argv.action);
    }

    if (argv.shouldUseSauce) {
        paramedicConfig.setShouldUseSauce(true);
    }

    if (argv.buildName) {
        paramedicConfig.setBuildName(argv.buildName);
    }

    if (argv.sauceUser) {
        paramedicConfig.setSauceUser(argv.sauceUser);
    }

    if (argv.sauceKey) {
        paramedicConfig.setSauceKey(argv.sauceKey);
    }

    paramedic.run(paramedicConfig)
    .catch(function (error) {
        if (error && error.stack) {
            console.error(error.stack);
        } else if (error) {
            console.error(error);
        }
        process.exit(1);
    })
    .done(function(isTestPassed) {
        process.exit(isTestPassed ? 0 : 1);
    });

} else {
    console.log(USAGE);
    process.exit(1);
}
<commit_msg>Don't ignore --useTunnel when using config (for reals)<commit_after>#!/usr/bin/env node

var parseArgs       = require('minimist');
var path            = require('path');
var paramedic       = require('./lib/paramedic');
var ParamedicConfig = require('./lib/ParamedicConfig');

var USAGE           = "Error missing args. \n" +
    "cordova-paramedic --platform PLATFORM --plugin PATH [--justbuild --timeout MSECS --startport PORTNUM --endport PORTNUM --browserify]\n" +
    "`PLATFORM` : the platform id. Currently supports 'ios', 'browser', 'windows', 'android', 'wp8'.\n" +
                    "\tPath to platform can be specified as link to git repo like:\n" +
                    "\twindows@https://github.com/apache/cordova-windows.git\n" +
                    "\tor path to local copied git repo like:\n" +
                    "\twindows@../cordova-windows/\n" +
    "`PATH` : the relative or absolute path to a plugin folder\n" +
                    "\texpected to have a 'tests' folder.\n" +
                    "\tYou may specify multiple --plugin flags and they will all\n" +
                    "\tbe installed and tested together.\n" +
    "`MSECS` : (optional) time in millisecs to wait for tests to pass|fail \n" +
              "\t(defaults to 10 minutes) \n" +
    "`PORTNUM` : (optional) ports to find available and use for posting results from emulator back to paramedic server(default is from 8008 to 8009)\n" +
    "--justbuild : (optional) just builds the project, without running the tests \n" +
    "--browserify : (optional) plugins are browserified into cordova.js \n" +
    "--verbose : (optional) verbose mode. Display more information output\n" +
    "--useTunnel : (optional) use tunneling instead of local address. default is false\n" +
    "--config : (optional) read configuration from paramedic configuration file\n" +
    "--outputDir: (optional) path to save Junit results file & Device logs\n" +
    "--cleanUpAfterRun: (optional) cleans up the application after the run\n" +
    "--logMins: (optional) Windows only - specifies number of minutes to get logs\n" +
    "--tccDb: (optional) iOS only - specifies the path for the TCC.db file to be copied." +
    "--shouldUseSauce: (optional) run tests on Saucelabs\n" +
    "--buildName: (optional) Build name to show in Saucelabs dashboard\n" +
    "--sauceUser: (optional) Saucelabs username\n" +
    "--sauceKey: (optional) Saucelabs access key";

var argv = parseArgs(process.argv.slice(2));
var pathToParamedicConfig = argv.config && path.resolve(argv.config);

if (pathToParamedicConfig || // --config
    argv.platform && argv.plugin) { // or --platform and --plugin

    var paramedicConfig = pathToParamedicConfig ?
        ParamedicConfig.parseFromFile(pathToParamedicConfig):
        ParamedicConfig.parseFromArguments(argv);

    if (argv.plugin) {
        paramedicConfig.setPlugins(argv.plugin);
    }

    if (argv.outputDir) {
        paramedicConfig.setOutputDir(argv.outputDir);
    }

    if (argv.logMins) {
        paramedicConfig.setLogMins(argv.logMins);
    }

    if (argv.tccDb){
        paramedicConfig.setTccDb(argv.tccDb);
    }

    if (argv.platform) {
        paramedicConfig.setPlatform(argv.platform);
    }

    if (argv.action) {
        paramedicConfig.setAction(argv.action);
    }

    if (argv.shouldUseSauce) {
        paramedicConfig.setShouldUseSauce(true);
    }

    if (argv.buildName) {
        paramedicConfig.setBuildName(argv.buildName);
    }

    if (argv.sauceUser) {
        paramedicConfig.setSauceUser(argv.sauceUser);
    }

    if (argv.sauceKey) {
        paramedicConfig.setSauceKey(argv.sauceKey);
    }

    if (argv.useTunnel) {
        paramedicConfig.setUseTunnel(true);
    }

    paramedic.run(paramedicConfig)
    .catch(function (error) {
        if (error && error.stack) {
            console.error(error.stack);
        } else if (error) {
            console.error(error);
        }
        process.exit(1);
    })
    .done(function(isTestPassed) {
        process.exit(isTestPassed ? 0 : 1);
    });

} else {
    console.log(USAGE);
    process.exit(1);
}
<|endoftext|>