<commit_before>"use strict";

const expect = require("chai").expect;
const {
	findLinks,
	findLinksWithSchema,
} = require("../../../../../client/js/helpers/ircmessageparser/findLinks");

describe("findLinks", () => {
	it("should find url", () => {
		const input = "irc://irc.example.com/thelounge";
		const expected = [
			{
				start: 0,
				end: 28,
				link: "irc://irc.example.com/thelounge",
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls with www", () => {
		const input = "www.nooooooooooooooo.com";
		const expected = [
			{
				start: 0,
				end: 24,
				link: "http://www.nooooooooooooooo.com",
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls in strings", () => {
		const input = "look at https://thelounge.chat/ for more information";
		const expected = [
			{
				link: "https://thelounge.chat/",
				start: 8,
				end: 31,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls in strings starting with www", () => {
		const input = "use www.duckduckgo.com for privacy reasons";
		const expected = [
			{
				link: "http://www.duckduckgo.com",
				start: 4,
				end: 22,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls with odd surroundings", () => {
		const input = "<https://theos.kyriasis.com/~kyrias/stats/archlinux.html>";
		const expected = [
			{
				link: "https://theos.kyriasis.com/~kyrias/stats/archlinux.html",
				start: 1,
				end: 56,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls with starting with http:// and odd surroundings", () => {
		const input = ".:http://www.github.com:. .:www.github.com:.";
		const expected = [
			{
				link: "http://www.github.com",
				start: 2,
				end: 23,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should not find urls", () => {
		const input = "text www. text";
		const expected = [];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should handle multiple www. correctly", () => {
		const input = "www.www.test.com";
		const expected = [
			{
				link: "http://www.www.test.com",
				start: 0,
				end: 16,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find domains without www. but valid tld", () => {
		const input = "google.com google.lv google.museum";
		const expected = [
			{
				link: "http://google.com",
				start: 0,
				end: 10,
			},
			{
				link: "http://google.lv",
				start: 11,
				end: 20,
			},
			{
				link: "http://google.museum",
				start: 21,
				end: 34,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find .onion domains", () => {
		const input = "facebookcorewwwi.onion/test?url";
		const expected = [
			{
				link: "http://facebookcorewwwi.onion/test?url",
				start: 0,
				end: 31,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should not consider invalid TLDs as domains", () => {
		const input = "google.wtfgugl google.xx www.google.wtfgugl www.google.xx";
		const expected = [];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should consider invalid TLDs as domains if protocol is specified", () => {
		const input =
			"http://google.wtfgugl http://google.xx http://www.google.wtfgugl http://www.google.xx";
		const expected = [
			{
				link: "http://google.wtfgugl",
				start: 0,
				end: 21,
			},
			{
				link: "http://google.xx",
				start: 22,
				end: 38,
			},
			{
				link: "http://www.google.wtfgugl",
				start: 39,
				end: 64,
			},
			{
				link: "http://www.google.xx",
				start: 65,
				end: 85,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should correctly stop at punctuation", () => {
		// Issue #2351
		const input =
			"https://en.wikipedia.org/wiki/Dig! " +
			"https://en.wikipedia.org/wiki/Dig? " +
			"https://en.wikipedia.org/wiki/Dig. " +
			"https://www.google.com* " +
			"https://www.google.com/test* " +
			"https://www.google.com@ " +
			"https://www.google.com/test@ " +
			"https://www.google.com! ";
		const expected = [
			{
				link: "https://en.wikipedia.org/wiki/Dig",
				start: 0,
				end: 33,
			},
			{
				link: "https://en.wikipedia.org/wiki/Dig",
				start: 35,
				end: 68,
			},
			{
				link: "https://en.wikipedia.org/wiki/Dig",
				start: 70,
				end: 103,
			},
			{
				link: "https://www.google.com",
				start: 105,
				end: 127,
			},
			{
				link: "https://www.google.com/test*",
				start: 129,
				end: 157,
			},
			{
				link: "https://www.google.com",
				start: 158,
				end: 180,
			},
			{
				link: "https://www.google.com/test@",
				start: 182,
				end: 210,
			},
			{
				link: "https://www.google.com",
				start: 211,
				end: 233,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should correctly stop at apostrophe", () => {
		const input = "https://www.google.com's www.google.com's google.com's"; // Issue #1302
		const expected = [
			{
				link: "https://www.google.com",
				start: 0,
				end: 22,
			},
			{
				link: "http://www.google.com",
				start: 25,
				end: 39,
			},
			{
				link: "http://google.com",
				start: 42,
				end: 52,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("does not find invalid urls", () => {
		const input = "www.example.com ssh://-oProxyCommand=whois"; // Issue #1412
		const expected = [
			{
				start: 0,
				end: 15,
				link: "http://www.example.com",
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);

		const input2 = "www.example.com http://root:'some%pass'@hostname/database"; // Issue #1618
		const expected2 = [
			{
				start: 0,
				end: 15,
				link: "http://www.example.com",
			},
			{
				start: 16,
				end: 57,
				link: "http://root:'some%pass'@hostname/database",
			},
		];

		const actual2 = findLinks(input2);

		expect(actual2).to.deep.equal(expected2);
	});

	it("keeps parsing after finding an invalid url", () => {
		const input = "www.example.com http://a:%p@c http://thelounge.chat";
		const expected = [
			{
				start: 0,
				end: 15,
				link: "http://www.example.com",
			},
			{
				start: 16,
				end: 29,
				link: "http://a:%p@c",
			},
			{
				start: 30,
				end: 51,
				link: "http://thelounge.chat",
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should add protocol to protocol-aware urls", () => {
		const input = "//example.com";
		const expected = [
			{
				link: "http://example.com",
				start: 0,
				end: 13,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should not return urls with no schema if flag is specified", () => {
		const input = "https://example.global //example.com http://example.group example.py";
		const expected = [
			{
				link: "https://example.global",
				start: 0,
				end: 22,
			},
			{
				end: 57,
				link: "http://example.group",
				start: 37,
			},
		];

		const actual = findLinksWithSchema(input);

		expect(actual).to.deep.equal(expected);
	});
});
<commit_msg>Fix length of the link in tests<commit_after>"use strict";

const expect = require("chai").expect;
const {
	findLinks,
	findLinksWithSchema,
} = require("../../../../../client/js/helpers/ircmessageparser/findLinks");

describe("findLinks", () => {
	it("should find url", () => {
		const input = "irc://irc.example.com/thelounge";
		const expected = [
			{
				start: 0,
				end: 31,
				link: "irc://irc.example.com/thelounge",
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls with www", () => {
		const input = "www.nooooooooooooooo.com";
		const expected = [
			{
				start: 0,
				end: 24,
				link: "http://www.nooooooooooooooo.com",
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls in strings", () => {
		const input = "look at https://thelounge.chat/ for more information";
		const expected = [
			{
				link: "https://thelounge.chat/",
				start: 8,
				end: 31,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls in strings starting with www", () => {
		const input = "use www.duckduckgo.com for privacy reasons";
		const expected = [
			{
				link: "http://www.duckduckgo.com",
				start: 4,
				end: 22,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls with odd surroundings", () => {
		const input = "<https://theos.kyriasis.com/~kyrias/stats/archlinux.html>";
		const expected = [
			{
				link: "https://theos.kyriasis.com/~kyrias/stats/archlinux.html",
				start: 1,
				end: 56,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find urls with starting with http:// and odd surroundings", () => {
		const input = ".:http://www.github.com:. .:www.github.com:.";
		const expected = [
			{
				link: "http://www.github.com",
				start: 2,
				end: 23,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should not find urls", () => {
		const input = "text www. text";
		const expected = [];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should handle multiple www. correctly", () => {
		const input = "www.www.test.com";
		const expected = [
			{
				link: "http://www.www.test.com",
				start: 0,
				end: 16,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find domains without www. but valid tld", () => {
		const input = "google.com google.lv google.museum";
		const expected = [
			{
				link: "http://google.com",
				start: 0,
				end: 10,
			},
			{
				link: "http://google.lv",
				start: 11,
				end: 20,
			},
			{
				link: "http://google.museum",
				start: 21,
				end: 34,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should find .onion domains", () => {
		const input = "facebookcorewwwi.onion/test?url";
		const expected = [
			{
				link: "http://facebookcorewwwi.onion/test?url",
				start: 0,
				end: 31,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should not consider invalid TLDs as domains", () => {
		const input = "google.wtfgugl google.xx www.google.wtfgugl www.google.xx";
		const expected = [];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should consider invalid TLDs as domains if protocol is specified", () => {
		const input =
			"http://google.wtfgugl http://google.xx http://www.google.wtfgugl http://www.google.xx";
		const expected = [
			{
				link: "http://google.wtfgugl",
				start: 0,
				end: 21,
			},
			{
				link: "http://google.xx",
				start: 22,
				end: 38,
			},
			{
				link: "http://www.google.wtfgugl",
				start: 39,
				end: 64,
			},
			{
				link: "http://www.google.xx",
				start: 65,
				end: 85,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should correctly stop at punctuation", () => {
		// Issue #2351
		const input =
			"https://en.wikipedia.org/wiki/Dig! " +
			"https://en.wikipedia.org/wiki/Dig? " +
			"https://en.wikipedia.org/wiki/Dig. " +
			"https://www.google.com* " +
			"https://www.google.com/test* " +
			"https://www.google.com@ " +
			"https://www.google.com/test@ " +
			"https://www.google.com! ";
		const expected = [
			{
				link: "https://en.wikipedia.org/wiki/Dig",
				start: 0,
				end: 33,
			},
			{
				link: "https://en.wikipedia.org/wiki/Dig",
				start: 35,
				end: 68,
			},
			{
				link: "https://en.wikipedia.org/wiki/Dig",
				start: 70,
				end: 103,
			},
			{
				link: "https://www.google.com",
				start: 105,
				end: 127,
			},
			{
				link: "https://www.google.com/test*",
				start: 129,
				end: 157,
			},
			{
				link: "https://www.google.com",
				start: 158,
				end: 180,
			},
			{
				link: "https://www.google.com/test@",
				start: 182,
				end: 210,
			},
			{
				link: "https://www.google.com",
				start: 211,
				end: 233,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should correctly stop at apostrophe", () => {
		const input = "https://www.google.com's www.google.com's google.com's"; // Issue #1302
		const expected = [
			{
				link: "https://www.google.com",
				start: 0,
				end: 22,
			},
			{
				link: "http://www.google.com",
				start: 25,
				end: 39,
			},
			{
				link: "http://google.com",
				start: 42,
				end: 52,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("does not find invalid urls", () => {
		const input = "www.example.com ssh://-oProxyCommand=whois"; // Issue #1412
		const expected = [
			{
				start: 0,
				end: 15,
				link: "http://www.example.com",
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);

		const input2 = "www.example.com http://root:'some%pass'@hostname/database"; // Issue #1618
		const expected2 = [
			{
				start: 0,
				end: 15,
				link: "http://www.example.com",
			},
			{
				start: 16,
				end: 57,
				link: "http://root:'some%pass'@hostname/database",
			},
		];

		const actual2 = findLinks(input2);

		expect(actual2).to.deep.equal(expected2);
	});

	it("keeps parsing after finding an invalid url", () => {
		const input = "www.example.com http://a:%p@c http://thelounge.chat";
		const expected = [
			{
				start: 0,
				end: 15,
				link: "http://www.example.com",
			},
			{
				start: 16,
				end: 29,
				link: "http://a:%p@c",
			},
			{
				start: 30,
				end: 51,
				link: "http://thelounge.chat",
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should add protocol to protocol-aware urls", () => {
		const input = "//example.com";
		const expected = [
			{
				link: "http://example.com",
				start: 0,
				end: 13,
			},
		];

		const actual = findLinks(input);

		expect(actual).to.deep.equal(expected);
	});

	it("should not return urls with no schema if flag is specified", () => {
		const input = "https://example.global //example.com http://example.group example.py";
		const expected = [
			{
				link: "https://example.global",
				start: 0,
				end: 22,
			},
			{
				end: 57,
				link: "http://example.group",
				start: 37,
			},
		];

		const actual = findLinksWithSchema(input);

		expect(actual).to.deep.equal(expected);
	});
});
<|endoftext|>


<commit_before>const test = require('../../../..');

test.serial('first pass', t => {
	t.pass();
	return new Promise(resolve => setTimeout(resolve, 3000));
});

test.serial('second pass', t => {
	t.pass();
});

test('third pass', t => {
	t.pass();
});
<commit_msg>Increase timeout in fail-fast interrupt test<commit_after>const test = require('../../../..');

test.serial('first pass', t => {
	t.pass();
	return new Promise(resolve => setTimeout(resolve, 60000));
});

test.serial('second pass', t => {
	t.pass();
});

test('third pass', t => {
	t.pass();
});
<|endoftext|>


<commit_before>import {validatedResource} from '../../../src/decorator/validated-resource';
import {association} from '../../../src/decorator/association';
import {Entity} from '../../../src/entity';
import {ensure} from 'aurelia-validation';

  @validatedResource('assoc-validation')
export class WithAssociationValidation extends Entity {

  @ensure(it => it.hasAssociation())
  @association()
  foo = null;

  @association('custom')
  bar = null;
}
<commit_msg>test(validation): Fixed indentation mishap<commit_after>import {validatedResource} from '../../../src/decorator/validated-resource';
import {association} from '../../../src/decorator/association';
import {Entity} from '../../../src/entity';
import {ensure} from 'aurelia-validation';

@validatedResource('assoc-validation')
export class WithAssociationValidation extends Entity {

  @ensure(it => it.hasAssociation())
  @association()
  foo = null;

  @association('custom')
  bar = null;
}
<|endoftext|>


<commit_before>import { browser } from '../../';
import assert from 'assertive';

describe('forced screenshot', () => {
  before(browser.beforeHook());

  it('my test', () => {
    this.browser.navigateTo('/');
    // This is supposed to be failing, the real status code is 200
    assert.equal('statuscode', 418, browser.getStatusCode());
  });

  it('some !%#__(*.>:; sPecial  chars', () => {
    browser.navigateTo('/');
    // Supposed to be failing as well, actual text is "only one here"
    browser.assert.elementHasText('.only', 'not on the page');
  });

  it('does not fail', () => {
    // empty test should never fail
    // This makes sure that when everything is fine we do not take
    // screenshots
  });
});
<commit_msg>Fail for the right reasons in screenshot test<commit_after>import { browser } from '../../';
import assert from 'assertive';

describe('forced screenshot', () => {
  before(browser.beforeHook());

  it('my test', () => {
    browser.navigateTo('/');
    // This is supposed to be failing, the real status code is 200
    assert.equal('statuscode', 418, browser.getStatusCode());
  });

  it('some !%#__(*.>:; sPecial  chars', () => {
    browser.navigateTo('/');
    // Supposed to be failing as well, actual text is "only one here"
    browser.assert.elementHasText('.only', 'not on the page');
  });

  it('does not fail', () => {
    // empty test should never fail
    // This makes sure that when everything is fine we do not take
    // screenshots
  });
});
<|endoftext|>


<commit_before>// Abstract Persistence driver

'use strict';

var aFrom                 = require('es5-ext/array/from')
  , compact               = require('es5-ext/array/#/compact')
  , isCopy                = require('es5-ext/array/#/is-copy')
  , ensureArray           = require('es5-ext/array/valid-array')
  , assign                = require('es5-ext/object/assign')
  , ensureCallable        = require('es5-ext/object/valid-callable')
  , ensureObject          = require('es5-ext/object/valid-object')
  , ensureString          = require('es5-ext/object/validate-stringifiable-value')
  , isSet                 = require('es6-set/is-set')
  , ensureSet             = require('es6-set/valid-set')
  , memoizeMethods        = require('memoizee/methods')
  , deferred              = require('deferred')
  , emitError             = require('event-emitter/emit-error')
  , d                     = require('d')
  , autoBind              = require('d/auto-bind')
  , lazy                  = require('d/lazy')
  , debug                 = require('debug-ext')('db')
  , ee                    = require('event-emitter')
  , getStamp              = require('time-uuid/time')
  , ensureObservableSet   = require('observable-set/valid-observable-set')
  , ensureDatabase        = require('dbjs/valid-dbjs')
  , Event                 = require('dbjs/_setup/event')
  , unserializeValue      = require('dbjs/_setup/unserialize/value')
  , serializeValue        = require('dbjs/_setup/serialize/value')
  , serializeKey          = require('dbjs/_setup/serialize/key')
  , resolveKeyPath        = require('dbjs/_setup/utils/resolve-property-path')
  , ensureDriver          = require('./ensure')
  , resolveMultipleEvents = require('./lib/resolve-multiple-events')
  , resolveEventKeys      = require('./lib/resolve-event-keys')

  , isArray = Array.isArray
  , isObjectId = RegExp.prototype.test.bind(/^[0-9a-z][0-9a-zA-Z]*$/)
  , isDbId = RegExp.prototype.test.bind(/^[0-9a-z][^\n]*$/)
  , isModelId = RegExp.prototype.test.bind(/^[A-Z]/)
  , tokenize = resolveKeyPath.tokenize, resolveObject = resolveKeyPath.resolveObject
  , create = Object.create;

var PersistenceDriver = module.exports = Object.defineProperties(function (dbjs/*, options*/) {
	var autoSaveFilter, options;
	if (!(this instanceof PersistenceDriver)) return new PersistenceDriver(dbjs, arguments[1]);
	options = Object(arguments[1]);
	this.db = ensureDatabase(dbjs);
	autoSaveFilter = (options.autoSaveFilter != null)
		? ensureCallable(options.autoSaveFilter) : this.constructor.defaultAutoSaveFilter;
	dbjs.objects.on('update', this._dbjsListener = function (event) {
		if (event.sourceId === 'persistentLayer') return;
		if (!autoSaveFilter(event)) return;
		this._loadedEventsMap[event.object.__valueId__ + '.' + event.stamp] = true;
		++this._runningOperations;
		this._handleStoreEvent(event).finally(this._onOperationEnd).done();
	}.bind(this));
}, {
	defaultAutoSaveFilter: d(function (event) { return !isModelId(event.object.master.__id__); })
});

var notImplemented = function () { throw new Error("Not implemented"); };

var ensureObjectId = function (objId) {
	objId = ensureString(objId);
	if (!isObjectId(objId)) throw new TypeError(objId + " is not a database object id");
	return objId;
};

ee(Object.defineProperties(PersistenceDriver.prototype, assign({
	// Any data
	_getRaw: d(notImplemented),
	_getRawObject: d(notImplemented),
	_storeRaw: d(notImplemented),

	// Database data
	_importValue: d(function (id, value, stamp) {
		var proto;
		if (this._loadedEventsMap[id + '.' + stamp]) return;
		this._loadedEventsMap[id + '.' + stamp] = true;
		value = unserializeValue(value, this.db.objects);
		if (value && value.__id__ && (value.constructor.prototype === value)) proto = value.constructor;
		return new Event(this.db.objects.unserialize(id, proto), value, stamp, 'persistentLayer');
	}),
	getValue: d(function (id) {
		id = ensureString(id);
		if (!isDbId(id)) throw new TypeError(id + " is not a database value id");
		this._ensureOpen();
		++this._runningOperations;
		return this._getRaw(id).finally(this._onOperationEnd);
	}),
	getObject: d(function (objId/*, options*/) {
		var keyPaths, options = arguments[1];
		objId = ensureObjectId(objId);
		this._ensureOpen();
		++this._runningOperations;
		if (options && (options.keyPaths != null)) keyPaths = ensureSet(options.keyPaths);
		return this._getRawObject(objId, keyPaths).finally(this._onOperationEnd);
	}),
	loadValue: d(function (id) {
		return this.getValue(id)(function (data) {
			if (!data) return null;
			return this._importValue(id, data.value, data.stamp);
		}.bind(this));
	}),
	loadObject: d(function (objId) {
		return this.getObject(objId)(function (data) {
			return compact.call(data.map(function (data) {
				return this._importValue(data.id, data.data.value, data.data.stamp);
			}, this));
		}.bind(this));
	}),
	loadAll: d(function () {
		this._ensureOpen();
		++this._runningOperations;
		return this._loadAll().finally(this._onOperationEnd);
	}),
	_handleStoreEvent: d(function (event) {
		var id = event.object.__valueId__, ownerId = event.object.master.__id__
		  , targetPath = id.slice(ownerId.length + 1) || null
		  , nu = { value: serializeValue(event.value), stamp: event.stamp };
		var keyPath = (event.object._kind_ === 'item')
			? targetPath.slice(0, -(event.object._sKey_.length + 1)) : targetPath;
		return this._getRaw(id)(function (old) {
			var driverEvent;
			if (old && (old.stamp >= nu.stamp)) return;
			return this._storeEvent(ownerId, targetPath, nu).aside(function () {
				driverEvent = {
					id: id,
					ownerId: ownerId,
					keyPath: keyPath,
					data: nu,
					old: old
				};
				debug("direct update %s %s", id, event.stamp);
				this.emit('direct:' + keyPath, driverEvent);
			}.bind(this));
		}.bind(this));
	}),
	storeEvent: d(function (event) {
		event = ensureObject(event);
		this._ensureOpen();
		++this._runningOperations;
		return this._handleStoreEvent(event).finally(this._onOperationEnd);
	}),
	storeEvents: d(function (events) {
		events = ensureArray(events);
		this._ensureOpen();
		++this._runningOperations;
		return deferred.map(events, this._handleStoreEvent, this).finally(this._onOperationEnd);
	}),
	_storeEvent: d(notImplemented),

	// Indexed database data
	getIndexedValue: d(function (objId, keyPath) {
		++this._runningOperations;
		return this._getIndexedValue(ensureObjectId(objId), ensureString(keyPath))
			.finally(this._onOperationEnd);
	}),
	_getIndexedValue: d(notImplemented),
	_storeIndexedValue: d(notImplemented),

	// Custom data
	getCustom: d(function (key) {
		key = ensureString(key);
		this._ensureOpen();
		++this._runningOperations;
		return this._getCustom(key).finally(this._onOperationEnd);
	}),
	storeCustom: d(function (key, value) {
		key = ensureString(key);
		this._ensureOpen();
		++this._runningOperations;
		debug("custom update %s", key);
		return this._getCustom(key)(function (data) {
			if (data) {
				if (data.value === value) return;
				data.value = value;
				data.stamp = getStamp();
			} else {
				data = { value: value, stamp: getStamp() };
			}
			return this._storeCustom(ensureString(key), data);
		}.bind(this)).finally(this._onOperationEnd);
	}),
	_getCustom: d(notImplemented),
	_storeCustom: d(notImplemented),

	// Storage export/import
	export: d(function (externalStore) {
		ensureDriver(externalStore);
		this._ensureOpen();
		++this._runningOperations;
		return this._exportAll(externalStore).finally(this._onOperationEnd);
	}),
	_exportAll: d(notImplemented),

	// Clonnection related
	isClosed: d(false),
	close: d(function () {
		this._ensureOpen();
		this.isClosed = true;
		this.db.objects.off('update', this._dbjsListener);
		if (this._runningOperations) {
			this._closeDeferred = deferred();
			return this._closeDeferred.promise;
		}
		return this._close();
	}),
	_ensureOpen: d(function () {
		if (this.isClosed) throw new Error("Database not accessible");
	}),
	_close: d(notImplemented)
}, autoBind({
	emitError: d(emitError),
	_onOperationEnd: d(function () {
		if (--this._runningOperations) return;
		if (!this._closeDeferred) return;
		this._closeDeferred.resolve(this._close());
	})
}), lazy({
	_loadedEventsMap: d(function () { return create(null); })
}), memoizeMethods({
	indexKeyPath: d(function (name, set/*, options*/) {
		var names, key, onAdd, onDelete, eventName, listener, update, options = Object(arguments[2])
		  , keyPath = options.keyPath;
		name = ensureString(name);
		set = ensureObservableSet(set);
		if (!keyPath) keyPath = name;
		names = tokenize(ensureString(keyPath));
		this._ensureOpen();
		key = names[names.length - 1];
		eventName = 'index:' + name;
		update = function (ownerId, sValue, stamp) {
			return this._getIndexedValue(ownerId, keyPath)(function (old) {
				var nu;
				if (old) {
					if (old.stamp >= stamp) {
						if (isArray(sValue)) {
							if (isCopy.call(resolveEventKeys(old.value), sValue)) return deferred(null);
						} else {
							if (old.value === sValue) return deferred(null);
						}
						stamp = old.stamp + 1; // most likely model update
					}
				}
				nu = {
					value: isArray(sValue) ? resolveMultipleEvents(stamp, sValue) : sValue,
					stamp: stamp
				};
				return this._storeIndexedValue(ownerId, name, nu).aside(function () {
					var driverEvent;
					debug("computed update %s %s %s", ownerId, name, stamp);
					driverEvent = {
						ownerId: ownerId,
						name: name,
						data: nu,
						old: old
					};
					this.emit(eventName, driverEvent);
					this.emit('object:' + ownerId, driverEvent);
				}.bind(this));
			}.bind(this));
		}.bind(this);
		listener = function (event) {
			var sValue, stamp, ownerId = event.target.object.master.__id__;
			stamp = event.dbjs ? event.dbjs.stamp : getStamp();
			if (isSet(event.target)) {
				sValue = [];
				event.target.forEach(function (value) { sValue.push(serializeKey(value)); });
			} else {
				sValue = serializeValue(event.newValue);
			}
			++this._runningOperations;
			update(ownerId, sValue, stamp).finally(this._onOperationEnd).done();
		}.bind(this);
		onAdd = function (owner) {
			var ownerId = owner.__id__, obj = ensureObject(resolveObject(owner, names))
			  , observable, value, stamp, sValue;
			if (obj.isKeyStatic(key)) {
				value = obj[key];
				stamp = 0;
			} else {
				value = obj._get_(key);
				observable = obj._getObservable_(key);
				stamp = observable.lastModified;
				if (isSet(value)) value.on('change', listener);
				else observable.on('change', listener);
			}
			if (isSet(value)) {
				sValue = [];
				value.forEach(function (value) { sValue.push(serializeKey(value)); });
			} else {
				sValue = serializeValue(value);
			}
			return update(ownerId, sValue, stamp);
		}.bind(this);
		onDelete = function (owner) {
			var obj = resolveObject(owner, names);
			if (obj && !obj.isKeyStatic(key)) obj._getObservable_(key).off('change', listener);
			return update(owner.__id__, '', getStamp());
		}.bind(this);
		set.on('change', function (event) {
			if (event.type === 'add') {
				++this._runningOperations;
				onAdd(event.value).finally(this._onOperationEnd).done();
				return;
			}
			if (event.type === 'delete') {
				++this._runningOperations;
				onDelete(event.value).finally(this._onOperationEnd).done();
				return;
			}
			if (event.type === 'batch') {
				if (event.added) {
					++this._runningOperations;
					deferred.map(event.added, onAdd).finally(this._onOperationEnd).done();
				}
				if (event.deleted) {
					++this._runningOperations;
					deferred.map(event.deleted, onDelete).finally(this._onOperationEnd).done();
				}
			}
		}.bind(this));
		++this._runningOperations;
		return deferred.map(aFrom(set), onAdd).finally(this._onOperationEnd);
	}, { primitive: true, length: 1 })
}))));
<commit_msg>Return resolved data on custom store<commit_after>// Abstract Persistence driver

'use strict';

var aFrom                 = require('es5-ext/array/from')
  , compact               = require('es5-ext/array/#/compact')
  , isCopy                = require('es5-ext/array/#/is-copy')
  , ensureArray           = require('es5-ext/array/valid-array')
  , assign                = require('es5-ext/object/assign')
  , ensureCallable        = require('es5-ext/object/valid-callable')
  , ensureObject          = require('es5-ext/object/valid-object')
  , ensureString          = require('es5-ext/object/validate-stringifiable-value')
  , isSet                 = require('es6-set/is-set')
  , ensureSet             = require('es6-set/valid-set')
  , memoizeMethods        = require('memoizee/methods')
  , deferred              = require('deferred')
  , emitError             = require('event-emitter/emit-error')
  , d                     = require('d')
  , autoBind              = require('d/auto-bind')
  , lazy                  = require('d/lazy')
  , debug                 = require('debug-ext')('db')
  , ee                    = require('event-emitter')
  , getStamp              = require('time-uuid/time')
  , ensureObservableSet   = require('observable-set/valid-observable-set')
  , ensureDatabase        = require('dbjs/valid-dbjs')
  , Event                 = require('dbjs/_setup/event')
  , unserializeValue      = require('dbjs/_setup/unserialize/value')
  , serializeValue        = require('dbjs/_setup/serialize/value')
  , serializeKey          = require('dbjs/_setup/serialize/key')
  , resolveKeyPath        = require('dbjs/_setup/utils/resolve-property-path')
  , ensureDriver          = require('./ensure')
  , resolveMultipleEvents = require('./lib/resolve-multiple-events')
  , resolveEventKeys      = require('./lib/resolve-event-keys')

  , isArray = Array.isArray
  , isObjectId = RegExp.prototype.test.bind(/^[0-9a-z][0-9a-zA-Z]*$/)
  , isDbId = RegExp.prototype.test.bind(/^[0-9a-z][^\n]*$/)
  , isModelId = RegExp.prototype.test.bind(/^[A-Z]/)
  , tokenize = resolveKeyPath.tokenize, resolveObject = resolveKeyPath.resolveObject
  , create = Object.create;

var PersistenceDriver = module.exports = Object.defineProperties(function (dbjs/*, options*/) {
	var autoSaveFilter, options;
	if (!(this instanceof PersistenceDriver)) return new PersistenceDriver(dbjs, arguments[1]);
	options = Object(arguments[1]);
	this.db = ensureDatabase(dbjs);
	autoSaveFilter = (options.autoSaveFilter != null)
		? ensureCallable(options.autoSaveFilter) : this.constructor.defaultAutoSaveFilter;
	dbjs.objects.on('update', this._dbjsListener = function (event) {
		if (event.sourceId === 'persistentLayer') return;
		if (!autoSaveFilter(event)) return;
		this._loadedEventsMap[event.object.__valueId__ + '.' + event.stamp] = true;
		++this._runningOperations;
		this._handleStoreEvent(event).finally(this._onOperationEnd).done();
	}.bind(this));
}, {
	defaultAutoSaveFilter: d(function (event) { return !isModelId(event.object.master.__id__); })
});

var notImplemented = function () { throw new Error("Not implemented"); };

var ensureObjectId = function (objId) {
	objId = ensureString(objId);
	if (!isObjectId(objId)) throw new TypeError(objId + " is not a database object id");
	return objId;
};

ee(Object.defineProperties(PersistenceDriver.prototype, assign({
	// Any data
	_getRaw: d(notImplemented),
	_getRawObject: d(notImplemented),
	_storeRaw: d(notImplemented),

	// Database data
	_importValue: d(function (id, value, stamp) {
		var proto;
		if (this._loadedEventsMap[id + '.' + stamp]) return;
		this._loadedEventsMap[id + '.' + stamp] = true;
		value = unserializeValue(value, this.db.objects);
		if (value && value.__id__ && (value.constructor.prototype === value)) proto = value.constructor;
		return new Event(this.db.objects.unserialize(id, proto), value, stamp, 'persistentLayer');
	}),
	getValue: d(function (id) {
		id = ensureString(id);
		if (!isDbId(id)) throw new TypeError(id + " is not a database value id");
		this._ensureOpen();
		++this._runningOperations;
		return this._getRaw(id).finally(this._onOperationEnd);
	}),
	getObject: d(function (objId/*, options*/) {
		var keyPaths, options = arguments[1];
		objId = ensureObjectId(objId);
		this._ensureOpen();
		++this._runningOperations;
		if (options && (options.keyPaths != null)) keyPaths = ensureSet(options.keyPaths);
		return this._getRawObject(objId, keyPaths).finally(this._onOperationEnd);
	}),
	loadValue: d(function (id) {
		return this.getValue(id)(function (data) {
			if (!data) return null;
			return this._importValue(id, data.value, data.stamp);
		}.bind(this));
	}),
	loadObject: d(function (objId) {
		return this.getObject(objId)(function (data) {
			return compact.call(data.map(function (data) {
				return this._importValue(data.id, data.data.value, data.data.stamp);
			}, this));
		}.bind(this));
	}),
	loadAll: d(function () {
		this._ensureOpen();
		++this._runningOperations;
		return this._loadAll().finally(this._onOperationEnd);
	}),
	_handleStoreEvent: d(function (event) {
		var id = event.object.__valueId__, ownerId = event.object.master.__id__
		  , targetPath = id.slice(ownerId.length + 1) || null
		  , nu = { value: serializeValue(event.value), stamp: event.stamp };
		var keyPath = (event.object._kind_ === 'item')
			? targetPath.slice(0, -(event.object._sKey_.length + 1)) : targetPath;
		return this._getRaw(id)(function (old) {
			var driverEvent;
			if (old && (old.stamp >= nu.stamp)) return;
			return this._storeEvent(ownerId, targetPath, nu).aside(function () {
				driverEvent = {
					id: id,
					ownerId: ownerId,
					keyPath: keyPath,
					data: nu,
					old: old
				};
				debug("direct update %s %s", id, event.stamp);
				this.emit('direct:' + keyPath, driverEvent);
			}.bind(this));
		}.bind(this));
	}),
	storeEvent: d(function (event) {
		event = ensureObject(event);
		this._ensureOpen();
		++this._runningOperations;
		return this._handleStoreEvent(event).finally(this._onOperationEnd);
	}),
	storeEvents: d(function (events) {
		events = ensureArray(events);
		this._ensureOpen();
		++this._runningOperations;
		return deferred.map(events, this._handleStoreEvent, this).finally(this._onOperationEnd);
	}),
	_storeEvent: d(notImplemented),

	// Indexed database data
	getIndexedValue: d(function (objId, keyPath) {
		++this._runningOperations;
		return this._getIndexedValue(ensureObjectId(objId), ensureString(keyPath))
			.finally(this._onOperationEnd);
	}),
	_getIndexedValue: d(notImplemented),
	_storeIndexedValue: d(notImplemented),

	// Custom data
	getCustom: d(function (key) {
		key = ensureString(key);
		this._ensureOpen();
		++this._runningOperations;
		return this._getCustom(key).finally(this._onOperationEnd);
	}),
	storeCustom: d(function (key, value) {
		key = ensureString(key);
		this._ensureOpen();
		++this._runningOperations;
		debug("custom update %s", key);
		return this._getCustom(key)(function (data) {
			if (data) {
				if (data.value === value) return;
				data.value = value;
				data.stamp = getStamp();
			} else {
				data = { value: value, stamp: getStamp() };
			}
			return this._storeCustom(ensureString(key), data)(data);
		}.bind(this)).finally(this._onOperationEnd);
	}),
	_getCustom: d(notImplemented),
	_storeCustom: d(notImplemented),

	// Storage export/import
	export: d(function (externalStore) {
		ensureDriver(externalStore);
		this._ensureOpen();
		++this._runningOperations;
		return this._exportAll(externalStore).finally(this._onOperationEnd);
	}),
	_exportAll: d(notImplemented),

	// Clonnection related
	isClosed: d(false),
	close: d(function () {
		this._ensureOpen();
		this.isClosed = true;
		this.db.objects.off('update', this._dbjsListener);
		if (this._runningOperations) {
			this._closeDeferred = deferred();
			return this._closeDeferred.promise;
		}
		return this._close();
	}),
	_ensureOpen: d(function () {
		if (this.isClosed) throw new Error("Database not accessible");
	}),
	_close: d(notImplemented)
}, autoBind({
	emitError: d(emitError),
	_onOperationEnd: d(function () {
		if (--this._runningOperations) return;
		if (!this._closeDeferred) return;
		this._closeDeferred.resolve(this._close());
	})
}), lazy({
	_loadedEventsMap: d(function () { return create(null); })
}), memoizeMethods({
	indexKeyPath: d(function (name, set/*, options*/) {
		var names, key, onAdd, onDelete, eventName, listener, update, options = Object(arguments[2])
		  , keyPath = options.keyPath;
		name = ensureString(name);
		set = ensureObservableSet(set);
		if (!keyPath) keyPath = name;
		names = tokenize(ensureString(keyPath));
		this._ensureOpen();
		key = names[names.length - 1];
		eventName = 'index:' + name;
		update = function (ownerId, sValue, stamp) {
			return this._getIndexedValue(ownerId, keyPath)(function (old) {
				var nu;
				if (old) {
					if (old.stamp >= stamp) {
						if (isArray(sValue)) {
							if (isCopy.call(resolveEventKeys(old.value), sValue)) return deferred(null);
						} else {
							if (old.value === sValue) return deferred(null);
						}
						stamp = old.stamp + 1; // most likely model update
					}
				}
				nu = {
					value: isArray(sValue) ? resolveMultipleEvents(stamp, sValue) : sValue,
					stamp: stamp
				};
				return this._storeIndexedValue(ownerId, name, nu).aside(function () {
					var driverEvent;
					debug("computed update %s %s %s", ownerId, name, stamp);
					driverEvent = {
						ownerId: ownerId,
						name: name,
						data: nu,
						old: old
					};
					this.emit(eventName, driverEvent);
					this.emit('object:' + ownerId, driverEvent);
				}.bind(this));
			}.bind(this));
		}.bind(this);
		listener = function (event) {
			var sValue, stamp, ownerId = event.target.object.master.__id__;
			stamp = event.dbjs ? event.dbjs.stamp : getStamp();
			if (isSet(event.target)) {
				sValue = [];
				event.target.forEach(function (value) { sValue.push(serializeKey(value)); });
			} else {
				sValue = serializeValue(event.newValue);
			}
			++this._runningOperations;
			update(ownerId, sValue, stamp).finally(this._onOperationEnd).done();
		}.bind(this);
		onAdd = function (owner) {
			var ownerId = owner.__id__, obj = ensureObject(resolveObject(owner, names))
			  , observable, value, stamp, sValue;
			if (obj.isKeyStatic(key)) {
				value = obj[key];
				stamp = 0;
			} else {
				value = obj._get_(key);
				observable = obj._getObservable_(key);
				stamp = observable.lastModified;
				if (isSet(value)) value.on('change', listener);
				else observable.on('change', listener);
			}
			if (isSet(value)) {
				sValue = [];
				value.forEach(function (value) { sValue.push(serializeKey(value)); });
			} else {
				sValue = serializeValue(value);
			}
			return update(ownerId, sValue, stamp);
		}.bind(this);
		onDelete = function (owner) {
			var obj = resolveObject(owner, names);
			if (obj && !obj.isKeyStatic(key)) obj._getObservable_(key).off('change', listener);
			return update(owner.__id__, '', getStamp());
		}.bind(this);
		set.on('change', function (event) {
			if (event.type === 'add') {
				++this._runningOperations;
				onAdd(event.value).finally(this._onOperationEnd).done();
				return;
			}
			if (event.type === 'delete') {
				++this._runningOperations;
				onDelete(event.value).finally(this._onOperationEnd).done();
				return;
			}
			if (event.type === 'batch') {
				if (event.added) {
					++this._runningOperations;
					deferred.map(event.added, onAdd).finally(this._onOperationEnd).done();
				}
				if (event.deleted) {
					++this._runningOperations;
					deferred.map(event.deleted, onDelete).finally(this._onOperationEnd).done();
				}
			}
		}.bind(this));
		++this._runningOperations;
		return deferred.map(aFrom(set), onAdd).finally(this._onOperationEnd);
	}, { primitive: true, length: 1 })
}))));
<|endoftext|>


<commit_before>module.exports = addCache;
function addCache(repo, hashCache) {
  var loadAs = repo.loadAs;
  var load = repo.load;
  var pending = {};

  repo.loadAs = loadAsCached;
  repo.load = loadCached;

  function loadAsCached(type, hash, callback) {
    if (!callback) return loadAsCached.bind(this, type, hash);
    if (hash in pending) return pending[hash].push(onObject);
    pending[hash] = [onObject];
    var object;
    hashCache.get(hash, onCache);
    function onCache(err, result) {
      if (err) return onDone(err);
      if (result) {
        if (result.type !== type) return onDone(new Error("Type mismatch"));
        object = result;
        return onDone();
      }
      return loadAs.call(repo, type, hash, onLoad);
    }
    function onLoad(err, result) {
      if (result === undefined) return onDone(err);
      object = {type: type, body: result};
      hashCache.set(hash, object, onDone);
    }
    function onDone(err) {
      flush(hash, err, object);
    }
    function onObject(err, object) {
      if (!object) return callback(err);
      callback(null, object.body);
    }
  }

  function loadCached(hash, callback) {
    if (!callback) return loadCached.bind(this, hash);
    if (hash in pending) return pending[hash].push(callback);
    pending[hash] = [callback];
    var object;
    hashCache.get(hash, onCache);
    function onCache(err, result) {
      if (err) return onDone(err);
      if (result) {
        object = result;
        return onDone();
      }
      load.call(repo, hash, onLoad);
    }
    function onLoad(err, result) {
      if (result === undefined) return onDone(err);
      object = result;
      hashCache.set(hash, object, onDone);
    }
    function onDone(err) {
      flush(hash, err, object);
    }
  }

  function flush(hash, err, object) {
    var callbacks = pending[hash];
    delete pending[hash];
    for (var i = 0, l = callbacks.length; i < l; i++) {
      callbacks[i](err, object);
    }
  }

}
<commit_msg>Fix type changed in cache<commit_after>module.exports = addCache;
function addCache(repo, hashCache) {
  var loadAs = repo.loadAs;
  var load = repo.load;
  var pending = {};

  repo.loadAs = loadAsCached;
  repo.load = loadCached;

  function loadAsCached(type, hash, callback) {
    if (!callback) return loadAsCached.bind(this, type, hash);
    if (hash in pending) return pending[hash].push(onObject);
    pending[hash] = [onObject];
    var object;
    hashCache.get(hash, onCache);
    function onCache(err, result) {
      if (err) return onDone(err);
      if (result) {
        if (result.type === "text" && type === "blob") {
          result.body = new Buffer(result.body);
          result.type = "blob";
        }
        else if (result.type === "blob" && type === "text") {
          result.body = result.body.toString();
          result.type = "text";
        }
        if (result.type !== type) return onDone(new Error("Type mismatch"));
        object = result;
        return onDone();
      }
      return loadAs.call(repo, type, hash, onLoad);
    }
    function onLoad(err, result) {
      if (result === undefined) return onDone(err);
      object = {type: type, body: result};
      hashCache.set(hash, object, onDone);
    }
    function onDone(err) {
      flush(hash, err, object);
    }
    function onObject(err, object) {
      if (!object) return callback(err);
      callback(null, object.body);
    }
  }

  function loadCached(hash, callback) {
    if (!callback) return loadCached.bind(this, hash);
    if (hash in pending) return pending[hash].push(callback);
    pending[hash] = [callback];
    var object;
    hashCache.get(hash, onCache);
    function onCache(err, result) {
      if (err) return onDone(err);
      if (result) {
        object = result;
        return onDone();
      }
      load.call(repo, hash, onLoad);
    }
    function onLoad(err, result) {
      if (result === undefined) return onDone(err);
      object = result;
      hashCache.set(hash, object, onDone);
    }
    function onDone(err) {
      flush(hash, err, object);
    }
  }

  function flush(hash, err, object) {
    var callbacks = pending[hash];
    delete pending[hash];
    for (var i = 0, l = callbacks.length; i < l; i++) {
      callbacks[i](err, object);
    }
  }

}
<|endoftext|>


<commit_before>const uuid = require('uuid');
const request = require('request-promise-native');

let params;

function initialize(paramsIn) {
  params = paramsIn;
}

function url() {
  return `https://voltage.sebacon.net/SebaconAPI/?auth=${params.auth}`;
}

function getMetaList(meta) {
  return request.post({
    url: url(),
    auth: {
      user: `${params.customer}\\${params.user}`,
      pass: `${params.password}`
    },
    json: {
      id: uuid.v4(),
      jsonrpc: '2.0',
      method: 'getApplicationObjectMeta',
      params: [ meta ]
    }
  }).then(res => {
    const obj = {};
    res.result.forEach(o => {
      const str = o.otsikko;
      obj[o.id] = str.charAt(0).toLocaleUpperCase() + str.slice(1).toLocaleLowerCase();
    });
    return obj;
  })
}

function getPositionTitles() {
  return getMetaList('tehtavanimikkeet');
}

function getDomainTitles() {
  return getMetaList('sopimusalat');
}

function getUserEmploymentHistory(id) {
  return request.post({
    url: url(),
    auth: {
      user: `${params.customer}\\${params.user}`,
      pass: `${params.password}`
    },
    json: {
      id: uuid.v4(),
      jsonrpc: '2.0',
      method: 'getPersonObject',
      params: [
        id,
        'tyosuhteet'
      ]
    }
  });
}

function getUserDomains(id) {
  return Promise.all([
    getDomainTitles(),
    getUserEmploymentHistory(id)
  ]).then(([ titles, res ]) =>
          res.result
          .map(o => titles[o.sopimusala])
          .filter(x => x));
}

function getUserEmploymentExtras(id) {
  return Promise.all([
    getDomainTitles(),
    getPositionTitles(),
    getUserEmploymentHistory(id)
  ]).then(([ domainTitles, positionTitles, res ]) => {
    const organisations = Promise.all(
      res.result.map(o => getOrganisation(o.tyonantaja).then(o => o.name || 'Tuntematon')));
    return Promise.all([ domainTitles, positionTitles, res, organisations ]);
  }).then(([ domainTitles, positionTitles, res, organisations ]) => {
    return {
      domains: res.result
        .map((o, i) => (domainTitles[o.sopimusala] || 'Tuntematon') +
             ` (${organisations[i]})`
            ),
      positions: res.result
        .map((o, i) => (positionTitles[o.tehtavanimike_val] || 'Tuntematon') +
             ` (${organisations[i]})`
            )
    }
  })
}

function getUserPositions(id) {
  return Promise.all([
    getPositionTitles(),
    getUserEmploymentHistory(id)
  ]).then(([ titles, res ]) =>
          res.result
            .map(o => titles[o.tehtavanimike_val])
            .filter(x => x));
}

function getUser(id) {
  return getObject(id, 'getPersonObject');
}

function getOrganisation(id) {
  return getObject(id, 'getOrganisationObject');
}

function getObject(id, method) {
  return request.post({
    url: url(),
    auth: {
      user: `${params.customer}\\${params.user}`,
      pass: `${params.password}`
    },
    json: {
      id: uuid.v4(),
      jsonrpc: '2.0',
      method,
      params: [
        id
      ]
    }
  });
}

function getUserFirstName(id) {
  return getUser(id)
    .then(res => res.result.firstname || '');
}

function getUserNickName(id) {
  return getUser(id)
    .then(res => res.result.kutsumanimi || '');
}

module.exports = {
  getUserPositions,
  getUserFirstName,
  getUserNickName,
  getUserDomains,
  getUserEmploymentExtras,
  getPositionTitles,
  getDomainTitles,
  initialize
}
<commit_msg>Get employer name from proper place<commit_after>const uuid = require('uuid');
const request = require('request-promise-native');

let params;

function initialize(paramsIn) {
  params = paramsIn;
}

function url() {
  return `https://voltage.sebacon.net/SebaconAPI/?auth=${params.auth}`;
}

function getMetaList(meta) {
  return request.post({
    url: url(),
    auth: {
      user: `${params.customer}\\${params.user}`,
      pass: `${params.password}`
    },
    json: {
      id: uuid.v4(),
      jsonrpc: '2.0',
      method: 'getApplicationObjectMeta',
      params: [ meta ]
    }
  }).then(res => {
    const obj = {};
    res.result.forEach(o => {
      const str = o.otsikko;
      obj[o.id] = str.charAt(0).toLocaleUpperCase() + str.slice(1).toLocaleLowerCase();
    });
    return obj;
  })
}

function getPositionTitles() {
  return getMetaList('tehtavanimikkeet');
}

function getDomainTitles() {
  return getMetaList('sopimusalat');
}

function getUserEmploymentHistory(id) {
  return request.post({
    url: url(),
    auth: {
      user: `${params.customer}\\${params.user}`,
      pass: `${params.password}`
    },
    json: {
      id: uuid.v4(),
      jsonrpc: '2.0',
      method: 'getPersonObject',
      params: [
        id,
        'tyosuhteet'
      ]
    }
  });
}

function getUserDomains(id) {
  return Promise.all([
    getDomainTitles(),
    getUserEmploymentHistory(id)
  ]).then(([ titles, res ]) =>
          res.result
          .map(o => titles[o.sopimusala])
          .filter(x => x));
}

function getUserEmploymentExtras(id) {
  return Promise.all([
    getDomainTitles(),
    getPositionTitles(),
    getUserEmploymentHistory(id)
  ]).then(([ domainTitles, positionTitles, res ]) => {
    const organisations = Promise.all(
      res.result.map(o => getOrganisation(o.tyonantaja).then(o => o.result.name || 'Tuntematon')));
    return Promise.all([ domainTitles, positionTitles, res, organisations ]);
  }).then(([ domainTitles, positionTitles, res, organisations ]) => {
    return {
      domains: res.result
        .map((o, i) => (domainTitles[o.sopimusala] || 'Tuntematon') +
             ` (${organisations[i]})`
            ),
      positions: res.result
        .map((o, i) => (positionTitles[o.tehtavanimike_val] || 'Tuntematon') +
             ` (${organisations[i]})`
            )
    }
  })
}

function getUserPositions(id) {
  return Promise.all([
    getPositionTitles(),
    getUserEmploymentHistory(id)
  ]).then(([ titles, res ]) =>
          res.result
            .map(o => titles[o.tehtavanimike_val])
            .filter(x => x));
}

function getUser(id) {
  return getObject(id, 'getPersonObject');
}

function getOrganisation(id) {
  return getObject(id, 'getOrganisationObject');
}

function getObject(id, method) {
  return request.post({
    url: url(),
    auth: {
      user: `${params.customer}\\${params.user}`,
      pass: `${params.password}`
    },
    json: {
      id: uuid.v4(),
      jsonrpc: '2.0',
      method,
      params: [
        id
      ]
    }
  });
}

function getUserFirstName(id) {
  return getUser(id)
    .then(res => res.result.firstname || '');
}

function getUserNickName(id) {
  return getUser(id)
    .then(res => res.result.kutsumanimi || '');
}

module.exports = {
  getUserPositions,
  getUserFirstName,
  getUserNickName,
  getUserDomains,
  getUserEmploymentExtras,
  getPositionTitles,
  getDomainTitles,
  initialize
}
<|endoftext|>


<commit_before>/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.3
 *
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },

    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },

    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});

function handler(event) {
    var orgEvent = event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;

    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(event || window.event);
    event.type = "mousewheel";

    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }

    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;

    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }

    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }

    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);

    return $.event.handle.apply(this, args);
}

})(jQuery);<commit_msg>Touch up patch for IE issue<commit_after>/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.3
 *
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },

    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },

    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});

function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";

    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }

    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;

    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }

    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }

    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);

    return $.event.handle.apply(this, args);
}

})(jQuery);<|endoftext|>


<commit_before>import * as React from "react";

// TODO: Make a generic little console for some of the styled container pieces,
//       then make this component inject the binder specific bits
export class BinderConsole extends React.Component {
  render() {
    const {
      logs,
      onFormSubmit,
      onGitrefChange,
      onRepoChange,
      repo,
      gitref
    } = this.props;
    return (

          <form onSubmit={onFormSubmit} className="form">

              GitHub Repo:
              <input
                onChange={onRepoChange}
                type="text"
                name="repo"
                value={repo}
              />

              Branch/commit:
              <input
                onChange={onGitrefChange}
                type="text"
                name="gitref"
                value={gitref}
              />

            <button type="submit"> Submit</button>
          </form>

        {logs.length > 0
          ? logs.map((log, index) => {
              return (

                  {log.phase}

                    {log.message}

              );
            })
          : null}

    );
  }
}
<commit_msg>change to use fieldset and use element type to style<commit_after>import * as React from "react";

// TODO: Make a generic little console for some of the styled container pieces,
//       then make this component inject the binder specific bits
export class BinderConsole extends React.Component {
  render() {
    const {
      logs,
      onFormSubmit,
      onGitrefChange,
      onRepoChange,
      repo,
      gitref
    } = this.props;
    return (

          <form onSubmit={onFormSubmit} className="form">
            <fieldset>
              GitHub Repo:
              <input
                id="repoInput"
                onChange={onRepoChange}
                type="text"
                name="repo"
                value={repo}
              />
              Branch/commit:
              <input
                id="gitrefInput"
                onChange={onGitrefChange}
                type="text"
                name="gitref"
                value={gitref}
              />
              <button type="submit"> Submit</button>
            </fieldset>
          </form>

        {logs.length > 0
          ? logs.map((log, index) => {
              return (

                  {log.phase}

                    {log.message}

              );
            })
          : null}

    );
  }
}
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import { MemoryRouter, Route } from 'react-router';
import LocationInterceptor from './LocationInterceptor';
import urlParser from 'url';

import type { ProxyProps } from 'react-cosmos-flow/proxy';

export function createRouterProxy() {
  const RouterProxy = (props: ProxyProps) => {
    const { nextProxy, fixture, onFixtureUpdate } = props;
    const { value: NextProxy, next } = nextProxy;
    const { route, url, locationState, provideRouterProps } = fixture;
    const nextProxyEl = <NextProxy {...props} nextProxy={next()} />;

    if (locationState && !url) {
      throw new Error('Must provide a url in fixture to use locationState');
    }

    if (!url) {
      return nextProxyEl;
    }

    const handleUrlChange = url => {
      onFixtureUpdate({ url });
    };

    const handleLocationStateChange = locationState => {
      onFixtureUpdate({ locationState });
    };

    const location = buildLocation(url, locationState);

    return (
      <MemoryRouter keyLength={0} initialEntries={[location]}>
        <LocationInterceptor
          onUrlChange={handleUrlChange}
          onLocationStateChange={handleLocationStateChange}
        >
          {route ? (
            <Route
              path={route}
              render={routerProps => {
                if (provideRouterProps) {
                  const newProxyProps = {
                    ...props,
                    fixture: {
                      ...props.fixture,
                      props: { ...props.fixture.props, ...routerProps }
                    }
                  };
                  return <NextProxy {...newProxyProps} nextProxy={next()} />;
                }

                return nextProxyEl;
              }}
            />
          ) : (
            nextProxyEl
          )}
        </LocationInterceptor>
      </MemoryRouter>
    );
  };

  return RouterProxy;
}

function buildLocation(url, locationState) {
  const { pathname, search, hash } = urlParser.parse(url);
  return {
    pathname,
    search,
    hash,
    key: 'mocked',
    state: locationState
  };
}
<commit_msg>Document keyLength props<commit_after>// @flow

import React from 'react';
import { MemoryRouter, Route } from 'react-router';
import LocationInterceptor from './LocationInterceptor';
import urlParser from 'url';

import type { ProxyProps } from 'react-cosmos-flow/proxy';

export function createRouterProxy() {
  const RouterProxy = (props: ProxyProps) => {
    const { nextProxy, fixture, onFixtureUpdate } = props;
    const { value: NextProxy, next } = nextProxy;
    const { route, url, locationState, provideRouterProps } = fixture;
    const nextProxyEl = <NextProxy {...props} nextProxy={next()} />;

    if (locationState && !url) {
      throw new Error('Must provide a url in fixture to use locationState');
    }

    if (!url) {
      return nextProxyEl;
    }

    const handleUrlChange = url => {
      onFixtureUpdate({ url });
    };

    const handleLocationStateChange = locationState => {
      onFixtureUpdate({ locationState });
    };

    const location = buildLocation(url, locationState);

    return (
      // keyLength=0 generates empty "" history keys, leading to deterministic
      // test snapshots https://github.com/react-cosmos/react-cosmos/pull/803
      <MemoryRouter keyLength={0} initialEntries={[location]}>
        <LocationInterceptor
          onUrlChange={handleUrlChange}
          onLocationStateChange={handleLocationStateChange}
        >
          {route ? (
            <Route
              path={route}
              render={routerProps => {
                if (provideRouterProps) {
                  const newProxyProps = {
                    ...props,
                    fixture: {
                      ...props.fixture,
                      props: { ...props.fixture.props, ...routerProps }
                    }
                  };
                  return <NextProxy {...newProxyProps} nextProxy={next()} />;
                }

                return nextProxyEl;
              }}
            />
          ) : (
            nextProxyEl
          )}
        </LocationInterceptor>
      </MemoryRouter>
    );
  };

  return RouterProxy;
}

function buildLocation(url, locationState) {
  const { pathname, search, hash } = urlParser.parse(url);
  return {
    pathname,
    search,
    hash,
    key: 'mocked',
    state: locationState
  };
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2013  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// WidgetModel, WidgetView, and WidgetManager
//============================================================================
/**
 * Base Widget classes
 * @module IPython
 * @namespace IPython
 * @submodule widget
 */

(function () {
    "use strict";

    // Use require.js 'define' method so that require.js is intelligent enough to
    // syncronously load everything within this file when it is being 'required'
    // elsewhere.
    define(["underscore",
             "backbone",
            ], function (underscore, backbone) {

        Backbone.sync = function (method, model, options, error) {
            var result = model._handle_sync(method, options);
            if (options.success) {
              options.success(result);
            }
        };

        //--------------------------------------------------------------------
        // WidgetManager class
        //--------------------------------------------------------------------
        var WidgetManager = function () {
            this.comm_manager = null;
            this._model_types = {}; /* Dictionary of model type names
                                      (target_name) and model types. */
            this._view_types = {}; /* Dictionary of view names and view types. */
            this._models = {}; /* Dictionary of model ids and model instances */
        };

        WidgetManager.prototype.attach_comm_manager = function (comm_manager) {
            this.comm_manager = comm_manager;

            // Register already-registered widget model types with the comm manager.
            for (var widget_model_name in this._model_types) {
                this.comm_manager.register_target(widget_model_name, $.proxy(this._handle_comm_open, this));
            }
        };

        WidgetManager.prototype.register_widget_model = function (widget_model_name, widget_model_type) {
            // Register the widget with the comm manager.  Make sure to pass this object's context
            // in so `this` works in the call back.
            if (this.comm_manager !== null) {
                this.comm_manager.register_target(widget_model_name, $.proxy(this._handle_comm_open, this));
            }
            this._model_types[widget_model_name] = widget_model_type;
        };

        WidgetManager.prototype.register_widget_view = function (widget_view_name, widget_view_type) {
            this._view_types[widget_view_name] = widget_view_type;
        };

        WidgetManager.prototype.handle_msg = function(msg, model) {
            var method = msg.content.data.method;
            switch (method) {
                case 'display':
                    var cell = this.get_msg_cell(msg.parent_header.msg_id);
                    if (cell === null) {
                        console.log("Could not determine where the display" +
                            " message was from.  Widget will not be displayed");
                    } else {
                        var view = this.create_view(model, msg.content.data.view_name);
                        if (view !== undefined
                            && cell.widget_subarea !== undefined
                            && cell.widget_subarea !== null) {

                            view.cell = cell;
                            cell.widget_area.show();
                            cell.widget_subarea.append(view.$el);
                        }
                    }
                    break;
            }
        }

<<<<<<< HEAD
<<<<<<< HEAD
        WidgetManager.prototype.create_view = function(model, view_name, cell) {
=======
        WidgetManager.prototype.create_view = function(model, view_name, options) {
>>>>>>> Completely remove cell from model and view.
            view_name = view_name || model.get('default_view_name');
<<<<<<< HEAD
=======
    WidgetManager.prototype.create_view = function(model, view_name, cell, options) {
        view_name = view_name || model.get('default_view_name');
>>>>>>> Add widget view options in creating child views
            var ViewType = this.widget_view_types[view_name];
=======
            var ViewType = this._view_types[view_name];
>>>>>>> _model_types, _view_types, _models - and document what keys and values are
            if (ViewType !== undefined && ViewType !== null) {
                var view = new ViewType({model: model, widget_manager: this, options: options});
                view.render();
                model.views.push(view);
                model.on('destroy', view.remove, view);
<<<<<<< HEAD
                /*
                    // TODO: handle view deletion.  Don't forget to delete child views
                    var that = this;
                    view.$el.on("remove", function () {
                        var index = that.views.indexOf(view);
                        if (index > -1) {
                            that.views.splice(index, 1);
=======
        /*
                // TODO: handle view deletion.  Don't forget to delete child views
                var that = this;
                view.$el.on("remove", function () {
                    var index = that.views.indexOf(view);
                    if (index > -1) {
                        that.views.splice(index, 1);
                    }
                    view.remove(); // Clean-up view

                    // Close the comm if there are no views left.
                    if (that.views.length() === 0) {
            //trigger comm close event?
                        }

                        if (that.comm !== undefined) {
                            that.comm.close();
                            delete that.comm.model; // Delete ref so GC will collect widget model.
                            delete that.comm;
>>>>>>> Add widget view options in creating child views
                        }
                        view.remove(); // Clean-up view

                        // Close the comm if there are no views left.
                        if (that.views.length() === 0) {
                //trigger comm close event?
                            }

                            if (that.comm !== undefined) {
                                that.comm.close();
                                delete that.comm.model; // Delete ref so GC will collect widget model.
                                delete that.comm;
                            }
                            delete that.model_id; // Delete id from model so widget manager cleans up.
                        });
                */
                return view;
            }
        },

        WidgetManager.prototype.get_msg_cell = function (msg_id) {
            var cell = null;
            // First, check to see if the msg was triggered by cell execution.
            if (IPython.notebook !== undefined && IPython.notebook !== null) {
                cell = IPython.notebook.get_msg_cell(msg_id);
            }
            if (cell !== null) {
                return cell
            }
            // Second, check to see if a get_cell callback was defined
            // for the message.  get_cell callbacks are registered for
            // widget messages, so this block is actually checking to see if the
            // message was triggered by a widget.
            var kernel = this.get_kernel();
            if (kernel !== undefined && kernel !== null) {
                var callbacks = kernel.get_callbacks_for_msg(msg_id);
                if (callbacks !== undefined &&
                    callbacks.iopub !== undefined &&
                    callbacks.iopub.get_cell !== undefined) {

                    return callbacks.iopub.get_cell();
                }
            }

            // Not triggered by a cell or widget (no get_cell callback
            // exists).
            return null;
        };

        WidgetManager.prototype.callbacks = function (view) {
            // callback handlers specific a view
            var callbacks = {};
            var cell = view.cell;
            if (cell !== null) {
                // Try to get output handlers
                var handle_output = null;
                var handle_clear_output = null;
                if (cell.output_area !== undefined && cell.output_area !== null) {
                    handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
                    handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
                }

                // Create callback dict using what is known
                var that = this;
                callbacks = {
                    iopub : {
                        output : handle_output,
                        clear_output : handle_clear_output,

                        status : function (msg) {
                            view.model._handle_status(msg, that.callbacks(view));
                        },

                        // Special function only registered by widget messages.
                        // Allows us to get the cell for a message so we know
                        // where to add widgets if the code requires it.
                        get_cell : function () {
                            return cell;
                        },
                    },
                };
            }
            return callbacks;
        };

        WidgetManager.prototype.get_model = function (model_id) {
            var model = this._models[model_id];
            if (model !== undefined && model.id == model_id) {
                return model;
            }
            return null;
        };

        WidgetManager.prototype.get_kernel = function () {
            if (this.comm_manager === null) {
                return null;
            } else {
                return this.comm_manager.kernel;
            }
        };

        WidgetManager.prototype.on_create_widget = function (callback) {
            this._create_widget_callback = callback;
        };

        WidgetManager.prototype._handle_create_widget = function (widget_model) {
            if (this._create_widget_callback) {
                try {
                    this._create_widget_callback(widget_model);
                } catch (e) {
                    console.log("Exception in WidgetManager callback", e, widget_model);
                }
            }
        };

        WidgetManager.prototype._handle_comm_open = function (comm, msg) {
            var widget_type_name = msg.content.target_name;
            var widget_model = new this._model_types[widget_type_name](this, comm.comm_id, comm);
            this._models[comm.comm_id] = widget_model; // comm_id == model_id
            this._handle_create_widget(widget_model);
        };

        //--------------------------------------------------------------------
        // Init code
        //--------------------------------------------------------------------
        IPython.WidgetManager = WidgetManager;
        if (IPython.widget_manager === undefined || IPython.widget_manager === null) {
            IPython.widget_manager = new WidgetManager();
        }

        return IPython.widget_manager;
    });
}());
<commit_msg>remove msg.content.data.view_name and corrosponding create_view param<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2013  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// WidgetModel, WidgetView, and WidgetManager
//============================================================================
/**
 * Base Widget classes
 * @module IPython
 * @namespace IPython
 * @submodule widget
 */

(function () {
    "use strict";

    // Use require.js 'define' method so that require.js is intelligent enough to
    // syncronously load everything within this file when it is being 'required'
    // elsewhere.
    define(["underscore",
             "backbone",
            ], function (underscore, backbone) {

        Backbone.sync = function (method, model, options, error) {
            var result = model._handle_sync(method, options);
            if (options.success) {
              options.success(result);
            }
        };

        //--------------------------------------------------------------------
        // WidgetManager class
        //--------------------------------------------------------------------
        var WidgetManager = function () {
            this.comm_manager = null;
            this._model_types = {}; /* Dictionary of model type names
                                      (target_name) and model types. */
            this._view_types = {}; /* Dictionary of view names and view types. */
            this._models = {}; /* Dictionary of model ids and model instances */
        };

        WidgetManager.prototype.attach_comm_manager = function (comm_manager) {
            this.comm_manager = comm_manager;

            // Register already-registered widget model types with the comm manager.
            for (var widget_model_name in this._model_types) {
                this.comm_manager.register_target(widget_model_name, $.proxy(this._handle_comm_open, this));
            }
        };

        WidgetManager.prototype.register_widget_model = function (widget_model_name, widget_model_type) {
            // Register the widget with the comm manager.  Make sure to pass this object's context
            // in so `this` works in the call back.
            if (this.comm_manager !== null) {
                this.comm_manager.register_target(widget_model_name, $.proxy(this._handle_comm_open, this));
            }
            this._model_types[widget_model_name] = widget_model_type;
        };

        WidgetManager.prototype.register_widget_view = function (widget_view_name, widget_view_type) {
            this._view_types[widget_view_name] = widget_view_type;
        };

        WidgetManager.prototype.handle_msg = function(msg, model) {
            var method = msg.content.data.method;
            switch (method) {
                case 'display':
                    var cell = this.get_msg_cell(msg.parent_header.msg_id);
                    if (cell === null) {
                        console.log("Could not determine where the display" +
                            " message was from.  Widget will not be displayed");
                    } else {
                        var view = this.create_view(model);
                        if (view !== undefined
                            && cell.widget_subarea !== undefined
                            && cell.widget_subarea !== null) {

                            view.cell = cell;
                            cell.widget_area.show();
                            cell.widget_subarea.append(view.$el);
                        }
                    }
                    break;
            }
        }

<<<<<<< HEAD
<<<<<<< HEAD
<<<<<<< HEAD
        WidgetManager.prototype.create_view = function(model, view_name, cell) {
=======
        WidgetManager.prototype.create_view = function(model, view_name, options) {
>>>>>>> Completely remove cell from model and view.
            view_name = view_name || model.get('default_view_name');
<<<<<<< HEAD
=======
    WidgetManager.prototype.create_view = function(model, view_name, cell, options) {
        view_name = view_name || model.get('default_view_name');
>>>>>>> Add widget view options in creating child views
            var ViewType = this.widget_view_types[view_name];
=======
=======
        WidgetManager.prototype.create_view = function(model, options) {
            var view_name = model.get('view_name');
>>>>>>> remove msg.content.data.view_name and corrosponding create_view param
            var ViewType = this._view_types[view_name];
>>>>>>> _model_types, _view_types, _models - and document what keys and values are
            if (ViewType !== undefined && ViewType !== null) {
                var view = new ViewType({model: model, widget_manager: this, options: options});
                view.render();
                model.views.push(view);
                model.on('destroy', view.remove, view);
<<<<<<< HEAD
<<<<<<< HEAD
                /*
                    // TODO: handle view deletion.  Don't forget to delete child views
                    var that = this;
                    view.$el.on("remove", function () {
                        var index = that.views.indexOf(view);
                        if (index > -1) {
                            that.views.splice(index, 1);
=======
        /*
                // TODO: handle view deletion.  Don't forget to delete child views
                var that = this;
                view.$el.on("remove", function () {
                    var index = that.views.indexOf(view);
                    if (index > -1) {
                        that.views.splice(index, 1);
                    }
                    view.remove(); // Clean-up view

                    // Close the comm if there are no views left.
                    if (that.views.length() === 0) {
            //trigger comm close event?
                        }

                        if (that.comm !== undefined) {
                            that.comm.close();
                            delete that.comm.model; // Delete ref so GC will collect widget model.
                            delete that.comm;
>>>>>>> Add widget view options in creating child views
                        }
                        view.remove(); // Clean-up view

                        // Close the comm if there are no views left.
                        if (that.views.length() === 0) {
                //trigger comm close event?
                            }

                            if (that.comm !== undefined) {
                                that.comm.close();
                                delete that.comm.model; // Delete ref so GC will collect widget model.
                                delete that.comm;
                            }
                            delete that.model_id; // Delete id from model so widget manager cleans up.
                        });
                */
=======
>>>>>>> remove msg.content.data.view_name and corrosponding create_view param
                return view;
            }
        },

        WidgetManager.prototype.get_msg_cell = function (msg_id) {
            var cell = null;
            // First, check to see if the msg was triggered by cell execution.
            if (IPython.notebook !== undefined && IPython.notebook !== null) {
                cell = IPython.notebook.get_msg_cell(msg_id);
            }
            if (cell !== null) {
                return cell
            }
            // Second, check to see if a get_cell callback was defined
            // for the message.  get_cell callbacks are registered for
            // widget messages, so this block is actually checking to see if the
            // message was triggered by a widget.
            var kernel = this.get_kernel();
            if (kernel !== undefined && kernel !== null) {
                var callbacks = kernel.get_callbacks_for_msg(msg_id);
                if (callbacks !== undefined &&
                    callbacks.iopub !== undefined &&
                    callbacks.iopub.get_cell !== undefined) {

                    return callbacks.iopub.get_cell();
                }
            }

            // Not triggered by a cell or widget (no get_cell callback
            // exists).
            return null;
        };

        WidgetManager.prototype.callbacks = function (view) {
            // callback handlers specific a view
            var callbacks = {};
            var cell = view.cell;
            if (cell !== null) {
                // Try to get output handlers
                var handle_output = null;
                var handle_clear_output = null;
                if (cell.output_area !== undefined && cell.output_area !== null) {
                    handle_output = $.proxy(cell.output_area.handle_output, cell.output_area);
                    handle_clear_output = $.proxy(cell.output_area.handle_clear_output, cell.output_area);
                }

                // Create callback dict using what is known
                var that = this;
                callbacks = {
                    iopub : {
                        output : handle_output,
                        clear_output : handle_clear_output,

                        status : function (msg) {
                            view.model._handle_status(msg, that.callbacks(view));
                        },

                        // Special function only registered by widget messages.
                        // Allows us to get the cell for a message so we know
                        // where to add widgets if the code requires it.
                        get_cell : function () {
                            return cell;
                        },
                    },
                };
            }
            return callbacks;
        };

        WidgetManager.prototype.get_model = function (model_id) {
            var model = this._models[model_id];
            if (model !== undefined && model.id == model_id) {
                return model;
            }
            return null;
        };

        WidgetManager.prototype.get_kernel = function () {
            if (this.comm_manager === null) {
                return null;
            } else {
                return this.comm_manager.kernel;
            }
        };

        WidgetManager.prototype.on_create_widget = function (callback) {
            this._create_widget_callback = callback;
        };

        WidgetManager.prototype._handle_create_widget = function (widget_model) {
            if (this._create_widget_callback) {
                try {
                    this._create_widget_callback(widget_model);
                } catch (e) {
                    console.log("Exception in WidgetManager callback", e, widget_model);
                }
            }
        };

        WidgetManager.prototype._handle_comm_open = function (comm, msg) {
            var widget_type_name = msg.content.target_name;
            var widget_model = new this._model_types[widget_type_name](this, comm.comm_id, comm);
            this._models[comm.comm_id] = widget_model; // comm_id == model_id
            this._handle_create_widget(widget_model);
        };

        //--------------------------------------------------------------------
        // Init code
        //--------------------------------------------------------------------
        IPython.WidgetManager = WidgetManager;
        if (IPython.widget_manager === undefined || IPython.widget_manager === null) {
            IPython.widget_manager = new WidgetManager();
        }

        return IPython.widget_manager;
    });
}());
<|endoftext|>


<commit_before>const routesTranslations = {
  // Routes for to walk mode
  "You have arrived at your destination.": "Você chegou ao seu destino."
  "Your destination is on the left.": "Seu destino está à esquerda."
  "Your destination is on the right.": "Seu destino está à direita."
  "Your destination is on the north.": "Seu destino está ao norte."
  "Your destination is on the south.": "Seu destino está ao sul."

  "Walk southeast.": "Ande em direção sudeste."
  "Walk northeast.": "Ande em direção nordeste."
  "Walk northwest.": "Ande em direção noroeste."
  "Walk southwest.": "Ande em direção sudoeste."
  "Walk east.": "Ande para o leste."
  "Walk west.": "Ande para o oeste."
  "Walk south.": "Ande para o sul."
  "Walk north.": "Ande para o norte."

  "Continue.": "Continue."
  "Turn left.": "Vire à esquerda."
  "Turn right.": "Vire à direita."
  "Turn north.": "Vire para o norte."
  "Turn south.": "Vire para o sul."

  "Bear right.": "Fique à direita."
  "Bear left.": "Fique à esquerda."
  "Bear north.": "Fique ao norte."
  "Bear south.": "Fique ao sul."

  "Continue on the walkway.": "Continue na calçada."
  "Turn right onto the walkway.": "Vire à direta na calçada."
  "Turn left onto the walkway.": "Vire à esquerda na calçada."
  "Walk east on the walkway.": "Ande para o leste na calçada."
  "Walk south on the walkway.": "Ande para o sul na calçada."
  "Walk west on the walkway.": "Ande para o oeste na calçada."
  "Walk north on the walkway.": "Ande para o norte na calçada."

  "Bear left onto the walkway.": "Fique à esquerda na calçada."
  "Bear right onto the walkway.": "Fique à direta na calçada."
  "Bear north onto the walkway.": "Fique ao norte na calçada."
  "Bear south onto the walkway.": "Fique ao sul na calçada."

  "Enter the roundabout and take the 1st exit.": "Entre na rotatória e pegue a 1ª saída."
  "Enter the roundabout and take the 2nd exit.": "Entre na rotatória e pegue a 2ª saída."
  "Exit the roundabout.": "Saia da rotatória."

  "Make a left U-turn.": "Faça uma curva U para à esquerda."
  "Make a right U-turn.": "Faça uma curva U para à direita."

  // "Turn sharp right onto the walkway.": ""
  // "Turn sharp right.": ""

  // Routes for by car mode

  // Routes for by bike mode
  "Bike east.": "Pedale em direção leste."
  "Bike west.": "Pedale em direção oeste."
  "Bike right.": "Pedale à direita."
  "Bike left.": "Pedale à esquerda."
  "Bike north.": "Pedale em direção norte."
  "Bike south.": "Pedale em direção sul."
  "Bike southeast.": "Pedale em direção sudeste."
  "Bike northeast.": "Pedale em direção nordeste."
  "Bike northwest.": "Pedale em direção noroeste."
  "Bike southwest.": "Pedale em direção sudeste."

  "Turn left onto the cycleway.": "Vire à esquerda na ciclovia."
  "Turn right onto the cycleway.": "Vire à direita na ciclovia."
  "Turn north onto the cycleway.": "Vire ao norte na ciclovia."
  "Turn south onto the cycleway.": "Vire ao sul na ciclovia."
};
<commit_msg>Translating more routes in by bike mode.<commit_after>const routesTranslations = {
  // Routes for to walk mode
  "You have arrived at your destination.": "Você chegou ao seu destino."
  "Your destination is on the left.": "Seu destino está à esquerda."
  "Your destination is on the right.": "Seu destino está à direita."
  "Your destination is on the north.": "Seu destino está ao norte."
  "Your destination is on the south.": "Seu destino está ao sul."

  "Walk southeast.": "Ande em direção sudeste."
  "Walk northeast.": "Ande em direção nordeste."
  "Walk northwest.": "Ande em direção noroeste."
  "Walk southwest.": "Ande em direção sudoeste."
  "Walk east.": "Ande para o leste."
  "Walk west.": "Ande para o oeste."
  "Walk south.": "Ande para o sul."
  "Walk north.": "Ande para o norte."

  "Continue.": "Continue."
  "Turn left.": "Vire à esquerda."
  "Turn right.": "Vire à direita."
  "Turn north.": "Vire para o norte."
  "Turn south.": "Vire para o sul."

  "Bear right.": "Fique à direita."
  "Bear left.": "Fique à esquerda."
  "Bear north.": "Fique ao norte."
  "Bear south.": "Fique ao sul."

  "Continue on the walkway.": "Continue na calçada."
  "Turn right onto the walkway.": "Vire à direta na calçada."
  "Turn left onto the walkway.": "Vire à esquerda na calçada."
  "Walk east on the walkway.": "Ande para o leste na calçada."
  "Walk south on the walkway.": "Ande para o sul na calçada."
  "Walk west on the walkway.": "Ande para o oeste na calçada."
  "Walk north on the walkway.": "Ande para o norte na calçada."

  "Bear left onto the walkway.": "Fique à esquerda na calçada."
  "Bear right onto the walkway.": "Fique à direta na calçada."
  "Bear north onto the walkway.": "Fique ao norte na calçada."
  "Bear south onto the walkway.": "Fique ao sul na calçada."

  "Enter the roundabout and take the 1st exit.": "Entre na rotatória e pegue a 1ª saída."
  "Enter the roundabout and take the 2nd exit.": "Entre na rotatória e pegue a 2ª saída."
  "Exit the roundabout.": "Saia da rotatória."

  "Make a left U-turn.": "Faça uma curva U para à esquerda."
  "Make a right U-turn.": "Faça uma curva U para à direita."

  // "Turn sharp right onto the walkway.": ""
  // "Turn sharp right.": ""

  // Routes for by car mode

  // Routes for by bike mode
  "Bike east.": "Pedale em direção leste."
  "Bike west.": "Pedale em direção oeste."
  "Bike right.": "Pedale à direita."
  "Bike left.": "Pedale à esquerda."
  "Bike north.": "Pedale em direção norte."
  "Bike south.": "Pedale em direção sul."
  "Bike southeast.": "Pedale em direção sudeste."
  "Bike northeast.": "Pedale em direção nordeste."
  "Bike northwest.": "Pedale em direção noroeste."
  "Bike southwest.": "Pedale em direção sudeste."

  "Turn left onto the cycleway.": "Vire à esquerda na ciclovia."
  "Turn right onto the cycleway.": "Vire à direita na ciclovia."
  "Turn north onto the cycleway.": "Vire ao norte na ciclovia."
  "Turn south onto the cycleway.": "Vire ao sul na ciclovia."

  "Bike east on the cycleway.": "Pedale em direção leste na ciclovia."
  "Bike west on the cycleway.": "Pedale em direção oeste na ciclovia."
  "Bike right on the cycleway.": "Pedale à direita na ciclovia."
  "Bike left on the cycleway.": "Pedale à esquerda na ciclovia."
  "Bike north on the cycleway.": "Pedale em direção norte na ciclovia."
  "Bike south on the cycleway.": "Pedale em direção sul na ciclovia."
  "Bike southeast on the cycleway.": "Pedale em direção sudeste na ciclovia."
  "Bike northeast on the cycleway.": "Pedale em direção nordeste na ciclovia."
  "Bike southwest on the cycleway.": "Pedale em direção sudeste na ciclovia."
  "Bike northwest on the cycleway.": "Pedale em direção noroeste na ciclovia."
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
  config = require('./gulpconfig'),
  requireDir = require('require-dir');

requireDir('./gulptasks');

gulp.task('build', [
  'build:bower',
  'build:styles',
  'build:scripts',
  'copy:fonts',
  'copy:images'<% if (onlyFrontend) { %>,
  'build:html'<% } %>
]);

gulp.task('watch', function () {
  gulp.watch(config.paths.bower(''), ['build:bower']);
  gulp.watch([config.paths.src.styles_all, config.paths.src.svg_files], ['build:styles']);
  gulp.watch(config.paths.src.scripts_all, ['build:scripts']);
  gulp.watch(config.paths.src.fonts, ['copy:fonts']);
  gulp.watch(config.paths.src.img, ['copy:images']);
  <% if (onlyFrontend) { %>gulp.watch(config.paths.src.templates_all, ['build:html']);<% } %>
});
<% if (onlyFrontend) { %>
gulp.task('serve', ['server:run', 'server:reload']);
<% } %>
gulp.task('default', ['build',<% if (onlyFrontend) { %> 'serve',<% } %> 'watch']);<commit_msg>Modified gulpfile template: Dynamic gulptasks.<commit_after>var gulp = require('gulp'),
  config = require('./gulpconfig'),
  requireDir = require('require-dir'),
  argv = require('yargs').argv,
  production = argv.production,
  buildTasks = [
    'build:bower',
    'build:styles',
    'build:scripts',
    'copy:fonts',
    'copy:images',
    'build:html'
  ],
  defaultTasks = [
    'build'
  ];

requireDir('./gulptasks');

if (production) {
  buildTasks.push('create:cname');
} else {
  defaultTasks.push('serve', 'watch');
}

gulp.task('build', buildTasks);

gulp.task('watch', function () {
  gulp.watch(config.paths.bower(''), ['build:bower']);
  gulp.watch([config.paths.src.styles_all, config.paths.src.svg_files], ['build:styles']);
  gulp.watch(config.paths.src.scripts_all, ['build:scripts']);
  gulp.watch(config.paths.src.fonts, ['copy:fonts']);
  gulp.watch(config.paths.src.img, ['copy:images']);
  gulp.watch(config.paths.src.templates_all, ['build:html']);
});

gulp.task('serve', ['server:run', 'server:reload']);

gulp.task('default', defaultTasks);<|endoftext|>