<commit_before>// Dummy model, used only for purpose of prototype application demo.

'use strict';

var Map          = require('es6-map')
  , db           = require('mano').db
  , d  = require('d')
  , User         = require('../../model/user')(db)
  , Role         = require('mano-auth/model/role')(db)
  , DateType     = require('dbjs-ext/date-time/date')(db)
  , StringLine   = require('dbjs-ext/string/string-line')(db)
  , Email        = require('dbjs-ext/string/string-line/email')(db)
  , UsDollar     = require('dbjs-ext/number/currency/us-dollar')(db)
  , UInteger     = require('dbjs-ext/number/integer/u-integer')(db)
  , SquareMeters = require('dbjs-ext/number/square-meters')(db)
  , Percentage   = require('dbjs-ext/number/percentage')(db)
  , Document     = require('../../model/document')(db)
  , Submission   = require('./submission')
  , File         = require('./file')
  , CompanyType  = require('./company-type')

  , user = User.prototype
  , BusinessActivity, BusinessActivityCategory, Partner, bcAgencyBusiness, bcInsurance
  , file, props
  , StreetTypeChoice
  , EnumTripleOption = require('./enum-triple-option');

db.Base.define('chooseLabel', d("Choose:"));
require('./address');
require('./business-process');
require('dbjs-ext/create-enum')(db);

StreetTypeChoice = db.StreetTypeChoice; // defined in address

Role.members.add('user');
Role.meta.get('user').setProperties({
	label: "Self employed"
});
Role.members.add('users-admin');
Role.meta.get('users-admin').setProperties({
	label: "Users Admin"
});
Role.members.add('meta-admin');
Role.meta.get('meta-admin').setProperties({
	label: "Meta Admin"
});
Role.members.add('demo-user');
Role.meta.get('demo-user').setProperties({
	label: "Demo User"
});
Role.members.add('official-revision');
Role.meta.get('official-revision').setProperties({
	label: "Revision"
});
Role.members.add('official-processing');
Role.meta.get('official-processing').setProperties({
	label: "Processing"
});
Role.members.add('official-registration');
Role.meta.get('official-registration').setProperties({
	label: "Registration"
});

BusinessActivityCategory = db.Object.extend('BusinessActivityCategory', {
	label: { type: StringLine, required: true }
});
bcAgencyBusiness = BusinessActivityCategory.newNamed('bcAgencyBusiness',
	{ label: "Agency Business" });
bcInsurance = BusinessActivityCategory.newNamed('bcInsurance', { label: "Insurance" });

BusinessActivity = db.Object.extend('BusinessActivity', {
	label: { type: StringLine, required: true },
	category: { type: BusinessActivityCategory, required: true },
	toString: { value: function (descriptor) { return this.label; } }
});

BusinessActivity.newNamed('baComissionAgent', {
	label: "Comission agent",
	category: bcAgencyBusiness
});
BusinessActivity.newNamed('baAirCharterAgent', {
	label: "Lorem ipsum dolor sit amet",
	category: bcAgencyBusiness
});
BusinessActivity.newNamed('baGeneralInsurance', {
	label: "General insurance and assurance",
	category: bcInsurance
});
BusinessActivity.newNamed('baReassurance', {
	label: "Re-assurance & endowment",
	category: bcInsurance
});

user.defineProperties({
	firstName: { type: StringLine, required: true, label: "First Name", value: "John" },
	lastName: { type: StringLine, required: true, label: "Last Name", value: "Smith" },
	fullName: { type: StringLine, required: true, label: "Full Name", value: function () {
		return this.firstName + ' ' + this.lastName;
	} },

	// Guide
	companyName: { type: StringLine, required: true, label: "Company Name" },
	businessActivity: { type: BusinessActivity, required: true, label: "Business activity" },
	isOwner: { type: db.Boolean, trueLabel: "I am the owner", falseLabel: "I rent it",
		label: "Owner of business premises",
		required: true },
	isLomas: { type: db.Boolean, trueLabel: "Yes", falseLabel: "No",
		label: "Lorem ipsum dolor:",
		required: true },
	isLomasLong: { type: db.Boolean, trueLabel: "Yes", falseLabel: "No",
		label: "Lorem ipsum dolor sit amet, consectetur adipiscing:",
		required: true },
	isType: { type: db.Boolean,
		trueLabel: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit ame",
		falseLabel: "Please choose x docs in the list: " },
	isValidated: { type: db.Boolean,
		trueLabel: "Validate document",
		falseLabel: "Reject document" },
	notification: {
		type: db.StringLine.createEnum('NotificationType', new Map([
			['optionOne', { label: "Use my home address." }],
			['optionTwo', { label: "Use my business address." }],
			['optionTree', { label: "The address for submissions is different" }]
		])),
		label: "Lorem ipsum dolor sit amet"
	},
	isDebtContinusStatus: { type: EnumTripleOption, required: true },
	isManager: { type: db.Boolean, label: "I am manager" },
	inventory: { type: UsDollar, label: "Inventory value", required: true, step: 1,
		inputHint: "Etiam vestibulum dui mi, nec ultrices diam ultricies id " },
	surfaceArea: { type: SquareMeters, label: "Area used for the activity", required: true,
		inputHint: "Etiam vestibulum dui mi, nec ultrices diam ultricies id " },
	members: { type: UInteger, label: "Quantity of members", required: true },
	companyType: { type: CompanyType, label: "Registration type", required: true },
	descriptionText: { type: db.String, label: "Your description", required: true,
		inputCols: 35, inputRows: 4 },
	rejectReason: { type: db.String, inputCols: 35, inputRows: 4 },
	isShoppingGallery: { type: db.Boolean, label: "A shopping gallery", required: true,
		trueLabel: "Yes", falseLabel: "No" },
	isARequested: { type: db.Boolean, label: "Registration A", required: true },
	isBRequested: { type: db.Boolean, label: "Etiam vestibulum dui mi," +
		" nec ultrices diam ultricies id vestibulum dui mi," +
		" nec ultrices diam ultricies id vestibulum dui mi,", required: true },

	dateOfBirth: { type: DateType, label: "Date of birth", required: true,
		value: new Date("October 13, 1984 11:13:00") },
	userEmail: { type: Email, label: "Email", value: 'john.smith@abc.com' },

	registerIds: { type: StringLine, multiple: true, label: "Padrón", pattern: /^\d{8}$/,
		inputMask: '88888888' },
	lomasActivity: { type: BusinessActivity, multiple: true, label: "Business activity:",
		pattern: /^\d{8}$/, inputMask: '88888888' },
	isAffidavitSigned: { type: db.Boolean },
	//Submission
	placeOfWithdraw: { type: StringLine, label: "Withdraw documents to" },
	pickCertificates: { type: db.Boolean, trueLabel: "I will pick the certificates.",
		falseLabel: "The following person will pick the certificates", label: "The following person" },

	incorporationCertificateFile: { type: File, nested: true, label: "Certificate of incorporation" },
	registeredArticlesFile: { type: File, nested: true,
		label: "Registered articles of association" },

	streetType: { type: StreetTypeChoice, value: 'street', required: true },
	streetName: { type: StringLine, required: true },
	street: { type: StringLine, label: "Type of street", required: true,
		value: function () {
			if (!this.streetType || !this.streetName) return null;
			return this.database.StreetTypeChoice.meta[this.streetType].label + ' ' + this.streetName;
		} },
	shareholdersNumber: { type: UInteger, label: "Shareholders", required: true },
	shareholderAmount: { type: UInteger, label: "Value of share", required: true },
	shares: { type: StringLine, label: "Shares split", required: true,
		value: function () {
			if (!this.shareholdersNumber || !this.shareholderAmount) return null;
			return this.shareholdersNumber + this.shareholderAmount;
		} }
});

module.exports = User;

User.newNamed('userVianney', {
	firstName: 'Vianney',
	lastName: 'Lesaffre',
	email: 'vianney@lesaffre.com',
	roles: ['users-admin']
});

db.BusinessProcessNew.instances.forEach(function (businessProcess) {
	db.userVianney.initialBusinessProcesses.add(businessProcess);
});

Partner = db.User.extend('Partner', {
	isDirector: { type: db.Boolean, label: "Director?",
		trueLabel: "Yes", falseLabel: "No", value: true },
	isSubscriber: { type: db.Boolean, label: "Subscriber?",
		trueLabel: "Yes", falseLabel: "No", value: true },
	completionStatus: { type: Percentage, value: 1 }
});

user.define('partners', {
	type: Partner,
	multiple: true
});

user.define('emptyPartners', {
	type: Partner,
	multiple: true
});

user.partners.add(Partner.newNamed('partnerFrank',
	{
		firstName: "Frank",
		lastName: "Grozel",
		dateOfBirth: new Date(1960, 0, 1),
		email: "frank@grozel.fr",
		companyType: 'private',
		inventory: 1000000,
		isOwner: true,
		surfaceArea: 123,
		businessActivity: db.baAirCharterAgent,
		members: 5
	}));
user.partners.add(Partner.newNamed('partnerBita', { firstName: "Bita", lastName: "Mortazavi" }));

Submission.extend('DocumentASubmission',
	{ legend: { type: StringLine, value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
		" Duis sodales nec ligula in accumsan. Etiam tempus consequat libero ac facilisis. " } },
	{ Document: { value: Document.extend('DocumentA', {}, { label: { value: "Document A" } }) } });
Submission.extend('DocumentBSubmission',
	{ legend: { type: StringLine, value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
		" Duis sodales nec ligula in accumsan. Etiam tempus consequat libero ac facilisis. " } },
	{ Document: { value: Document.extend('DocumentB', {}, { label: { value: "Document B" } }) } });
Submission.extend('DocumentCSubmission',
	{ legend: { type: StringLine, value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
		" Duis sodales nec ligula in accumsan. Etiam tempus consequat libero ac facilisis. " } },
	{ Document: { value: Document.extend('DocumentC', {}, { label: { value: "Document C" } }) } });

user.define('submissions', {
	type: db.Object,
	nested: true
});
user.submissions.defineProperties({
	documentA: { type: db.DocumentASubmission, nested: true },
	documentB: { type: db.DocumentBSubmission, nested: true },
	documentC: { type: db.DocumentCSubmission, nested: true }
});
user.define('requiredSubmissions', {
	type: db.DocumentSubmission,
	multiple: true,
	value: [user.submissions.documentA, user.submissions.documentB, user.submissions.documentC]
});
user.define('correctionDocuments', {
	type: db.DocumentSubmission,
	multiple: true,
	value: [user.submissions.documentB]
});

file = db.SubmissionFile.newNamed('docASubFile1', props = {
	name: 'idoc.jpg',
	type: 'image/jpeg',
	diskSize: 376306,
	url: '/uploads/doc-a-sub-file1.idoc.jpg'
});
file.preview = file;
file.thumb.url  =  '/uploads/doc-a-sub-file1.thumb.idoc.jpg';
file.thumb.name = 'idoc.jpg';
user.submissions.documentA.files.add(file);
user.registeredArticlesFile.setProperties(props);
user.registeredArticlesFile.preview = file;

file = db.SubmissionFile.newNamed('docASubFile2', {
	name: 'idoc.png',
	type: 'image/png',
	diskSize: 124998,
	url: '/uploads/doc-a-sub-file2.idoc.png'
});
file.preview = db.JpegFile.newNamed('docASubFile2Preview', {
	url: '/uploads/doc-a-sub-file2.thumb.idoc.png.jpg',
	name: 'idoc.png'
});
file.thumb.url = '/uploads/doc-a-sub-file2.thumb.idoc.png.jpg';
file.thumb.name = 'idoc.png';

user.submissions.documentA.files.add(file);

file = db.SubmissionFile.newNamed('docBSubFile1', {
	name: 'idoc.jpg',
	type: 'image/jpeg',
	diskSize: 426150,
	url: '/uploads/doc-b-sub-file1.idoc.jpg'
});
file.preview = file;
file.thumb.url = '/uploads/doc-b-sub-file1.thumb.idoc.jpg';
file.thumb.name = 'idoc.jpg';

user.submissions.documentB.files.add(file);
<commit_msg>Dummy model for manager views<commit_after>// Dummy model, used only for purpose of prototype application demo.

'use strict';

var Map          = require('es6-map')
  , db           = require('mano').db
  , d  = require('d')
  , User         = require('../../model/user')(db)
  , Role         = require('mano-auth/model/role')(db)
  , DateType     = require('dbjs-ext/date-time/date')(db)
  , StringLine   = require('dbjs-ext/string/string-line')(db)
  , Email        = require('dbjs-ext/string/string-line/email')(db)
  , UsDollar     = require('dbjs-ext/number/currency/us-dollar')(db)
  , UInteger     = require('dbjs-ext/number/integer/u-integer')(db)
  , SquareMeters = require('dbjs-ext/number/square-meters')(db)
  , Percentage   = require('dbjs-ext/number/percentage')(db)
  , Document     = require('../../model/document')(db)
  , Submission   = require('./submission')
  , File         = require('./file')
  , CompanyType  = require('./company-type')

  , user = User.prototype
  , BusinessActivity, BusinessActivityCategory, Partner, bcAgencyBusiness, bcInsurance
  , file, props
  , StreetTypeChoice
  , EnumTripleOption = require('./enum-triple-option');

db.Base.define('chooseLabel', d("Choose:"));
require('./address');
require('./business-process');
require('dbjs-ext/create-enum')(db);

StreetTypeChoice = db.StreetTypeChoice; // defined in address

Role.members.add('user');
Role.meta.get('user').setProperties({
	label: "Self employed"
});
Role.members.add('users-admin');
Role.meta.get('users-admin').setProperties({
	label: "Users Admin"
});
Role.members.add('meta-admin');
Role.meta.get('meta-admin').setProperties({
	label: "Meta Admin"
});
Role.members.add('demo-user');
Role.meta.get('demo-user').setProperties({
	label: "Demo User"
});
Role.members.add('official-revision');
Role.meta.get('official-revision').setProperties({
	label: "Revision"
});
Role.members.add('official-processing');
Role.meta.get('official-processing').setProperties({
	label: "Processing"
});
Role.members.add('official-registration');
Role.meta.get('official-registration').setProperties({
	label: "Registration"
});

BusinessActivityCategory = db.Object.extend('BusinessActivityCategory', {
	label: { type: StringLine, required: true }
});
bcAgencyBusiness = BusinessActivityCategory.newNamed('bcAgencyBusiness',
	{ label: "Agency Business" });
bcInsurance = BusinessActivityCategory.newNamed('bcInsurance', { label: "Insurance" });

BusinessActivity = db.Object.extend('BusinessActivity', {
	label: { type: StringLine, required: true },
	category: { type: BusinessActivityCategory, required: true },
	toString: { value: function (descriptor) { return this.label; } }
});

BusinessActivity.newNamed('baComissionAgent', {
	label: "Comission agent",
	category: bcAgencyBusiness
});
BusinessActivity.newNamed('baAirCharterAgent', {
	label: "Lorem ipsum dolor sit amet",
	category: bcAgencyBusiness
});
BusinessActivity.newNamed('baGeneralInsurance', {
	label: "General insurance and assurance",
	category: bcInsurance
});
BusinessActivity.newNamed('baReassurance', {
	label: "Re-assurance & endowment",
	category: bcInsurance
});

user.defineProperties({
	firstName: { type: StringLine, required: true, label: "First Name", value: "John" },
	lastName: { type: StringLine, required: true, label: "Last Name", value: "Smith" },
	fullName: { type: StringLine, required: true, label: "Full Name", value: function () {
		return this.firstName + ' ' + this.lastName;
	} },

	// Guide
	companyName: { type: StringLine, required: true, label: "Company Name" },
	businessActivity: { type: BusinessActivity, required: true, label: "Business activity" },
	isOwner: { type: db.Boolean, trueLabel: "I am the owner", falseLabel: "I rent it",
		label: "Owner of business premises",
		required: true },
	isLomas: { type: db.Boolean, trueLabel: "Yes", falseLabel: "No",
		label: "Lorem ipsum dolor:",
		required: true },
	isLomasLong: { type: db.Boolean, trueLabel: "Yes", falseLabel: "No",
		label: "Lorem ipsum dolor sit amet, consectetur adipiscing:",
		required: true },
	isType: { type: db.Boolean,
		trueLabel: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit ame",
		falseLabel: "Please choose x docs in the list: " },
	isValidated: { type: db.Boolean,
		trueLabel: "Validate document",
		falseLabel: "Reject document" },
	notification: {
		type: db.StringLine.createEnum('NotificationType', new Map([
			['optionOne', { label: "Use my home address." }],
			['optionTwo', { label: "Use my business address." }],
			['optionTree', { label: "The address for submissions is different" }]
		])),
		label: "Lorem ipsum dolor sit amet"
	},
	isDebtContinusStatus: { type: EnumTripleOption, required: true },
	isManager: { type: db.Boolean, label: "I am manager" },
	inventory: { type: UsDollar, label: "Inventory value", required: true, step: 1,
		inputHint: "Etiam vestibulum dui mi, nec ultrices diam ultricies id " },
	surfaceArea: { type: SquareMeters, label: "Area used for the activity", required: true,
		inputHint: "Etiam vestibulum dui mi, nec ultrices diam ultricies id " },
	members: { type: UInteger, label: "Quantity of members", required: true },
	companyType: { type: CompanyType, label: "Registration type", required: true },
	descriptionText: { type: db.String, label: "Your description", required: true,
		inputCols: 35, inputRows: 4 },
	rejectReason: { type: db.String, inputCols: 35, inputRows: 4 },
	isShoppingGallery: { type: db.Boolean, label: "A shopping gallery", required: true,
		trueLabel: "Yes", falseLabel: "No" },
	isARequested: { type: db.Boolean, label: "Registration A", required: true },
	isBRequested: { type: db.Boolean, label: "Etiam vestibulum dui mi," +
		" nec ultrices diam ultricies id vestibulum dui mi," +
		" nec ultrices diam ultricies id vestibulum dui mi,", required: true },

	dateOfBirth: { type: DateType, label: "Date of birth", required: true,
		value: new Date("October 13, 1984 11:13:00") },
	userEmail: { type: Email, label: "Email", value: 'john.smith@abc.com' },

	registerIds: { type: StringLine, multiple: true, label: "Padrón", pattern: /^\d{8}$/,
		inputMask: '88888888' },
	lomasActivity: { type: BusinessActivity, multiple: true, label: "Business activity:",
		pattern: /^\d{8}$/, inputMask: '88888888' },
	isAffidavitSigned: { type: db.Boolean },
	//Submission
	placeOfWithdraw: { type: StringLine, label: "Withdraw documents to" },
	pickCertificates: { type: db.Boolean, trueLabel: "I will pick the certificates.",
		falseLabel: "The following person will pick the certificates", label: "The following person" },

	incorporationCertificateFile: { type: File, nested: true, label: "Certificate of incorporation" },
	registeredArticlesFile: { type: File, nested: true,
		label: "Registered articles of association" },

	streetType: { type: StreetTypeChoice, value: 'street', required: true },
	streetName: { type: StringLine, required: true },
	street: { type: StringLine, label: "Type of street", required: true,
		value: function () {
			if (!this.streetType || !this.streetName) return null;
			return this.database.StreetTypeChoice.meta[this.streetType].label + ' ' + this.streetName;
		} },
	shareholdersNumber: { type: UInteger, label: "Shareholders", required: true },
	shareholderAmount: { type: UInteger, label: "Value of share", required: true },
	shares: { type: StringLine, label: "Shares split", required: true,
		value: function () {
			if (!this.shareholdersNumber || !this.shareholderAmount) return null;
			return this.shareholdersNumber + this.shareholderAmount;
		} }
});

module.exports = User;

User.newNamed('notary', {
	firstName: 'User',
	lastName: 'Manager',
	email: 'notary@eregistraions.com',
	roles: ['user'],
	isManager: true
});

User.newNamed('userVianney', {
	firstName: 'Vianney',
	lastName: 'Lesaffre',
	email: 'vianney@lesaffre.com',
	roles: ['users-admin']
});
db.notary.clients.add(db.userVianney);
User.newNamed('otherGuy', {
	firstName: 'Other',
	lastName: 'Not linked',
	email: 'other-guy@lesaffre.com'
});
db.notary.clients.add(db.otherGuy);

db.BusinessProcessNew.instances.forEach(function (businessProcess) {
	db.userVianney.initialBusinessProcesses.add(businessProcess);
});

Partner = db.User.extend('Partner', {
	isDirector: { type: db.Boolean, label: "Director?",
		trueLabel: "Yes", falseLabel: "No", value: true },
	isSubscriber: { type: db.Boolean, label: "Subscriber?",
		trueLabel: "Yes", falseLabel: "No", value: true },
	completionStatus: { type: Percentage, value: 1 }
});

user.define('partners', {
	type: Partner,
	multiple: true
});

user.define('emptyPartners', {
	type: Partner,
	multiple: true
});

user.partners.add(Partner.newNamed('partnerFrank',
	{
		firstName: "Frank",
		lastName: "Grozel",
		dateOfBirth: new Date(1960, 0, 1),
		email: "frank@grozel.fr",
		companyType: 'private',
		inventory: 1000000,
		isOwner: true,
		surfaceArea: 123,
		businessActivity: db.baAirCharterAgent,
		members: 5
	}));
user.partners.add(Partner.newNamed('partnerBita', { firstName: "Bita", lastName: "Mortazavi" }));

Submission.extend('DocumentASubmission',
	{ legend: { type: StringLine, value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
		" Duis sodales nec ligula in accumsan. Etiam tempus consequat libero ac facilisis. " } },
	{ Document: { value: Document.extend('DocumentA', {}, { label: { value: "Document A" } }) } });
Submission.extend('DocumentBSubmission',
	{ legend: { type: StringLine, value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
		" Duis sodales nec ligula in accumsan. Etiam tempus consequat libero ac facilisis. " } },
	{ Document: { value: Document.extend('DocumentB', {}, { label: { value: "Document B" } }) } });
Submission.extend('DocumentCSubmission',
	{ legend: { type: StringLine, value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
		" Duis sodales nec ligula in accumsan. Etiam tempus consequat libero ac facilisis. " } },
	{ Document: { value: Document.extend('DocumentC', {}, { label: { value: "Document C" } }) } });

user.define('submissions', {
	type: db.Object,
	nested: true
});
user.submissions.defineProperties({
	documentA: { type: db.DocumentASubmission, nested: true },
	documentB: { type: db.DocumentBSubmission, nested: true },
	documentC: { type: db.DocumentCSubmission, nested: true }
});
user.define('requiredSubmissions', {
	type: db.DocumentSubmission,
	multiple: true,
	value: [user.submissions.documentA, user.submissions.documentB, user.submissions.documentC]
});
user.define('correctionDocuments', {
	type: db.DocumentSubmission,
	multiple: true,
	value: [user.submissions.documentB]
});

file = db.SubmissionFile.newNamed('docASubFile1', props = {
	name: 'idoc.jpg',
	type: 'image/jpeg',
	diskSize: 376306,
	url: '/uploads/doc-a-sub-file1.idoc.jpg'
});
file.preview = file;
file.thumb.url  =  '/uploads/doc-a-sub-file1.thumb.idoc.jpg';
file.thumb.name = 'idoc.jpg';
user.submissions.documentA.files.add(file);
user.registeredArticlesFile.setProperties(props);
user.registeredArticlesFile.preview = file;

file = db.SubmissionFile.newNamed('docASubFile2', {
	name: 'idoc.png',
	type: 'image/png',
	diskSize: 124998,
	url: '/uploads/doc-a-sub-file2.idoc.png'
});
file.preview = db.JpegFile.newNamed('docASubFile2Preview', {
	url: '/uploads/doc-a-sub-file2.thumb.idoc.png.jpg',
	name: 'idoc.png'
});
file.thumb.url = '/uploads/doc-a-sub-file2.thumb.idoc.png.jpg';
file.thumb.name = 'idoc.png';

user.submissions.documentA.files.add(file);

file = db.SubmissionFile.newNamed('docBSubFile1', {
	name: 'idoc.jpg',
	type: 'image/jpeg',
	diskSize: 426150,
	url: '/uploads/doc-b-sub-file1.idoc.jpg'
});
file.preview = file;
file.thumb.url = '/uploads/doc-b-sub-file1.thumb.idoc.jpg';
file.thumb.name = 'idoc.jpg';

user.submissions.documentB.files.add(file);
<|endoftext|>


<commit_before>/*!
 * Unit tests for pre-defined Lisp functions
 *
 * @author pfleidi
 */

var Functions = require('../lib/native_functions');
var Assert = require('assert');

exports['test plus'] = function () {
  var val1 = Functions['+']([1, 2, 3, 4, 5]);
  Assert.strictEqual(val1, 15);

  var val2 = Functions['+']([1, 2, 3, 4, -5]);
  Assert.strictEqual(val2, 5);

  Assert.throws(
    function () {
      var val3 = Functions['+']([]);
    },
    /At least two arguments are needed./
  );

  Assert.throws(
    function () {
      var val4 = Functions['+']([1, 'hurr']);
    },
    /is not a number/
  );
};

exports['test minus'] = function () {
  var val1 = Functions['-']([1, 2, 3, 4, 5]);
  Assert.strictEqual(val1, -13);

  var val2 = Functions['-']([1, 2, 3, 4, -5]);
  Assert.strictEqual(val2, -3);

  Assert.throws(
    function () {
      var val3 = Functions['-']([]);
    },
    /At least two arguments are needed./
  );
};

exports['test multiply'] = function () {
  var val1 = Functions['*']([1, 2, 3, 4, 5]);
  Assert.strictEqual(val1, 120);

  var val2 = Functions['*']([1, 2, 3, 4, -5]);
  Assert.strictEqual(val2, -120);
};

exports['test divide'] = function () {
  var val1 = Functions['/']([1, 2, 3, 4, 5]);
  Assert.strictEqual(val1, 0.008333333333333333);

  var val2 = Functions['/']([1, 2, 3, 4, -5]);
  Assert.strictEqual(val2, -0.008333333333333333);

  var val4 = Functions['/']([4, 0]);
  Assert.strictEqual(val4, Infinity);
};

exports['test equals'] = function () {
  var val1 = Functions['eq?']([1, 2]);
  Assert.strictEqual(val1, false);

  var val2 = Functions['eq?']([false, false]);
  Assert.strictEqual(val2, true);

  var val3 = Functions['eq?'](['doo', 'doo']);
  Assert.strictEqual(val3, true);
};
<commit_msg>Add cons/car/cdr tests<commit_after>/*!
 * Unit tests for pre-defined Lisp functions
 *
 * @author pfleidi
 */

var Functions = require('../lib/native_functions');
var Assert = require('assert');

exports['test plus'] = function () {
  var val1 = Functions['+']([1, 2, 3, 4, 5]);
  Assert.strictEqual(val1, 15);

  var val2 = Functions['+']([1, 2, 3, 4, -5]);
  Assert.strictEqual(val2, 5);

  Assert.throws(
    function () {
      var val3 = Functions['+']([]);
    },
    /At least two arguments are needed./
  );

  Assert.throws(
    function () {
      var val4 = Functions['+']([1, 'hurr']);
    },
    /is not a number/
  );
};

exports['test minus'] = function () {
  var val1 = Functions['-']([1, 2, 3, 4, 5]);
  Assert.strictEqual(val1, -13);

  var val2 = Functions['-']([1, 2, 3, 4, -5]);
  Assert.strictEqual(val2, -3);

  Assert.throws(
    function () {
      var val3 = Functions['-']([]);
    },
    /At least two arguments are needed./
  );
};

exports['test multiply'] = function () {
  var val1 = Functions['*']([1, 2, 3, 4, 5]);
  Assert.strictEqual(val1, 120);

  var val2 = Functions['*']([1, 2, 3, 4, -5]);
  Assert.strictEqual(val2, -120);
};

exports['test divide'] = function () {
  var val1 = Functions['/']([1, 2, 3, 4, 5]);
  Assert.strictEqual(val1, 0.008333333333333333);

  var val2 = Functions['/']([1, 2, 3, 4, -5]);
  Assert.strictEqual(val2, -0.008333333333333333);

  var val4 = Functions['/']([4, 0]);
  Assert.strictEqual(val4, Infinity);
};

exports['test equals'] = function () {
  var val1 = Functions['eq?']([1, 2]);
  Assert.strictEqual(val1, false);

  var val2 = Functions['eq?']([false, false]);
  Assert.strictEqual(val2, true);

  var val3 = Functions['eq?'](['doo', 'doo']);
  Assert.strictEqual(val3, true);
};

exports['test cons'] = function () {
  var val1 = Functions.cons(['a', 23]);
  Assert.deepEqual(val1, ['a', 23]);
};

exports['test car'] = function () {
  Assert.strictEqual(Functions.car([['a', 'b']]), 'a');
};

exports['test cdr'] = function () {
  Assert.strictEqual(Functions.cdr([['a', 'b']]), 'b');
};
<|endoftext|>


<commit_before>

var Gpio = require('pigpio').Gpio;
var colourConversions = require('./colours.js');
var request = require('request');

const config = require('./config.json');

var redLED = new Gpio(17, {mode: Gpio.OUTPUT});
var greenLED = new Gpio(18, {mode: Gpio.OUTPUT});
var blueLED = new Gpio(27, {mode: Gpio.OUTPUT});

function updateLightState(){

    var url = `http://${config.bridgeIP}/api/${config.bridgeKey}/lights/${config.masterID}`;

    request.get({
        uri : url,
        json : true
    }, (err, res) => {

        if(err){ console.log(err); return; }

        try{

            var state = res.body.state;
            var rgb = colourConversions.hueStateToRgb(state);
            setRGBValues(rgb);
        }catch(err){
            console.log(err);
        }
    });

}

function setRGBValues(rgb){

    console.log(rgb);

    var red = Math.floor(rgb.r);
    var green = Math.floor(rgb.g);
    var blue = Math.floor(rgb.b);

    try{
        redLED.pwmWrite(red);
        greenLED.pwmWrite(green);
        blueLED.pwmWrite(blue);
    }catch(e){
        console.log(e);
    };
}

var repeat = setInterval(updateLightState, config.pollRate);

setRGBValues({r : 225, g : 255, b : 255});<commit_msg>remove logging<commit_after>

var Gpio = require('pigpio').Gpio;
var colourConversions = require('./colours.js');
var request = require('request');

const config = require('./config.json');

var redLED = new Gpio(17, {mode: Gpio.OUTPUT});
var greenLED = new Gpio(18, {mode: Gpio.OUTPUT});
var blueLED = new Gpio(27, {mode: Gpio.OUTPUT});

function updateLightState(){

    var url = `http://${config.bridgeIP}/api/${config.bridgeKey}/lights/${config.masterID}`;

    request.get({
        uri : url,
        json : true
    }, (err, res) => {

        if(err){ console.log(err); return; }

        try{

            var state = res.body.state;
            var rgb = colourConversions.hueStateToRgb(state);
            setRGBValues(rgb);
        }catch(err){
            console.log(err);
        }
    });

}

function setRGBValues(rgb){

    var red = Math.floor(rgb.r);
    var green = Math.floor(rgb.g);
    var blue = Math.floor(rgb.b);

    try{
        redLED.pwmWrite(red);
        greenLED.pwmWrite(green);
        blueLED.pwmWrite(blue);
    }catch(e){
        console.log(e);
    };
}

var repeat = setInterval(updateLightState, config.pollRate);

setRGBValues({r : 225, g : 255, b : 255});

console.log("Starting light receiver");<|endoftext|>


<commit_before>// @flow

import React, { Component } from "react";
import PropTypes from "prop-types";

const propTypes = {
  loading: PropTypes.bool.isRequired,
  info: PropTypes.string
};

const defaultProps = {};

class Foo extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return
Bar
;
  }
}

Foo.propTypes = propTypes;
Foo.defaultProps = defaultProps;

export default Foo;
<commit_msg>Attempt<commit_after>// @flow

import React, { Component } from "react";
import PropTypes from "prop-types";

const propTypes = {
  loading: PropTypes.bool.isRequired,
  info: PropTypes.string
};

const defaultProps = {};

class Foo extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return
Bar
;
  }
}

Foo.propTypes = propTypes;
Foo.defaultProps = defaultProps;

export default Foo;
<|endoftext|>


<commit_before>// Generated on 2014-03-11 using generator-angular 0.6.0

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

var debug = true;

module.exports = function (grunt) {
  'use strict';
  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || '',
      dist: 'dist'
    },
    revision: {
      options: {
        property: 'meta.revision',
        ref: 'HEAD',
        short: true
      }
    },
    preprocess: {
      options: {
        context: {
          DEBUG : debug,
          revision : '<%= meta.revision %>'
        }
      },
      multifile : {
        files:{
          'dist/js/views/main.html' : 'js/views/main.html',
          'dist/index.html' : 'index.html',
          'dist/js/app.js' : 'js/app.js'
        }
      }

      // html : {
      //     src : 'index.html',
      //     dest : 'dist/index.html'
      // },
    },
    protractor: {
      options: {
        keepAlive: true,
        configFile: 'protractor.js',
        args:{}
      },
      run: {}
    },
    // Watches files for changes and runs tasks based on the changed files
    watch: {
      copy:{
        files: [
            'bower_components/angular/angular.js',
            'bower_components/angular-animate/angular-animate.js',
            'bower_components/angular-resource/angular-resource.js',
            'bower_components/angular-ui/build/angular-ui.js',
            'bower_components/angular-touch/angular-touch.js',
            'bower_components/angular-route/angular-route.js',
            'bower_components/jquery/jquery.js',
            'bower_components/normalize.css/normalize.css',
            'vendor/three.js/build/three.js',
            'vendor/three.js/examples/js/Detector.js',
            'vendor/threex.windowresize.js',
            'vendor/threex.domevent.js',
            'vendor/perlin.js',
            'vendor/require.js/require.js',
            '*.htm*',
            '*.js*',
            'favicon.ico',
            'images/**/*',
            'fonts/**/*',
            'views/**/*',
            'js/**/*',
            'css/**/*.css',
            'assets/**/*',
            'data/**/*'
          ],
        tasks : ['copy:dist', 'revision', 'preprocess']

      },
      js: {
        files: ['<%= yeoman.app %>/js/{,*/}{,*/}*.js'],
        tasks: ['newer:jshint:all']
      },
      // testable: {
  //       files: [
  //         '<%= yeoman.app %>/js/{,*/}{,*/}*.js',
  //         '<%= yeoman.app %>/protractor*.js',
  //         '<%= yeoman.app %>/test/e2e/{,*/}{,*/}*.js',
  //         '<%= yeoman.app %>/test/spec/{,*/}{,*/}*.js'
  //       ],
  //       tasks: ['karma:unit']// 'protractor'
  //     },
      compass: {
        files: ['<%= yeoman.app %>/{scss,sass}/{,*/}*.scss'],
        tasks: ['compass']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [//comment these files during profiling to avoid accidentally resetting the profiler
          '!<%= yeoman.app %>/dist/*.html',
          '<%= yeoman.app %>/{,*/}*.html',
          '<%= yeoman.app %>/js/{,*/}*.js',
          '<%= yeoman.app %>/css/{,*/}*.scss',
          '<%= yeoman.app %>/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        base: '<%= yeoman.dist %>',
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '<%= yeoman.dist %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            'test',
            '<%= yeoman.dist %>'
          ]
        }
      }
    },

    // Make sure code css are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/js/{,*/}*.js'
      ]
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
        // autoWatch: true
      }
    },
    compass: {
      options: {
        config: 'config.rb'
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },
    // Empties folders to start fresh
    clean: {
      server: {},
      dist: {
        files: [{
          dot: true,
          src: [
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/js/{,*/}*.js',
            '<%= yeoman.dist %>/css/{,*/}*.css',
            '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= yeoman.dist %>/css/fonts/*'
          ]
        }
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            'bower_components/angular/angular.js',
            'bower_components/angular-animate/angular-animate.js',
            'bower_components/angular-resource/angular-resource.js',
            'bower_components/angular-ui/build/angular-ui.js',
            'bower_components/angular-touch/angular-touch.js',
            'bower_components/angular-route/angular-route.js',
            'bower_components/jquery/jquery.js',
            'bower_components/normalize.css/normalize.css',
            'vendor/three.js/build/three.js',
            'vendor/three.js/examples/js/Detector.js',
            'vendor/threex.windowresize.js',
            'vendor/threex.domevent.js',
            'vendor/perlin.js',
            'vendor/require.js/require.js',
            '*.htm*',
            '*.js*',
            'favicon.ico',
            'images/**/*',
            'fonts/**/*',
            'views/**/*',
            'js/**/*',
            'css/**/*.css',
            'assets/**/*',
            'data/**/*'
          ]
        }]
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass'
      ]
    }
  });

  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }
      grunt.task.run([
       'revision',
       'copy',
       'preprocess',
       'clean:server',
       'concurrent:server',
       'connect:livereload',
       // 'karma',
       'watch'
     ]);
  });

  grunt.loadNpmTasks('grunt-git-revision');
  grunt.loadNpmTasks('grunt-preprocess');
  // grunt.loadNpmTasks('grunt-karma');

  grunt.loadNpmTasks('grunt-protractor-runner');

  grunt.registerTask('server', function () {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve']);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'connect:test',
    'karma'//,
    // 'protractor:run'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>clean up<commit_after>// Generated on 2014-03-11 using generator-angular 0.6.0

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

var debug = true;

module.exports = function (grunt) {
  'use strict';
  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || '',
      dist: 'dist'
    },
    revision: {
      options: {
        property: 'meta.revision',
        ref: 'HEAD',
        short: true
      }
    },
    preprocess: {
      options: {
        context: {
          DEBUG : debug,
          revision : '<%= meta.revision %>'
        }
      },
      multifile : {
        files:{
          'dist/js/views/main.html' : 'js/views/main.html',
          'dist/index.html' : 'index.html',
          'dist/js/app.js' : 'js/app.js'
        }
      }
    },
    protractor: {
      options: {
        keepAlive: true,
        configFile: 'protractor.js',
        args:{}
      },
      run: {}
    },
    // Watches files for changes and runs tasks based on the changed files
    watch: {
      copy:{
        files: [
            'bower_components/angular/angular.js',
            'bower_components/angular-animate/angular-animate.js',
            'bower_components/angular-resource/angular-resource.js',
            'bower_components/angular-ui/build/angular-ui.js',
            'bower_components/angular-touch/angular-touch.js',
            'bower_components/angular-route/angular-route.js',
            'bower_components/jquery/jquery.js',
            'bower_components/normalize.css/normalize.css',
            'vendor/three.js/build/three.js',
            'vendor/three.js/examples/js/Detector.js',
            'vendor/threex.windowresize.js',
            'vendor/threex.domevent.js',
            'vendor/perlin.js',
            'vendor/require.js/require.js',
            '*.htm*',
            '*.js*',
            'favicon.ico',
            'images/**/*',
            'fonts/**/*',
            'views/**/*',
            'js/**/*',
            'css/**/*.css',
            'assets/**/*',
            'data/**/*'
          ],
        tasks : ['copy:dist', 'revision', 'preprocess']

      },
      js: {
        files: ['<%= yeoman.app %>/js/{,*/}{,*/}*.js'],
        tasks: ['newer:jshint:all']
      },
      // testable: {
  //       files: [
  //         '<%= yeoman.app %>/js/{,*/}{,*/}*.js',
  //         '<%= yeoman.app %>/protractor*.js',
  //         '<%= yeoman.app %>/test/e2e/{,*/}{,*/}*.js',
  //         '<%= yeoman.app %>/test/spec/{,*/}{,*/}*.js'
  //       ],
  //       tasks: ['karma:unit']// 'protractor'
  //     },
      compass: {
        files: ['<%= yeoman.app %>/{scss,sass}/{,*/}*.scss'],
        tasks: ['compass']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [//comment these files during profiling to avoid accidentally resetting the profiler
          '!<%= yeoman.app %>/dist/*.html',
          '<%= yeoman.app %>/{,*/}*.html',
          '<%= yeoman.app %>/js/{,*/}*.js',
          '<%= yeoman.app %>/css/{,*/}*.scss',
          '<%= yeoman.app %>/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        base: '<%= yeoman.dist %>',
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '<%= yeoman.dist %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>'
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            'test',
            '<%= yeoman.dist %>'
          ]
        }
      }
    },

    // Make sure code css are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/js/{,*/}*.js'
      ]
    },
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
        // autoWatch: true
      }
    },
    compass: {
      options: {
        config: 'config.rb'
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },
    // Empties folders to start fresh
    clean: {
      server: {},
      dist: {
        files: [{
          dot: true,
          src: [
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/js/{,*/}*.js',
            '<%= yeoman.dist %>/css/{,*/}*.css',
            '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            '<%= yeoman.dist %>/css/fonts/*'
          ]
        }
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            'bower_components/angular/angular.js',
            'bower_components/angular-animate/angular-animate.js',
            'bower_components/angular-resource/angular-resource.js',
            'bower_components/angular-ui/build/angular-ui.js',
            'bower_components/angular-touch/angular-touch.js',
            'bower_components/angular-route/angular-route.js',
            'bower_components/jquery/jquery.js',
            'bower_components/normalize.css/normalize.css',
            'vendor/three.js/build/three.js',
            'vendor/three.js/examples/js/Detector.js',
            'vendor/threex.windowresize.js',
            'vendor/threex.domevent.js',
            'vendor/perlin.js',
            'vendor/require.js/require.js',
            '*.htm*',
            '*.js*',
            'favicon.ico',
            'images/**/*',
            'fonts/**/*',
            'views/**/*',
            'js/**/*',
            'css/**/*.css',
            'assets/**/*',
            'data/**/*'
          ]
        }]
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass'
      ]
    }
  });

  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }
      grunt.task.run([
       'revision',
       'copy',
       'preprocess',
       'clean:server',
       'concurrent:server',
       'connect:livereload',
       // 'karma',
       'watch'
     ]);
  });

  grunt.loadNpmTasks('grunt-git-revision');
  grunt.loadNpmTasks('grunt-preprocess');
  // grunt.loadNpmTasks('grunt-karma');

  grunt.loadNpmTasks('grunt-protractor-runner');

  grunt.registerTask('server', function () {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve']);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'connect:test',
    'karma'//,
    // 'protractor:run'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()
const jsonld = require('jsonld')
const fs = require('fs')
const path = require('path')
const frame = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'misc', 'frame.json')))

module.exports = (app) => {
  const fetch = require('../fetch')(app)
  app.get('/api/v1/resources/work/:workId', jsonParser, (request, response) => {
    fetch(`http://services:8005/work/${request.params.workId}`, { headers: { accept: 'application/n-triples;charset=utf-8' } })
      .then(res => {
        if (res.status === 200) {
          return res.text()
        } else {
          response.status(res.status).send(res.statusText)
          throw Error()
        }
      }).then(ntdata => jsonld.fromRDF(ntdata, { format: 'application/nquads' }, (error, ntdoc) => {
        if (error) {
          response.status(500).send(error)
        }

        // Remove type -> Work relations on all works, except the work in focus, to avoid
        // problems when work has subjects which themselves are works.
        // TODO revise this hack - it might make it difficult to present the work relations on work page.
        ntdoc = ntdoc.map(el => {
          if (el[ '@type' ] && el[ '@type' ].includes('http://data.deichman.no/ontology#Work') && el[ '@id' ] !== `http://data.deichman.no/work/${request.params.workId}`) {
            delete el[ '@type' ]
          }
          return el
        })

        jsonld.frame(ntdoc, frame, (error, framed) => {
          if (error) {
            response.status(500).send(error)
          }
          try {
            response.status(200).send(transformWork(framed[ '@graph' ][ 0 ]))
          } catch (error) {
            response.status(500).send(error)
          }
        })
      })
    ).catch(error => {
      response.sendStatus(500)
      console.log(error)
    })
  })

  app.get('/api/v1/resources/work/:workId/items', jsonParser, (request, response) => {
    fetch(`http://services:8005/work/${request.params.workId}/listRecordIds`)
      .then(res => {
        if (res.status === 200) {
          return res.json()
        } else {
          response.status(res.status).send(res.statusText)
          throw Error()
        }
      }).then(json => Promise.all(json.recordIds.map(recordId => fetch(`http://xkoha:8081/api/v1/biblios/${recordId}/expanded`).then(res => res.json())))
      .then(itemResponses => {
        const itemsByRecordId = {}
        itemResponses.forEach(itemResponse => {
          const items = {}
          itemResponse.items.forEach(item => {
            if (item.status === 'Utilgjengelig') {
              // Theese items should not count, or be processed further,
              // as they are not available to end users.
              return
            }
            const newItem = {
              shelfmark: item.itemcallnumber,
              status: item.status,
              reservable: item.reservable === 1,
              branchcode: item.homebranch,
              barcode: item.barcode,
              location: item.location,
              notforloan: item.status === 'Ikke til hjemlån'
            }
            const key = `${newItem.branchcode}_${newItem.shelfmark}_${newItem.location}_${newItem.notforloan}`
            if (!items[ key ]) {
              newItem.available = 0
              newItem.total = 0
              items[ key ] = newItem
            }
            if (newItem.status === 'Ledig' || newItem.notforloan) {
              items[ key ].available++
            }
            items[ key ].total++
            if (newItem.reservable) {
              items[ key ].reservable = true
            }
          })
          itemsByRecordId[ itemResponse.biblio.biblionumber ] = items
        })
        const itemsyo = {}
        Object.keys(itemsByRecordId).forEach(key => {
          itemsyo[ key ] = Object.keys(itemsByRecordId[ key ]).map(key2 => itemsByRecordId[ key ][ key2 ])
        })
        response.status(200).send(itemsyo)
      }).catch(error => {
        console.log(error)
        response.sendStatus(500)
      })
    ).catch(error => {
      response.sendStatus(500)
      console.log(error)
    })
  })
}

function transformWork (input) {
  try {
    const contributors = transformContributors(input.contributors)
    const work = {
      _original: process.env.NODE_ENV !== 'production' ? input : undefined,
      audiences: input.audiences,
      biographies: input.biographies,
      by: transformBy(contributors),
      classifications: transformClassifications(input.classifications),
      compositionType: transformCompositionType(input.compositionType),
      contentAdaptations: input.contentAdaptations,
      contributors: contributors,
      deweyNumber: input.hasClassification ? input.hasClassification.hasClassificationNumber : undefined,
      fictionNonfiction: input.fictionNonfiction,
      genres: input.genres,
      hasSummary: input.hasSummary,
      id: getId(input.id),
      instruments: transformInstruments(input.hasInstrument),
      items: [],
      languages: input.languages,
      literaryForms: input.literaryForms,
      mainTitle: input.mainTitle,
      partNumber: input.partNumber,
      partTitle: input.partTitle,
      publicationYear: input.publicationYear,
      publications: transformPublications(input.publications),
      serials: transformSerials(input),
      subtitle: input.subtitle,
      subjects: input.subjects,
      uri: input.id
    }
    const publicationWithImage = work.publications.find(publication => publication.image)
    if (publicationWithImage) {
      work.image = publicationWithImage.image
    }
    return work
  } catch (error) {
    console.log(error)
  }
}

function transformPublications (publications) {
  return publications.map(publication => {
    return {
      ageLimit: publication.ageLimit,
      binding: publication.binding,
      contentAdaptations: publication.contentAdaptations,
      contributors: transformContributors(publication.contributors),
      description: publication.description,
      duration: publication.duration,
      ean: publication.ean,
      edition: publication.edition,
      extent: publication.extent,
      formatAdaptations: publication.formatAdaptations,
      formats: publication.formats,
      genres: publication.genres,
      id: getId(publication.id),
      image: publication.image,
      isbn: publication.isbn,
      items: [],
      languages: publication.languages,
      mainTitle: publication.mainTitle,
      mediaTypes: publication.mediaTypes,
      numberOfPages: publication.numberOfPages,
      partNumber: publication.partNumber,
      partTitle: publication.partTitle,
      placeOfPublication: publication.hasPlaceOfPublication ? publication.hasPlaceOfPublication.prefLabel : undefined,
      publicationParts: transformPublicationParts(publication.publicationParts),
      publicationYear: publication.publicationYear,
      publisher: publication.publishedBy ? publication.publishedBy.name : undefined,
      publishers: publication.publishers,
      recordId: publication.recordId,
      serialIssues: transformSerialIssues(publication.serialIssues),
      subtitle: publication.subtitle,
      subtitles: publication.subtitles,
      uri: publication.id
    }
  })
}

function transformPublicationParts (input) {
  try {
    return input.map(inputPublicationPart => {
      return {
        /* TODO */
      }
    })
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformSerials (work) {
  try {
    return [].concat(...work.publications.map(publication => publication.serialIssues.map(inSerial => inSerial.name)))
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformContributors (input) {
  try {
    const contributors = {}
    input.forEach(inputContributor => {
      const contributor = inputContributor.agent
      contributor.uri = contributor.id
      contributor.id = getId(contributor.id)
      contributor.relativeUri = relativeUri(contributor.uri)
      contributors[ inputContributor.role ] = contributors[ inputContributor.role ] || []
      contributors[ inputContributor.role ].push(contributor)
    })
    return contributors
  } catch (error) {
    console.log(error)
    return {}
  }
}

function transformSerialIssues (input) {
  try {
    return input.map(serialIssue => {
      return {
        uri: serialIssue.serial.id,
        name: serialIssue.serial.mainTitle,
        subtitle: serialIssue.serial.subtitle,
        issue: serialIssue.issue
      }
    })
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformBy (contributors) {
  try {
    return []
      .concat(contributors[ 'http://data.deichman.no/role#author' ])
      .concat(contributors[ 'http://data.deichman.no/role#director' ])
      .concat(contributors[ 'http://data.deichman.no/role#composer' ])
      .concat(contributors[ 'http://data.deichman.no/role#performer' ])
      .filter(by => by)
      .map(by => by.name)
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformCompositionType (hasCompositionType = []) {
  try {
    return hasCompositionType.map(compositionType => compositionType.prefLabel)
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformInstruments (hasInstrument = []) {
  try {
    return hasInstrument.map(instrument => instrument.hasInstrument.prefLabel)
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformClassifications (input) {
  try {
    return input.map(classification => classification.hasClassificationNumber)
  } catch (error) {
    console.log(error)
    return []
  }
}

const urijs = require('urijs')

function relativeUri (uri) {
  return urijs(uri).path()
}

function getId (uri) {
  return uri.substring(uri.lastIndexOf('/') + 1)
}
<commit_msg>patron-client: don't fail if publication is gone in Koha<commit_after>const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()
const jsonld = require('jsonld')
const fs = require('fs')
const path = require('path')
const frame = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'misc', 'frame.json')))

module.exports = (app) => {
  const fetch = require('../fetch')(app)
  app.get('/api/v1/resources/work/:workId', jsonParser, (request, response) => {
    fetch(`http://services:8005/work/${request.params.workId}`, { headers: { accept: 'application/n-triples;charset=utf-8' } })
      .then(res => {
        if (res.status === 200) {
          return res.text()
        } else {
          response.status(res.status).send(res.statusText)
          throw Error()
        }
      }).then(ntdata => jsonld.fromRDF(ntdata, { format: 'application/nquads' }, (error, ntdoc) => {
        if (error) {
          response.status(500).send(error)
        }

        // Remove type -> Work relations on all works, except the work in focus, to avoid
        // problems when work has subjects which themselves are works.
        // TODO revise this hack - it might make it difficult to present the work relations on work page.
        ntdoc = ntdoc.map(el => {
          if (el[ '@type' ] && el[ '@type' ].includes('http://data.deichman.no/ontology#Work') && el[ '@id' ] !== `http://data.deichman.no/work/${request.params.workId}`) {
            delete el[ '@type' ]
          }
          return el
        })

        jsonld.frame(ntdoc, frame, (error, framed) => {
          if (error) {
            response.status(500).send(error)
          }
          try {
            response.status(200).send(transformWork(framed[ '@graph' ][ 0 ]))
          } catch (error) {
            response.status(500).send(error)
          }
        })
      })
    ).catch(error => {
      response.sendStatus(500)
      console.log(error)
    })
  })

  app.get('/api/v1/resources/work/:workId/items', jsonParser, (request, response) => {
    fetch(`http://services:8005/work/${request.params.workId}/listRecordIds`)
      .then(res => {
        if (res.status === 200) {
          return res.json()
        } else {
          response.status(res.status).send(res.statusText)
          throw Error()
        }
      }).then(json => Promise.all(json.recordIds.map(recordId => fetch(`http://xkoha:8081/api/v1/biblios/${recordId}/expanded`).then(res => {
        if (res.status === 200) {
          return res.json()
        } else {
          return undefined
        }
      })))
      .then(itemResponses => {
        const itemsByRecordId = {}
        itemResponses.filter(itemResponse => itemResponse).forEach(itemResponse => {
          const items = {}
          itemResponse.items.forEach(item => {
            if (item.status === 'Utilgjengelig') {
              // Theese items should not count, or be processed further,
              // as they are not available to end users.
              return
            }
            const newItem = {
              shelfmark: item.itemcallnumber,
              status: item.status,
              reservable: item.reservable === 1,
              branchcode: item.homebranch,
              barcode: item.barcode,
              location: item.location,
              notforloan: item.status === 'Ikke til hjemlån'
            }
            const key = `${newItem.branchcode}_${newItem.shelfmark}_${newItem.location}_${newItem.notforloan}`
            if (!items[ key ]) {
              newItem.available = 0
              newItem.total = 0
              items[ key ] = newItem
            }
            if (newItem.status === 'Ledig' || newItem.notforloan) {
              items[ key ].available++
            }
            items[ key ].total++
            if (newItem.reservable) {
              items[ key ].reservable = true
            }
          })
          itemsByRecordId[ itemResponse.biblio.biblionumber ] = items
        })
        const itemsyo = {}
        Object.keys(itemsByRecordId).forEach(key => {
          itemsyo[ key ] = Object.keys(itemsByRecordId[ key ]).map(key2 => itemsByRecordId[ key ][ key2 ])
        })
        response.status(200).send(itemsyo)
      }).catch(error => {
        console.log(error)
        response.sendStatus(500)
      })
    ).catch(error => {
      response.sendStatus(500)
      console.log(error)
    })
  })
}

function transformWork (input) {
  try {
    const contributors = transformContributors(input.contributors)
    const work = {
      _original: process.env.NODE_ENV !== 'production' ? input : undefined,
      audiences: input.audiences,
      biographies: input.biographies,
      by: transformBy(contributors),
      classifications: transformClassifications(input.classifications),
      compositionType: transformCompositionType(input.compositionType),
      contentAdaptations: input.contentAdaptations,
      contributors: contributors,
      deweyNumber: input.hasClassification ? input.hasClassification.hasClassificationNumber : undefined,
      fictionNonfiction: input.fictionNonfiction,
      genres: input.genres,
      hasSummary: input.hasSummary,
      id: getId(input.id),
      instruments: transformInstruments(input.hasInstrument),
      items: [],
      languages: input.languages,
      literaryForms: input.literaryForms,
      mainTitle: input.mainTitle,
      partNumber: input.partNumber,
      partTitle: input.partTitle,
      publicationYear: input.publicationYear,
      publications: transformPublications(input.publications),
      serials: transformSerials(input),
      subtitle: input.subtitle,
      subjects: input.subjects,
      uri: input.id
    }
    const publicationWithImage = work.publications.find(publication => publication.image)
    if (publicationWithImage) {
      work.image = publicationWithImage.image
    }
    return work
  } catch (error) {
    console.log(error)
  }
}

function transformPublications (publications) {
  return publications.map(publication => {
    return {
      ageLimit: publication.ageLimit,
      binding: publication.binding,
      contentAdaptations: publication.contentAdaptations,
      contributors: transformContributors(publication.contributors),
      description: publication.description,
      duration: publication.duration,
      ean: publication.ean,
      edition: publication.edition,
      extent: publication.extent,
      formatAdaptations: publication.formatAdaptations,
      formats: publication.formats,
      genres: publication.genres,
      id: getId(publication.id),
      image: publication.image,
      isbn: publication.isbn,
      items: [],
      languages: publication.languages,
      mainTitle: publication.mainTitle,
      mediaTypes: publication.mediaTypes,
      numberOfPages: publication.numberOfPages,
      partNumber: publication.partNumber,
      partTitle: publication.partTitle,
      placeOfPublication: publication.hasPlaceOfPublication ? publication.hasPlaceOfPublication.prefLabel : undefined,
      publicationParts: transformPublicationParts(publication.publicationParts),
      publicationYear: publication.publicationYear,
      publisher: publication.publishedBy ? publication.publishedBy.name : undefined,
      publishers: publication.publishers,
      recordId: publication.recordId,
      serialIssues: transformSerialIssues(publication.serialIssues),
      subtitle: publication.subtitle,
      subtitles: publication.subtitles,
      uri: publication.id
    }
  })
}

function transformPublicationParts (input) {
  try {
    return input.map(inputPublicationPart => {
      return {
        /* TODO */
      }
    })
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformSerials (work) {
  try {
    return [].concat(...work.publications.map(publication => publication.serialIssues.map(inSerial => inSerial.name)))
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformContributors (input) {
  try {
    const contributors = {}
    input.forEach(inputContributor => {
      const contributor = inputContributor.agent
      contributor.uri = contributor.id
      contributor.id = getId(contributor.id)
      contributor.relativeUri = relativeUri(contributor.uri)
      contributors[ inputContributor.role ] = contributors[ inputContributor.role ] || []
      contributors[ inputContributor.role ].push(contributor)
    })
    return contributors
  } catch (error) {
    console.log(error)
    return {}
  }
}

function transformSerialIssues (input) {
  try {
    return input.map(serialIssue => {
      return {
        uri: serialIssue.serial.id,
        name: serialIssue.serial.mainTitle,
        subtitle: serialIssue.serial.subtitle,
        issue: serialIssue.issue
      }
    })
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformBy (contributors) {
  try {
    return []
      .concat(contributors[ 'http://data.deichman.no/role#author' ])
      .concat(contributors[ 'http://data.deichman.no/role#director' ])
      .concat(contributors[ 'http://data.deichman.no/role#composer' ])
      .concat(contributors[ 'http://data.deichman.no/role#performer' ])
      .filter(by => by)
      .map(by => by.name)
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformCompositionType (hasCompositionType = []) {
  try {
    return hasCompositionType.map(compositionType => compositionType.prefLabel)
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformInstruments (hasInstrument = []) {
  try {
    return hasInstrument.map(instrument => instrument.hasInstrument.prefLabel)
  } catch (error) {
    console.log(error)
    return []
  }
}

function transformClassifications (input) {
  try {
    return input.map(classification => classification.hasClassificationNumber)
  } catch (error) {
    console.log(error)
    return []
  }
}

const urijs = require('urijs')

function relativeUri (uri) {
  return urijs(uri).path()
}

function getId (uri) {
  return uri.substring(uri.lastIndexOf('/') + 1)
}
<|endoftext|>


<commit_before>import EmberObject from '@ember/object';
import RSVP from 'rsvp';
import { setupRenderingTest } from 'ember-qunit';
import {
  render,
  settled,
  click,
  findAll
} from '@ember/test-helpers';
import { module, skip, test } from 'qunit';
import hbs from 'htmlbars-inline-precompile';
import { setupIntl } from 'ember-intl/test-support';
const { resolve } = RSVP;

module('Integration | Component | objective sort manager', function(hooks) {
  setupRenderingTest(hooks);
  setupIntl(hooks);

  test('it renders', async function(assert) {
    assert.expect(5);

    const objective1 = EmberObject.create({
      title: 'Objective 1',
      position: 1,
    });

    const objective2 = EmberObject.create({
      title: 'Objective 2',
      position: 0
    });

    const subject = EmberObject.create({
      objectives: resolve([ objective1, objective2 ])
    });

    this.set('subject', subject);

    await render(hbs`<ObjectiveSortManager @subject={{this.subject}} @close={{noop}} />`);

    return settled().then(() => {
      assert.dom('.draggable-object').exists({ count: 2 });
      assert.dom('.draggable-object').hasText(objective2.get('title'));
      assert.dom(findAll('.draggable-object')[1]).hasText(objective1.get('title'));
      assert.dom('.actions .bigadd').exists({ count: 1 });
      assert.dom('.actions .bigcancel').exists({ count: 1 });
    });
  });

  test('cancel', async function(assert) {
    assert.expect(1);
    const subject = EmberObject.create({
      objectives: resolve([
        EmberObject.create({
          title: 'Objective A',
          position: 1,
        }),
        EmberObject.create({
          title: 'Objective B',
          position: 2
        })
      ]),
    });
    this.set('subject', subject);
    this.set('cancel', () => {
      assert.ok(true, 'Cancel action was invoked correctly.');
    });
    await render(hbs`<ObjectiveSortManager @subject={{this.subject}} @close={{this.cancel}} />`);

    return settled().then(async () => {
      await click('.actions .bigcancel');
    });
  });

  skip('reorder and save', function(assert) {
    assert.ok(false);
    // @todo figure out how to simulate drag and drop and implement this test [ST 2017/02/13]
  });
});
<commit_msg>rewires objective-sort-manager test.<commit_after>import { setupRenderingTest } from 'ember-qunit';
import { render, click, findAll } from '@ember/test-helpers';
import { module, skip, test } from 'qunit';
import hbs from 'htmlbars-inline-precompile';
import { setupIntl } from 'ember-intl/test-support';
import { setupMirage } from 'ember-cli-mirage/test-support';

module('Integration | Component | objective sort manager', async function(hooks) {
  setupRenderingTest(hooks);
  setupIntl(hooks);
  setupMirage(hooks);

  test('it renders for session', async function(assert) {
    assert.expect(5);

    const objective1 = this.server.create('objective');
    const objective2 = this.server.create('objective');
    const session = this.server.create('session');
    this.server.create('session-objective', { session, objective: objective1, position: 1 });
    this.server.create('session-objective', { session, objective: objective2, position: 0 });
    const subject = await this.owner.lookup('service:store').find('session', session.id);
    this.set('subject', subject);
    await render(hbs`<ObjectiveSortManager @subject={{this.subject}} @close={{noop}} />`);
    assert.dom('.draggable-object').exists({ count: 2 });
    assert.dom('.draggable-object').hasText(objective2.title);
    assert.dom(findAll('.draggable-object')[1]).hasText(objective1.title);
    assert.dom('.actions .bigadd').exists({ count: 1 });
    assert.dom('.actions .bigcancel').exists({ count: 1 });
  });

  test('it renders for course', async function(assert) {
    assert.expect(5);
    const objective1 = this.server.create('objective');
    const objective2 = this.server.create('objective');
    const course = this.server.create('course');
    this.server.create('course-objective', { course, objective: objective1, position: 1 });
    this.server.create('course-objective', { course, objective: objective2, position: 0 });
    const subject = await this.owner.lookup('service:store').find('course', course.id);
    this.set('subject', subject);
    await render(hbs`<ObjectiveSortManager @subject={{this.subject}} @close={{noop}} />`);
    assert.dom('.draggable-object').exists({ count: 2 });
    assert.dom('.draggable-object').hasText(objective2.title);
    assert.dom(findAll('.draggable-object')[1]).hasText(objective1.title);
    assert.dom('.actions .bigadd').exists({ count: 1 });
    assert.dom('.actions .bigcancel').exists({ count: 1 });
  });

  test('it renders for program-year', async function(assert) {
    assert.expect(5);

    const objective1 = this.server.create('objective');
    const objective2 = this.server.create('objective');
    const programYear = this.server.create('programYear');
    this.server.create('program-year-objective', { programYear, objective: objective1, position: 1 });
    this.server.create('program-year-objective', { programYear, objective: objective2, position: 0 });
    const subject = await this.owner.lookup('service:store').find('programYear', programYear.id);
    this.set('subject', subject);
    await render(hbs`<ObjectiveSortManager @subject={{this.subject}} @close={{noop}} />`);
    assert.dom('.draggable-object').exists({ count: 2 });
    assert.dom('.draggable-object').hasText(objective2.title);
    assert.dom(findAll('.draggable-object')[1]).hasText(objective1.title);
    assert.dom('.actions .bigadd').exists({ count: 1 });
    assert.dom('.actions .bigcancel').exists({ count: 1 });
  });

  test('cancel', async function(assert) {
    assert.expect(1);
    const course = this.server.create('course');
    const subject = await this.owner.lookup('service:store').find('course', course.id);
    this.set('subject', subject);
    this.set('cancel', () => {
      assert.ok(true, 'Cancel action was invoked correctly.');
    });
    await render(hbs`<ObjectiveSortManager @subject={{this.subject}} @close={{this.cancel}} />`);
    await click('.actions .bigcancel');
  });

  skip('reorder and save', function(assert) {
    assert.ok(false);
    // @todo figure out how to simulate drag and drop and implement this test [ST 2017/02/13]
  });
});
<|endoftext|>


<commit_before>E2.p = E2.plugins["array_to_mesh_modulator"] = function(core, node)
{
	this.desc = 'Converts the supplied array to a mesh.';

	this.input_slots = [
		{ name: 'vertices', dt: core.datatypes.ARRAY, desc: 'The vertex array (x, y, z).' },
		{ name: 'normals', dt: core.datatypes.ARRAY, desc: 'The normal array (x, y, z).' },
		{ name: 'colors', dt: core.datatypes.ARRAY, desc: 'The vertex color array (r, g, b, a).' },
		{ name: 'uv0', dt: core.datatypes.ARRAY, desc: 'The first UV coord array (x, y).' },
		{ name: 'uv1', dt: core.datatypes.ARRAY, desc: 'The second UV coord array (x, y).' },
		{ name: 'uv2', dt: core.datatypes.ARRAY, desc: 'The third UV coord array (x, y).' },
		{ name: 'uv3', dt: core.datatypes.ARRAY, desc: 'The forth UV coord array (x, y).' },
		{ name: 'index', dt: core.datatypes.ARRAY, desc: 'The index buffer (depends on primitive type).' }
	];

	this.output_slots = [
		{ name: 'mesh', dt: core.datatypes.MESH, desc: 'The resulting mesh.' }
	];

	this.gl = core.renderer.context;
	this.mesh = new Mesh(this.gl, this.gl.TRIANGLES);
	this.vertices = null;
	this.normals = null;
	this.colors = null;
	this.uv0 = null;
	this.uv1 = null;
	this.uv2 = null;
	this.uv3 = null;
};

E2.p.prototype.update_vertex_buffer = function(v_name, v_type, data)
{
	var vbs = this.mesh.vertex_buffers;

	if(data)
	{

		if(!vbs[v_type])
			vbs[v_name] = new VertexBuffer(this.gl, v_type);

		vbs[v_name].bind_data(data);
	}
	else
		vbs[v_name] = null;
};

E2.p.prototype.update_input = function(slot, data)
{
	if(slot.index === 0)
		this.update_vertex_buffer('VERTEX', VertexBuffer.vertex_type.VERTEX, data);
	else if(slot.index === 1)
		this.update_vertex_buffer('NORMAL', VertexBuffer.vertex_type.NORMAL, data);
	else if(slot.index === 2)
		this.update_vertex_buffer('COLOR', VertexBuffer.vertex_type.NORMAL, data);
	else if(slot.index === 3)
		this.update_vertex_buffer('UV0', VertexBuffer.vertex_type.UV0, data);
	else if(slot.index === 4)
		this.update_vertex_buffer('UV1', VertexBuffer.vertex_type.UV1, data);
	else if(slot.index === 5)
		this.update_vertex_buffer('UV2', VertexBuffer.vertex_type.UV2, data);
	else if(slot.index === 6)
		this.update_vertex_buffer('UV3', VertexBuffer.vertex_type.UV3, data);
	else if(slot.index === 7)
	{
		var ib = this.mesh.index_buffer;

		if(data)
		{

			if(!ib)
				ib = new IndexBuffer(this.gl);

			ib.bind_data(data);
		}
		else
			ib = null;
	}
};

E2.p.prototype.update_state = function()
{
	var count = 0;
	var vbs = this.mesh.vertex_buffers;

	if(vbs['VERTEX'])
		count = Math.max(count, vbs['VERTEX'].count);

	this.mesh.generate_shader();
	this.vertex_count = count;
};

E2.p.prototype.update_output = function(slot)
{
	return this.mesh;
};
<commit_msg>Fixed vertex buffer leak in the array to mesh plugin; this has the potential to cause unintentional crashes in browser or display drivers . Changed the buffer update logic to use draw mode DYNAMIC instead of STATIC as a driver hint.<commit_after>E2.p = E2.plugins["array_to_mesh_modulator"] = function(core, node)
{
	this.desc = 'Converts the supplied array to a mesh.';

	this.input_slots = [
		{ name: 'vertices', dt: core.datatypes.ARRAY, desc: 'The vertex array (x, y, z).' },
		{ name: 'normals', dt: core.datatypes.ARRAY, desc: 'The normal array (x, y, z).' },
		{ name: 'colors', dt: core.datatypes.ARRAY, desc: 'The vertex color array (r, g, b, a).' },
		{ name: 'uv0', dt: core.datatypes.ARRAY, desc: 'The first UV coord array (x, y).' },
		{ name: 'uv1', dt: core.datatypes.ARRAY, desc: 'The second UV coord array (x, y).' },
		{ name: 'uv2', dt: core.datatypes.ARRAY, desc: 'The third UV coord array (x, y).' },
		{ name: 'uv3', dt: core.datatypes.ARRAY, desc: 'The forth UV coord array (x, y).' },
		{ name: 'index', dt: core.datatypes.ARRAY, desc: 'The index buffer (depends on primitive type).' }
	];

	this.output_slots = [
		{ name: 'mesh', dt: core.datatypes.MESH, desc: 'The resulting mesh.' }
	];

	this.gl = core.renderer.context;
	this.mesh = new Mesh(this.gl, this.gl.TRIANGLES);
	this.vertices = null;
	this.normals = null;
	this.colors = null;
	this.uv0 = null;
	this.uv1 = null;
	this.uv2 = null;
	this.uv3 = null;
};

E2.p.prototype.update_vertex_buffer = function(v_name, v_type, data)
{
	var vbs = this.mesh.vertex_buffers;

	if(data)
	{

		if(!vbs[v_name])
			vbs[v_name] = new VertexBuffer(this.gl, v_type);

		vbs[v_name].bind_data(data, this.gl.DRAW_DYNAMIC);
	}
	else
		vbs[v_name] = null;
};

E2.p.prototype.update_input = function(slot, data)
{
	if(slot.index === 0)
		this.update_vertex_buffer('VERTEX', VertexBuffer.vertex_type.VERTEX, data);
	else if(slot.index === 1)
		this.update_vertex_buffer('NORMAL', VertexBuffer.vertex_type.NORMAL, data);
	else if(slot.index === 2)
		this.update_vertex_buffer('COLOR', VertexBuffer.vertex_type.NORMAL, data);
	else if(slot.index === 3)
		this.update_vertex_buffer('UV0', VertexBuffer.vertex_type.UV0, data);
	else if(slot.index === 4)
		this.update_vertex_buffer('UV1', VertexBuffer.vertex_type.UV1, data);
	else if(slot.index === 5)
		this.update_vertex_buffer('UV2', VertexBuffer.vertex_type.UV2, data);
	else if(slot.index === 6)
		this.update_vertex_buffer('UV3', VertexBuffer.vertex_type.UV3, data);
	else if(slot.index === 7)
	{
		var ib = this.mesh.index_buffer;

		if(data)
		{

			if(!ib)
				ib = new IndexBuffer(this.gl);

			ib.bind_data(data);
		}
		else
			ib = null;
	}
};

E2.p.prototype.update_state = function()
{
	var count = 0;
	var vbs = this.mesh.vertex_buffers;

	if(vbs['VERTEX'])
		count = Math.max(count, vbs['VERTEX'].count);

	this.mesh.generate_shader();
	this.vertex_count = count;
};

E2.p.prototype.update_output = function(slot)
{
	return this.mesh;
};
<|endoftext|>


<commit_before>'use strict';

Template.navButton.helpers({
  icon: function() {
    return Meteor.user() ? '' : 'github square icon';
  },
  text: function() {
    return Meteor.user() ? 'Sign out' : 'Login with GitHub';
  }
});

Template.navButton.events({
  'click #nav-button': function() {
    if (Meteor.user()) {
      Meteor.logout();
    }
    else {
      Meteor.loginWithGithub({
        requestPermissions: [
          'user:email',
          'repo',
          'admin:repo_hook',
          'read:org',
          'admin:org_hook',
        ]
      });
    }
  },
});
<commit_msg>redirect to accounts page on successful login<commit_after>'use strict';

Template.navButton.helpers({
  icon: function() {
    return Meteor.user() ? '' : 'github square icon';
  },
  text: function() {
    return Meteor.user() ? 'Sign out' : 'Login with GitHub';
  }
});

Template.navButton.events({
  'click #nav-button': function() {
    if (Meteor.user()) {
      Meteor.logout();
    }
    else {
      Meteor.loginWithGithub({
        requestPermissions: [
          'user:email',
          'repo',
          'admin:repo_hook',
          'read:org',
          'admin:org_hook',
        ]
      }, function(err){
        if (!err) {
          Router.go('accounts');
        }
      });
    }
  },
});
<|endoftext|>


<commit_before>/* eslint no-unused-expressions:0, max-nested-callbacks: [2, 5] */

"use strict";
import DbSession from "../../src/js/db/DbSession.js";
import DbParameters from "../../src/js/db/DbParameters.js";
import UserSession from "../../src/js/user/UserSession.js";
import { assert } from "chai";
import sinon from "sinon";

describe("DbSession", () => {
    let parametersFake = null, allSandbox = null;
    before("DbSession", () => {
        allSandbox = sinon.sandbox.create();
        allSandbox.stub(console, "warn");
        parametersFake = {
            "type": () => {
                return "PouchDB";
            },
            "getLocalDbUrl": () => {
                return "localDb";
            },
            "getRemoteDbUrl": () => {
                return "remoteDb";
            },
            "clearInstance": () => {}
        };
        allSandbox.stub(DbParameters, "instance").returns(parametersFake);
    });

    after("DbSession", () => {
        allSandbox.restore();
    });

    describe("instance", () => {
        let userSession = null, userSessionMock = null, dbSession = null, sandbox = null;
        beforeEach("DbSession", () => {
            dbSession = new DbSession();
            userSession = new UserSession();
            sandbox = sinon.sandbox.create();
            sandbox.stub(DbSession, "new").returns(dbSession);

            sandbox.stub(UserSession, "instance").returns(userSession);
            userSessionMock = sinon.mock(userSession).expects("setLastAccessedTime");
        });

        afterEach("DbSession", () => {
            DbSession.clearInstance();
            sandbox.restore();
        });

        it("should create the remote db instance", (done) => {
            let dbSessionRemoteDbInstanceMock = sandbox.mock(dbSession).expects("remoteDbInstance").returns(Promise.resolve("session"));
            DbSession.instance().then(session => {
                assert.strictEqual("session", session);
                assert.strictEqual("session", DbSession.db);
                userSessionMock.verify();
                dbSessionRemoteDbInstanceMock.verify();
                done();
            });
        });

        it("should return the previously created db instance", (done) => {
            let dbSessionRemoteDbInstanceMock = sandbox.mock(dbSession).expects("remoteDbInstance").returns(Promise.resolve("session"));
            userSessionMock.twice();
            DbSession.instance().then(session1 => { //eslint-disable-line

                DbSession.instance().then(session2 => {
                    assert.strictEqual("session", session2);
                    assert.strictEqual("session", DbSession.db);
                    userSessionMock.verify();
                    dbSessionRemoteDbInstanceMock.verify();
                    done();
                });
            });
        });
    });

    describe("remoteDbInstance", () => {
        let dbInstance = null, sandbox = null;
        beforeEach("remoteDbInstance", () => {
            sandbox = sinon.sandbox.create();
            dbInstance = new DbSession();
        });

        afterEach("remoteDbInstance", () => {
            sandbox.restore();
        });

        it("should create pouch db of remote instance and initiate replication", (done) => {
            let remotePouchDbMock = sandbox.mock(DbSession).expects("newRemotePouchDb");
            let replicationMock = sandbox.mock(dbInstance).expects("replicateDb").withArgs(parametersFake.getRemoteDbUrl(), parametersFake.getLocalDbUrl(), {
                "retry": true,
                "live": false
            }, true);
            remotePouchDbMock.returns(Promise.resolve("session"));
            dbInstance.remoteDbInstance().then(session => {
                assert.strictEqual("session", session);
                remotePouchDbMock.verify();
                replicationMock.verify();
                done();
            });
        });
    });

    describe("sync", () => {
        let dbSession = null;
        beforeEach("Sync", () => {
            dbSession = new DbSession();
        });

        afterEach("Sync", () => {

        });

        it("should start the pouchd db sync with remote db. Second call should stop the existing sync", () => {
            let cancelReturn = {
                "cancel": () => {
                }
            };
            let cancelSpy = sinon.spy(cancelReturn, "cancel");

            let dbSessionReplicateDbMock = allSandbox.mock(dbSession).expects("replicateDb").withArgs(parametersFake.getLocalDbUrl(), parametersFake.getRemoteDbUrl(), {
                "retry": true,
                "live": true
            }, false).returns(cancelReturn).twice();

            let THREEMINUTE = 180000;
            let replicateRemoteDbMock = allSandbox.mock(dbSession).expects("replicateRemoteDb");
            replicateRemoteDbMock.withArgs(THREEMINUTE).twice();

            dbSession.sync();
            dbSession.sync();
            dbSessionReplicateDbMock.verify();
            replicateRemoteDbMock.verify();

            assert.isTrue(cancelSpy.calledOnce);
            cancelSpy.restore();
        });
    });

    describe("replicate", () => {
        let dbSession = null, sandbox = null, dbSessionPouchDbMock = null, dbSessionLocalPouchDbMock = null, pouchDbSyncMock = null;
        let pouchDbDummy = null;
        beforeEach("replicate", () => {
            sandbox = sinon.sandbox.create();
            dbSession = new DbSession();
            pouchDbDummy = {
                "sync": (toDb, options) => {

                }
            }
            dbSessionPouchDbMock = sandbox.mock(DbSession).expects("newPouchDb");
            dbSessionLocalPouchDbMock = sandbox.mock(DbSession).expects("newLocalPouchDb");
            pouchDbSyncMock = sandbox.mock(pouchDbDummy).expects("sync");
        });

        afterEach("replicate", () => {
            sandbox.restore();
        });

        it("should start the pouchd db replicate with remote db and start sync. Replace db with local db once replication completed", (done) => {
            dbSessionPouchDbMock.withArgs("localDb").returns(pouchDbDummy);
            dbSessionLocalPouchDbMock.returns(Promise.resolve("session"));
            sandbox.mock(dbSession).expects("sync");

            let dbObj = { "on": (action, callback) => {
                callback(); //eslint-disable-line callback-return
                if(action === "complete") {
                    dbSessionLocalPouchDbMock.verify();
                    dbSessionPouchDbMock.verify();
                    pouchDbSyncMock.verify();
                    done();
                }
                return dbObj;
            }
            };

            pouchDbSyncMock.withArgs("remoteDb", {
                "retry": true,
                "live": true
            }).returns(dbObj);

            dbSession.replicateDb("localDb", "remoteDb", {
                "retry": true,
                "live": true
            }, true);
        });
    });
});
<commit_msg>[Vik] modified test cases in DbSession<commit_after>/* eslint no-unused-expressions:0, max-nested-callbacks: [2, 5] */

"use strict";
import DbSession from "../../src/js/db/DbSession.js";
import DbParameters from "../../src/js/db/DbParameters.js";
import UserSession from "../../src/js/user/UserSession.js";
import { assert } from "chai";
import sinon from "sinon";

describe("DbSession", () => {
    let parametersFake = null, allSandbox = null;
    before("DbSession", () => {
        allSandbox = sinon.sandbox.create();
        allSandbox.stub(console, "warn");
        parametersFake = {
            "type": () => {
                return "PouchDB";
            },
            "getLocalDbUrl": () => {
                return "localDb";
            },
            "getRemoteDbUrl": () => {
                return "remoteDb";
            },
            "clearInstance": () => {}
        };
        allSandbox.stub(DbParameters, "instance").returns(parametersFake);
    });

    after("DbSession", () => {
        allSandbox.restore();
    });

    describe("instance", () => {
        let userSession = null, userSessionMock = null, dbSession = null, sandbox = null;
        beforeEach("DbSession", () => {
            DbSession.clearInstance();

            dbSession = new DbSession();
            userSession = new UserSession();
            sandbox = sinon.sandbox.create();
            sandbox.stub(DbSession, "new").returns(dbSession);

            sandbox.stub(UserSession, "instance").returns(userSession);
            userSessionMock = sinon.mock(userSession).expects("setLastAccessedTime");
        });

        afterEach("DbSession", () => {
            sandbox.restore();
        });

        it("should create the remote db instance", (done) => {
            let dbSessionRemoteDbInstanceMock = sandbox.mock(dbSession).expects("remoteDbInstance").returns(Promise.resolve("session"));
            DbSession.instance().then(session => {
                assert.strictEqual("session", session);
                assert.strictEqual("session", DbSession.db);
                userSessionMock.verify();
                dbSessionRemoteDbInstanceMock.verify();
                done();
            });
        });

        it("should return the previously created db instance", (done) => {
            let dbSessionRemoteDbInstanceMock = sandbox.mock(dbSession).expects("remoteDbInstance").returns(Promise.resolve("session"));
            userSessionMock.twice();
            DbSession.instance().then(session1 => { //eslint-disable-line

                DbSession.instance().then(session2 => {
                    assert.strictEqual("session", session2);
                    assert.strictEqual("session", DbSession.db);
                    userSessionMock.verify();
                    dbSessionRemoteDbInstanceMock.verify();
                    done();
                });
            });
        });
    });

    describe("remoteDbInstance", () => {
        let dbInstance = null, sandbox = null;
        beforeEach("remoteDbInstance", () => {
            sandbox = sinon.sandbox.create();
            dbInstance = new DbSession();
        });

        afterEach("remoteDbInstance", () => {
            sandbox.restore();
        });

        it("should create pouch db of remote instance and initiate replication", (done) => {
            let remotePouchDbMock = sandbox.mock(DbSession).expects("newRemotePouchDb");
            let replicationMock = sandbox.mock(dbInstance).expects("replicateDb").withArgs(parametersFake.getRemoteDbUrl(), parametersFake.getLocalDbUrl(), {
                "retry": true,
                "live": false
            }, true);
            remotePouchDbMock.returns(Promise.resolve("session"));
            dbInstance.remoteDbInstance().then(session => {
                assert.strictEqual("session", session);
                remotePouchDbMock.verify();
                replicationMock.verify();
                done();
            });
        });
    });

    describe("sync", () => {
        let dbSession = null;
        beforeEach("Sync", () => {
            dbSession = new DbSession();
        });

        afterEach("Sync", () => {

        });

        it("should start the pouchd db sync with remote db. Second call should stop the existing sync", () => {
            let cancelReturn = {
                "cancel": () => {
                }
            };
            let cancelSpy = sinon.spy(cancelReturn, "cancel");

            let dbSessionReplicateDbMock = allSandbox.mock(dbSession).expects("replicateDb").withArgs(parametersFake.getLocalDbUrl(), parametersFake.getRemoteDbUrl(), {
                "retry": true,
                "live": true
            }, false).returns(cancelReturn).twice();

            let THREEMINUTE = 180000;
            let replicateRemoteDbMock = allSandbox.mock(dbSession).expects("replicateRemoteDb");
            replicateRemoteDbMock.withArgs(THREEMINUTE).twice();

            dbSession.sync();
            dbSession.sync();
            dbSessionReplicateDbMock.verify();
            replicateRemoteDbMock.verify();

            assert.isTrue(cancelSpy.calledOnce);
            cancelSpy.restore();
        });
    });

    describe("replicate", () => {
        let dbSession = null, sandbox = null, dbSessionPouchDbMock = null, dbSessionLocalPouchDbMock = null, pouchDbSyncMock = null;
        let pouchDbDummy = null;
        beforeEach("replicate", () => {
            sandbox = sinon.sandbox.create();
            dbSession = new DbSession();
            pouchDbDummy = {
                "sync": (toDb, options) => {

                }
            }
            dbSessionPouchDbMock = sandbox.mock(DbSession).expects("newPouchDb");
            dbSessionLocalPouchDbMock = sandbox.mock(DbSession).expects("newLocalPouchDb");
            pouchDbSyncMock = sandbox.mock(pouchDbDummy).expects("sync");
        });

        afterEach("replicate", () => {
            sandbox.restore();
        });

        it("should start the pouchd db replicate with remote db and start sync. Replace db with local db once replication completed", (done) => {
            dbSessionPouchDbMock.withArgs("localDb").returns(pouchDbDummy);
            dbSessionLocalPouchDbMock.returns(Promise.resolve("session"));
            sandbox.mock(dbSession).expects("sync");

            let dbObj = { "on": (action, callback) => {
                callback(); //eslint-disable-line callback-return
                if(action === "complete") {
                    dbSessionLocalPouchDbMock.verify();
                    dbSessionPouchDbMock.verify();
                    pouchDbSyncMock.verify();
                    done();
                }
                return dbObj;
            }
            };

            pouchDbSyncMock.withArgs("remoteDb", {
                "retry": true,
                "live": true
            }).returns(dbObj);

            dbSession.replicateDb("localDb", "remoteDb", {
                "retry": true,
                "live": true
            }, true);
        });
    });
});
<|endoftext|>


<commit_before>var gulp = require('gulp')
var rename = require('gulp-rename')
var pug = require('gulp-pug')
var less = require('gulp-less')
var autoprefixer = require('gulp-autoprefixer')
var clean_css = require('gulp-clean-css')
var sourcemaps = require('gulp-sourcemaps')

gulp.task('pug:docs', function () {
  return gulp.src('docs/{index,base,obj,comp,help,atom}.pug')
    .pipe(pug({
      basedir: './',
      locals: {
        Docs: require('./docs/_models/Docs.class.js'),
      },
    }))
    .pipe(gulp.dest('./docs/'))
})

gulp.task('lessc:docs', function () {
  return gulp.src('docs/styles/docs.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./docs/styles/'))
})

gulp.task('lessc:xmeter', function () {
  return gulp.src('xmeter.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./'))
})

gulp.task('minify', ['lessc:xmeter'], function () {
  return gulp.src('xmeter.css')
    .pipe(sourcemaps.init())
    .pipe(clean_css())
    .pipe(rename('xmeter.min.css'))
    .pipe(sourcemaps.write('./')) // writes to an external .map file
    .pipe(gulp.dest('./'))
})

gulp.task('build', ['pug:docs', 'lessc:docs', 'minify'])
<commit_msg>rename gulp task<commit_after>var gulp = require('gulp')
var rename = require('gulp-rename')
var pug = require('gulp-pug')
var less = require('gulp-less')
var autoprefixer = require('gulp-autoprefixer')
var clean_css = require('gulp-clean-css')
var sourcemaps = require('gulp-sourcemaps')

gulp.task('pug:docs', function () {
  return gulp.src('docs/{index,base,obj,comp,help,atom}.pug')
    .pipe(pug({
      basedir: './',
      locals: {
        Docs: require('./docs/_models/Docs.class.js'),
      },
    }))
    .pipe(gulp.dest('./docs/'))
})

gulp.task('lessc:docs', function () {
  return gulp.src('docs/styles/docs.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./docs/styles/'))
})

gulp.task('lessc:core', function () {
  return gulp.src('xmeter.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./'))
})

gulp.task('minify', ['lessc:core'], function () {
  return gulp.src('xmeter.css')
    .pipe(sourcemaps.init())
    .pipe(clean_css())
    .pipe(rename('xmeter.min.css'))
    .pipe(sourcemaps.write('./')) // writes to an external .map file
    .pipe(gulp.dest('./'))
})

gulp.task('build', ['pug:docs', 'lessc:docs', 'minify'])
<|endoftext|>