<commit_before>import test from 'tape';
import src from '../src';
import key from '../src/key';
import isObject from 'lodash/isObject';
import isFunction from 'lodash/isFunction';
import isPlainObject from 'lodash/isPlainObject';

test('global', assert => {
	assert.plan(3);

	const signal = src;
	assert.ok(isFunction(signal.on), `signal is a singleton`);
	assert.ok(isFunction(signal.emit), `signal is a singleton`);
	assert.ok(signal[key], `signal has a Map`);

	assert.end();
});

test('factory', assert => {
	assert.plan(4);

	const signal = src;
	assert.ok(isFunction(signal), `signal is a factory`);
	assert.doesNotThrow(() => signal(), `signal can be called`);
	assert.ok(isFunction(signal()), `signal factory creates a factory`);
	assert.ok(isFunction(signal().on), `created signal has methods`);

	assert.end();
});

test('instancing', assert => {
	assert.plan(9);

	const signal = src;
	const local1 = src();
	const local2 = local1();

	let globalTrigger = 0;
	let local1Trigger = 0;
	let local2Trigger = 0;

	signal.on('foo', () => { globalTrigger += 1; });
	local1.on('foo', () => { local1Trigger += 1; });
	local2.on('foo', () => { local2Trigger += 1; });

	signal.trigger('foo');
	assert.is(globalTrigger, 1, `global fired`);
	assert.is(local1Trigger, 0, `local1 did not fire`);
	assert.is(local2Trigger, 0, `local2 did not fire`);

	local1.trigger('foo');
	assert.is(globalTrigger, 1, `global did not fire`);
	assert.is(local1Trigger, 1, `local1 fired`);
	assert.is(local2Trigger, 0, `local2 did not fire`);

	local2.trigger('foo');
	assert.is(globalTrigger, 1, `global did not fire`);
	assert.is(local1Trigger, 1, `local1 did not fire`);
	assert.is(local2Trigger, 1, `local2 fired`);

	assert.end();
});

test('event: add', assert => {
	assert.plan(4);

	const signal = src();
	assert.doesNotThrow(() => signal.on('foo', () => {}), `valid registration does not throw`);
	assert.throws(() => signal.on(null, () => {}), `an invalid name throws`);
	assert.throws(() => signal.on('foo', null), `an invalid callback throws`);
	assert.ok(isObject(signal.on(1, () => {})), `can listen to an id/number`);

	assert.end();
});

test('event: add invalid', assert => {
	assert.plan(1);

	const signal = src();
	assert.throws(() => signal.on('foo', {}), `invalid function throws`);

	assert.end();
});

test('event: symbol', assert => {
	assert.plan(3);

	const signal = src();
	const symbol = Symbol('foo');
	let trigger = false;
	assert.doesNotThrow(() => signal.on(symbol, function() { trigger = true; }), `symbol .on does not throw`);
	assert.doesNotThrow(() => signal.emit(symbol), `symbol .emit does not throw`);
	assert.is(trigger, true, `symbol event fired`);

	assert.end();
});

test('event: emit', assert => {
	assert.plan(3);

	const signal = src();
	let trigger = false;
	signal.on('foo:bar.baz', function() { trigger = true; });
	signal.trigger('foo:bar.baz');

	assert.ok(trigger, `events can trigger`);

	trigger = false;
	signal.emit('foo:bar.baz');

	assert.ok(trigger, `emit is a proxy`);

	assert.throws(() => signal.trigger(), `an event name is required to trigger`);

	assert.end();
});

test('event: emit empty', assert => {
	assert.plan(1);

	const signal = src();
	assert.doesNotThrow(() => signal.trigger('nothing.here'), `can trigger without a listener`);

	assert.end();
});

test('event: remove', assert => {
	assert.plan(3);

	const signal = src();
	const evt = 'foo:bar.baz';
	let trigger = 0;
	const fn1 = () => { trigger += 1; };
	const fn2 = () => { trigger += 1; };
	signal.on(evt, fn1);
	signal.on(evt, fn2);

	assert.is(signal.size(evt), 2, `successful registered events`);
	signal.off(evt);
	assert.is(signal.size(evt), 0, `successful removed events`);

	signal.trigger(evt);
	assert.is(trigger, 0, `event unbound successfully`);

	assert.end();
});

test('event: remove specific', assert => {
	assert.plan(2);

	const signal = src();
	const fn1 = () => {};
	const fn2 = () => {};

	signal.on('foo', fn1);
	signal.on('foo', fn2);

	assert.ok(signal.listeners('foo').length, 2, `registered functions`);

	signal.off('foo', fn1);

	assert.ok(signal.listeners('foo').length, 1, `only removed one function`);

	assert.end();
});

test('event: remove invalid', assert => {
	assert.plan(1);

	const signal = src();
	assert.throws(() => signal.off(), `an event name is required for off`);

	assert.end();
});

test('event: once', assert => {
	assert.plan(6);

	const signal = src();
	let trigger = 0;
	signal.once('foo', () => { trigger += 1; });

	assert.is(signal.listeners('foo').length, 1, `registered the event using once`);
	signal.trigger('foo');
	assert.is(trigger, 1, `event has been called`);
	assert.is(signal.listeners('foo').length, 0, `event has been removed after being called`);
	signal.trigger('foo');
	assert.is(trigger, 1, `calling event again as not effect`);

	assert.throws(() => signal.once(undefined, () => {}), `once requires an event name`);
	assert.throws(() => signal.once('foo'), `once requires an function`);

	assert.end();
});

test('event: multiple', assert => {
	assert.plan(1);

	const signal = src();
	let trigger = 0;
	const fn = () => { trigger += 1; };
	signal.on('foo', fn);
	signal.on('foo.bar', fn);
	signal.on('bar', fn);
	signal.on('bar.foo', fn);

	signal.trigger('foo')
		.trigger('foo.bar')
		.trigger('bar')
		.trigger('bar.foo')
		.trigger('baz');
	assert.is(trigger, 4, `calling multiple events has the desired effect`);

	assert.end();
});

test('params', assert => {
	assert.plan(10);

	const signal = src();

	let boolTest;
	let objectTest;
	let arrayTest;
	let numberTest;
	let stringTest;
	let undefTest;
	let nullTest;
	let nanTest;
	let infinTest;
	let fnTest;

	signal.on('paramtest', function(
		param1,
		param2,
		param3,
		param4,
		param5,
		param6,
		param7,
		param8,
		param9,
		param10
	) {
		if (param1 === false) boolTest = true;
		if (isPlainObject(param2)) objectTest = true;
		if (Array.isArray(param3)) arrayTest = true;
		if (param4 === 0) numberTest = true;
		if (param5 === '') stringTest = true;
		if (param6 === undefined) undefTest = true;
		if (param7 === null) nullTest = true;
		if (Number.isNaN(param8)) nanTest = true;
		if (param9 === Infinity) infinTest = true;
		if (isFunction(param10)) fnTest = true;
	});

	signal.trigger('paramtest',
		false,
		{},
		[],
		0,
		'',
		undefined,
		null,
		NaN,
		Infinity,
		() => {}
	);

	assert.ok(boolTest, `Booleans can be passed`);
	assert.ok(objectTest, `Objects can be passed`);
	assert.ok(arrayTest, `Arrays can be passed`);
	assert.ok(numberTest, `Numbers can be passed`);
	assert.ok(stringTest, `Strings can be passed`);
	assert.ok(undefTest, `undefined can be passed`);
	assert.ok(nullTest, `null can be passed`);
	assert.ok(nanTest, `NaN can be passed`);
	assert.ok(infinTest, `Infinity can be passed`);
	assert.ok(fnTest, `Function can be passed`);

	assert.end();
});

test('listeners', assert => {
	assert.plan(5);

	const empty = src();
	assert.is(empty.listeners().length, 0, 'an empty instance has no functions');

	const signal = src();
	const fn1 = () => {};
	const fn2 = () => {};

	signal.on('foo', fn1);

	assert.ok(Array.isArray(signal.listeners('foo')), `an array of functions can be retrieved`);
	assert.ok(isFunction(signal.listeners('foo')[0]), `there are functions in the array`);

	signal.on('foo', fn2);
	assert.is(signal.listeners('foo').length, 2, `multiple registered functions are retrieved`);

	signal.on('bar', () => {});
	assert.is(signal.listeners().length, 3, `all registered functions are retrieved`);

	assert.end();
});

test('names', assert => {
	assert.plan(4);

	const signal = src();
	signal.on('foo', () => {});

	assert.ok(Array.isArray(signal.names()), `an array of names can be retrieved`);
	assert.is(signal.names()[0], 'foo', `there are event names in the array`);

	signal.on('foo', () => {});
	assert.is(signal.names().length, 1, `multiple registered functions under a single name allow for only one name entry`);

	signal.on('bar', () => {});
	assert.is(signal.names().length, 2, `multiple names can be retrieved`);

	assert.end();
});

test('size', assert => {
	assert.plan(4);

	const signal = src();
	signal.on('foo', () => {});

	assert.is(signal.size(), 1, `one event results in a size of 1`);

	signal.on('foo', () => {});
	assert.is(signal.size(), 2, `two events under the same event name results in a size of 2`);

	signal.on('bar', () => {});
	assert.is(signal.size(), 3, `multiple names keeps a consistent count`);

	assert.is(signal.size('foo'), 2, `a size of a single name can be queried`);

	assert.end();
});

test('disable/enable', assert => {
	assert.plan(10);

	const signal = src();
	let trigger = 0;
	const fn = () => { trigger += 1; };

	signal.on('foo', fn);
	signal.trigger('foo');

	assert.ok(isFunction(signal.disable), `disable is a function`);
	assert.ok(isFunction(signal.enable), `enable is a function`);
	assert.is(trigger, 1, `can trigger an event`);

	assert.doesNotThrow(() => signal.disable(), `disable doesn't throw`);
	assert.doesNotThrow(() => signal.disable(), `calling disable multiple times doesn't throw`);
	assert.doesNotEqual(() => signal.trigger('foo'), `calling a disabled signal doesn't throw`);
	assert.is(trigger, 1, `when disabled, the event is not called`);

	assert.doesNotThrow(() => signal.enable(), `enable doesn't throw`);
	assert.doesNotThrow(() => signal.enable(), `calling enable multiple times doesn't throw`);
	signal.trigger('foo');
	assert.is(trigger, 2, `when re-enabled, the event is called`);

	assert.end();
});

test('clear', assert => {
	assert.plan(7);

	const signal = src();
	let trigger = 0;
	const fn = () => { trigger += 1; };

	signal.on('foo', fn);
	signal.on('bar', fn);

	signal.trigger('foo');
	assert.is(trigger, 1, `foo triggered`);
	signal.trigger('bar');
	assert.is(trigger, 2, `bar triggered`);

	assert.ok(isFunction(signal.clear), `clear is a function`);
	assert.doesNotThrow(() => signal.clear(), `calling clear does not throw`);
	assert.doesNotThrow(() => signal.clear(), `calling clear multiple times does not throw`);

	signal.trigger('foo');
	assert.is(trigger, 2, `foo did not trigger`);
	signal.trigger('bar');
	assert.is(trigger, 2, `bar did not trigger`);

	assert.end();
});

test('chaining', assert => {
	assert.plan(1);

	assert.doesNotThrow(() => {
		return src()
			.on('foo', () => {})
			.emit('foo')
			.off('foo')
			.once('bar', () => {})
			.emit('bar')
			.disable()
			.enable()
			.clear();
	});

	assert.end();
});<commit_msg>check error messages<commit_after>import test from 'tape';
import src from '../src';
import key from '../src/key';
import isObject from 'lodash/isObject';
import isFunction from 'lodash/isFunction';
import isPlainObject from 'lodash/isPlainObject';

test('global', assert => {
	assert.plan(3);

	const signal = src;
	assert.ok(isFunction(signal.on), `signal is a singleton`);
	assert.ok(isFunction(signal.emit), `signal is a singleton`);
	assert.ok(signal[key], `signal has a Map`);

	assert.end();
});

test('factory', assert => {
	assert.plan(4);

	const signal = src;
	assert.ok(isFunction(signal), `signal is a factory`);
	assert.doesNotThrow(() => signal(), `signal can be called`);
	assert.ok(isFunction(signal()), `signal factory creates a factory`);
	assert.ok(isFunction(signal().on), `created signal has methods`);

	assert.end();
});

test('instancing', assert => {
	assert.plan(9);

	const signal = src;
	const local1 = src();
	const local2 = local1();

	let globalTrigger = 0;
	let local1Trigger = 0;
	let local2Trigger = 0;

	signal.on('foo', () => { globalTrigger += 1; });
	local1.on('foo', () => { local1Trigger += 1; });
	local2.on('foo', () => { local2Trigger += 1; });

	signal.trigger('foo');
	assert.is(globalTrigger, 1, `global fired`);
	assert.is(local1Trigger, 0, `local1 did not fire`);
	assert.is(local2Trigger, 0, `local2 did not fire`);

	local1.trigger('foo');
	assert.is(globalTrigger, 1, `global did not fire`);
	assert.is(local1Trigger, 1, `local1 fired`);
	assert.is(local2Trigger, 0, `local2 did not fire`);

	local2.trigger('foo');
	assert.is(globalTrigger, 1, `global did not fire`);
	assert.is(local1Trigger, 1, `local1 did not fire`);
	assert.is(local2Trigger, 1, `local2 fired`);

	assert.end();
});

test('event: add', assert => {
	assert.plan(4);

	const signal = src();
	assert.doesNotThrow(() => signal.on('foo', () => {}), `valid registration does not throw`);
	assert.throws(() => signal.on(null, () => {}), `an invalid name throws`);
	assert.throws(() => signal.on('foo', null), `an invalid callback throws`);
	assert.ok(isObject(signal.on(1, () => {})), `can listen to an id/number`);

	assert.end();
});

test('event: add invalid', assert => {
	assert.plan(1);

	const signal = src();
	assert.throws(() => signal.on('foo', {}), `invalid function throws`);

	assert.end();
});

test('event: symbol', assert => {
	assert.plan(3);

	const signal = src();
	const symbol = Symbol('foo');
	let trigger = false;
	assert.doesNotThrow(() => signal.on(symbol, function() { trigger = true; }), `symbol .on does not throw`);
	assert.doesNotThrow(() => signal.emit(symbol), `symbol .emit does not throw`);
	assert.is(trigger, true, `symbol event fired`);

	assert.end();
});

test('event: emit', assert => {
	assert.plan(3);

	const signal = src();
	let trigger = false;
	signal.on('foo:bar.baz', function() { trigger = true; });
	signal.trigger('foo:bar.baz');

	assert.ok(trigger, `events can trigger`);

	trigger = false;
	signal.emit('foo:bar.baz');

	assert.ok(trigger, `emit is a proxy`);

	assert.throws(() => signal.trigger(), `an event name is required to trigger`);

	assert.end();
});

test('event: emit empty', assert => {
	assert.plan(1);

	const signal = src();
	assert.doesNotThrow(() => signal.trigger('nothing.here'), `can trigger without a listener`);

	assert.end();
});

test('event: remove', assert => {
	assert.plan(3);

	const signal = src();
	const evt = 'foo:bar.baz';
	let trigger = 0;
	const fn1 = () => { trigger += 1; };
	const fn2 = () => { trigger += 1; };
	signal.on(evt, fn1);
	signal.on(evt, fn2);

	assert.is(signal.size(evt), 2, `successful registered events`);
	signal.off(evt);
	assert.is(signal.size(evt), 0, `successful removed events`);

	signal.trigger(evt);
	assert.is(trigger, 0, `event unbound successfully`);

	assert.end();
});

test('event: remove specific', assert => {
	assert.plan(2);

	const signal = src();
	const fn1 = () => {};
	const fn2 = () => {};

	signal.on('foo', fn1);
	signal.on('foo', fn2);

	assert.ok(signal.listeners('foo').length, 2, `registered functions`);

	signal.off('foo', fn1);

	assert.ok(signal.listeners('foo').length, 1, `only removed one function`);

	assert.end();
});

test('event: remove invalid', assert => {
	assert.plan(1);

	const signal = src();
	assert.throws(() => signal.off(), /requires event name/);

	assert.end();
});

test('event: once', assert => {
	assert.plan(6);

	const signal = src();
	let trigger = 0;
	signal.once('foo', () => { trigger += 1; });

	assert.is(signal.listeners('foo').length, 1, `registered the event using once`);
	signal.trigger('foo');
	assert.is(trigger, 1, `event has been called`);
	assert.is(signal.listeners('foo').length, 0, `event has been removed after being called`);
	signal.trigger('foo');
	assert.is(trigger, 1, `calling event again as not effect`);

	assert.throws(() => signal.once(undefined, () => {}), /requires event name/);
	assert.throws(() => signal.once('foo'), /requires callback/);

	assert.end();
});

test('event: multiple', assert => {
	assert.plan(1);

	const signal = src();
	let trigger = 0;
	const fn = () => { trigger += 1; };
	signal.on('foo', fn);
	signal.on('foo.bar', fn);
	signal.on('bar', fn);
	signal.on('bar.foo', fn);

	signal.trigger('foo')
		.trigger('foo.bar')
		.trigger('bar')
		.trigger('bar.foo')
		.trigger('baz');
	assert.is(trigger, 4, `calling multiple events has the desired effect`);

	assert.end();
});

test('params', assert => {
	assert.plan(10);

	const signal = src();

	let boolTest;
	let objectTest;
	let arrayTest;
	let numberTest;
	let stringTest;
	let undefTest;
	let nullTest;
	let nanTest;
	let infinTest;
	let fnTest;

	signal.on('paramtest', function(
		param1,
		param2,
		param3,
		param4,
		param5,
		param6,
		param7,
		param8,
		param9,
		param10
	) {
		if (param1 === false) boolTest = true;
		if (isPlainObject(param2)) objectTest = true;
		if (Array.isArray(param3)) arrayTest = true;
		if (param4 === 0) numberTest = true;
		if (param5 === '') stringTest = true;
		if (param6 === undefined) undefTest = true;
		if (param7 === null) nullTest = true;
		if (Number.isNaN(param8)) nanTest = true;
		if (param9 === Infinity) infinTest = true;
		if (isFunction(param10)) fnTest = true;
	});

	signal.trigger('paramtest',
		false,
		{},
		[],
		0,
		'',
		undefined,
		null,
		NaN,
		Infinity,
		() => {}
	);

	assert.ok(boolTest, `Booleans can be passed`);
	assert.ok(objectTest, `Objects can be passed`);
	assert.ok(arrayTest, `Arrays can be passed`);
	assert.ok(numberTest, `Numbers can be passed`);
	assert.ok(stringTest, `Strings can be passed`);
	assert.ok(undefTest, `undefined can be passed`);
	assert.ok(nullTest, `null can be passed`);
	assert.ok(nanTest, `NaN can be passed`);
	assert.ok(infinTest, `Infinity can be passed`);
	assert.ok(fnTest, `Function can be passed`);

	assert.end();
});

test('listeners', assert => {
	assert.plan(5);

	const empty = src();
	assert.is(empty.listeners().length, 0, 'an empty instance has no functions');

	const signal = src();
	const fn1 = () => {};
	const fn2 = () => {};

	signal.on('foo', fn1);

	assert.ok(Array.isArray(signal.listeners('foo')), `an array of functions can be retrieved`);
	assert.ok(isFunction(signal.listeners('foo')[0]), `there are functions in the array`);

	signal.on('foo', fn2);
	assert.is(signal.listeners('foo').length, 2, `multiple registered functions are retrieved`);

	signal.on('bar', () => {});
	assert.is(signal.listeners().length, 3, `all registered functions are retrieved`);

	assert.end();
});

test('names', assert => {
	assert.plan(4);

	const signal = src();
	signal.on('foo', () => {});

	assert.ok(Array.isArray(signal.names()), `an array of names can be retrieved`);
	assert.is(signal.names()[0], 'foo', `there are event names in the array`);

	signal.on('foo', () => {});
	assert.is(signal.names().length, 1, `multiple registered functions under a single name allow for only one name entry`);

	signal.on('bar', () => {});
	assert.is(signal.names().length, 2, `multiple names can be retrieved`);

	assert.end();
});

test('size', assert => {
	assert.plan(4);

	const signal = src();
	signal.on('foo', () => {});

	assert.is(signal.size(), 1, `one event results in a size of 1`);

	signal.on('foo', () => {});
	assert.is(signal.size(), 2, `two events under the same event name results in a size of 2`);

	signal.on('bar', () => {});
	assert.is(signal.size(), 3, `multiple names keeps a consistent count`);

	assert.is(signal.size('foo'), 2, `a size of a single name can be queried`);

	assert.end();
});

test('disable/enable', assert => {
	assert.plan(10);

	const signal = src();
	let trigger = 0;
	const fn = () => { trigger += 1; };

	signal.on('foo', fn);
	signal.trigger('foo');

	assert.ok(isFunction(signal.disable), `disable is a function`);
	assert.ok(isFunction(signal.enable), `enable is a function`);
	assert.is(trigger, 1, `can trigger an event`);

	assert.doesNotThrow(() => signal.disable(), `disable doesn't throw`);
	assert.doesNotThrow(() => signal.disable(), `calling disable multiple times doesn't throw`);
	assert.doesNotEqual(() => signal.trigger('foo'), `calling a disabled signal doesn't throw`);
	assert.is(trigger, 1, `when disabled, the event is not called`);

	assert.doesNotThrow(() => signal.enable(), `enable doesn't throw`);
	assert.doesNotThrow(() => signal.enable(), `calling enable multiple times doesn't throw`);
	signal.trigger('foo');
	assert.is(trigger, 2, `when re-enabled, the event is called`);

	assert.end();
});

test('clear', assert => {
	assert.plan(7);

	const signal = src();
	let trigger = 0;
	const fn = () => { trigger += 1; };

	signal.on('foo', fn);
	signal.on('bar', fn);

	signal.trigger('foo');
	assert.is(trigger, 1, `foo triggered`);
	signal.trigger('bar');
	assert.is(trigger, 2, `bar triggered`);

	assert.ok(isFunction(signal.clear), `clear is a function`);
	assert.doesNotThrow(() => signal.clear(), `calling clear does not throw`);
	assert.doesNotThrow(() => signal.clear(), `calling clear multiple times does not throw`);

	signal.trigger('foo');
	assert.is(trigger, 2, `foo did not trigger`);
	signal.trigger('bar');
	assert.is(trigger, 2, `bar did not trigger`);

	assert.end();
});

test('chaining', assert => {
	assert.plan(1);

	assert.doesNotThrow(() => {
		return src()
			.on('foo', () => {})
			.emit('foo')
			.off('foo')
			.once('bar', () => {})
			.emit('bar')
			.disable()
			.enable()
			.clear();
	});

	assert.end();
});<|endoftext|>


<commit_before>var V = require('ssb-validate')
var tape = require('tape')
var ssbKeys = require('ssb-keys')
var keys = ssbKeys.generate()

var pull = require('pull-stream')
var explain = require('explain-error')
var timestamp = require('monotonic-timestamp')

var dirname = '/tmp/test_ssb_append'+Date.now()

var K = [keys]

for(var i = 0; i < 100; i++) K.push(ssbKeys.generate())

var a
var db = a = require('../minimal')(dirname)
db.ready.set(true)
var MSG
tape('setup', function (t) {
  console.log("SETUP:APPEND")
  a.append({keys: keys, content: {type: 'empty'}}, function (err, msg) {
    if(err) throw err
    MSG = msg
    t.ok(msg)
    db.last.get(function (err, value) {
      t.deepEqual(value[keys.id], {
        id: msg.key,
        sequence: msg.value.sequence,
        ts: msg.value.timestamp
      })
      t.end()
    })
  })
})

var state = V.initial()
var N = 10000

tape('generate', function (t) {
  var start = Date.now()
  var l = N
  state = V.append(state, MSG.value)
  console.log(state)

  while(l--) {
    if(!(l%1000)) console.log(l)
    var keys = K[~~(Math.random()*K.length)]
    var content = {
      date: Date.now(), random: Math.random(), type: 'test'
    }
    var msg = V.create(
      state.feeds[keys.id],
      keys, null,
      content, timestamp()
    )
    state = V.append(state, msg)
    if(state.error) throw explain(err, 'error on generate')
  }
  console.log('generate', N/((Date.now()-start)/1000))
  t.end()
})

tape('loads', function (t) {
  var start = Date.now()
  db.since(function (s) {
    k++
    if(!(k%10)) console.log(j, k, s)
  })

  //set j=1 to skip first message, which has already been appended.
  var j = 1, k = 0
  ;(function next () {
    if(j >= state.queue.length) return a.flush(function () {
      console.log('append', N/((Date.now()-start)/1000))
      t.end()
    })

    a.queue(state.queue[j], function (err) {
      if(err) throw explain(err, 'queued invalid message')
      if(!(++j%1000)) console.log(j)
      if(Math.random() < 0.01)
        setImmediate(next)
      else next()
    })
  })()

})

tape('read back', function (t) {
  var msgs = state.queue //[MSG.value].concat(state.queue)
  var i = 0
  var _state = V.initial()
  var ts = 0
  var start = Date.now()
  pull(
    db.stream({seqs: false}),
    pull.drain(function (msg) {
      if(!(msg.timestamp > ts))
      t.fail('messages out of order')
      ts = msg.timestamp
      _state = V.append(_state, msg.value)
      if(_state.error) throw _state.error
    }, function (err) {
      if(err) throw err
      t.equal(_state.queue.length, msgs.length)

      console.log('revalidate', N/((Date.now()-start)/1000))
      t.end()
    })
  )
})

<commit_msg>update test to use ssb-validate@3<commit_after>var V = require('ssb-validate')
var tape = require('tape')
var ssbKeys = require('ssb-keys')
var keys = ssbKeys.generate()

var pull = require('pull-stream')
var explain = require('explain-error')
var timestamp = require('monotonic-timestamp')

var dirname = '/tmp/test_ssb_append'+Date.now()

var K = [keys]

for(var i = 0; i < 100; i++) K.push(ssbKeys.generate())

var a
var db = a = require('../minimal')(dirname)
db.ready.set(true)
var MSG
tape('setup', function (t) {
  console.log("SETUP:APPEND")
  a.append({keys: keys, content: {type: 'empty'}}, function (err, msg) {
    if(err) throw err
    MSG = msg
    t.ok(msg)
    db.last.get(function (err, value) {
      t.deepEqual(value[keys.id], {
        id: msg.key,
        sequence: msg.value.sequence,
        ts: msg.value.timestamp
      })
      t.end()
    })
  })
})

var state = V.initial()
var N = 10000

tape('generate', function (t) {
  var start = Date.now()
  var l = N
  state = V.append(state, null, MSG.value)
  console.log(state)

  while(l--) {
    if(!(l%1000)) console.log(l)
    var keys = K[~~(Math.random()*K.length)]
    var content = {
      date: Date.now(), random: Math.random(), type: 'test'
    }
    var msg = V.create(
      state.feeds[keys.id],
      keys, null,
      content, timestamp()
    )
    state = V.append(state, null, msg)
    if(state.error) throw explain(err, 'error on generate')
  }
  console.log('generate', N/((Date.now()-start)/1000))
  t.end()
})

tape('loads', function (t) {
  var start = Date.now()
  db.since(function (s) {
    k++
    if(!(k%10)) console.log(j, k, s)
  })

  //set j=1 to skip first message, which has already been appended.
  var j = 1, k = 0
  ;(function next () {
    if(j >= state.queue.length) return a.flush(function () {
      console.log('append', N/((Date.now()-start)/1000))
      t.end()
    })

    a.queue(state.queue[j], function (err) {
      if(err) throw explain(err, 'queued invalid message')
      if(!(++j%1000)) console.log(j)
      if(Math.random() < 0.01)
        setImmediate(next)
      else next()
    })
  })()

})

tape('read back', function (t) {
  var msgs = state.queue //[MSG.value].concat(state.queue)
  var i = 0
  var _state = V.initial()
  var ts = 0
  var start = Date.now()
  pull(
    db.stream({seqs: false}),
    pull.drain(function (msg) {
      if(!(msg.timestamp > ts))
      t.fail('messages out of order')
      ts = msg.timestamp
      _state = V.append(_state, null, msg.value)
      if(_state.error) throw _state.error
    }, function (err) {
      if(err) throw err
      t.equal(_state.queue.length, msgs.length)

      console.log('revalidate', N/((Date.now()-start)/1000))
      t.end()
    })
  )
})

<|endoftext|>


<commit_before>var fs = require('fs');
var util = ProjRequire('./lib/util.js');
module.exports = {
	spec : function() {
		return {
			name : 'closeFileWrite',
			desc : '',
			fields : [
			{type:'string',name:'file',description:'',required:true},
			{type:'string',name:'name',description:'',required:true},
			{type:'boolean',name:'append',description:'',},
			]
		}
	}
	,
	process : function(ctx, step, checkNext) {
		if(step.append) {
			fs.appendFileSync(step.file, ctx.openFileWritesHandler[step.name].toString());
		}
		else {
			fs.writeFileSync(step.file, ctx.openFileWritesHandler[step.name].toString());
		}
		ctx.openFileWritesHandler[step.name] = '';
		process.nextTick(checkNext);
	}
}<commit_msg>fix #48<commit_after>var fs = require('fs');
var util = ProjRequire('./lib/util.js');
module.exports = {
	spec : function() {
		return {
			name : 'closeFileWrite',
			desc : '',
			fields : [
			{type:'string',name:'file',description:'',required:true},
			{type:'string',name:'name',description:'',required:true},
			{type:'boolean',name:'append',description:''}
			]
		}
	}
	,
	process : function(ctx, step, checkNext) {
		if(step.append) {
			fs.appendFileSync(step.file, ctx.openFileWritesHandler[step.name].toString());
		}
		else {
			fs.writeFileSync(step.file, ctx.openFileWritesHandler[step.name].toString());
		}
		ctx.openFileWritesHandler[step.name] = '';
		process.nextTick(checkNext);
	}
}<|endoftext|>


<commit_before>var Ballot = artifacts.require("./Ballot.sol");

contract('Ballot', function(accounts) {
    it("should return 0 as the ballot winner", function() {
        return Ballot.deployed().then(function(instance) {
            return instance.winningProposal.call();
        }).then(function(winner) {
            assert.equal(winner.valueOf(), 0, "0 was the winner");
        });
    });
    it("should be able to add a voter and vote", function() {

        var ballot;
        var proposals = ["first", "second"];
        var account_zero = "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1";
        var account_two = "0x22d491bde2303f2f43325b2108d26f1eaba1e32b";

        return Ballot.new(proposals).then(function(instance) {
            ballot = instance;
            console.log("ballot: " + ballot);
            for(var propName in ballot) {
                propValue = ballot[propName]

                console.log(propName,propValue);
            }
            return ballot.giveRightToVote(account_two, {from: account_zero} );
        }).then(function() {
            return ballot.vote(1, {from: account_two});
        }).then(function() {
            return ballot.winningProposal.call();
        }).then(function(winner) {
            assert.equal(winner.valueOf(), 1, "proposal 1 was the winner");
        });
    });

    it("should not allow voting twice", function() {

        var ballot;
        var proposals = ["first", "second"];
        var account_zero = "0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1";
        var account_two = "0x22d491bde2303f2f43325b2108d26f1eaba1e32b";

        return Ballot.new(proposals).then(function(instance) {
            ballot = instance;
            return ballot.giveRightToVote(account_two, {from: account_zero} );
        }).then(function() {
            return ballot.vote(1, {from: account_two});
        }).then(function() {
            // This should throw an exception as can only call once
            return ballot.vote(2, {from: account_two});
        }).then(function() {
            assert.isOk(false, "Should have thrown exception on second vote");
        });
    });

});
<commit_msg>Fixed the hard coded accounts.<commit_after>var Ballot = artifacts.require("./Ballot.sol");

contract('Ballot', function(accounts) {
    it("should return 0 as the ballot winner", function() {
        return Ballot.deployed().then(function(instance) {
            return instance.winningProposal.call();
        }).then(function(winner) {
            assert.equal(winner.valueOf(), 0, "0 was the winner");
        });
    });
    it("should be able to add a voter and vote", function() {

        var ballot;
        var proposals = ["first", "second"];
        var account_zero = accounts[0];
        var account_two = accounts[2];

        return Ballot.new(proposals).then(function(instance) {
            ballot = instance;
            console.log("ballot: " + ballot);
            for(var propName in ballot) {
                propValue = ballot[propName]

                console.log(propName,propValue);
            }
            return ballot.giveRightToVote(account_two, {from: account_zero} );
        }).then(function() {
            return ballot.vote(1, {from: account_two});
        }).then(function() {
            return ballot.winningProposal.call();
        }).then(function(winner) {
            assert.equal(winner.valueOf(), 1, "proposal 1 was the winner");
        });
    });

    it("should not allow voting twice", function() {

        var ballot;
        var proposals = ["first", "second"];
        var account_zero = accounts[0];
        var account_two = accounts[2];

        return Ballot.new(proposals).then(function(instance) {
            ballot = instance;
            return ballot.giveRightToVote(account_two, {from: account_zero} );
        }).then(function() {
            return ballot.vote(1, {from: account_two});
        }).then(function() {
            // This should throw an exception as can only call once
            return ballot.vote(2, {from: account_two});
        }).then(function() {
            assert.isOk(false, "Should have thrown exception on second vote");
        });
    });

});
<|endoftext|>


<commit_before>'use strict';

class Employee {
  constructor(status) {
    this.status = status;
  }

  isDead() {
    return this.status === 'DEAD';
  }

  isSeparated() {
    return this.status === 'SEPARATED';
  }

  isRetired() {
    return this.status === 'RETIRED';
  }

  getPaymentAmount() {
    let result = '';
    if (this.isDead()) return deadAmount();
    if (this.isSeparated()) return separatedAmount();
    if (this.isRetired()) {
      result = retiredAmount()
    } else {
      result = normalPayAmount()
    }
    return result
  }
}

function deadAmount() {
  return 'deadAmount';
}
function separatedAmount() {
  return 'separatedAmount';
}
function retiredAmount() {
  return 'retiredAmount';
}
function normalPayAmount() {
  return 'normalPayAmount';
}

module.exports = Employee;<commit_msg>[jiefeng] [Replace Nested Conditional with Guard Clauses] replace last nexted conditional with Guard Clauses and delete the useless flag.<commit_after>'use strict';

class Employee {
  constructor(status) {
    this.status = status;
  }

  isDead() {
    return this.status === 'DEAD';
  }

  isSeparated() {
    return this.status === 'SEPARATED';
  }

  isRetired() {
    return this.status === 'RETIRED';
  }

  getPaymentAmount() {
    if (this.isDead()) return deadAmount();
    if (this.isSeparated()) return separatedAmount();
    if (this.isRetired()) return retiredAmount();
    return normalPayAmount();
  }
}

function deadAmount() {
  return 'deadAmount';
}
function separatedAmount() {
  return 'separatedAmount';
}
function retiredAmount() {
  return 'retiredAmount';
}
function normalPayAmount() {
  return 'normalPayAmount';
}

module.exports = Employee;<|endoftext|>


<commit_before>/**
 * editor_plugin_src.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 *
 * Adds auto-save capability to the TinyMCE text editor to rescue content
 * inadvertently lost. This plugin was originally developed by Speednet
 * and that project can be found here: http://code.google.com/p/tinyautosave/
 *
 * TECHNOLOGY DISCUSSION:
 *
 * The plugin attempts to use the most advanced features available in the current browser to save
 * as much content as possible.  There are a total of four different methods used to autosave the
 * content.  In order of preference, they are:
 *
 * 1. localStorage - A new feature of HTML 5, localStorage can store megabytes of data per domain
 * on the client computer. Data stored in the localStorage area has no expiration date, so we must
 * manage expiring the data ourselves.  localStorage is fully supported by IE8, and it is supposed
 * to be working in Firefox 3 and Safari 3.2, but in reality is is flaky in those browsers.  As
 * HTML 5 gets wider support, the AutoSave plugin will use it automatically. In Windows Vista/7,
 * localStorage is stored in the following folder:
 * C:\Users\[username]\AppData\Local\Microsoft\Internet Explorer\DOMStore\[tempFolder]
 *
 * 2. sessionStorage - A new feature of HTML 5, sessionStorage works similarly to localStorage,
 * except it is designed to expire after a certain amount of time.  Because the specification
 * around expiration date/time is very loosely-described, it is preferrable to use locaStorage and
 * manage the expiration ourselves.  sessionStorage has similar storage characteristics to
 * localStorage, although it seems to have better support by Firefox 3 at the moment.  (That will
 * certainly change as Firefox continues getting better at HTML 5 adoption.)
 *
 * 3. UserData - A very under-exploited feature of Microsoft Internet Explorer, UserData is a
 * way to store up to 128K of data per "document", or up to 1MB of data per domain, on the client
 * computer.  The feature is available for IE 5+, which makes it available for every version of IE
 * supported by TinyMCE.  The content is persistent across browser restarts and expires on the
 * date/time specified, just like a cookie.  However, the data is not cleared when the user clears
 * cookies on the browser, which makes it well-suited for rescuing autosaved content.  UserData,
 * like other Microsoft IE browser technologies, is implemented as a behavior attached to a
 * specific DOM object, so in this case we attach the behavior to the same DOM element that the
 * TinyMCE editor instance is attached to.
 */

(function(tinymce) {
	// Setup constants to help the compressor to reduce script size
	var PLUGIN_NAME = 'autosave',
		RESTORE_DRAFT = 'restoredraft',
		TRUE = true,
		undefined,
		unloadHandlerAdded,
		Dispatcher = tinymce.util.Dispatcher;

	// Load language pack for the autosave plugin
	tinymce.PluginManager.requireLangPack(PLUGIN_NAME);

	/**
	 * This plugin adds auto-save capability to the TinyMCE text editor to rescue content
	 * inadvertently lost. By using localStorage.
	 *
	 * @class tinymce.plugins.AutoSave
	 */
	tinymce.create('tinymce.plugins.AutoSave', {
		/**
		 * Initializes the plugin, this will be executed after the plugin has been created.
		 * This call is done before the editor instance has finished it's initialization so use the onInit event
		 * of the editor instance to intercept that event.
		 *
		 * @method init
		 * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
		 * @param {string} url Absolute URL to where the plugin is located.
		 */
		init : function(ed, url) {
			var self = this, settings = ed.settings;

			self.editor = ed;

			// Parses the specified time string into a milisecond number 10m, 10s etc.
			function parseTime(time) {
				var multipels = {
					s : 1000,
					m : 60000
				};

				time = /^(\d+)([ms]?)$/.exec('' + time);

				return (time[2] ? multipels[time[2]] : 1) * parseInt(time);
			};

			// Default config
			tinymce.each({
				ask_before_unload : TRUE,
				interval : '30s',
				retention : '20m',
				minlength : 50
			}, function(value, key) {
				key = PLUGIN_NAME + '_' + key;

				if (settings[key] === undefined)
					settings[key] = value;
			});

			// Parse times
			settings.autosave_interval = parseTime(settings.autosave_interval);
			settings.autosave_retention = parseTime(settings.autosave_retention);

			// Register restore button
			ed.addButton(RESTORE_DRAFT, {
				title : PLUGIN_NAME + ".restore_content",
				onclick : function() {
					if (ed.getContent().replace(/\s| |<\/?p[^>]*>|<br[^>]*>/gi, "").length > 0) {
						// Show confirm dialog if the editor isn't empty
						ed.windowManager.confirm(
							PLUGIN_NAME + ".warning_message",
							function(ok) {
								if (ok)
									self.restoreDraft();
							}
						);
					} else
						self.restoreDraft();
				}
			});

			// Enable/disable restoredraft button depending on if there is a draft stored or not
			ed.onNodeChange.add(function() {
				var controlManager = ed.controlManager;

				if (controlManager.get(RESTORE_DRAFT))
					controlManager.setDisabled(RESTORE_DRAFT, !self.hasDraft());
			});

			ed.onInit.add(function() {
				// Check if the user added the restore button, then setup auto storage logic
				if (ed.controlManager.get(RESTORE_DRAFT)) {
					// Setup storage engine
					self.setupStorage(ed);

					// Auto save contents each interval time
					setInterval(function() {
						self.storeDraft();
						ed.nodeChanged();
					}, settings.autosave_interval);
				}
			});

			/**
			 * This event gets fired when a draft is stored to local storage.
			 *
			 * @event onStoreDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onStoreDraft = new Dispatcher(self);

			/**
			 * This event gets fired when a draft is restored from local storage.
			 *
			 * @event onStoreDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onRestoreDraft = new Dispatcher(self);

			/**
			 * This event gets fired when a draft removed/expired.
			 *
			 * @event onRemoveDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onRemoveDraft = new Dispatcher(self);

			// Add ask before unload dialog only add one unload handler
			if (!unloadHandlerAdded) {
				window.onbeforeunload = tinymce.plugins.AutoSave._beforeUnloadHandler;
				unloadHandlerAdded = TRUE;
			}
		},

		/**
		 * Returns information about the plugin as a name/value array.
		 * The current keys are longname, author, authorurl, infourl and version.
		 *
		 * @method getInfo
		 * @return {Object} Name/value array containing information about the plugin.
		 */
		getInfo : function() {
			return {
				longname : 'Auto save',
				author : 'Moxiecode Systems AB',
				authorurl : 'http://tinymce.moxiecode.com',
				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autosave',
				version : tinymce.majorVersion + "." + tinymce.minorVersion
			};
		},

		/**
		 * Returns an expiration date UTC string.
		 *
		 * @method getExpDate
		 * @return {String} Expiration date UTC string.
		 */
		getExpDate : function() {
			return new Date(
				new Date().getTime() + this.editor.settings.autosave_retention
			).toUTCString();
		},

		/**
		 * This method will setup the storage engine. If the browser has support for it.
		 *
		 * @method setupStorage
		 */
		setupStorage : function(ed) {
			var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK";

			self.key = PLUGIN_NAME + ed.id;

			// Loop though each storage engine type until we find one that works
			tinymce.each([
				function() {
					// Try HTML5 Local Storage
					if (localStorage) {
						localStorage.setItem(testKey, testVal);

						if (localStorage.getItem(testKey) === testVal) {
							localStorage.removeItem(testKey);

							return localStorage;
						}
					}
				},

				function() {
					// Try HTML5 Session Storage
					if (sessionStorage) {
						sessionStorage.setItem(testKey, testVal);

						if (sessionStorage.getItem(testKey) === testVal) {
							sessionStorage.removeItem(testKey);

							return sessionStorage;
						}
					}
				},

				function() {
					// Try IE userData
					if (tinymce.isIE) {
						ed.getElement().style.behavior = "url('#default#userData')";

						// Fake localStorage on old IE
						return {
							autoExpires : TRUE,

							setItem : function(key, value) {
								var userDataElement = ed.getElement();

								userDataElement.setAttribute(key, value);
								userDataElement.expires = self.getExpDate();
								userDataElement.save("TinyMCE");
							},

							getItem : function(key) {
								var userDataElement = ed.getElement();

								userDataElement.load("TinyMCE");

								return userDataElement.getAttribute(key);
							},

							removeItem : function(key) {
								ed.getElement().removeAttribute(key);
							}
						};
					}
				},
			], function(setup) {
				// Try executing each function to find a suitable storage engine
				try {
					self.storage = setup();

					if (self.storage)
						return false;
				} catch (e) {
					// Ignore
				}
			});
		},

		/**
		 * This method will store the current contents in the the storage engine.
		 *
		 * @method storeDraft
		 */
		storeDraft : function() {
			var self = this, storage = self.storage, editor = self.editor, expires, content;

			// Is the contents dirty
			if (storage) {
				// If there is no existing key and the contents hasn't been changed since
				// it's original value then there is no point in saving a draft
				if (!storage.getItem(self.key) && !editor.isDirty())
					return;

				// Store contents if the contents if longer than the minlength of characters
				content = editor.getContent();
				if (content.length > editor.settings.autosave_minlength) {
					expires = self.getExpDate();

					// Store expiration date if needed IE userData has auto expire built in
					if (!self.storage.autoExpires)
						self.storage.setItem(self.key + "_expires", expires);

					self.storage.setItem(self.key, content);
					self.onStoreDraft.dispatch(self, {
						expires : expires,
						content : content
					});
				}
			}
		},

		/**
		 * This method will restore the contents from the storage engine back to the editor.
		 *
		 * @method restoreDraft
		 */
		restoreDraft : function() {
			var self = this, storage = self.storage;

			if (storage) {
				content = storage.getItem(self.key);

				if (content) {
					self.editor.setContent(content);
					self.onRestoreDraft.dispatch(self, {
						content : content
					});
				}
			}
		},

		/**
		 * This method will return true/false if there is a local storage draft available.
		 *
		 * @method hasDraft
		 * @return {boolean} true/false state if there is a local draft.
		 */
		hasDraft : function() {
			var self = this, storage = self.storage, expDate, exists;

			if (storage) {
				// Does the item exist at all
				exists = !!storage.getItem(self.key);
				if (exists) {
					expDate = new Date(storage.getItem(self.key + "_expires"));

					// Contents hasn't expired
					if (new Date().getTime() < expDate.getTime())
						return TRUE;

					// Remove it if it has
					self.removeDraft();
				}
			}

			return false;
		},

		/**
		 * Removes the currently stored draft.
		 *
		 * @method removeDraft
		 */
		removeDraft : function() {
			var self = this, storage = self.storage, key = self.key, content;

			if (storage) {
				// Get current contents and remove the existing draft
				content = storage.getItem(key);
				storage.removeItem(key);
				storage.removeItem(key + "_expires");

				// Dispatch remove event if we had any contents
				if (content) {
					self.onRemoveDraft.dispatch(self, {
						content : content
					});
				}
			}
		},

		"static" : {
			// Internal unload handler will be called before the page is unloaded
			_beforeUnloadHandler : function(e) {
				var msg;

				tinymce.each(tinyMCE.editors, function(ed) {
					// Store a draft for each editor instance
					if (ed.plugins.autosave)
						ed.plugins.autosave.storeDraft();

					// Never ask in fullscreen mode
					if (ed.getParam("fullscreen_is_enabled"))
						return;

					// Setup a return message if the editor is dirty
					if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload"))
						msg = ed.getLang("autosave.unload_msg");
				});

				return msg;
			}
		}
	});

	tinymce.PluginManager.add('autosave', tinymce.plugins.AutoSave);
})(tinymce);
<commit_msg>Fixed IE issue with expiration of contents in the new autosave logic.<commit_after>/**
 * editor_plugin_src.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 *
 * Adds auto-save capability to the TinyMCE text editor to rescue content
 * inadvertently lost. This plugin was originally developed by Speednet
 * and that project can be found here: http://code.google.com/p/tinyautosave/
 *
 * TECHNOLOGY DISCUSSION:
 *
 * The plugin attempts to use the most advanced features available in the current browser to save
 * as much content as possible.  There are a total of four different methods used to autosave the
 * content.  In order of preference, they are:
 *
 * 1. localStorage - A new feature of HTML 5, localStorage can store megabytes of data per domain
 * on the client computer. Data stored in the localStorage area has no expiration date, so we must
 * manage expiring the data ourselves.  localStorage is fully supported by IE8, and it is supposed
 * to be working in Firefox 3 and Safari 3.2, but in reality is is flaky in those browsers.  As
 * HTML 5 gets wider support, the AutoSave plugin will use it automatically. In Windows Vista/7,
 * localStorage is stored in the following folder:
 * C:\Users\[username]\AppData\Local\Microsoft\Internet Explorer\DOMStore\[tempFolder]
 *
 * 2. sessionStorage - A new feature of HTML 5, sessionStorage works similarly to localStorage,
 * except it is designed to expire after a certain amount of time.  Because the specification
 * around expiration date/time is very loosely-described, it is preferrable to use locaStorage and
 * manage the expiration ourselves.  sessionStorage has similar storage characteristics to
 * localStorage, although it seems to have better support by Firefox 3 at the moment.  (That will
 * certainly change as Firefox continues getting better at HTML 5 adoption.)
 *
 * 3. UserData - A very under-exploited feature of Microsoft Internet Explorer, UserData is a
 * way to store up to 128K of data per "document", or up to 1MB of data per domain, on the client
 * computer.  The feature is available for IE 5+, which makes it available for every version of IE
 * supported by TinyMCE.  The content is persistent across browser restarts and expires on the
 * date/time specified, just like a cookie.  However, the data is not cleared when the user clears
 * cookies on the browser, which makes it well-suited for rescuing autosaved content.  UserData,
 * like other Microsoft IE browser technologies, is implemented as a behavior attached to a
 * specific DOM object, so in this case we attach the behavior to the same DOM element that the
 * TinyMCE editor instance is attached to.
 */

(function(tinymce) {
	// Setup constants to help the compressor to reduce script size
	var PLUGIN_NAME = 'autosave',
		RESTORE_DRAFT = 'restoredraft',
		TRUE = true,
		undefined,
		unloadHandlerAdded,
		Dispatcher = tinymce.util.Dispatcher;

	// Load language pack for the autosave plugin
	tinymce.PluginManager.requireLangPack(PLUGIN_NAME);

	/**
	 * This plugin adds auto-save capability to the TinyMCE text editor to rescue content
	 * inadvertently lost. By using localStorage.
	 *
	 * @class tinymce.plugins.AutoSave
	 */
	tinymce.create('tinymce.plugins.AutoSave', {
		/**
		 * Initializes the plugin, this will be executed after the plugin has been created.
		 * This call is done before the editor instance has finished it's initialization so use the onInit event
		 * of the editor instance to intercept that event.
		 *
		 * @method init
		 * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
		 * @param {string} url Absolute URL to where the plugin is located.
		 */
		init : function(ed, url) {
			var self = this, settings = ed.settings;

			self.editor = ed;

			// Parses the specified time string into a milisecond number 10m, 10s etc.
			function parseTime(time) {
				var multipels = {
					s : 1000,
					m : 60000
				};

				time = /^(\d+)([ms]?)$/.exec('' + time);

				return (time[2] ? multipels[time[2]] : 1) * parseInt(time);
			};

			// Default config
			tinymce.each({
				ask_before_unload : TRUE,
				interval : '30s',
				retention : '20m',
				minlength : 50
			}, function(value, key) {
				key = PLUGIN_NAME + '_' + key;

				if (settings[key] === undefined)
					settings[key] = value;
			});

			// Parse times
			settings.autosave_interval = parseTime(settings.autosave_interval);
			settings.autosave_retention = parseTime(settings.autosave_retention);

			// Register restore button
			ed.addButton(RESTORE_DRAFT, {
				title : PLUGIN_NAME + ".restore_content",
				onclick : function() {
					if (ed.getContent().replace(/\s| |<\/?p[^>]*>|<br[^>]*>/gi, "").length > 0) {
						// Show confirm dialog if the editor isn't empty
						ed.windowManager.confirm(
							PLUGIN_NAME + ".warning_message",
							function(ok) {
								if (ok)
									self.restoreDraft();
							}
						);
					} else
						self.restoreDraft();
				}
			});

			// Enable/disable restoredraft button depending on if there is a draft stored or not
			ed.onNodeChange.add(function() {
				var controlManager = ed.controlManager;

				if (controlManager.get(RESTORE_DRAFT))
					controlManager.setDisabled(RESTORE_DRAFT, !self.hasDraft());
			});

			ed.onInit.add(function() {
				// Check if the user added the restore button, then setup auto storage logic
				if (ed.controlManager.get(RESTORE_DRAFT)) {
					// Setup storage engine
					self.setupStorage(ed);

					// Auto save contents each interval time
					setInterval(function() {
						self.storeDraft();
						ed.nodeChanged();
					}, settings.autosave_interval);
				}
			});

			/**
			 * This event gets fired when a draft is stored to local storage.
			 *
			 * @event onStoreDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onStoreDraft = new Dispatcher(self);

			/**
			 * This event gets fired when a draft is restored from local storage.
			 *
			 * @event onStoreDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onRestoreDraft = new Dispatcher(self);

			/**
			 * This event gets fired when a draft removed/expired.
			 *
			 * @event onRemoveDraft
			 * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
			 * @param {Object} draft Draft object containing the HTML contents of the editor.
			 */
			self.onRemoveDraft = new Dispatcher(self);

			// Add ask before unload dialog only add one unload handler
			if (!unloadHandlerAdded) {
				window.onbeforeunload = tinymce.plugins.AutoSave._beforeUnloadHandler;
				unloadHandlerAdded = TRUE;
			}
		},

		/**
		 * Returns information about the plugin as a name/value array.
		 * The current keys are longname, author, authorurl, infourl and version.
		 *
		 * @method getInfo
		 * @return {Object} Name/value array containing information about the plugin.
		 */
		getInfo : function() {
			return {
				longname : 'Auto save',
				author : 'Moxiecode Systems AB',
				authorurl : 'http://tinymce.moxiecode.com',
				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autosave',
				version : tinymce.majorVersion + "." + tinymce.minorVersion
			};
		},

		/**
		 * Returns an expiration date UTC string.
		 *
		 * @method getExpDate
		 * @return {String} Expiration date UTC string.
		 */
		getExpDate : function() {
			return new Date(
				new Date().getTime() + this.editor.settings.autosave_retention
			).toUTCString();
		},

		/**
		 * This method will setup the storage engine. If the browser has support for it.
		 *
		 * @method setupStorage
		 */
		setupStorage : function(ed) {
			var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK";

			self.key = PLUGIN_NAME + ed.id;

			// Loop though each storage engine type until we find one that works
			tinymce.each([
				function() {
					// Try HTML5 Local Storage
					if (localStorage) {
						localStorage.setItem(testKey, testVal);

						if (localStorage.getItem(testKey) === testVal) {
							localStorage.removeItem(testKey);

							return localStorage;
						}
					}
				},

				function() {
					// Try HTML5 Session Storage
					if (sessionStorage) {
						sessionStorage.setItem(testKey, testVal);

						if (sessionStorage.getItem(testKey) === testVal) {
							sessionStorage.removeItem(testKey);

							return sessionStorage;
						}
					}
				},

				function() {
					// Try IE userData
					if (tinymce.isIE) {
						ed.getElement().style.behavior = "url('#default#userData')";

						// Fake localStorage on old IE
						return {
							autoExpires : TRUE,

							setItem : function(key, value) {
								var userDataElement = ed.getElement();

								userDataElement.setAttribute(key, value);
								userDataElement.expires = self.getExpDate();
								userDataElement.save("TinyMCE");
							},

							getItem : function(key) {
								var userDataElement = ed.getElement();

								userDataElement.load("TinyMCE");

								return userDataElement.getAttribute(key);
							},

							removeItem : function(key) {
								ed.getElement().removeAttribute(key);
							}
						};
					}
				},
			], function(setup) {
				// Try executing each function to find a suitable storage engine
				try {
					self.storage = setup();

					if (self.storage)
						return false;
				} catch (e) {
					// Ignore
				}
			});
		},

		/**
		 * This method will store the current contents in the the storage engine.
		 *
		 * @method storeDraft
		 */
		storeDraft : function() {
			var self = this, storage = self.storage, editor = self.editor, expires, content;

			// Is the contents dirty
			if (storage) {
				// If there is no existing key and the contents hasn't been changed since
				// it's original value then there is no point in saving a draft
				if (!storage.getItem(self.key) && !editor.isDirty())
					return;

				// Store contents if the contents if longer than the minlength of characters
				content = editor.getContent();
				if (content.length > editor.settings.autosave_minlength) {
					expires = self.getExpDate();

					// Store expiration date if needed IE userData has auto expire built in
					if (!self.storage.autoExpires)
						self.storage.setItem(self.key + "_expires", expires);

					self.storage.setItem(self.key, content);
					self.onStoreDraft.dispatch(self, {
						expires : expires,
						content : content
					});
				}
			}
		},

		/**
		 * This method will restore the contents from the storage engine back to the editor.
		 *
		 * @method restoreDraft
		 */
		restoreDraft : function() {
			var self = this, storage = self.storage;

			if (storage) {
				content = storage.getItem(self.key);

				if (content) {
					self.editor.setContent(content);
					self.onRestoreDraft.dispatch(self, {
						content : content
					});
				}
			}
		},

		/**
		 * This method will return true/false if there is a local storage draft available.
		 *
		 * @method hasDraft
		 * @return {boolean} true/false state if there is a local draft.
		 */
		hasDraft : function() {
			var self = this, storage = self.storage, expDate, exists;

			if (storage) {
				// Does the item exist at all
				exists = !!storage.getItem(self.key);
				if (exists) {
					// Storage needs autoexpire
					if (!self.storage.autoExpires) {
						expDate = new Date(storage.getItem(self.key + "_expires"));

						// Contents hasn't expired
						if (new Date().getTime() < expDate.getTime())
							return TRUE;

						// Remove it if it has
						self.removeDraft();
					} else
						return TRUE;
				}
			}

			return false;
		},

		/**
		 * Removes the currently stored draft.
		 *
		 * @method removeDraft
		 */
		removeDraft : function() {
			var self = this, storage = self.storage, key = self.key, content;

			if (storage) {
				// Get current contents and remove the existing draft
				content = storage.getItem(key);
				storage.removeItem(key);
				storage.removeItem(key + "_expires");

				// Dispatch remove event if we had any contents
				if (content) {
					self.onRemoveDraft.dispatch(self, {
						content : content
					});
				}
			}
		},

		"static" : {
			// Internal unload handler will be called before the page is unloaded
			_beforeUnloadHandler : function(e) {
				var msg;

				tinymce.each(tinyMCE.editors, function(ed) {
					// Store a draft for each editor instance
					if (ed.plugins.autosave)
						ed.plugins.autosave.storeDraft();

					// Never ask in fullscreen mode
					if (ed.getParam("fullscreen_is_enabled"))
						return;

					// Setup a return message if the editor is dirty
					if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload"))
						msg = ed.getLang("autosave.unload_msg");
				});

				return msg;
			}
		}
	});

	tinymce.PluginManager.add('autosave', tinymce.plugins.AutoSave);
})(tinymce);
<|endoftext|>


<commit_before>/**
 * Copyright 2015 aixigo AG
 * Released under the MIT license.
 * http://laxarjs.org/license
 */
define( [
   'angular'
], function( ng, template ) {
   'use strict';

   var directiveName = 'axGauge';

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   var gaugeDirective = [ '$document', '$interval', function( $document, $interval ) {
      var numInstances = 0;

      return {
         restrict: 'A',
         replace: true,
         template: template,
         transclude: true,
         scope: {
            value: '=' + directiveName,
            interval: '=' + directiveName + 'Interval'
         },
         link: function( scope, element, attrs ) {
            var defs = $document.find( '#ax-gauge-defs' );
            var fill = element.find( '.ax-gauge-fill' )[0];
            var glow = element.find( '.ax-gauge-glow' )[0];
            var progress = element.find( '.ax-gauge-progress' )[0];

            if( defs.length === 0 ) {
               defs = ng.element( svgGlobalDefs );
               $document.find( 'body' ).append( defs );
            }

            numInstances++;

            scope.active = scope.prev = scope.next = scope.length = 0;

            scope.$watch( 'value', function( newValue, oldValue ) {
               setGauge( fill, newValue );
               setGauge( glow, newValue );
            } );
            scope.$watch( 'active', function( newValue, oldValue ) {
               if( scope.length < 1 ) return;
               var start = (newValue / scope.length) * 1.5 * Math.PI;
               var angle = ((newValue + 1) / scope.length) * 1.5 * Math.PI;

               var radius = progress.pathSegList.getItem(0).y;

               console.log( start, angle, radius );

               setArc( progress.pathSegList.getItem(1), angle );
            } );

            element.on( '$destroy', function() {
               if( --numInstances === 0 ) {
                  defs.remove();
               }
            } );
         },
         controller: function GaugeController( $scope ) {
            var panes = [];

            if( $scope.interval ) {
               var scrollInterval = $interval(function() {
                  setActivePane( $scope.active + 1 );
               }, $scope.interval );

               $scope.$on( '$destroy', $interval.cancel.bind( $interval, scrollInterval ) );
            }

            function setActivePane( num ) {
               var length = $scope.length = panes.length;

               panes.forEach( function( pane ) {
                  pane.active = pane.next = pane.prev = false;
               } );

               $scope.prev = $scope.active % length;
               $scope.active = num % length;
               $scope.next = (num + 1) % length;

               panes[ $scope.prev ].prev = true;
               panes[ $scope.active ].active = true;
               panes[ $scope.next ].next = true;
            };

            this.setActivePane = setActivePane;

            this.addPane = function addPane( scope ) {
               scope.next = scope.prev = false;
               scope.active = !(panes.length);
               panes.push( scope );
               $scope.length = panes.length;
            };

            this.removePane = function removePane( scope ) {
               scope.active = scope.next = scope.prev = false;
               panes.splice( panes.indexOf( scope ), 1 );
               $scope.length = panes.length;
            };
         }
      };
   } ];

   var gaugePaneDirective = [ function() {
      return {
         restrict: 'A',
         replace: true,
         require: '^' + directiveName,
         template: '

',
         scope: {},
         transclude: true,
         link: function( scope, element, attrs, gaugeCtrl ) {
            gaugeCtrl.addPane( scope );

            element.on( '$destroy', gaugeCtrl.removePane.bind( gaugeCtrl, scope ) );
         }
      };
   } ];

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function setArc( pathSeg, rad ) {
      pathSeg.x = -Math.sin( rad ) * pathSeg.r1;
      pathSeg.y = Math.cos( rad ) * pathSeg.r2;
      pathSeg.sweepFlag = true;
      pathSeg.largeArcFlag = rad > Math.PI;
   }

   function setGauge( element, value ) {
      var rad = Math.PI * value * 1.5; // value = 1.0  -> rad = 270deg = 1.5rad
      setArc(element.pathSegList.getItem(1), rad);
   }

   var template = '' +
      '
' +
         '
' +
         '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewbox="-50 -50 100 100">' +
            '<g transform="rotate(45)">' +
               '<g mask="url(#ax-gauge-ring-mask)">' +
                  '<path class="ax-gauge-back" d="M 0 50 A 50 50 0 1 1 50 0 L 0 0 z" />' +
                  '<path class="ax-gauge-fill" d="M 0 50 A 50 50 0 1 0 0 50 L 0 0 z" />' +
               '</g>' +
               '<g filter="url(#ax-gauge-glow)">' +
                  '<path class="ax-gauge-glow" mask="url(#ax-gauge-ring-mask)"' +
                       ' d="M 0 50 A 50 50 0 1 0 0 50 L 0 0 z" />' +
               '</g>' +
               '<path class="ax-gauge-progress"' +
                    ' d="M 0 30 A 30 30 0 1 0 0 30" fill="none" />' +
            '</g>' +
         '</svg>' +
      '
';

   var svgGlobalDefs = '' +
      '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="0" height="0"' +
          ' style="position: absolute">' +
         '<defs id="ax-gauge-defs">' +
            '<mask id="ax-gauge-ring-mask" x="0" y="0" width="100" height="100">' +
               '<path fill="white" d="M 0 48 A 48 48 0 1 1 48 0 ' +
                                     'L 33 0 A 33 33 0 1 0 0 33 z" />' +
               '<path stroke="black" stroke-width="3"' +
                    ' d="M 0 50 L 0 0 ' +
                        'M -50 50 L 0 0 ' +
                        'M -50 0 L 0 0 ' +
                        'M -50 -50 L 0 0 ' +
                        'M 0 -50 L 0 0 ' +
                        'M 50 -50 L 0 0 ' +
                        'M 50 0 L 0 0" />' +
               '<path stroke="black" stroke-width="3" transform="rotate(22.5)"' +
                    ' d="M 0 50 L 0 0 ' +
                        'M -50 50 L 0 0 ' +
                        'M -50 0 L 0 0 ' +
                        'M -50 -50 L 0 0 ' +
                        'M 0 -50 L 0 0 ' +
                        'M 50 -50 L 0 0" />' +
            '</mask>' +
            '<filter id="ax-gauge-glow">' +
               '<feGaussianBlur in="SourceGraphic" stdDeviation="2" />' +
               '<feComponentTransfer>' +
                  '<feFuncA type="linear" slope="0.4" />' +
               '</feComponentTransfer>' +
               '<feBlend mode="screen" />' +
            '</filter>' +
            '<radialGradient id="ax-gauge-inner-fill">' +
               '<stop offset="85%" stop-color="white" />' +
               '<stop offset="100%" stop-color="black" />' +
            '</radialGradient>' +
            '<mask id="ax-gauge-inner-mask" maskUnits="objectBoundingBox" maskContentUnits="objectBoundingBox">' +
               '<circle cx=".5" cy=".5" r=".3" fill="url(#ax-gauge-inner-fill)" />' +
            '</mask>' +
         '</defs>' +
      '</svg>';

   return {
      createForModule: function( module ) {
         module.directive( directiveName, gaugeDirective );
         module.directive( directiveName + 'Pane', gaugePaneDirective );
      }
   };

} );
<commit_msg>Remove unused parameter, variable and logging<commit_after>/**
 * Copyright 2015 aixigo AG
 * Released under the MIT license.
 * http://laxarjs.org/license
 */
define( [
   'angular'
], function( ng ) {
   'use strict';

   var directiveName = 'axGauge';

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   var gaugeDirective = [ '$document', '$interval', function( $document, $interval ) {
      var numInstances = 0;

      return {
         restrict: 'A',
         replace: true,
         template: template,
         transclude: true,
         scope: {
            value: '=' + directiveName,
            interval: '=' + directiveName + 'Interval'
         },
         link: function( scope, element, attrs ) {
            var defs = $document.find( '#ax-gauge-defs' );
            var fill = element.find( '.ax-gauge-fill' )[0];
            var glow = element.find( '.ax-gauge-glow' )[0];
            var progress = element.find( '.ax-gauge-progress' )[0];

            if( defs.length === 0 ) {
               defs = ng.element( svgGlobalDefs );
               $document.find( 'body' ).append( defs );
            }

            numInstances++;

            scope.active = scope.prev = scope.next = scope.length = 0;

            scope.$watch( 'value', function( newValue, oldValue ) {
               setGauge( fill, newValue );
               setGauge( glow, newValue );
            } );
            scope.$watch( 'active', function( newValue, oldValue ) {
               if( scope.length < 1 ) return;
               var start = (newValue / scope.length) * 1.5 * Math.PI;
               var angle = ((newValue + 1) / scope.length) * 1.5 * Math.PI;

               setArc( progress.pathSegList.getItem(1), angle );
            } );

            element.on( '$destroy', function() {
               if( --numInstances === 0 ) {
                  defs.remove();
               }
            } );
         },
         controller: function GaugeController( $scope ) {
            var panes = [];

            if( $scope.interval ) {
               var scrollInterval = $interval(function() {
                  setActivePane( $scope.active + 1 );
               }, $scope.interval );

               $scope.$on( '$destroy', $interval.cancel.bind( $interval, scrollInterval ) );
            }

            function setActivePane( num ) {
               var length = $scope.length = panes.length;

               panes.forEach( function( pane ) {
                  pane.active = pane.next = pane.prev = false;
               } );

               $scope.prev = $scope.active % length;
               $scope.active = num % length;
               $scope.next = (num + 1) % length;

               panes[ $scope.prev ].prev = true;
               panes[ $scope.active ].active = true;
               panes[ $scope.next ].next = true;
            };

            this.setActivePane = setActivePane;

            this.addPane = function addPane( scope ) {
               scope.next = scope.prev = false;
               scope.active = !(panes.length);
               panes.push( scope );
               $scope.length = panes.length;
            };

            this.removePane = function removePane( scope ) {
               scope.active = scope.next = scope.prev = false;
               panes.splice( panes.indexOf( scope ), 1 );
               $scope.length = panes.length;
            };
         }
      };
   } ];

   var gaugePaneDirective = [ function() {
      return {
         restrict: 'A',
         replace: true,
         require: '^' + directiveName,
         template: '

',
         scope: {},
         transclude: true,
         link: function( scope, element, attrs, gaugeCtrl ) {
            gaugeCtrl.addPane( scope );

            element.on( '$destroy', gaugeCtrl.removePane.bind( gaugeCtrl, scope ) );
         }
      };
   } ];

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   function setArc( pathSeg, rad ) {
      pathSeg.x = -Math.sin( rad ) * pathSeg.r1;
      pathSeg.y = Math.cos( rad ) * pathSeg.r2;
      pathSeg.sweepFlag = true;
      pathSeg.largeArcFlag = rad > Math.PI;
   }

   function setGauge( element, value ) {
      var rad = Math.PI * value * 1.5; // value = 1.0  -> rad = 270deg = 1.5rad
      setArc(element.pathSegList.getItem(1), rad);
   }

   var template = '' +
      '
' +
         '
' +
         '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewbox="-50 -50 100 100">' +
            '<g transform="rotate(45)">' +
               '<g mask="url(#ax-gauge-ring-mask)">' +
                  '<path class="ax-gauge-back" d="M 0 50 A 50 50 0 1 1 50 0 L 0 0 z" />' +
                  '<path class="ax-gauge-fill" d="M 0 50 A 50 50 0 1 0 0 50 L 0 0 z" />' +
               '</g>' +
               '<g filter="url(#ax-gauge-glow)">' +
                  '<path class="ax-gauge-glow" mask="url(#ax-gauge-ring-mask)"' +
                       ' d="M 0 50 A 50 50 0 1 0 0 50 L 0 0 z" />' +
               '</g>' +
               '<path class="ax-gauge-progress"' +
                    ' d="M 0 30 A 30 30 0 1 0 0 30" fill="none" />' +
            '</g>' +
         '</svg>' +
      '
';

   var svgGlobalDefs = '' +
      '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="0" height="0"' +
          ' style="position: absolute">' +
         '<defs id="ax-gauge-defs">' +
            '<mask id="ax-gauge-ring-mask" x="0" y="0" width="100" height="100">' +
               '<path fill="white" d="M 0 48 A 48 48 0 1 1 48 0 ' +
                                     'L 33 0 A 33 33 0 1 0 0 33 z" />' +
               '<path stroke="black" stroke-width="3"' +
                    ' d="M 0 50 L 0 0 ' +
                        'M -50 50 L 0 0 ' +
                        'M -50 0 L 0 0 ' +
                        'M -50 -50 L 0 0 ' +
                        'M 0 -50 L 0 0 ' +
                        'M 50 -50 L 0 0 ' +
                        'M 50 0 L 0 0" />' +
               '<path stroke="black" stroke-width="3" transform="rotate(22.5)"' +
                    ' d="M 0 50 L 0 0 ' +
                        'M -50 50 L 0 0 ' +
                        'M -50 0 L 0 0 ' +
                        'M -50 -50 L 0 0 ' +
                        'M 0 -50 L 0 0 ' +
                        'M 50 -50 L 0 0" />' +
            '</mask>' +
            '<filter id="ax-gauge-glow">' +
               '<feGaussianBlur in="SourceGraphic" stdDeviation="2" />' +
               '<feComponentTransfer>' +
                  '<feFuncA type="linear" slope="0.4" />' +
               '</feComponentTransfer>' +
               '<feBlend mode="screen" />' +
            '</filter>' +
            '<radialGradient id="ax-gauge-inner-fill">' +
               '<stop offset="85%" stop-color="white" />' +
               '<stop offset="100%" stop-color="black" />' +
            '</radialGradient>' +
            '<mask id="ax-gauge-inner-mask" maskUnits="objectBoundingBox" maskContentUnits="objectBoundingBox">' +
               '<circle cx=".5" cy=".5" r=".3" fill="url(#ax-gauge-inner-fill)" />' +
            '</mask>' +
         '</defs>' +
      '</svg>';

   return {
      createForModule: function( module ) {
         module.directive( directiveName, gaugeDirective );
         module.directive( directiveName + 'Pane', gaugePaneDirective );
      }
   };

} );
<|endoftext|>


<commit_before>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: go_dlink.js
 */

module.exports = {
    malloc: function (root_object_val) {
        return new GoBaseMgrClass(root_object_val);
    },
};

function GoBaseMgrClass(root_object_val) {
    "use strict";

    this.init__ = function (root_object_val) {
        this.theRootObject = root_object_val;
        this.debug(true, "init__", "");
    };

    this.objectName = function () {
        return "GoBaseMgrClass";
    };

    this.rootObject = function () {
        return this.theRootObject;
    };

    this.importObject = function () {
        return this.rootObject().importObject();
    };

    this.baseListObject = function () {
        return this.rootObject().baseListObject();
    };

    this.utilObject = function () {
        return this.rootObject().utilObject();
    };

    this.mallocBase = function () {
        var base = this.importObject().importBase().malloc(this.rootObject(), this.baseListObject().allocId());
        this.baseListObject().insertEntry(base);
        this.debug(false, "mallocBase", "baseId=" + base.baseId());
        return base.baseId();
    };

    this.receiveData = function (base_id_val, data_val) {
        this.debug(false, "receiveData", "data=" + data_val);
        var base = this.baseListObject().searchId(base_id_val);
        if (!base) {
            return;
        }
        base.portObject().receiveStringData(data_val);
    };

    this.transmitData = function (base_id_val) {
        var base = this.baseListObject().searchId(base_id_val);
        if (!base) {
            return null;
        }
        return base.portObject().dequeueTransmitData();
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.rootObject().LOG_IT(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.rootObject().ABEND(this.objectName() + "." + str1_val, str2_val);
    };

    this.init__(root_object_val);
}

<commit_msg>matrix<commit_after>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: go_dlink.js
 */

var the_go_base_mgr_object = null;

module.exports = {
    malloc: function (root_object_val) {
        the_go_base_mgr_object = new GoBaseMgrClass(root_object_val);
        return the_go_base_mgr_object;
    },

    get_the_go_base_mgr_object: function () {
        return the_go_base_mgr_object;
    },

    malloc_base: function () {
        return the_go_base_mgr_object.mallocBase();
    },

    receive_data: function (base_id_val, data_val) {
        the_go_base_mgr_object.receiveData(base_id_val, data_val);
    },

    transmit_data: function (base_id_val) {
        return the_go_base_mgr_object.transmitData(base_id_val);
    },
};

function GoBaseMgrClass(root_object_val) {
    "use strict";

    this.init__ = function (root_object_val) {
        this.theRootObject = root_object_val;
        this.debug(true, "init__", "");
    };

    this.objectName = function () {
        return "GoBaseMgrClass";
    };

    this.rootObject = function () {
        return this.theRootObject;
    };

    this.importObject = function () {
        return this.rootObject().importObject();
    };

    this.baseListObject = function () {
        return this.rootObject().baseListObject();
    };

    this.utilObject = function () {
        return this.rootObject().utilObject();
    };

    this.mallocBase = function () {
        var base = this.importObject().importBase().malloc(this.rootObject(), this.baseListObject().allocId());
        this.baseListObject().insertEntry(base);
        this.debug(false, "mallocBase", "baseId=" + base.baseId());
        return base.baseId();
    };

    this.receiveData = function (base_id_val, data_val) {
        this.debug(false, "receiveData", "data=" + data_val);
        var base = this.baseListObject().searchId(base_id_val);
        if (!base) {
            return;
        }
        base.portObject().receiveStringData(data_val);
    };

    this.transmitData = function (base_id_val) {
        var base = this.baseListObject().searchId(base_id_val);
        if (!base) {
            return null;
        }
        return base.portObject().dequeueTransmitData();
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.rootObject().LOG_IT(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.rootObject().ABEND(this.objectName() + "." + str1_val, str2_val);
    };

    this.init__(root_object_val);
}

<|endoftext|>