<commit_before>import OptionManager from "./file/options/option-manager";
import * as messages from "babel-messages";
import Store from "../store";
import traverse from "babel-traverse";
import clone from "lodash/clone";

const GLOBAL_VISITOR_PROPS = ["enter", "exit"];

export default class Plugin extends Store {
  constructor(plugin: Object, key?: string) {
    super();

    this.initialized = false;
    this.raw = Object.assign({}, plugin);
    this.key = this.take("name") || key;

    this.manipulateOptions = this.take("manipulateOptions");
    this.post = this.take("post");
    this.pre = this.take("pre");
    this.visitor = this.normaliseVisitor(clone(this.take("visitor")) || {});
  }

  initialized: boolean;
  raw: Object;
  manipulateOptions: ?Function;
  post: ?Function;
  pre: ?Function;
  visitor: Object;

  take(key) {
    const val = this.raw[key];
    delete this.raw[key];
    return val;
  }

  chain(target, key) {
    if (!target[key]) return this[key];
    if (!this[key]) return target[key];

    const fns: Array<?Function> = [target[key], this[key]];

    return function (...args) {
      let val;
      for (const fn of fns) {
        if (fn) {
          const ret = fn.apply(this, args);
          if (ret != null) val = ret;
        }
      }
      return val;
    };
  }

  maybeInherit(loc: string) {
    let inherits = this.take("inherits");
    if (!inherits) return;

    inherits = OptionManager.normalisePlugin(inherits, loc, "inherits");

    this.manipulateOptions = this.chain(inherits, "manipulateOptions");
    this.post = this.chain(inherits, "post");
    this.pre = this.chain(inherits, "pre");
    this.visitor = traverse.visitors.merge([inherits.visitor, this.visitor]);
  }

  /**
   * We lazy initialise parts of a plugin that rely on contextual information such as
   * position on disk and how it was specified.
   */

  init(loc: string, i: number) {
    if (this.initialized) return;
    this.initialized = true;

    this.maybeInherit(loc);

    for (const key in this.raw) {
      throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
    }
  }

  normaliseVisitor(visitor: Object): Object {
    for (const key of GLOBAL_VISITOR_PROPS) {
      if (visitor[key]) {
        throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " +
          "Please target individual nodes.");
      }
    }

    traverse.explode(visitor);
    return visitor;
  }
}
<commit_msg>Remove store subclassing from Plugin class.<commit_after>import OptionManager from "./file/options/option-manager";
import * as messages from "babel-messages";
import traverse from "babel-traverse";
import clone from "lodash/clone";

const GLOBAL_VISITOR_PROPS = ["enter", "exit"];

export default class Plugin {
  constructor(plugin: Object, key?: string) {
    this.initialized = false;
    this.raw = Object.assign({}, plugin);
    this.key = this.take("name") || key;

    this.manipulateOptions = this.take("manipulateOptions");
    this.post = this.take("post");
    this.pre = this.take("pre");
    this.visitor = this.normaliseVisitor(clone(this.take("visitor")) || {});
  }

  initialized: boolean;
  raw: Object;
  manipulateOptions: ?Function;
  post: ?Function;
  pre: ?Function;
  visitor: Object;

  take(key) {
    const val = this.raw[key];
    delete this.raw[key];
    return val;
  }

  chain(target, key) {
    if (!target[key]) return this[key];
    if (!this[key]) return target[key];

    const fns: Array<?Function> = [target[key], this[key]];

    return function (...args) {
      let val;
      for (const fn of fns) {
        if (fn) {
          const ret = fn.apply(this, args);
          if (ret != null) val = ret;
        }
      }
      return val;
    };
  }

  maybeInherit(loc: string) {
    let inherits = this.take("inherits");
    if (!inherits) return;

    inherits = OptionManager.normalisePlugin(inherits, loc, "inherits");

    this.manipulateOptions = this.chain(inherits, "manipulateOptions");
    this.post = this.chain(inherits, "post");
    this.pre = this.chain(inherits, "pre");
    this.visitor = traverse.visitors.merge([inherits.visitor, this.visitor]);
  }

  /**
   * We lazy initialise parts of a plugin that rely on contextual information such as
   * position on disk and how it was specified.
   */

  init(loc: string, i: number) {
    if (this.initialized) return;
    this.initialized = true;

    this.maybeInherit(loc);

    for (const key in this.raw) {
      throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
    }
  }

  normaliseVisitor(visitor: Object): Object {
    for (const key of GLOBAL_VISITOR_PROPS) {
      if (visitor[key]) {
        throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " +
          "Please target individual nodes.");
      }
    }

    traverse.explode(visitor);
    return visitor;
  }
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

const { Object, RSVP } = Ember;
const { resolve } = RSVP;

moduleForComponent('programyear-objective-list-item', 'Integration | Component | programyear objective list item', {
  integration: true
});

test('it renders', function(assert) {
  let objective = Object.create({
    title: 'fake title'
  });
  this.set('objective', objective);
  this.on('nothing', parseInt);

  this.render(hbs`{{programyear-objective-list-item
    objective=objective
    manageDescriptors=(action 'nothing')
    manageCompetency=(action 'nothing')
  }}`);

  assert.equal(this.$('td:eq(0)').text().trim(), 'fake title');
  assert.equal(this.$('td:eq(1) button').text().trim(), 'Add New');
  assert.equal(this.$('td:eq(2) button').text().trim(), 'Add New');
});

test('can change title', function(assert) {
  let objective = Object.create({
    title: 'fake title',
    save(){
      assert.equal(this.get('title'), '
new title
');
      return resolve();
    }
  });
  this.set('objective', objective);
  this.on('nothing', parseInt);

  this.render(hbs`{{programyear-objective-list-item
    objective=objective
    remove=(action 'nothing')
    manageDescriptors=(action 'nothing')
    manageCompetency=(action 'nothing')
  }}`);

  this.$('td:eq(0) .editable').click();
  this.$('td:eq(0) .froalaEditor').froalaEditor('html.set', 'new title');
  this.$('td:eq(0) .froalaEditor').froalaEditor('events.trigger', 'contentChanged');
  this.$('td:eq(0) .done').click();

});

test('can manage competency', function(assert) {
  let objective = Object.create({
    title: 'fake title'
  });
  this.set('objective', objective);
  this.on('nothing', parseInt);
  this.on('something', ()=>{
    assert.ok(true);
  });

  this.render(hbs`{{programyear-objective-list-item
    objective=objective
    remove=(action 'nothing')
    manageDescriptors=(action 'nothing')
    manageCompetency=(action 'something')
  }}`);

  this.$('td:eq(1) button').click();

});

test('can manage descriptors', function(assert) {
  let objective = Object.create({
    title: 'fake title'
  });
  this.set('objective', objective);
  this.on('nothing', parseInt);
  this.on('something', ()=>{
    assert.ok(true);
  });

  this.render(hbs`{{programyear-objective-list-item
    objective=objective
    remove=(action 'nothing')
    manageDescriptors=(action 'something')
    manageCompetency=(action 'nothing')
  }}`);

  this.$('td:eq(2) button').click();

});
<commit_msg>updated tests.<commit_after>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

const { Object, RSVP } = Ember;
const { resolve } = RSVP;

moduleForComponent('programyear-objective-list-item', 'Integration | Component | programyear objective list item', {
  integration: true
});

test('it renders', function(assert) {
  let objective = Object.create({
    title: 'fake title'
  });
  this.set('objective', objective);
  this.on('nothing', parseInt);

  this.render(hbs`{{programyear-objective-list-item
    objective=objective
    manageDescriptors=(action 'nothing')
    manageCompetency=(action 'nothing')
    editable=true
  }}`);

  assert.equal(this.$('td:eq(0)').text().trim(), 'fake title');
  assert.equal(this.$('td:eq(1) button').text().trim(), 'Add New');
  assert.equal(this.$('td:eq(2) button').text().trim(), 'Add New');
});

test('can change title', function(assert) {
  let objective = Object.create({
    title: 'fake title',
    save(){
      assert.equal(this.get('title'), '
new title
');
      return resolve();
    }
  });
  this.set('objective', objective);
  this.on('nothing', parseInt);

  this.render(hbs`{{programyear-objective-list-item
    objective=objective
    remove=(action 'nothing')
    manageDescriptors=(action 'nothing')
    manageCompetency=(action 'nothing')
    editable=true
  }}`);

  this.$('td:eq(0) .editable').click();
  this.$('td:eq(0) .froalaEditor').froalaEditor('html.set', 'new title');
  this.$('td:eq(0) .froalaEditor').froalaEditor('events.trigger', 'contentChanged');
  this.$('td:eq(0) .done').click();

});

test('can manage competency', function(assert) {
  let objective = Object.create({
    title: 'fake title'
  });
  this.set('objective', objective);
  this.on('nothing', parseInt);
  this.on('something', ()=>{
    assert.ok(true);
  });

  this.render(hbs`{{programyear-objective-list-item
    objective=objective
    remove=(action 'nothing')
    manageDescriptors=(action 'nothing')
    manageCompetency=(action 'something')
    editable=true
  }}`);

  this.$('td:eq(1) button').click();

});

test('can manage descriptors', function(assert) {
  let objective = Object.create({
    title: 'fake title'
  });
  this.set('objective', objective);
  this.on('nothing', parseInt);
  this.on('something', ()=>{
    assert.ok(true);
  });

  this.render(hbs`{{programyear-objective-list-item
    objective=objective
    remove=(action 'nothing')
    manageDescriptors=(action 'something')
    manageCompetency=(action 'nothing')
    editable=true
  }}`);

  this.$('td:eq(2) button').click();

});
<|endoftext|>


<commit_before>require({
	shim: {
		"controllers/workerController": {
			deps: [
				"app",
				"cubism",
				"services/jobsProcessedCounter",
				"services/jobsSuccessCounter",
				"services/jobsFailedCounter",
				"services/workersStartListener",
				"services/workersStopListener",
				"services/workersPauseListener",
				"services/workersResumeListener"
			]
		},
		"controllers/jobController": {
			deps: [
				"app",
				"services/jobsProcessedCounter",
				"services/jobsFailedCounter"
			]
		},
		"controllers/scheduledJobController": {
			deps: ["app", "calheatmap"]
		},
		"controllers/lastestJobGraphController": {
			deps: ["app"]
		},
		"controllers/lastestJobHeatmapController": {
			deps: ["app", "calheatmap"]
		},
		"controllers/pendingJobController": {
			deps: ["app"]
		},
		"controllers/loadOverviewController": {
			deps: ["app", "d3"]
		},
		"controllers/jobClassDistributionController": {
			deps: ["app"]
		},
		"controllers/logActivityController": {
			deps: ["app", "moment", "cookie", "jsrender"]
		},
		"controllers/queueController": {
			deps: [
				"app",
				"services/jobsProcessedCounter",
				"services/workersStartListener",
				"services/workersStopListener"
			]
		},
		"directives/graphHorizonChart": {
			deps: ["app"]
		},
		"directives/graphPie": {
			deps: ["app", "d3"]
		},
		"directives/iconJob": {
			deps: ["app"]
		},
		"directives/placeholder": {
			deps: ["app"]
		},
		"filters/uptime": {
			deps: ["app"]
		},
		"filters/urlencode": {
			deps: ["app"]
		},
		"filters/bspopover": {
			deps: ["app"]
		},
		"libs/angular-resource": {
			deps: ["libs/angular"]
		},
		"services/jobsProcessedCounter": {
			deps: ["app", "services/socket"]
		},
		"services/jobsSuccessCounter": {
			deps: ["app", "services/socket"]
		},
		"services/jobsFailedCounter": {
			deps: ["app", "services/socket"]
		},
		"services/workersStartListener": {
			deps: ["app", "services/socket"]
		},
		"services/workersStopListener": {
			deps: ["app", "services/socket"]
		},
		"services/workersPauseListener": {
			deps: ["app", "services/socket"]
		},
		"services/workersResumeListener": {
			deps: ["app", "services/socket"]
		},
		"app": {
			deps: ["libs/angular", "libs/angular-resource", "ui.bootstrap", "jquery", "bootstrapjs", "highlightjs"]
		},
		"bootstrap": {
			deps: ["app"]
		},
		"bootstrapjs": {
			deps: ["jquery"]
		},
		"calheatmap": {
			deps: ["d3"]
		},
		"cookie" : {
			deps: ["jquery"]
		},
		"cubism": {
			deps: ["d3"]
		},
		"ui.bootstrap": {
			deps: ["libs/angular"]
		}
	},
	paths: {
		jquery: "/js/libs/jquery-2.0.0.min",
		d3: "/js/libs/d3",
		calheatmap: "/js/libs/cal-heatmap",
		highlightjs: "/js/libs/highlightjs-7.3.min",
		moment:  "/js/libs/moment-2.0.0.min",
		cookie: "/js/libs/jquery.cookie-1.1.min",
		cubism: "/js/libs/cubism.v1.2.2.min",
		jsrender: "/js/libs/jquery.jsrender-1.0.min",
		"ui.bootstrap": "/js/libs/ui-bootstrap-tpls-0.3.0.min"
	}
}, ["require",
	"controllers/workerController", "controllers/jobController", "controllers/lastestJobGraphController",
	"controllers/queueController", "controllers/lastestJobHeatmapController", "controllers/scheduledJobController",
	"controllers/pendingJobController", "controllers/loadOverviewController", "controllers/logActivityController",
	"controllers/jobClassDistributionController",
	"filters/uptime", "filters/urlencode", "filters/bspopover",
	"directives/graphHorizonChart", "directives/graphPie", "directives/iconJob", "directives/placeholder"
	], function(require) {
	return angular.element(document).ready(function() {
		return require(["bootstrap"]);
	});
});
<commit_msg>Load jsrender properly with requireJS<commit_after>require({
	shim: {
		"controllers/workerController": {
			deps: [
				"app",
				"cubism",
				"services/jobsProcessedCounter",
				"services/jobsSuccessCounter",
				"services/jobsFailedCounter",
				"services/workersStartListener",
				"services/workersStopListener",
				"services/workersPauseListener",
				"services/workersResumeListener"
			]
		},
		"controllers/jobController": {
			deps: [
				"app",
				"services/jobsProcessedCounter",
				"services/jobsFailedCounter"
			]
		},
		"controllers/scheduledJobController": {
			deps: ["app", "calheatmap"]
		},
		"controllers/lastestJobGraphController": {
			deps: ["app"]
		},
		"controllers/lastestJobHeatmapController": {
			deps: ["app", "calheatmap"]
		},
		"controllers/pendingJobController": {
			deps: ["app"]
		},
		"controllers/loadOverviewController": {
			deps: ["app", "d3"]
		},
		"controllers/jobClassDistributionController": {
			deps: ["app"]
		},
		"controllers/logActivityController": {
			deps: ["app", "moment", "cookie", "jsrender"]
		},
		"controllers/queueController": {
			deps: [
				"app",
				"services/jobsProcessedCounter",
				"services/workersStartListener",
				"services/workersStopListener"
			]
		},
		"directives/graphHorizonChart": {
			deps: ["app"]
		},
		"directives/graphPie": {
			deps: ["app", "d3"]
		},
		"directives/iconJob": {
			deps: ["app"]
		},
		"directives/placeholder": {
			deps: ["app"]
		},
		"filters/uptime": {
			deps: ["app"]
		},
		"filters/urlencode": {
			deps: ["app"]
		},
		"filters/bspopover": {
			deps: ["app"]
		},
		"libs/angular-resource": {
			deps: ["libs/angular"]
		},
		"services/jobsProcessedCounter": {
			deps: ["app", "services/socket"]
		},
		"services/jobsSuccessCounter": {
			deps: ["app", "services/socket"]
		},
		"services/jobsFailedCounter": {
			deps: ["app", "services/socket"]
		},
		"services/workersStartListener": {
			deps: ["app", "services/socket"]
		},
		"services/workersStopListener": {
			deps: ["app", "services/socket"]
		},
		"services/workersPauseListener": {
			deps: ["app", "services/socket"]
		},
		"services/workersResumeListener": {
			deps: ["app", "services/socket"]
		},
		"app": {
			deps: ["libs/angular", "libs/angular-resource", "ui.bootstrap", "jquery", "bootstrapjs", "highlightjs"]
		},
		"bootstrap": {
			deps: ["app"]
		},
		"bootstrapjs": {
			deps: ["jquery"]
		},
		"calheatmap": {
			deps: ["d3"]
		},
		"cookie" : {
			deps: ["jquery"]
		},
		"cubism": {
			deps: ["d3"]
		},
		"ui.bootstrap": {
			deps: ["libs/angular"]
		},
		jsrender: {
			deps: ["jquery"]
		}
	},
	paths: {
		jquery: "/js/libs/jquery-2.0.0.min",
		d3: "/js/libs/d3",
		calheatmap: "/js/libs/cal-heatmap",
		highlightjs: "/js/libs/highlightjs-7.3.min",
		moment:  "/js/libs/moment-2.0.0.min",
		cookie: "/js/libs/jquery.cookie-1.1.min",
		cubism: "/js/libs/cubism.v1.2.2.min",
		jsrender: "/js/libs/jquery.jsrender-1.0.min",
		"ui.bootstrap": "/js/libs/ui-bootstrap-tpls-0.3.0.min"
	}
}, ["require",
	"controllers/workerController", "controllers/jobController", "controllers/lastestJobGraphController",
	"controllers/queueController", "controllers/lastestJobHeatmapController", "controllers/scheduledJobController",
	"controllers/pendingJobController", "controllers/loadOverviewController", "controllers/logActivityController",
	"controllers/jobClassDistributionController",
	"filters/uptime", "filters/urlencode", "filters/bspopover",
	"directives/graphHorizonChart", "directives/graphPie", "directives/iconJob", "directives/placeholder"
	], function(require) {
	return angular.element(document).ready(function() {
		return require(["bootstrap"]);
	});
});
<|endoftext|>


<commit_before>var Parse = require('parse').Parse,
		comm = require('commander'),

		auth = require('./auth'),
		models = require('./models');

require('colors');

comm.parse(process.argv);

auth.session(function(user) {
	console.log(user.get('username').cyan);

	var query = new Parse.Query(models.Tag);
	query.find().then(function(tags) {
		for (var i = 0; i < tags.length; i++) {
			console.log(tags[i].get('name').green);
		};
	}, function(error) {
		console.error(error);
	})

});<commit_msg>Add bookmark lookup by tag<commit_after>var Parse = require('parse').Parse,
		comm = require('commander'),
		inquirer = require('inquirer'),
		exec = require('child_process').exec,
		spawn = require('child_process').spawn,

		auth = require('./auth'),
		models = require('./models'),
		spinner = require('./spinner');

require('colors');

comm.parse(process.argv);

function validNum(length, input) {
	return input > 0 && input <= length;
}

auth.session(function(user) {

	// List tags with user omits <tag>
	if (!comm.args.length) {
		spinner.start('Fetching tags'.grey);
		var query = new Parse.Query(models.Tag);
		query.find().then(function(tags) {
			spinner.stop();
			for (var i = 0; i < tags.length; i++) {
				console.log(tags[i].get('name').green);
			};
		}, function(error) {
			spinner.stop();
			console.error(error.message.red);
		});
	}

	// List Bookmarks with <tag>
	else {
		spinner.start('Fetching bookmarks'.grey);
		var query = new Parse.Query(models.Bookmark);
		query.containsAll('tags', comm.args);
		query.ascending('title');
		query.find().then(function(bookmarks) {
			spinner.stop();
			console.log(
				'\n' +
				bookmarks.length + ' bookmarks matching ' +
				comm.args.join(', ').yellow + ':'.white +
				'\n'
			);
			for (var i = 0; i < bookmarks.length; i++) {
				var b = bookmarks[i];
				console.log(
					((i+1)+'  ').white +
					b.get('title').blue.bold + '  ' +
					b.get('url').green + '\n   ' +
					('#' + b.get('tags').join(', #')).grey +
					'\n'
				);
			};
			var inqNum = {
				name:'num',
				message:'Open bookmark number:',
				validate: validNum.bind(null, bookmarks.length)
			};
			inquirer.prompt([inqNum], function(input) {
				var url = bookmarks[input.num-1].get('url');
				spawn('open', [url]);
			});
		}, function(error) {
			spinner.stop();
			console.error(error.message.red);
		});
	}

});<|endoftext|>


<commit_before>$(document).ready(function () {

    function convertIntegerToDateFormat(value) {
        var formatValue;
        var length = value.toString().length;
        var minutes = value.toString().substr(length - 2, length);
        if (value >= 1300) {
            formatValue = (Math.round(value / 100) - 12) + ':' + minutes + ' PM';
        } else {
            formatValue = Math.round(value / 100) + ':' + minutes + ' AM';
        }

        return formatValue;
    }

    function generateTimeSeries(_this) {
        var stepValue = 60 / _this.slotInMinutes;

        _this.fromValues = [];
        _this.toValues = [];
        _this.totalValues = [];

        for (var hourIndex = 0; hourIndex < 2400; hourIndex = hourIndex + 100) {
            var minuteIndex = 0;

            for (var minuteIndex = 0; minuteIndex < stepValue; minuteIndex++) {
                var value = hourIndex + _this.slotInMinutes * minuteIndex;
                _this.fromValues.push(value);
                _this.toValues.push(value);
                _this.totalValues.push(value);
            }
        }

        _this.toValues.shift();
        _this.toValues.push(2400);

        return _this;
    }

    function convertFormatToInteger(formatValue) {
        var lowerCaseFormatValue = formatValue.toLowerCase();
        var array = lowerCaseFormatValue.split(':');
        var hour = parseInt(array[0]);
        var minutes = parseInt(array[1]);
        var value;

        if (lowerCaseFormatValue.indexOf('am') == -1) {
            value = ((hour + 12) * 100) + minutes;
        } else {
            value = (hour * 100) + minutes;
        }

        return value;
    }

    function convertFormatToIntegerArray(selectedValues) {
        return selectedValues.map(function (value) {
            return $.map(value, function (range) {
                return convertFormatToInteger(range);
            })
        })
    }

    $.fn.createAvailability = function createAvailability() {
        this.each(function (index, ele) {
            var _this = ele;
            _this.fromEle = $(_this).find('.from-time');
            _this.toEle = $(_this).find('.to-time');
            _this.timeSelectedArea = $(_this).find('.time-selected-area');
            _this.selectedValues = convertFormatToIntegerArray($(_this).data('values'));
            _this.slotInMinutes = $(_this).data('minutes') || 30;
            _this = generateTimeSeries(_this);

            function createDefaultAvailabilities() {
                _this.selectedValues.forEach(function (slot) {
                    createTemplate(slot[0], slot[1]);
                })
            }

            function postValuesFromTime() {
                _this.fromEle.html('');

                _this.fromValues.forEach(function (fromValue) {
                    if (!isSelectedFromValue(fromValue)) {
                        _this.fromEle.append("<option value=" + fromValue + ">" + convertIntegerToDateFormat(fromValue) + "</option>");
                    }
                })
            }

            function isSelectedFromValue(value) {
                var isSelected = false;

                _this.selectedValues.forEach(function (selectedSlot) {
                    if (selectedSlot[0] <= value && value < selectedSlot[1]) {
                        isSelected = true;
                    }
                });

                return isSelected;
            }

            function fromTimeEventChange() {
                var selectedFromTime = _this.fromEle.val();
                _this.toEle.removeAttr('disabled');
                postValuesToTime(selectedFromTime);
            }

            function postValuesToTime(fromValue) {
                var toSelectedValuesLocal = [];
                var flag = true;
                var index = 0;

                _this.toEle.html('');

                _this.toValues.forEach(function (toValue) {
                    if (!isSelectedToValue(toValue) && toValue > fromValue) {
                        toSelectedValuesLocal.push(toValue);
                    }
                });

                toSelectedValuesLocal.forEach(function (toValue) {
                    if (index == 0 || isConsecutiveSeries(toValue, toSelectedValuesLocal) && flag) {
                        _this.toEle.append("<option value=" + toValue + ">" + convertIntegerToDateFormat(toValue) + "</option>");
                        index = 1;
                    } else {
                        flag = false;
                    }
                })
            }

            function isConsecutiveSeries(value, series) {
                var prevExpectedVal = 0;
                var isEnable = false;

                for (var index = 0; index < _this.totalValues.length; index++) {
                    if (value == _this.totalValues[index]) {
                        prevExpectedVal = _this.totalValues[index - 1];
                    }
                    if (value == 2400) {
                        prevExpectedVal = _this.totalValues[_this.totalValues.length - 1];
                    }
                }

                for (var index = 0; index < series.length; index++) {
                    if (series[index] == value) {
                        isEnable = (series[index - 1] == prevExpectedVal);
                    }
                }

                return isEnable;
            }

            function isSelectedToValue(value) {
                var isSelected = false;
                var index = 0;

                _this.selectedValues.forEach(function (selectedSlot) {
                    if (selectedSlot[0] < value && value <= selectedSlot[1]) {
                        isSelected = true;
                    }
                });
                return isSelected;
            }

            function createTemplate(fromTime, toTime) {
                var selectedRange = [fromTime, toTime];

                var template = "
" +
                    "from <input class='input-from-time' data-raw-value=" + fromTime + " value='" + convertIntegerToDateFormat(fromTime) + "' disabled='disabled' />" +
                    "to <input class='input-to-time' data-raw-value=" + toTime + " value='" + convertIntegerToDateFormat(toTime) + "' disabled='disabled' />" +
                    "<button class='remove-availability'>" +
                    "X" +
                    "</button>" +
                    "
";

                _this.timeSelectedArea.prepend(template);

                var removeTimeEleBtn = _this.timeSelectedArea.find('.remove-availability');
                removeTimeEleBtn.unbind('click');
                removeTimeEleBtn.bind('click', removeTimeAvailability);
                resetDropDowns();
            }

            function createTimeAvailability() {
                var fromTime = $(_this.fromEle).val();
                var toTime = $(_this.toEle).val();

                _this.selectedValues.push([fromTime, toTime]);
                createTemplate(fromTime, toTime);
            }

            function resetDropDowns() {
                _this.toEle.html('');
                postValuesFromTime();

                if ($(_this).data('to-disabled')) {
                    _this.toEle.attr('disabled', 'disabled');
                } else {
                    fromTimeEventChange();
                }
            }

            function removeTimeAvailability(event) {
                var newSelectedList = [];
                var selectedEle = $(event.currentTarget).parent('.time-slot');
                var fromTime = selectedEle.find('.input-from-time').data('raw-value');
                var toTime = selectedEle.find('.input-to-time').data('raw-value');
                var selectedRange = [fromTime, toTime];

                _this.selectedValues.forEach(function (selectedSlot) {
                    if (fromTime != selectedSlot[0] && toTime != selectedSlot[1]) {
                        newSelectedList.push(selectedSlot);
                    }
                });

                _this.selectedValues = newSelectedList;
                selectedEle.remove();
                resetDropDowns();
            }

            $(_this).find('.add-availability').click(createTimeAvailability);
            $(_this).find('.remove-availability').click(removeTimeAvailability);

            function defaultsLoad() {
                createDefaultAvailabilities();
                postValuesFromTime();
                $(_this.fromEle).change(fromTimeEventChange);
                resetDropDowns();
            }

            defaultsLoad();
        })
    };

    $('.time-select').createAvailability();
});
<commit_msg>Cleaning up date conversions<commit_after>$(document).ready(function () {

    function convertIntegerToDateFormat(value) {
        var formatValue;
        var length = value.toString().length;
        var minutes = value.toString().substr(length - 2, length);
        if (value >= 1200 && value < 1300) {
            formatValue = Math.round(value / 100) + ':' + minutes + ' PM';
        }
        else if (value == 2400) {
            formatValue = '00:00 AM';
        } else if (value >= 1300) {
            formatValue = (Math.round(value / 100) - 12) + ':' + minutes + ' PM';
        }
        else {
            formatValue = Math.round(value / 100) + ':' + minutes + ' AM';
        }

        return formatValue;
    }

    function generateTimeSeries(_this) {
        var stepValue = 60 / _this.slotInMinutes;

        _this.fromValues = [];
        _this.toValues = [];
        _this.totalValues = [];

        for (var hourIndex = 0; hourIndex < 2400; hourIndex = hourIndex + 100) {
            var minuteIndex = 0;

            for (var minuteIndex = 0; minuteIndex < stepValue; minuteIndex++) {
                var value = hourIndex + _this.slotInMinutes * minuteIndex;
                _this.fromValues.push(value);
                _this.toValues.push(value);
                _this.totalValues.push(value);
            }
        }

        _this.toValues.shift();
        _this.toValues.push(2400);

        return _this;
    }

    function convertFormatToInteger(formatValue) {
        var lowerCaseFormatValue = formatValue.toLowerCase();
        var array = lowerCaseFormatValue.split(':');
        var hour = parseInt(array[0]);
        var minutes = parseInt(array[1]);
        var value;

        if ((hour == 12 && lowerCaseFormatValue.indexOf('am') == -1)) {
            value = (hour * 100) + minutes;
        }
        else if (hour == 00 && minutes == 00 && lowerCaseFormatValue.indexOf('am') != -1) {
            value = 2400;
        } else if (lowerCaseFormatValue.indexOf('am') == -1) {
            value = ((hour + 12) * 100) + minutes;
        }
        else {
            value = (hour * 100) + minutes;
        }

        return value;
    }

    function convertFormatToIntegerArray(selectedValues) {
        return selectedValues.map(function (value) {
            return $.map(value, function (range) {
                return convertFormatToInteger(range);
            })
        })
    }

    $.fn.createAvailability = function createAvailability() {
        this.each(function (index, ele) {
            var _this = ele;
            _this.fromEle = $(_this).find('.from-time');
            _this.toEle = $(_this).find('.to-time');
            _this.timeSelectedArea = $(_this).find('.time-selected-area');
            _this.selectedValues = convertFormatToIntegerArray($(_this).data('values'));
            _this.slotInMinutes = $(_this).data('minutes') || 30;
            _this = generateTimeSeries(_this);

            function createDefaultAvailabilities() {
                _this.selectedValues.forEach(function (slot) {
                    createTemplate(slot[0], slot[1]);
                })
            }

            function postValuesFromTime() {
                _this.fromEle.html('');

                _this.fromValues.forEach(function (fromValue) {
                    if (!isSelectedFromValue(fromValue)) {
                        _this.fromEle.append("<option value=" + fromValue + ">" + convertIntegerToDateFormat(fromValue) + "</option>");
                    }
                })
            }

            function isSelectedFromValue(value) {
                var isSelected = false;

                _this.selectedValues.forEach(function (selectedSlot) {
                    if (selectedSlot[0] <= value && value < selectedSlot[1]) {
                        isSelected = true;
                    }
                });

                return isSelected;
            }

            function fromTimeEventChange() {
                var selectedFromTime = _this.fromEle.val();
                _this.toEle.removeAttr('disabled');
                postValuesToTime(selectedFromTime);
            }

            function postValuesToTime(fromValue) {
                var toSelectedValuesLocal = [];
                var flag = true;
                var index = 0;

                _this.toEle.html('');

                _this.toValues.forEach(function (toValue) {
                    if (!isSelectedToValue(toValue) && toValue > fromValue) {
                        toSelectedValuesLocal.push(toValue);
                    }
                });

                toSelectedValuesLocal.forEach(function (toValue) {
                    if (index == 0 || isConsecutiveSeries(toValue, toSelectedValuesLocal) && flag) {
                        _this.toEle.append("<option value=" + toValue + ">" + convertIntegerToDateFormat(toValue) + "</option>");
                        index = 1;
                    } else {
                        flag = false;
                    }
                })
            }

            function isConsecutiveSeries(value, series) {
                var prevExpectedVal = 0;
                var isEnable = false;

                for (var index = 0; index < _this.totalValues.length; index++) {
                    if (value == _this.totalValues[index]) {
                        prevExpectedVal = _this.totalValues[index - 1];
                    }
                    if (value == 2400) {
                        prevExpectedVal = _this.totalValues[_this.totalValues.length - 1];
                    }
                }

                for (var index = 0; index < series.length; index++) {
                    if (series[index] == value) {
                        isEnable = (series[index - 1] == prevExpectedVal);
                    }
                }

                return isEnable;
            }

            function isSelectedToValue(value) {
                var isSelected = false;
                var index = 0;

                _this.selectedValues.forEach(function (selectedSlot) {
                    if (selectedSlot[0] < value && value <= selectedSlot[1]) {
                        isSelected = true;
                    }
                });
                return isSelected;
            }

            function createTemplate(fromTime, toTime) {
                var selectedRange = [fromTime, toTime];

                var template = "
" +
                    "from <input class='input-from-time' data-raw-value=" + fromTime + " value='" + convertIntegerToDateFormat(fromTime) + "' disabled='disabled' />" +
                    "to <input class='input-to-time' data-raw-value=" + toTime + " value='" + convertIntegerToDateFormat(toTime) + "' disabled='disabled' />" +
                    "<button class='remove-availability'>" +
                    "X" +
                    "</button>" +
                    "
";

                _this.timeSelectedArea.prepend(template);

                var removeTimeEleBtn = _this.timeSelectedArea.find('.remove-availability');
                removeTimeEleBtn.unbind('click');
                removeTimeEleBtn.bind('click', removeTimeAvailability);
                resetDropDowns();
            }

            function createTimeAvailability() {
                var fromTime = $(_this.fromEle).val();
                var toTime = $(_this.toEle).val();

                _this.selectedValues.push([fromTime, toTime]);
                createTemplate(fromTime, toTime);
            }

            function resetDropDowns() {
                _this.toEle.html('');
                postValuesFromTime();

                if ($(_this).data('to-disabled')) {
                    _this.toEle.attr('disabled', 'disabled');
                } else {
                    fromTimeEventChange();
                }
            }

            function removeTimeAvailability(event) {
                var newSelectedList = [];
                var selectedEle = $(event.currentTarget).parent('.time-slot');
                var fromTime = selectedEle.find('.input-from-time').data('raw-value');
                var toTime = selectedEle.find('.input-to-time').data('raw-value');
                var selectedRange = [fromTime, toTime];

                _this.selectedValues.forEach(function (selectedSlot) {
                    if (fromTime != selectedSlot[0] && toTime != selectedSlot[1]) {
                        newSelectedList.push(selectedSlot);
                    }
                });

                _this.selectedValues = newSelectedList;
                selectedEle.remove();
                resetDropDowns();
            }

            $(_this).find('.add-availability').click(createTimeAvailability);
            $(_this).find('.remove-availability').click(removeTimeAvailability);

            function defaultsLoad() {
                createDefaultAvailabilities();
                postValuesFromTime();
                $(_this.fromEle).change(fromTimeEventChange);
                resetDropDowns();
            }

            defaultsLoad();
        })
    };

    $('.time-select').createAvailability();
});
<|endoftext|>


<commit_before>/**
 * @fileoverview Script to create a new RingoJS web application.
 */

require('core/string');
var {join, Path, makeDirectory, move, copy, base} = require('fs');
var engine = require('ringo/engine');
var shell = require('ringo/shell');
var Parser = require('ringo/args').Parser;

export('createApplication', 'createPackage', 'main', 'description');

var description = "Create a new RingoJS web application or package";

/**
 * Create a new RingoJS web application at the given path.
 * @param path the path where to create the application
 */
function createApplication(path, options) {
    if (!path) {
        throw new Error("No destination path given");
    }

    var dest = new Path(path);

    if (dest.exists() && !dest.isDirectory()) {
        throw dest + " exists but is not a directory.";
    } else if (dest.isDirectory() && dest.list().length > 0) {
        throw new Error("Directory " + dest + " exists but is not empty");
    }

    var home = engine.properties["ringo.home"];

    if (options.appengine) {
        copyTree(home, "apps/appengine", dest);
        copyTree(home, "modules", join(dest, "WEB-INF", "modules"));
        copyTree(home, "apps/skeleton", join(dest, "WEB-INF", "app"));
        fixAppEngineDirs(dest);
        copyJars(home, dest);
    } else {
        copyTree(home, "apps/skeleton", dest);
    }
}

/**
 * Create a new RingoJS package at the given path.
 * @param path the path where to create the package
 */
function createPackage(path, options) {
    if (!path) {
        throw new Error("No destination path given");
    }

    var home = engine.properties["ringo.home"];
    var dest = new Path(home, "packages", path);

    if (dest.exists() && !dest.isDirectory()) {
        throw dest + " exists but is not a directory.";
    } else if (dest.isDirectory() && dest.list().length > 0) {
        throw new Error("Directory " + dest + " exists but is not empty");
    }

    copyTree(home, "packages/namespace-skeleton", dest);
}

function copyTree(home, from, to) {
    var source = new Path(home, from);
    if (!source.exists() || !source.isDirectory()) {
        throw new Error("Can't find directory " + source);
    }

    shell.write("Copying files from " + from + " to "  + to + "... ");
    source.copyTree(to);
    print("done");
}

function fixAppEngineDirs(dest) {
    makeDirectory(join(dest, "static"));
    var webinf = join(dest, "WEB-INF");
    makeDirectory(join(webinf, "lib"));
    makeDirectory(join(webinf, "classes"));
    makeDirectory(join(webinf, "packages"));
    move(join(webinf, "app", "static"), join(dest, "static"));
}

function copyJars(home, dest) {
    var jars = [
        "ringo.jar",
        "js.jar",
        "log4j-1.2.15.jar",
        "slf4j/slf4j-api-1.5.10.jar",
        "slf4j/slf4j-log4j12-1.5.10.jar"
    ];
    var libsrc = join(home, "lib");
    var libdest = join(dest, "WEB-INF", "lib");
    for each (var jar in jars) {
        copy(join(libsrc, jar), join(libdest, base(jar)));
    }
}

/**
 * Create a new RingoJS web application from the command line.
 * @param args
 */
function main(args) {
    var script = args.shift();
    var parser = new Parser();
    parser.addOption("a", "appengine", null, "Create a new Google App Engine application");
    parser.addOption("p", "package", null, "Create a new package");
    parser.addOption("h", "help", null, "Print help message and exit");
    var opts = parser.parse(args);
    if (opts.help) {
        print("Creates a new RingoJS application or package");
        print("Usage:");
        print("  ringo " + script + " [path]");
        print("Options:");
        print(parser.help());
        return;
    }

    var path = args[0]
            || shell.readln("Please enter the path for your application/package: ");

    if (!path) {
        print("No path, exiting.");
    } else if (opts.package) {
        createPackage(path, opts);
    } else {
        createApplication(path, opts);
    }
}

if (require.main == module.id) {
    try {
        main(system.args);
    } catch (error) {
        print(error);
        print("Use -h or --help to get a list of available options.");
    }
}
<commit_msg>Fix `ringo-admin create -a` bug on win32<commit_after>/**
 * @fileoverview Script to create a new RingoJS web application.
 */

require('core/string');
var {join, Path, makeDirectory, move, copy, base} = require('fs');
var engine = require('ringo/engine');
var shell = require('ringo/shell');
var Parser = require('ringo/args').Parser;

export('createApplication', 'createPackage', 'main', 'description');

var description = "Create a new RingoJS web application or package";

/**
 * Create a new RingoJS web application at the given path.
 * @param path the path where to create the application
 */
function createApplication(path, options) {
    if (!path) {
        throw new Error("No destination path given");
    }

    var dest = new Path(path);

    if (dest.exists() && !dest.isDirectory()) {
        throw dest + " exists but is not a directory.";
    } else if (dest.isDirectory() && dest.list().length > 0) {
        throw new Error("Directory " + dest + " exists but is not empty");
    }

    var home = engine.properties["ringo.home"];

    if (options.appengine) {
        copyTree(home, "apps/appengine", dest);
        copyTree(home, "modules", join(dest, "WEB-INF", "modules"));
        copyTree(home, "apps/skeleton", join(dest, "WEB-INF", "app"));
        fixAppEngineDirs(dest);
        copyJars(home, dest);
    } else {
        copyTree(home, "apps/skeleton", dest);
    }
}

/**
 * Create a new RingoJS package at the given path.
 * @param path the path where to create the package
 */
function createPackage(path, options) {
    if (!path) {
        throw new Error("No destination path given");
    }

    var home = engine.properties["ringo.home"];
    var dest = new Path(home, "packages", path);

    if (dest.exists() && !dest.isDirectory()) {
        throw dest + " exists but is not a directory.";
    } else if (dest.isDirectory() && dest.list().length > 0) {
        throw new Error("Directory " + dest + " exists but is not empty");
    }

    copyTree(home, "packages/namespace-skeleton", dest);
}

function copyTree(home, from, to) {
    var source = new Path(home, from);
    if (!source.exists() || !source.isDirectory()) {
        throw new Error("Can't find directory " + source);
    }

    shell.write("Copying files from " + from + " to "  + to + "... ");
    source.copyTree(to);
    print("done");
}

function fixAppEngineDirs(dest) {
    var webinf = join(dest, "WEB-INF");
    makeDirectory(join(webinf, "lib"));
    makeDirectory(join(webinf, "classes"));
    makeDirectory(join(webinf, "packages"));
    move(join(webinf, "app", "static"), join(dest, "static"));
}

function copyJars(home, dest) {
    var jars = [
        "ringo.jar",
        "js.jar",
        "log4j-1.2.15.jar",
        "slf4j/slf4j-api-1.5.10.jar",
        "slf4j/slf4j-log4j12-1.5.10.jar"
    ];
    var libsrc = join(home, "lib");
    var libdest = join(dest, "WEB-INF", "lib");
    for each (var jar in jars) {
        copy(join(libsrc, jar), join(libdest, base(jar)));
    }
}

/**
 * Create a new RingoJS web application from the command line.
 * @param args
 */
function main(args) {
    var script = args.shift();
    var parser = new Parser();
    parser.addOption("a", "appengine", null, "Create a new Google App Engine application");
    parser.addOption("p", "package", null, "Create a new package");
    parser.addOption("h", "help", null, "Print help message and exit");
    var opts = parser.parse(args);
    if (opts.help) {
        print("Creates a new RingoJS application or package");
        print("Usage:");
        print("  ringo " + script + " [path]");
        print("Options:");
        print(parser.help());
        return;
    }

    var path = args[0]
            || shell.readln("Please enter the path for your application/package: ");

    if (!path) {
        print("No path, exiting.");
    } else if (opts.package) {
        createPackage(path, opts);
    } else {
        createApplication(path, opts);
    }
}

if (require.main == module.id) {
    try {
        main(system.args);
    } catch (error) {
        print(error);
        print("Use -h or --help to get a list of available options.");
    }
}
<|endoftext|>


<commit_before>module.exports = function(objects, bbox, Q) {
  var x0 = isFinite(bbox[0]) ? bbox[0] : 0,
      y0 = isFinite(bbox[1]) ? bbox[1] : 0,
      x1 = isFinite(bbox[2]) ? bbox[2] : 0,
      y1 = isFinite(bbox[3]) ? bbox[3] : 0,
      kx = x1 - x0 ? (Q - 1) / (x1 - x0) : 1,
      ky = y1 - y0 ? (Q - 1) / (y1 - y0) : 1,
      line = false,
      count = 0,
      px,
      py;

  function quantizeGeometry(geometry) {
    if (geometry && quantizeGeometryType.hasOwnProperty(geometry.type)) quantizeGeometryType[geometry.type](geometry);
  }

  var quantizeGeometryType = {
    GeometryCollection: function(o) { o.geometries.forEach(quantizeGeometry); },
    Point: function(o) { quantizePoint(o.coordinates); },
    MultiPoint: function(o) { o.coordinates.forEach(quantizePoint); },
    LineString: function(o) {
      var line = o.coordinates;
      quantizeLine(line);
      if (line.length < 2) line[1] = line[0]; // must have 2+
    },
    MultiLineString: function(o) {
      for (var lines = o.coordinates, i = 0, n = lines.length; i < n; ++i) {
        var line = lines[i];
        quantizeLine(line);
        if (line.length < 2) line[1] = line[0]; // must have 2+
      }
    },
    Polygon: function(o) {
      for (var rings = o.coordinates, i = 0, n = rings.length; i < n; ++i) {
        var ring = rings[i];
        quantizeLine(ring);
        while (ring.length < 4) ring.push(ring[0]); // must have 4+
      }
    },
    MultiPolygon: function(o) {
      for (var polygons = o.coordinates, i = 0, n = polygons.length; i < n; ++i) {
        for (var rings = polygons[i], j = 0, m = rings.length; j < m; ++j) {
          var ring = rings[j];
          quantizeLine(ring);
          while (ring.length < 4) ring.push(ring[0]); // must have 4+
        }
      }
    }
  };

  function quantizePoint(coordinates) {
    coordinates[0] = Math.round((coordinates[0] - x0) * kx);
    coordinates[1] = Math.round((coordinates[1] - y0) * ky);
  }

  function quantizeLine(coordinates) {
    var i = 0,
        j = 1,
        n = coordinates.length,
        pi = coordinates[0],
        pj,
        px = pi[0] = Math.round((pi[0] - x0) * kx),
        py = pi[1] = Math.round((pi[1] - y0) * ky),
        x,
        y;

    while (++i < n) {
      pi = coordinates[i];
      x = Math.round((pi[0] - x0) * kx);
      y = Math.round((pi[1] - y0) * ky);
      if (x !== px || y !== py) { // skip coincident points
        pj = coordinates[j++];
        pj[0] = px = x;
        pj[1] = py = y;
      }
    }

    coordinates.length = j;
  }

  for (var key in objects) {
    quantizeGeometry(objects[key]);
  }

  return {
    scale: [1 / kx, 1 / ky],
    translate: [x0, y0]
  };
};
<commit_msg>Remove unused variables.<commit_after>module.exports = function(objects, bbox, Q) {
  var x0 = isFinite(bbox[0]) ? bbox[0] : 0,
      y0 = isFinite(bbox[1]) ? bbox[1] : 0,
      x1 = isFinite(bbox[2]) ? bbox[2] : 0,
      y1 = isFinite(bbox[3]) ? bbox[3] : 0,
      kx = x1 - x0 ? (Q - 1) / (x1 - x0) : 1,
      ky = y1 - y0 ? (Q - 1) / (y1 - y0) : 1;

  function quantizeGeometry(geometry) {
    if (geometry && quantizeGeometryType.hasOwnProperty(geometry.type)) quantizeGeometryType[geometry.type](geometry);
  }

  var quantizeGeometryType = {
    GeometryCollection: function(o) { o.geometries.forEach(quantizeGeometry); },
    Point: function(o) { quantizePoint(o.coordinates); },
    MultiPoint: function(o) { o.coordinates.forEach(quantizePoint); },
    LineString: function(o) {
      var line = o.coordinates;
      quantizeLine(line);
      if (line.length < 2) line[1] = line[0]; // must have 2+
    },
    MultiLineString: function(o) {
      for (var lines = o.coordinates, i = 0, n = lines.length; i < n; ++i) {
        var line = lines[i];
        quantizeLine(line);
        if (line.length < 2) line[1] = line[0]; // must have 2+
      }
    },
    Polygon: function(o) {
      for (var rings = o.coordinates, i = 0, n = rings.length; i < n; ++i) {
        var ring = rings[i];
        quantizeLine(ring);
        while (ring.length < 4) ring.push(ring[0]); // must have 4+
      }
    },
    MultiPolygon: function(o) {
      for (var polygons = o.coordinates, i = 0, n = polygons.length; i < n; ++i) {
        for (var rings = polygons[i], j = 0, m = rings.length; j < m; ++j) {
          var ring = rings[j];
          quantizeLine(ring);
          while (ring.length < 4) ring.push(ring[0]); // must have 4+
        }
      }
    }
  };

  function quantizePoint(coordinates) {
    coordinates[0] = Math.round((coordinates[0] - x0) * kx);
    coordinates[1] = Math.round((coordinates[1] - y0) * ky);
  }

  function quantizeLine(coordinates) {
    var i = 0,
        j = 1,
        n = coordinates.length,
        pi = coordinates[0],
        pj,
        px = pi[0] = Math.round((pi[0] - x0) * kx),
        py = pi[1] = Math.round((pi[1] - y0) * ky),
        x,
        y;

    while (++i < n) {
      pi = coordinates[i];
      x = Math.round((pi[0] - x0) * kx);
      y = Math.round((pi[1] - y0) * ky);
      if (x !== px || y !== py) { // skip coincident points
        pj = coordinates[j++];
        pj[0] = px = x;
        pj[1] = py = y;
      }
    }

    coordinates.length = j;
  }

  for (var key in objects) {
    quantizeGeometry(objects[key]);
  }

  return {
    scale: [1 / kx, 1 / ky],
    translate: [x0, y0]
  };
};
<|endoftext|>


<commit_before>var minHeap = require("./min-heap"),
    area = require("./area");

module.exports = function(topology, minArea) {
  var heap = minHeap(),
      maxArea = 0,
      triangle,
      N = 0,
      M = 0;

  topology.arcs.forEach(function(arc) {
    var triangles = [];

    arc.forEach(transformAbsolute(topology.transform));

    for (var i = 1, n = arc.length - 1; i < n; ++i) {
      triangle = arc.slice(i - 1, i + 2);
      triangle.push(triangle[0]);
      triangle[1].area = Math.abs(area(triangle));
      triangles.push(triangle);
      heap.push(triangle);
    }

    // Always keep the arc endpoints!
    arc[0].area = arc[n].area = Infinity;

    N += n + 1;

    for (var i = 0, n = triangles.length; i < n; ++i) {
      triangle = triangles[i];
      triangle.previous = triangles[i - 1];
      triangle.next = triangles[i + 1];
    }
  });

  while (triangle = heap.pop()) {
    var previous = triangle.previous,
        next = triangle.next;

    // If the area of the current point is less than that of the previous point
    // to be eliminated, use the latter's area instead. This ensures that the
    // current point cannot be eliminated without eliminating previously-
    // eliminated points.
    if (triangle[1].area < maxArea) triangle[1].area = maxArea;
    else maxArea = triangle[1].area;

    if (previous) {
      previous.next = next;
      previous[2] = triangle[2];
      update(previous);
    }

    if (next) {
      next.previous = previous;
      next[0] = triangle[0];
      update(next);
    }
  }

  topology.arcs = topology.arcs.map(function(arc) {
    return arc.filter(function(point, i) {
      return point.area >= minArea;
    });
  });

  topology.arcs.forEach(function(arc) {
    arc.forEach(transformRelative(topology.transform));
    M += arc.length;
  });

  function update(triangle) {
    heap.remove(triangle);
    triangle[1].area = Math.abs(area(triangle));
    heap.push(triangle);
  }

  console.warn("retained " + M + " / " + N + " points (" + Math.round((M / N) * 100) + "%)")

  return topology;
};

function transformAbsolute(transform) {
  var x0 = 0,
      y0 = 0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(point, i) {
    point[0] = (x0 += point[0]) * kx + dx;
    point[1] = (y0 += point[1]) * ky + dy;
  };
}

function transformRelative(transform) {
  var x0 = 0,
      y0 = 0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(point, i) {
    var x1 = (point[0] - dx) / kx | 0,
        y1 = (point[1] - dy) / ky | 0;
    point[0] = x1 - x0;
    point[1] = y1 - y0;
    x0 = x1;
    y0 = y1;
  };
}
<commit_msg>Fix (again) for spherical triangle area.<commit_after>var minHeap = require("./min-heap");

var π = Math.PI,
    radians = π / 180;

module.exports = function(topology, minArea) {
  var heap = minHeap(),
      maxArea = 0,
      triangle,
      N = 0,
      M = 0;

  topology.arcs.forEach(function(arc) {
    var triangles = [];

    arc.forEach(transformAbsolute(topology.transform));

    for (var i = 1, n = arc.length - 1; i < n; ++i) {
      triangle = arc.slice(i - 1, i + 2);
      triangle.push(triangle[0]);
      triangle[1].area = area(triangle);
      triangles.push(triangle);
      heap.push(triangle);
    }

    // Always keep the arc endpoints!
    arc[0].area = arc[n].area = Infinity;

    N += n + 1;

    for (var i = 0, n = triangles.length; i < n; ++i) {
      triangle = triangles[i];
      triangle.previous = triangles[i - 1];
      triangle.next = triangles[i + 1];
    }
  });

  while (triangle = heap.pop()) {
    var previous = triangle.previous,
        next = triangle.next;

    // If the area of the current point is less than that of the previous point
    // to be eliminated, use the latter's area instead. This ensures that the
    // current point cannot be eliminated without eliminating previously-
    // eliminated points.
    if (triangle[1].area < maxArea) triangle[1].area = maxArea;
    else maxArea = triangle[1].area;

    if (previous) {
      previous.next = next;
      previous[2] = triangle[2];
      update(previous);
    }

    if (next) {
      next.previous = previous;
      next[0] = triangle[0];
      update(next);
    }
  }

  topology.arcs = topology.arcs.map(function(arc) {
    return arc.filter(function(point, i) {
      return point.area >= minArea;
    });
  });

  topology.arcs.forEach(function(arc) {
    arc.forEach(transformRelative(topology.transform));
    M += arc.length;
  });

  function update(triangle) {
    heap.remove(triangle);
    triangle[1].area = area(triangle);
    heap.push(triangle);
  }

  console.warn("retained " + M + " / " + N + " points (" + Math.round((M / N) * 100) + "%)")

  return topology;
};

function transformAbsolute(transform) {
  var x0 = 0,
      y0 = 0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(point, i) {
    point[0] = (x0 += point[0]) * kx + dx;
    point[1] = (y0 += point[1]) * ky + dy;
  };
}

function transformRelative(transform) {
  var x0 = 0,
      y0 = 0,
      kx = transform.scale[0],
      ky = transform.scale[1],
      dx = transform.translate[0],
      dy = transform.translate[1];
  return function(point, i) {
    var x1 = (point[0] - dx) / kx | 0,
        y1 = (point[1] - dy) / ky | 0;
    point[0] = x1 - x0;
    point[1] = y1 - y0;
    x0 = x1;
    y0 = y1;
  };
}

function area(t) {
  var a = distance(t[0], t[1]),
      b = distance(t[1], t[2]),
      c = distance(t[2], t[0]);
  return 4 * Math.atan(Math.sqrt(Math.tan((a + b + c) / 2) * Math.tan((b + c) / 2) * Math.tan((a + c) / 2) * Math.tan((a + b) / 2)));
}

function distance(p0, p1) {
  var x0 = p0[0] * radians,
      y0 = p0[1] * radians,
      x1 = p1[0] * radians,
      y1 = p1[1] * radians;
  return Math.acos(Math.max(-1, Math.min(1, Math.sin(y0) * Math.sin(y1) + Math.cos(y0) * Math.cos(y1) * Math.cos(x1 - x0))));
}
<|endoftext|>


<commit_before>var current_cost_duration = 'hourly';
var current_region = 'us-east-1';
var current_reserved_term = 'yrTerm1.noUpfront';
var data_table = null;

var require = Array();
require['memory'] = 0;
require['computeunits'] = 0;
require['storage'] = 0;

function init_data_table() {
  data_table = $('#data').DataTable({
    "bPaginate": false,
    "bInfo": false,
    "bStateSave": true,
    "oSearch": {
      "bRegex" : true,
      "bSmart": false
    },
    "aoColumnDefs": [
      {
        "aTargets": ["memory", "computeunits", "cores", "coreunits", "storage", "ebs-throughput", "ebs-iops", "networkperf", "max_bandwidth"],
        "sType": "span-sort"
      },
      {
        "aTargets": ["ecu-per-core", "enhanced-networking", "maxips", "linux-virtualization", "cost-ondemand-mswinSQLWeb", "cost-ondemand-mswinSQL", "cost-reserved-mswinSQLWeb", "cost-reserved-mswinSQL", "ebs-throughput", "ebs-iops", "max_bandwidth"],
        "bVisible": false
      }
    ],
    // default sort by linux cost
    "aaSorting": [
      [ 14, "asc" ]
    ],
    'initComplete': function() {
      // fire event in separate context so that calls to get_data_table()
      // receive the cached object.
      setTimeout(function() {
        on_data_table_initialized();
      }, 0);
    },
    'drawCallback': function() {
      // abort if initialization hasn't finished yet (initial draw)
      if (data_table === null) {
        return;
      }

      // Whenever the table is drawn, update the costs. This is necessary
      // because the cost duration may have changed while a filter was being
      // used and so some rows will need updating.
      redraw_costs();
    }
  });

  return data_table;
}

$(document).ready(function() {
  init_data_table();
});

function change_cost(duration) {
  // update menu text
  var first = duration.charAt(0).toUpperCase();
  var text = first + duration.substr(1);
  $("#cost-dropdown .dropdown-toggle .text").text("Cost: "+text);

  // update selected menu option
  $('#cost-dropdown li a').each(function(i, e) {
    e = $(e);
    if (e.attr('duration') == duration) {
      e.parent().addClass('active');
    } else {
      e.parent().removeClass('active');
    }
  });

  var hour_multipliers = {
    "hourly": 1,
    "daily": 24,
    "weekly": (7*24),
    "monthly": (30*24),
    "annually": (365*24)
  };
  var multiplier = hour_multipliers[duration];
  var per_time;
  $.each($("td.cost-ondemand"), function(i, elem) {
    elem = $(elem);
    per_time = elem.data("pricing")[current_region];
    if (per_time && !isNaN(per_time)) {
      per_time = (per_time * multiplier).toFixed(3);
      elem.text("$" + per_time + " " + duration);
    } else {
      elem.text("unavailable");
    }
  });

  $.each($("td.cost-reserved"), function(i, elem) {
    elem = $(elem);
    per_time = elem.data("pricing")[current_region];

    if(!per_time) {
      elem.text("unavailable");
      return;
    }

    per_time = per_time[current_reserved_term];

    if (per_time && !isNaN(per_time)) {
      per_time = (per_time * multiplier).toFixed(3);
      elem.text("$" + per_time + " " + duration);
    } else {
      elem.text("unavailable");
    }
  });

  current_cost_duration = duration;
  maybe_update_url();
}

function change_region(region) {
  current_region = region;
  var region_name = null;
  $('#region-dropdown li a').each(function(i, e) {
    e = $(e);
    if (e.data('region') === region) {
      e.parent().addClass('active');
      region_name = e.text();
    } else {
      e.parent().removeClass('active');
    }
  });
  $("#region-dropdown .dropdown-toggle .text").text(region_name);
  change_cost(current_cost_duration);
}

function change_reserved_term(term) {
  current_reserved_term = term;
  var $dropdown = $('#reserved-term-dropdown'),
      $activeLink = $dropdown.find('li a[data-reserved-term="'+term+'"]'),
      term_name = $activeLink.text();

  $dropdown.find('li').removeClass('active');
  $activeLink.closest('li').addClass('active');

  $dropdown.find('.dropdown-toggle .text').text(term_name);
  change_cost(current_cost_duration);
}

// Update all visible costs to the current duration.
// Called after new columns or rows are shown as their costs may be inaccurate.
function redraw_costs() {
  change_cost(current_cost_duration);
}

function setup_column_toggle() {
  $.each(data_table.columns().indexes(), function(i, idx) {
    var column = data_table.column(idx);
    $("#filter-dropdown ul").append(
      $('<li>')
      .toggleClass('active', column.visible())
      .append(
        $('<a>', {href: "javascript:;"})
        .text($(column.header()).text())
        .click(function(e) {
          toggle_column(i);
          $(this).parent().toggleClass("active");
          $(this).blur(); // prevent focus style from sticking in Firefox
          e.stopPropagation(); // keep dropdown menu open
        })
      )
    );
  });
}

function url_for_selections() {
  var settings = {
    min_memory: require['memory'],
    min_computeunits: require['computeunits'],
    min_storage: require['storage'],
    filter: data_table.settings()[0].oPreviousSearch['sSearch'],
    region: current_region,
    cost: current_cost_duration
  };
  if (settings.min_memory == '') delete settings.min_memory;
  if (settings.min_computeunits == '') delete settings.min_computeunits;
  if (settings.min_storage == '') delete settings.min_storage;

  if (settings.filter == '') delete settings.filter
  if (settings.region == 'us-east-1') delete settings.region;
  if (settings.cost == 'hourly') delete settings.cost;
  var url = location.origin + location.pathname;
  var parameters = [];
  for (var setting in settings) {
    if (settings[setting] !== undefined) {
      parameters.push(setting + '=' + settings[setting]);
    }
  }
  if (parameters.length > 0)
    url = url + '?' + parameters.join('&');
  return url;
}

function maybe_update_url() {

  if (!history.replaceState)
    return
  try {
    var url = url_for_selections();
    if (document.location == url)
      return;

    history.replaceState(null, '', url);
  } catch(ex) {
    // doesn't matter
  }
}

var apply_min_values = function() {
    var all_filters = $('[data-action="datafilter"]');
    var data_rows = $('#data tr:has(td)');

    data_rows.show();

    all_filters.each(function() {
        var filter_on = $(this).data('type');
        var filter_val = parseFloat($(this).val()) || 0;

        // update global variable for dynamic URL
        require[filter_on] = filter_val;

        var match_fail = data_rows.filter(function() {
            var row_val;
            row_val = parseFloat(
                $(this).find('td[class~="' + filter_on + '"] span').attr('sort')
                );
            return row_val < filter_val;
        });

        match_fail.hide();
    });
    maybe_update_url();
};

function on_data_table_initialized() {
  // process URL settings
  var url_settings = get_url_parameters();
  for (var key in url_settings) {
    switch(key) {
      case 'region':
        change_region(url_settings['region']);
        break;
      case 'cost':
        change_cost(url_settings['cost']);
        break;
      case 'filter':
        data_table.filter(url_settings['filter']);
        break;
      case 'min_memory':
        $('[data-action="datafilter"][data-type="memory"]').val(url_settings['min_memory']);
        apply_min_values();
        break;
      case 'min_computeunits':
        $('[data-action="datafilter"][data-type="computeunits"]').val(url_settings['min_computeunits']);
        apply_min_values();
        break;
      case 'min_storage':
        $('[data-action="datafilter"][data-type="storage"]').val(url_settings['min_storage']);
        apply_min_values();
        break;
    }
  }

  configureHighlighting();

  // Allow row filtering by min-value match.
  $('[data-action=datafilter]').on('keyup', apply_min_values);

  $('#url-button').click(function() {
    $('#share_url').val(url_for_selections()).select();
    return false;
  });

  change_region('us-east-1');
  change_cost('hourly');
  change_reserved_term('yrTerm1.noUpfront');

  $.extend($.fn.dataTableExt.oStdClasses, {
    "sWrapper": "dataTables_wrapper form-inline"
  });

  setup_column_toggle();

  // enable bootstrap tooltips
  $('abbr').tooltip({
    placement: function(tt, el) {
      return (this.$element.parents('thead').length) ? 'top' : 'right';
    }
  });

  $("#cost-dropdown li").bind("click", function(e) {
    change_cost(e.target.getAttribute("duration"));
  });

  $("#region-dropdown li").bind("click", function(e) {
    change_region($(e.target).data('region'));
  });

  $("#reserved-term-dropdown li").bind("click", function(e) {
    change_reserved_term($(e.target).data('reservedTerm'));
  });
}

// sorting for colums with more complex data
// http://datatables.net/plug-ins/sorting#hidden_title
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
  "span-sort-pre": function(elem) {
    var matches = elem.match(/sort="(.*?)"/);
    if (matches) {
      return parseInt(matches[1], 10);
    }
    return 0;
  },

  "span-sort-asc": function(a, b) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },

  "span-sort-desc": function(a, b) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
});

// toggle columns
function toggle_column(col_index) {
  var is_visible = data_table.column(col_index).visible();
  data_table.column(col_index).visible(is_visible ? false : true);
  redraw_costs();
}

// retrieve all the parameters from the location string
function get_url_parameters() {
  var params = location.search.slice(1).split('&');
  var settings = {};
  params.forEach(function(param) {
    settings[param.split('=')[0]] = param.split('=')[1];
  });

  return settings;
}

function configureHighlighting() {
  var compareOn = false,
      $compareBtn = $('.btn-compare'),
      $rows = $('#data tbody tr');

  // Allow row highlighting by clicking.
  $rows.click(function() {
    $(this).toggleClass('highlight');

    if(!compareOn) {
      $compareBtn.prop('disabled', !$rows.is('.highlight'));
    }
  });

  $compareBtn.prop('disabled', true);
  $compareBtn.text($compareBtn.data('textOff'));

  $compareBtn.click(function() {
    if(compareOn) {
      $rows.show();
      $compareBtn.text($compareBtn.data('textOff'))
                 .addClass('btn-primary')
                 .removeClass('btn-success')
                 .prop('disabled', !$rows.is('.highlight'));
    } else {
      $rows.filter(':not(.highlight)').hide();
      $compareBtn.text($compareBtn.data('textOn'))
                 .addClass('btn-success')
                 .removeClass('btn-primary');
    }

    compareOn = !compareOn;
  });
}
<commit_msg>Include highlighted row information in URL.<commit_after>var current_cost_duration = 'hourly';
var current_region = 'us-east-1';
var current_reserved_term = 'yrTerm1.noUpfront';
var data_table = null;

var require = Array();
require['memory'] = 0;
require['computeunits'] = 0;
require['storage'] = 0;

function init_data_table() {
  data_table = $('#data').DataTable({
    "bPaginate": false,
    "bInfo": false,
    "bStateSave": true,
    "oSearch": {
      "bRegex" : true,
      "bSmart": false
    },
    "aoColumnDefs": [
      {
        "aTargets": ["memory", "computeunits", "cores", "coreunits", "storage", "ebs-throughput", "ebs-iops", "networkperf", "max_bandwidth"],
        "sType": "span-sort"
      },
      {
        "aTargets": ["ecu-per-core", "enhanced-networking", "maxips", "linux-virtualization", "cost-ondemand-mswinSQLWeb", "cost-ondemand-mswinSQL", "cost-reserved-mswinSQLWeb", "cost-reserved-mswinSQL", "ebs-throughput", "ebs-iops", "max_bandwidth"],
        "bVisible": false
      }
    ],
    // default sort by linux cost
    "aaSorting": [
      [ 14, "asc" ]
    ],
    'initComplete': function() {
      // fire event in separate context so that calls to get_data_table()
      // receive the cached object.
      setTimeout(function() {
        on_data_table_initialized();
      }, 0);
    },
    'drawCallback': function() {
      // abort if initialization hasn't finished yet (initial draw)
      if (data_table === null) {
        return;
      }

      // Whenever the table is drawn, update the costs. This is necessary
      // because the cost duration may have changed while a filter was being
      // used and so some rows will need updating.
      redraw_costs();
    }
  });

  return data_table;
}

$(document).ready(function() {
  init_data_table();
});

function change_cost(duration) {
  // update menu text
  var first = duration.charAt(0).toUpperCase();
  var text = first + duration.substr(1);
  $("#cost-dropdown .dropdown-toggle .text").text("Cost: "+text);

  // update selected menu option
  $('#cost-dropdown li a').each(function(i, e) {
    e = $(e);
    if (e.attr('duration') == duration) {
      e.parent().addClass('active');
    } else {
      e.parent().removeClass('active');
    }
  });

  var hour_multipliers = {
    "hourly": 1,
    "daily": 24,
    "weekly": (7*24),
    "monthly": (30*24),
    "annually": (365*24)
  };
  var multiplier = hour_multipliers[duration];
  var per_time;
  $.each($("td.cost-ondemand"), function(i, elem) {
    elem = $(elem);
    per_time = elem.data("pricing")[current_region];
    if (per_time && !isNaN(per_time)) {
      per_time = (per_time * multiplier).toFixed(3);
      elem.text("$" + per_time + " " + duration);
    } else {
      elem.text("unavailable");
    }
  });

  $.each($("td.cost-reserved"), function(i, elem) {
    elem = $(elem);
    per_time = elem.data("pricing")[current_region];

    if(!per_time) {
      elem.text("unavailable");
      return;
    }

    per_time = per_time[current_reserved_term];

    if (per_time && !isNaN(per_time)) {
      per_time = (per_time * multiplier).toFixed(3);
      elem.text("$" + per_time + " " + duration);
    } else {
      elem.text("unavailable");
    }
  });

  current_cost_duration = duration;
  maybe_update_url();
}

function change_region(region) {
  current_region = region;
  var region_name = null;
  $('#region-dropdown li a').each(function(i, e) {
    e = $(e);
    if (e.data('region') === region) {
      e.parent().addClass('active');
      region_name = e.text();
    } else {
      e.parent().removeClass('active');
    }
  });
  $("#region-dropdown .dropdown-toggle .text").text(region_name);
  change_cost(current_cost_duration);
}

function change_reserved_term(term) {
  current_reserved_term = term;
  var $dropdown = $('#reserved-term-dropdown'),
      $activeLink = $dropdown.find('li a[data-reserved-term="'+term+'"]'),
      term_name = $activeLink.text();

  $dropdown.find('li').removeClass('active');
  $activeLink.closest('li').addClass('active');

  $dropdown.find('.dropdown-toggle .text').text(term_name);
  change_cost(current_cost_duration);
}

// Update all visible costs to the current duration.
// Called after new columns or rows are shown as their costs may be inaccurate.
function redraw_costs() {
  change_cost(current_cost_duration);
}

function setup_column_toggle() {
  $.each(data_table.columns().indexes(), function(i, idx) {
    var column = data_table.column(idx);
    $("#filter-dropdown ul").append(
      $('<li>')
      .toggleClass('active', column.visible())
      .append(
        $('<a>', {href: "javascript:;"})
        .text($(column.header()).text())
        .click(function(e) {
          toggle_column(i);
          $(this).parent().toggleClass("active");
          $(this).blur(); // prevent focus style from sticking in Firefox
          e.stopPropagation(); // keep dropdown menu open
        })
      )
    );
  });
}

function url_for_selections() {
  var settings = {
    min_memory: require['memory'],
    min_computeunits: require['computeunits'],
    min_storage: require['storage'],
    filter: data_table.settings()[0].oPreviousSearch['sSearch'],
    region: current_region,
    cost: current_cost_duration
  };
  if (settings.min_memory == '') delete settings.min_memory;
  if (settings.min_computeunits == '') delete settings.min_computeunits;
  if (settings.min_storage == '') delete settings.min_storage;

  if (settings.filter == '') delete settings.filter
  if (settings.region == 'us-east-1') delete settings.region;
  if (settings.cost == 'hourly') delete settings.cost;

  // selected rows
  var selected_row_ids = $('#data tbody tr.highlight').map(function() {
    return this.id;
  }).get();
  if (selected_row_ids.length > 0) {
    settings.selected = selected_row_ids;
  }

  var url = location.origin + location.pathname;
  var parameters = [];
  for (var setting in settings) {
    if (settings[setting] !== undefined) {
      parameters.push(setting + '=' + settings[setting]);
    }
  }
  if (parameters.length > 0)
    url = url + '?' + parameters.join('&');
  return url;
}

function maybe_update_url() {
  if (!history.replaceState) {
    return;
  }

  try {
    var url = url_for_selections();
    if (document.location == url) {
      return;
    }

    history.replaceState(null, '', url);
  } catch(ex) {
    // doesn't matter
  }
}

var apply_min_values = function() {
    var all_filters = $('[data-action="datafilter"]');
    var data_rows = $('#data tr:has(td)');

    data_rows.show();

    all_filters.each(function() {
        var filter_on = $(this).data('type');
        var filter_val = parseFloat($(this).val()) || 0;

        // update global variable for dynamic URL
        require[filter_on] = filter_val;

        var match_fail = data_rows.filter(function() {
            var row_val;
            row_val = parseFloat(
                $(this).find('td[class~="' + filter_on + '"] span').attr('sort')
                );
            return row_val < filter_val;
        });

        match_fail.hide();
    });
    maybe_update_url();
};

function on_data_table_initialized() {
  // process URL settings
  var url_settings = get_url_parameters();
  for (var key in url_settings) {
    switch(key) {
      case 'region':
        change_region(url_settings['region']);
        break;
      case 'cost':
        change_cost(url_settings['cost']);
        break;
      case 'filter':
        data_table.filter(url_settings['filter']);
        break;
      case 'min_memory':
        $('[data-action="datafilter"][data-type="memory"]').val(url_settings['min_memory']);
        apply_min_values();
        break;
      case 'min_computeunits':
        $('[data-action="datafilter"][data-type="computeunits"]').val(url_settings['min_computeunits']);
        apply_min_values();
        break;
      case 'min_storage':
        $('[data-action="datafilter"][data-type="storage"]').val(url_settings['min_storage']);
        apply_min_values();
        break;
      case 'selected':
        // apply highlight to selected rows
        $.each(url_settings['selected'].split(','), function(_, id) {
          id = id.replace('.', '\\.');
          $('#'+id).addClass('highlight');
        })
        break;
    }
  }

  configure_highlighting();

  // Allow row filtering by min-value match.
  $('[data-action=datafilter]').on('keyup', apply_min_values);

  $('#url-button').click(function() {
    $('#share_url').val(url_for_selections()).select();
    return false;
  });

  change_region('us-east-1');
  change_cost('hourly');
  change_reserved_term('yrTerm1.noUpfront');

  $.extend($.fn.dataTableExt.oStdClasses, {
    "sWrapper": "dataTables_wrapper form-inline"
  });

  setup_column_toggle();

  // enable bootstrap tooltips
  $('abbr').tooltip({
    placement: function(tt, el) {
      return (this.$element.parents('thead').length) ? 'top' : 'right';
    }
  });

  $("#cost-dropdown li").bind("click", function(e) {
    change_cost(e.target.getAttribute("duration"));
  });

  $("#region-dropdown li").bind("click", function(e) {
    change_region($(e.target).data('region'));
  });

  $("#reserved-term-dropdown li").bind("click", function(e) {
    change_reserved_term($(e.target).data('reservedTerm'));
  });
}

// sorting for colums with more complex data
// http://datatables.net/plug-ins/sorting#hidden_title
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
  "span-sort-pre": function(elem) {
    var matches = elem.match(/sort="(.*?)"/);
    if (matches) {
      return parseInt(matches[1], 10);
    }
    return 0;
  },

  "span-sort-asc": function(a, b) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },

  "span-sort-desc": function(a, b) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
});

// toggle columns
function toggle_column(col_index) {
  var is_visible = data_table.column(col_index).visible();
  data_table.column(col_index).visible(is_visible ? false : true);
  redraw_costs();
}

// retrieve all the parameters from the location string
function get_url_parameters() {
  var params = location.search.slice(1).split('&');
  var settings = {};
  params.forEach(function(param) {
    settings[param.split('=')[0]] = param.split('=')[1];
  });

  return settings;
}

function configure_highlighting() {
  var compareOn = false,
      $compareBtn = $('.btn-compare'),
      $rows = $('#data tbody tr');

  // Allow row highlighting by clicking.
  $rows.click(function() {
    $(this).toggleClass('highlight');

    if (!compareOn) {
      $compareBtn.prop('disabled', !$rows.is('.highlight'));
    }

    maybe_update_url();
  });

  $compareBtn.prop('disabled', !$($rows).is('.highlight'));
  $compareBtn.text($compareBtn.data('textOff'));

  $compareBtn.click(function() {
    if (compareOn) {
      $rows.show();
      $compareBtn.text($compareBtn.data('textOff'))
                 .addClass('btn-primary')
                 .removeClass('btn-success')
                 .prop('disabled', !$rows.is('.highlight'));
    } else {
      $rows.filter(':not(.highlight)').hide();
      $compareBtn.text($compareBtn.data('textOn'))
                 .addClass('btn-success')
                 .removeClass('btn-primary');
    }

    compareOn = !compareOn;
  });
}
<|endoftext|>


<commit_before>// User options for overriding core options.js

module.exports = {
    // Restart app after changing core options
    core: {
    },

    // Run `grunt` after changing assets options. Or use`grunt watch-all`.
    assets: {
        modulesEnabled : {
            // Overriding example
            // trimSpaces: true
        },

        modulesOptions : {
            // Modules options example
            // innerNavigation : {
            //   hashSymb: '!'
            //   }
        },

        // Plugins
        pluginsEnabled : {
            // user/plugins/counter/counter.js enabling example
            // 'counter/counter': true
        },

        pluginsOptions : {
            // Plugins options example
            // somePlugin : {
            //     someOption: true
            // }
        }
    }
};<commit_msg>Turning off auto-focus on navigation pages<commit_after>// User options for overriding core options.js

module.exports = {
    // Restart app after changing core options
    core: {
    },

    // Run `grunt` after changing assets options. Or use`grunt watch-all`.
    assets: {
        modulesEnabled : {
            // Overriding example
            // trimSpaces: true
        },

        modulesOptions : {
            search: {
                autoFocusOnNavigationPage: false
            }
        },

        // Plugins
        pluginsEnabled : {
            // user/plugins/counter/counter.js enabling example
            // 'counter/counter': true
        },

        pluginsOptions : {
            // Plugins options example
            // somePlugin : {
            //     someOption: true
            // }
        }
    }
};<|endoftext|>


<commit_before>var current_cost_duration = null;

function change_cost(duration) {
  // update menu text
  var first = duration.charAt(0).toUpperCase();
  var text = first + duration.substr(1);
  $("#cost-dropdown .dropdown-toggle .text").text("Cost: "+text);

  // update selected menu option
  $('#cost-dropdown li a').each(function(i, e) {
    e = $(e);
    if (e.attr('duration') == duration) {
      e.parent().addClass('active');
    } else {
      e.parent().removeClass('active');
    }
  });

  var hour_multipliers = {
    "hourly": 1,
    "daily": 24,
    "weekly": (7*24),
    "monthly": (24*30),
    "yearly": (365*24)
  };
  var multiplier = hour_multipliers[duration];
  var per_time;
  $.each($("td.cost"), function(i, elem) {
    elem = $(elem);
    per_time = elem.attr("hour_cost");
    per_time = (per_time * multiplier).toFixed(2);
    elem.text("$" + per_time + " " + duration);
  });

  current_cost_duration = duration;
}

function setup_column_toggle() {
  // get column headings, add to filter button
  $.each($("#data thead tr th"), function(i, elem) {
    $("#filter-dropdown ul").append(
      $('<li>', {class: "active"}).append(
        $('<a>', {href: "javascript:;"})
          .text($(elem).text())
          .click(function(e) {
            toggle_column(i);
            $(this).parent().toggleClass("active");
            $(this).blur(); // prevent focus style from sticking in Firefox
            e.stopPropagation(); // keep dropdown menu open
          })
      )
    );
  });
}

$(function() {
  $(document).ready(function() {
    $('#data').dataTable({
      "bPaginate": false,
      "bInfo": false,
      "bStateSave": true,
      "aoColumnDefs": [
        {
          "aTargets": ["memory", "computeunits", "storage", "ioperf"],
          "sType": "span-sort"
        }
      ],
      // default sort by linux cost
      "aaSorting": [
        [ 8, "asc" ]
      ],
      "fnDrawCallback": function() {
        // Whenever the table is drawn, update the costs. This is necessary
        // because the cost duration may have changed while a filter was being
        // used and so some rows will need updating.
        change_cost(current_cost_duration);
      }
    });
  });

  $.extend($.fn.dataTableExt.oStdClasses, {
    "sWrapper": "dataTables_wrapper form-inline"
  });

  change_cost('hourly');

  setup_column_toggle();

  // enable bootstrap tooltips
  $('abbr').tooltip({
    placement: function(tt, el) {
      return (this.$element.parents('thead').length) ? 'top' : 'right';
    }
  });
});

$("#cost-dropdown li").bind("click", function(e) {
  change_cost(e.target.getAttribute("duration"));
});

// sorting for colums with more complex data
// http://datatables.net/plug-ins/sorting#hidden_title
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
  "span-sort-pre": function(elem) {
    var matches = elem.match(/sort="(.*?)"/);
    if (matches) {
      return parseInt(matches[1], 10);
    }
    return 0;
  },

  "span-sort-asc": function(a, b) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },

  "span-sort-desc": function(a, b) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
});

// toggle columns
function toggle_column(col_index) {
  var table = $('#data').dataTable();
  var is_visible = table.fnSettings().aoColumns[col_index].bVisible;
  table.fnSetColumnVis(col_index, is_visible ? false : true);
}<commit_msg>Turn on regex for the search field<commit_after>var current_cost_duration = null;

function change_cost(duration) {
  // update menu text
  var first = duration.charAt(0).toUpperCase();
  var text = first + duration.substr(1);
  $("#cost-dropdown .dropdown-toggle .text").text("Cost: "+text);

  // update selected menu option
  $('#cost-dropdown li a').each(function(i, e) {
    e = $(e);
    if (e.attr('duration') == duration) {
      e.parent().addClass('active');
    } else {
      e.parent().removeClass('active');
    }
  });

  var hour_multipliers = {
    "hourly": 1,
    "daily": 24,
    "weekly": (7*24),
    "monthly": (24*30),
    "yearly": (365*24)
  };
  var multiplier = hour_multipliers[duration];
  var per_time;
  $.each($("td.cost"), function(i, elem) {
    elem = $(elem);
    per_time = elem.attr("hour_cost");
    per_time = (per_time * multiplier).toFixed(2);
    elem.text("$" + per_time + " " + duration);
  });

  current_cost_duration = duration;
}

function setup_column_toggle() {
  // get column headings, add to filter button
  $.each($("#data thead tr th"), function(i, elem) {
    $("#filter-dropdown ul").append(
      $('<li>', {class: "active"}).append(
        $('<a>', {href: "javascript:;"})
          .text($(elem).text())
          .click(function(e) {
            toggle_column(i);
            $(this).parent().toggleClass("active");
            $(this).blur(); // prevent focus style from sticking in Firefox
            e.stopPropagation(); // keep dropdown menu open
          })
      )
    );
  });
}

$(function() {
  $(document).ready(function() {
    $('#data').dataTable({
      "bPaginate": false,
      "bInfo": false,
      "bStateSave": true,
      "oSearch": {
        "bRegex" : true,
        "bSmart": false
      },
      "aoColumnDefs": [
        {
          "aTargets": ["memory", "computeunits", "storage", "ioperf"],
          "sType": "span-sort"
        }
      ],
      // default sort by linux cost
      "aaSorting": [
        [ 8, "asc" ]
      ],
      "fnDrawCallback": function() {
        // Whenever the table is drawn, update the costs. This is necessary
        // because the cost duration may have changed while a filter was being
        // used and so some rows will need updating.
        change_cost(current_cost_duration);
      }
    });
  });

  $.extend($.fn.dataTableExt.oStdClasses, {
    "sWrapper": "dataTables_wrapper form-inline"
  });

  change_cost('hourly');

  setup_column_toggle();

  // enable bootstrap tooltips
  $('abbr').tooltip({
    placement: function(tt, el) {
      return (this.$element.parents('thead').length) ? 'top' : 'right';
    }
  });
});

$("#cost-dropdown li").bind("click", function(e) {
  change_cost(e.target.getAttribute("duration"));
});

// sorting for colums with more complex data
// http://datatables.net/plug-ins/sorting#hidden_title
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
  "span-sort-pre": function(elem) {
    var matches = elem.match(/sort="(.*?)"/);
    if (matches) {
      return parseInt(matches[1], 10);
    }
    return 0;
  },

  "span-sort-asc": function(a, b) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },

  "span-sort-desc": function(a, b) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
});

// toggle columns
function toggle_column(col_index) {
  var table = $('#data').dataTable();
  var is_visible = table.fnSettings().aoColumns[col_index].bVisible;
  table.fnSetColumnVis(col_index, is_visible ? false : true);
}<|endoftext|>


<commit_before>/**
 * Image Element constructor
 *
 * @class Roguelike.UI.Element.Image
 * @classdesc An UI image element
 * Inherits from Roguelike.UI.Element
 */
Roguelike.UI.Element.Image = function(position, image) {

	/**
	 * Inherit the constructor from the Element class
	 */
	Roguelike.UI.Element.call(this, position);

	/**
	 * @property {String} image - The source of the image that is being used
	 */
	this.image = image;

};

Roguelike.UI.Element.Image.prototype = Object.create(Roguelike.UI.Element.prototype, {

	/**
	 * Returns a function that handles rendering the current Element
	 * @protected
	 */
	render: {

		value: function(context, parentPosition) {

			//Create a new starting position using the provided position and the position of this element
			var newPosition = parentPosition.combine(this.position);

			//TODO: Use a preloader and only get the file once, not every frame
			//Get the image
			var image = document.getElementById(this.image);

			//Draw the image on the canvas context
			context.drawImage(
				image,
				newPosition.x,
				newPosition.y,
				304,
				64
			);

		}

	}

});
<commit_msg>It's now possible to define a scale to an UI image. The scale is optional and defaults to 1.<commit_after>/**
 * Image Element constructor
 *
 * @class Roguelike.UI.Element.Image
 * @classdesc An UI image element
 * Inherits from Roguelike.UI.Element
 *
 * @param {Roguelike.Vector2} position - The position of the previous container that called this render function
 * @param {String} image - The source of the image that is being used
 * @param {Number} scale - (optional) The scale of the image, defaults to 1
 */
Roguelike.UI.Element.Image = function(position, image, scale) {

	/**
	 * Inherit the constructor from the Element class
	 */
	Roguelike.UI.Element.call(this, position, scale);

	/**
	 * @property {String} image - The source of the image that is being used
	 */
	this.image = image;

	/**
	 * @property {Number} scale - The scale of the image, defaults to 1
	 */
	this.scale = scale || 1;

};

Roguelike.UI.Element.Image.prototype = Object.create(Roguelike.UI.Element.prototype, {

	render: {

		/**
		 * Returns a function that handles rendering the current Element
		 * @protected
		 *
		 * @param {Object} context - Reference to the current canvas context
		 * @param {Roguelike.Vector2} parentPosition - The position of the previous container that called this render function
		 */
		value: function(context, parentPosition) {

			//Create a new starting position using the provided position and the position of this element
			var newPosition = parentPosition.combine(this.position);

			//TODO: Use a preloader and only get the file once, not every frame
			//Get the image
			var image = document.getElementById(this.image);

			//Draw the image on the canvas context
			context.drawImage(
				image,
				newPosition.x,
				newPosition.y,
				image.width * this.scale,
				image.height * this.scale
			);

		}

	}

});
<|endoftext|>


<commit_before>function saveButton() {
  saveScheme(document.getElementById("css").value);

    var status = document.getElementById("status");
    status.innerHTML = "Options Saved.";
    setTimeout(function() {
	  	status.innerHTML = "";
    }, 750);
}

function setSchemeEditor(scheme) {
	var css = document.getElementById("css");
	css.value = scheme;
}

document.querySelector('#save').addEventListener('click', saveButton);

var css = document.getElementById("css");
setSchemeEditor(currentScheme());<commit_msg>Convert tabs to spaces<commit_after>function saveButton() {
  saveScheme(document.getElementById("css").value);

    var status = document.getElementById("status");
    status.innerHTML = "Options Saved.";
    setTimeout(function() {
      status.innerHTML = "";
    }, 750);
}

function setSchemeEditor(scheme) {
	var css = document.getElementById("css");
	css.value = scheme;
}

document.querySelector('#save').addEventListener('click', saveButton);

var css = document.getElementById("css");
setSchemeEditor(currentScheme());
<|endoftext|>


<commit_before>angular.module('vc.details', ['ngStorage'])

.controller('DetailsCtrl', function($scope, $rootScope, Services, geoLocation, $q, Stations){

  $rootScope.pageTitle = "Détails Station";

  var stations = Stations.getStations();
  console.log(stations);
  $scope.map = (function(elemId) {

    // Default center for the map
    var defaultCenter = {
      lng: 4.871454,
      lat: 45.784011,
      zoom: 13
    }

    // Max bounds for the map - restrained to Lyon
    var southWest = L.latLng(45.709621, 4.938827),
      northEast = L.latLng(45.803759, 4.777122),
      bounds = L.latLngBounds(southWest, northEast);

    // Red station icon
    var redIcon = L.divIcon({
      className: 'station-red-marker',
      html: '',
      iconSize: [35, 35],
      iconAnchor: [35, 35]
    });

    // Current location coordinates
    var meIcon = L.divIcon({
        className: 'me-marker',
        html: '

',
        iconSize: [35, 35],
        iconAnchor: [35, 35]
    });

    // Instantiate the Map object
    var map = L.map(elemId, {
      maxBounds: bounds
    });

    // Adds tiles
    L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
        maxZoom: 18
    }).addTo(map);

    // Get the current position
    var currentPosition = {
      lat: geoLocation.getGeolocation().lat,
      lng: geoLocation.getGeolocation().lng
    };

    var position = L.latLng(currentPosition.lat, currentPosition.lng);

    // Adds the current position marker
    var marker = L.marker([position.lat, position.lng], {
        icon: meIcon
    }).addTo(map);
    marker.on('click', function() {
        console.log(position);
        map.setView([position.lat, position.lng]);
    });

    // Get the station position
    var stationPos = L.latLng(defaultCenter.lat, defaultCenter.lng);

    // Adds the target station marker
    var marker = L.marker(stationPos, {
        icon: redIcon
    }).addTo(map);

    // Polyline latLng list
    var latlngs = [
      position,
      stationPos
    ];

    //Get distance between points
    var distance = parseInt(position.distanceTo(stationPos), 10);
    if(distance > 1000) {
      var round = distance / 1000;
      round = distance.toFixed(1);
      distance =  round + "Km";
    } else {
      distance = distance.toFixed(0) + "m";
    }

    // Distance popup
    var dPopup = L.popup({
      closeButton: false,
      closeOnClick: false,
      className: 'distance-popup'
    }).setContent(distance);

    // Instantiates the polyline
    var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map).bindPopup(dPopup);
    setTimeout(()=>{
      polyline.openPopup();
    },0);

    console.log(distance);

    map.setView(position, defaultCenter.zoom);
    map.fitBounds(polyline.getBounds().pad(0.1));
    map.setMaxBounds(polyline.getBounds().pad(0.1));

  })("details-map");

});<commit_msg>function in timeout<commit_after>angular.module('vc.details', ['ngStorage'])

.controller('DetailsCtrl', function($scope, $rootScope, Services, geoLocation, $q, Stations){

  $rootScope.pageTitle = "Détails Station";

  var stations = Stations.getStations();
  console.log(stations);
  $scope.map = (function(elemId) {

    // Default center for the map
    var defaultCenter = {
      lng: 4.871454,
      lat: 45.784011,
      zoom: 13
    }

    // Max bounds for the map - restrained to Lyon
    var southWest = L.latLng(45.709621, 4.938827),
      northEast = L.latLng(45.803759, 4.777122),
      bounds = L.latLngBounds(southWest, northEast);

    // Red station icon
    var redIcon = L.divIcon({
      className: 'station-red-marker',
      html: '',
      iconSize: [35, 35],
      iconAnchor: [35, 35]
    });

    // Current location coordinates
    var meIcon = L.divIcon({
        className: 'me-marker',
        html: '

',
        iconSize: [35, 35],
        iconAnchor: [35, 35]
    });

    // Instantiate the Map object
    var map = L.map(elemId, {
      maxBounds: bounds
    });

    // Adds tiles
    L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
        maxZoom: 18
    }).addTo(map);

    // Get the current position
    var currentPosition = {
      lat: geoLocation.getGeolocation().lat,
      lng: geoLocation.getGeolocation().lng
    };

    var position = L.latLng(currentPosition.lat, currentPosition.lng);

    // Adds the current position marker
    var marker = L.marker([position.lat, position.lng], {
        icon: meIcon
    }).addTo(map);
    marker.on('click', function() {
        console.log(position);
        map.setView([position.lat, position.lng]);
    });

    // Get the station position
    var stationPos = L.latLng(defaultCenter.lat, defaultCenter.lng);

    // Adds the target station marker
    var marker = L.marker(stationPos, {
        icon: redIcon
    }).addTo(map);

    // Polyline latLng list
    var latlngs = [
      position,
      stationPos
    ];

    //Get distance between points
    var distance = parseInt(position.distanceTo(stationPos), 10);
    if(distance > 1000) {
      var round = distance / 1000;
      round = distance.toFixed(1);
      distance =  round + "Km";
    } else {
      distance = distance.toFixed(0) + "m";
    }

    // Distance popup
    var dPopup = L.popup({
      closeButton: false,
      closeOnClick: false,
      className: 'distance-popup'
    }).setContent(distance);

    // Instantiates the polyline
    var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map).bindPopup(dPopup);
    setTimeout(function(){
      polyline.openPopup();
    },0);

    console.log(distance);

    map.setView(position, defaultCenter.zoom);
    map.fitBounds(polyline.getBounds().pad(0.1));
    map.setMaxBounds(polyline.getBounds().pad(0.1));

  })("details-map");

});<|endoftext|>