<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:18-02-19');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:18-02-20');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>
function setNameOptionsByCharName(charName, columnNumber) {
	if (charName == "") {
		charName = document.getElementById("charName").value;
	}
	var columnType = document.getElementById("columnType" + columnNumber).value;
	if (columnType == "Datum") {
		hide("conditionPropertyPrompt" + columnNumber);
		hide("conditionPropertyLabel" + columnNumber);
		FindingManager.getDatumNameOptions(charName, function (data) {
			dwr.util.removeAllOptions("columnName" + columnNumber);
			dwr.util.addOptions("columnName" + columnNumber, [""]);
			dwr.util.addOptions("columnName" + columnNumber, data);
			dwr.util.addOptions("columnName" + columnNumber, ["[Other]"]);
		});
	} else {
		if (columnType == "Condition") {
			show("conditionPropertyPrompt" + columnNumber);
			show("conditionPropertyLabel" + columnNumber);
			FindingManager.getConditionOptions(function (data) {
				dwr.util.removeAllOptions("columnName" + columnNumber);
				dwr.util.addOptions("columnName" + columnNumber, [""]);
				dwr.util.addOptions("columnName" + columnNumber, data);
				dwr.util.addOptions("columnName" + columnNumber, ["[Other]"]);
			});
		} else {
			hide("conditionPropertyPrompt" + columnNumber);
			hide("conditionPropertyLabel" + columnNumber);
			dwr.util.removeAllOptions("columnName" + columnNumber);
			dwr.util.addOptions("columnName" + columnNumber, [""]);
			dwr.util.addOptions("columnName" + columnNumber, ["[Other]"]);
		}
	}
}
function setConditionPropertyOptionsByCharName(conditionName, columnNumber) {
	if (document.getElementById("columnType" + columnNumber).value == "Condition") {
		if (conditionName == null) {
			conditionName = document.getElementById("columnName" + columnNumber).value;
		}
		FindingManager.getConditionPropertyOptions(conditionName, function (data) {
			dwr.util.removeAllOptions("conditionProperty" + columnNumber);
			dwr.util.addOptions("conditionProperty" + columnNumber, [""]);
			dwr.util.addOptions("conditionProperty" + columnNumber, data);
			dwr.util.addOptions("conditionProperty" + columnNumber, ["[Other]"]);
		});
	}
}
function setColumnValueUnit(columnNumber) {
	var name = null, property = null;
	if (document.getElementById("columnType" + columnNumber).value == "Condition") {
		property = document.getElementById("conditionProperty" + columnNumber).value;
	}
	name = document.getElementById("columnName" + columnNumber).value;
	FindingManager.getColumnValueUnitOptions(name, property, function (data) {
		dwr.util.removeAllOptions("valueUnit" + columnNumber);
		dwr.util.addOptions("valueUnit" + columnNumber, [""]);
		dwr.util.addOptions("valueUnit" + columnNumber, data);
		dwr.util.addOptions("valueUnit" + columnNumber, ["[Other]"]);
	});
}
function resetTheFinding(isShow) {
	editFinding = false;
	headerColumnCount = 0;
	datumHeaderColumnCount = 0;
	conditionHeaderColumnCount = 0;
	columnCount = 0;
	rowCount = 0;
	if (isShow) {
		show("newFinding");
	} else {
		hide("newFinding");
		return;
	}
}
function setTheFinding(form, actionName, findingId) {
	form.action = actionName + ".do?dispatch=getFinding&findingId=" + findingId + "&page=0";
	form.submit();
}
function populateFinding(finding) {
	if (finding != null) {
		dwr.util.setValue("colNum", finding.numberOfColumns);
		dwr.util.setValue("rowNum", finding.numberOfRows);
		for (i = 0; i < finding.columnHeaders.length; i++) {
			alert(finding.columnHeaders[i].displayName);
			dwr.util.setValue("columnHeaderDisplayName" + i + 1, finding.columnHeaders[i].displayName);
		}
	}
}
function clearFile() {
	dwr.util.setValue("fileType", "");
	dwr.util.setValue("fileTitle", "");
	dwr.util.setValue("fileKeywords", "");
	dwr.util.setValue("fileVisibility", "");
	dwr.util.setValue("external0", 1);
	dwr.util.setValue("uploadedFile", null);
	show("load");
	dwr.util.setValue("externalUrl", "");
	FindingManager.resetFile(function (file) {
		currentFile = file;
	});
}
function addFile(form, actionName) {
	submitAction(form, actionName, "addFile");
}
function setTheFile(index) {
	show("newFile");
	show("deleteFile");
	currentFileIndex = index;
	window.setTimeout("updateFile()", 300);
}
function updateFile() {
	FindingManager.getFileFromList(currentFileIndex, populateFile);
}
function populateFile(file) {
	if (file != null) {
		currentFile = file;
		dwr.util.setValue("fileType", file.domainFile.type);
		dwr.util.setValue("fileTitle", file.domainFile.Title);
		dwr.util.setValue("fileKeywords", file.keywordStr);
		dwr.util.setValue("fileVisibility", file.visibilities);
		dwr.util.setValue("external0", 1);
	    //dwr.util.setValue("uploadedFile", null);
	}
}
function updateMatrix(form) {
	var colNum = dwr.util.getValue("colNum");
	var rowNum = dwr.util.getValue("rowNum");
	if (colNum > 0 && rowNum > 0) {
		form.action = "characterization.do?dispatch=drawMatrix&page=0";
		form.submit();
	}
}
function reduceMatrix(form, type, index) {
	form.action = "characterization.do?dispatch=drawMatrix&page=0&remove" + type + "=" + index;
	form.submit();
}
function openColumnForm(characterizationName, columnNumber) {
	var promptbox = document.createElement("div");
	promptbox.setAttribute("id", "newColumn" + columnNumber);
	document.getElementById("column" + columnNumber).appendChild(promptbox);
	FindingManager.getSubmitColumnPage(columnNumber, function (pageData) {
		document.getElementById("newColumn" + columnNumber).innerHTML = pageData;
		//populate column entry table from hidden values, use timeout to populate drop down first
		dwr.util.setValue("columnType" + columnNumber, dwr.util.getValue("theColumnType" + columnNumber));
		setNameOptionsByCharName(characterizationName, columnNumber);
		window.setTimeout("delaySetColumnName(" + columnNumber + ")", 100);
		dwr.util.setValue("valueType" + columnNumber, dwr.util.getValue("theValueType" + columnNumber));
		dwr.util.setValue("constantValue" + columnNumber, dwr.util.getValue("theConstantValue" + columnNumber));
	});
	    //set style of the column entry table
	document.getElementById("newColumn" + columnNumber).style.display = "block";
	document.getElementById("newColumn" + columnNumber).style.position = "absolute";
	document.getElementById("newColumn" + columnNumber).style.top = "20px";
	document.getElementById("newColumn" + columnNumber).style.left = "10px";
	document.getElementById("newColumn" + columnNumber).style.width = "350px";
	document.getElementById("newColumn" + columnNumber).style.zIndex = "5";
}
function delaySetColumnName(columnNumber) {
	dwr.util.setValue("columnName" + columnNumber, dwr.util.getValue("theColumnName" + columnNumber));
	setConditionPropertyOptionsByCharName(null, columnNumber);
	setColumnValueUnit(columnNumber);
	window.setTimeout("delaySetConditionProperty(" + columnNumber + ")", 100);
	window.setTimeout("delaySetColumnValueUnit(" + columnNumber + ")", 100);
}
function delaySetConditionProperty(columnNumber) {
	dwr.util.setValue("conditionProperty" + columnNumber, dwr.util.getValue("theConditionProperty" + columnNumber));
	setColumnValueUnit(columnNumber);
	window.setTimeout("delaySetColumnValueUnit(" + columnNumber + ")", 100);
}
function delaySetColumnValueUnit(columnNumber) {
	dwr.util.setValue("valueUnit" + columnNumber, dwr.util.getValue("theValueUnit" + columnNumber));
}
function cancelColumn(columnNumber) {
	document.getElementById("column" + columnNumber).removeChild(document.getElementById("newColumn" + columnNumber));
}
function addColumnHeader(columnNumber) {
	var columnHeader = {"columnName":dwr.util.getValue("columnName" + columnNumber), "columnType":dwr.util.getValue("columnType" + columnNumber), "conditionProperty":dwr.util.getValue("conditionProperty" + columnNumber), "valueType":dwr.util.getValue("valueType" + columnNumber), "valueUnit":dwr.util.getValue("valueUnit" + columnNumber), "constantValue":dwr.util.getValue("constantValue" + columnNumber)};
	var numberOfRows = dwr.util.getValue("rowNum");
	if (columnHeader.constantValue != null) {
		for (i = 0; i < numberOfRows; i++) {
			dwr.util.setValue("cellValue" + i + ":" + columnNumber, columnHeader.constantValue);
		}
	}
	FindingManager.addColumnHeader(columnHeader, function (displayName) {
		dwr.util.setValue("columnHeaderDisplayName" + columnNumber, displayName);
		//set the hidden properties
		dwr.util.setValue("theColumnType" + columnNumber, columnHeader.columnType);
		dwr.util.setValue("theColumnName" + columnNumber, columnHeader.columnName);
		dwr.util.setValue("theConditionProperty" + columnNumber, columnHeader.conditionProperty);
		dwr.util.setValue("theValueType" + columnNumber, columnHeader.valueType);
		dwr.util.setValue("theValueUnit" + columnNumber, columnHeader.valueUnit);
		dwr.util.setValue("theConstantValue" + columnNumber, columnHeader.constantValue);
	});
	hide("newColumn" + columnNumber);
}

<commit_msg>updated file related functions<commit_after>
function setNameOptionsByCharName(charName, columnNumber) {
	if (charName == "") {
		charName = document.getElementById("charName").value;
	}
	var columnType = document.getElementById("columnType" + columnNumber).value;
	if (columnType == "Datum") {
		hide("conditionPropertyPrompt" + columnNumber);
		hide("conditionPropertyLabel" + columnNumber);
		FindingManager.getDatumNameOptions(charName, function (data) {
			dwr.util.removeAllOptions("columnName" + columnNumber);
			dwr.util.addOptions("columnName" + columnNumber, [""]);
			dwr.util.addOptions("columnName" + columnNumber, data);
			dwr.util.addOptions("columnName" + columnNumber, ["[Other]"]);
		});
	} else {
		if (columnType == "Condition") {
			show("conditionPropertyPrompt" + columnNumber);
			show("conditionPropertyLabel" + columnNumber);
			FindingManager.getConditionOptions(function (data) {
				dwr.util.removeAllOptions("columnName" + columnNumber);
				dwr.util.addOptions("columnName" + columnNumber, [""]);
				dwr.util.addOptions("columnName" + columnNumber, data);
				dwr.util.addOptions("columnName" + columnNumber, ["[Other]"]);
			});
		} else {
			hide("conditionPropertyPrompt" + columnNumber);
			hide("conditionPropertyLabel" + columnNumber);
			dwr.util.removeAllOptions("columnName" + columnNumber);
			dwr.util.addOptions("columnName" + columnNumber, [""]);
			dwr.util.addOptions("columnName" + columnNumber, ["[Other]"]);
		}
	}
}
function setConditionPropertyOptionsByCharName(conditionName, columnNumber) {
	if (document.getElementById("columnType" + columnNumber).value == "Condition") {
		if (conditionName == null) {
			conditionName = document.getElementById("columnName" + columnNumber).value;
		}
		FindingManager.getConditionPropertyOptions(conditionName, function (data) {
			dwr.util.removeAllOptions("conditionProperty" + columnNumber);
			dwr.util.addOptions("conditionProperty" + columnNumber, [""]);
			dwr.util.addOptions("conditionProperty" + columnNumber, data);
			dwr.util.addOptions("conditionProperty" + columnNumber, ["[Other]"]);
		});
	}
}
function setColumnValueUnit(columnNumber) {
	var name = null, property = null;
	if (document.getElementById("columnType" + columnNumber).value == "Condition") {
		property = document.getElementById("conditionProperty" + columnNumber).value;
	}
	name = document.getElementById("columnName" + columnNumber).value;
	FindingManager.getColumnValueUnitOptions(name, property, function (data) {
		dwr.util.removeAllOptions("valueUnit" + columnNumber);
		dwr.util.addOptions("valueUnit" + columnNumber, [""]);
		dwr.util.addOptions("valueUnit" + columnNumber, data);
		dwr.util.addOptions("valueUnit" + columnNumber, ["[Other]"]);
	});
}
function resetTheFinding(form, isShow) {
	form.action = "characterization.do?dispatch=resetFinding&page=0";
	form.submit();
}
function setTheFinding(form, actionName, findingId) {
	form.action = actionName + ".do?dispatch=getFinding&findingId=" + findingId + "&page=0";
	form.submit();
}
function populateFinding(finding) {
	if (finding != null) {
		dwr.util.setValue("colNum", finding.numberOfColumns);
		dwr.util.setValue("rowNum", finding.numberOfRows);
		for (i = 0; i < finding.columnHeaders.length; i++) {
			dwr.util.setValue("columnHeaderDisplayName" + i + 1, finding.columnHeaders[i].displayName);
		}
	} else {
		dwr.util.setValue("colNum", 0);
		dwr.util.setValue("rowNum", 0);
	}
}
function clearFile() {
	dwr.util.setValue("fileType", "");
	dwr.util.setValue("fileTitle", "");
	dwr.util.setValue("fileKeywords", "");
	dwr.util.setValue("fileVisibility", "");
	show("load");
	hide("link");
	dwr.util.setValue("external0", true);
	dwr.util.setValue("external1", false);
	FindingManager.resetFile(function (file) {
		currentFile = file;
	});
}
function addFile(form) {
	form.action = "characterization.do?dispatch=addFile&page=0";
	form.submit();
}
function setTheFile(index) {
	//window.setTimeout("updateFile(" + index + ")", 300);
	FindingManager.getFileFromList(index, populateFile);
	show("newFile");
	show("deleteFile");
}
function updateFile(index) {
	FindingManager.getFileFromList(index, populateFile);
}
function populateFile(file) {
	if (file != null) {
		dwr.util.setValue("fileType", file.domainFile.type);
		dwr.util.setValue("fileTitle", file.domainFile.Title);
		dwr.util.setValue("fileKeywords", file.keywordStr);
		dwr.util.setValue("fileVisibility", file.visibilities);
		dwr.util.setValue("external0", 1);
	    //dwr.util.setValue("uploadedFile", null);
	}
}
function updateMatrix(form) {
	var colNum = dwr.util.getValue("colNum");
	var rowNum = dwr.util.getValue("rowNum");
	if (colNum > 0 && rowNum > 0) {
		form.action = "characterization.do?dispatch=drawMatrix&page=0";
		form.submit();
	}
}
function reduceMatrix(form, type, index) {
	form.action = "characterization.do?dispatch=drawMatrix&page=0&remove" + type + "=" + index;
	form.submit();
}
function openColumnForm(characterizationName, columnNumber) {
	var promptbox = document.createElement("div");
	promptbox.setAttribute("id", "newColumn" + columnNumber);
	document.getElementById("column" + columnNumber).appendChild(promptbox);
	FindingManager.getSubmitColumnPage(columnNumber, function (pageData) {
		document.getElementById("newColumn" + columnNumber).innerHTML = pageData;
		//populate column entry table from hidden values, use timeout to populate drop down first
		dwr.util.setValue("columnType" + columnNumber, dwr.util.getValue("theColumnType" + columnNumber));
		setNameOptionsByCharName(characterizationName, columnNumber);
		window.setTimeout("delaySetColumnName(" + columnNumber + ")", 100);
		dwr.util.setValue("valueType" + columnNumber, dwr.util.getValue("theValueType" + columnNumber));
		dwr.util.setValue("constantValue" + columnNumber, dwr.util.getValue("theConstantValue" + columnNumber));
	});
	    //set style of the column entry table
	document.getElementById("newColumn" + columnNumber).style.display = "block";
	document.getElementById("newColumn" + columnNumber).style.position = "absolute";
	document.getElementById("newColumn" + columnNumber).style.top = "20px";
	document.getElementById("newColumn" + columnNumber).style.left = "10px";
	document.getElementById("newColumn" + columnNumber).style.width = "350px";
	document.getElementById("newColumn" + columnNumber).style.zIndex = "5";
}
function delaySetColumnName(columnNumber) {
	dwr.util.setValue("columnName" + columnNumber, dwr.util.getValue("theColumnName" + columnNumber));
	setConditionPropertyOptionsByCharName(null, columnNumber);
	setColumnValueUnit(columnNumber);
	window.setTimeout("delaySetConditionProperty(" + columnNumber + ")", 100);
	window.setTimeout("delaySetColumnValueUnit(" + columnNumber + ")", 100);
}
function delaySetConditionProperty(columnNumber) {
	dwr.util.setValue("conditionProperty" + columnNumber, dwr.util.getValue("theConditionProperty" + columnNumber));
	setColumnValueUnit(columnNumber);
	window.setTimeout("delaySetColumnValueUnit(" + columnNumber + ")", 100);
}
function delaySetColumnValueUnit(columnNumber) {
	dwr.util.setValue("valueUnit" + columnNumber, dwr.util.getValue("theValueUnit" + columnNumber));
}
function cancelColumn(columnNumber) {
	document.getElementById("column" + columnNumber).removeChild(document.getElementById("newColumn" + columnNumber));
}
function addColumnHeader(columnNumber) {
	var columnHeader = {"columnName":dwr.util.getValue("columnName" + columnNumber), "columnType":dwr.util.getValue("columnType" + columnNumber), "conditionProperty":dwr.util.getValue("conditionProperty" + columnNumber), "valueType":dwr.util.getValue("valueType" + columnNumber), "valueUnit":dwr.util.getValue("valueUnit" + columnNumber), "constantValue":dwr.util.getValue("constantValue" + columnNumber)};
	var numberOfRows = dwr.util.getValue("rowNum");
	if (columnHeader.constantValue != null) {
		for (i = 0; i < numberOfRows; i++) {
			dwr.util.setValue("cellValue" + i + ":" + columnNumber, columnHeader.constantValue);
		}
	}
	FindingManager.addColumnHeader(columnHeader, function (displayName) {
		dwr.util.setValue("columnHeaderDisplayName" + columnNumber, displayName);
		//set the hidden properties
		dwr.util.setValue("theColumnType" + columnNumber, columnHeader.columnType);
		dwr.util.setValue("theColumnName" + columnNumber, columnHeader.columnName);
		dwr.util.setValue("theConditionProperty" + columnNumber, columnHeader.conditionProperty);
		dwr.util.setValue("theValueType" + columnNumber, columnHeader.valueType);
		dwr.util.setValue("theValueUnit" + columnNumber, columnHeader.valueUnit);
		dwr.util.setValue("theConstantValue" + columnNumber, columnHeader.constantValue);
	});
	hide("newColumn" + columnNumber);
}

<|endoftext|>


<commit_before>var moment = require('moment');
var DateType = require('../date/DateType');
var FieldType = require('../Type');
var util = require('util');
var utils = require('keystone-utils');

var parseFormats = ['YYYY-MM-DD', 'YYYY-MM-DD h:m:s a', 'YYYY-MM-DD h:m a', 'YYYY-MM-DD H:m:s', 'YYYY-MM-DD H:m'];

/**
 * DateTime FieldType Constructor
 * @extends Field
 * @api public
 */
function datetime (list, path, options) {
	this._nativeType = Date;
	this._underscoreMethods = ['format', 'moment', 'parse'];
	this._fixedSize = 'full';
	this._properties = ['formatString', 'isUTC'];
	this.typeDescription = 'date and time';
	this.parseFormatString = options.parseFormat || parseFormats;
	this.formatString = (options.format === false) ? false : (options.format || 'YYYY-MM-DD h:m:s a');
	this.isUTC = options.utc || false;
	if (this.formatString && typeof this.formatString !== 'string') {
		throw new Error('FieldType.DateTime: options.format must be a string.');
	}
	datetime.super_.call(this, list, path, options);
	this.paths = {
		date: this._path.append('_date'),
		time: this._path.append('_time'),
	};
}
util.inherits(datetime, FieldType);

/* Inherit from DateType prototype */
datetime.prototype.addFilterToQuery = DateType.prototype.addFilterToQuery;
datetime.prototype.format = DateType.prototype.format;
datetime.prototype.moment = DateType.prototype.moment;
datetime.prototype.parse = DateType.prototype.parse;

/**
 * Get the value from a data object; may be simple or a pair of fields
 */
datetime.prototype.getInputFromData = function (data) {
	var dateValue = this.getValueFromData(data, '_date');
	var timeValue = this.getValueFromData(data, '_time');
	if (dateValue && timeValue) {
		return dateValue + ' ' + timeValue;
	}
	return this.getValueFromData(data);
};

/**
 * Parses input with the correct moment version (normal or utc) and uses
 * either the provided input format or the default set
 */
datetime.prototype.parse = function (input, format) {
	var m = this.isUTC ? moment.utc : moment;
	return m(input, format || parseFormats);
};

/**
 * Asynchronously confirms that the provided date is valid
 */
datetime.prototype.validateInput = function (data, callback) {
	var input = this.getInputFromData(data);
	var result = true;
	if (input) {
		result = this.parse(input).isValid();
	}
	utils.defer(callback, result);
};

/**
 * Asynchronously confirms that the provided date is valid
 */
datetime.prototype.validateRequiredInput = function (item, data, callback) {
	var input = this.getInputFromData(data);
	var result = !!input;
	if (input === undefined && item.get(this.path)) {
		result = true;
	}
	utils.defer(callback, result);
};

/**
 * Checks that a valid date has been provided in a data object
 * An empty value clears the stored value and is considered valid
 *
 * Deprecated
 */
datetime.prototype.inputIsValid = function (data, required, item) {
	if (!(this.path in data && !(this.paths.date in data && this.paths.time in data)) && item && item.get(this.path)) return true;
	var newValue = moment(this.getInputFromData(data), parseFormats);
	if (required && (!newValue || !newValue.isValid())) {
		return false;
	} else if (this.getInputFromData(data) && newValue && !newValue.isValid()) {
		return false;
	} else {
		return true;
	}
};

/**
 * Updates the value for this field in the item from a data object
 */
datetime.prototype.updateItem = function (item, data, callback) {
	var input = this.getInputFromData(data);
	if (input === undefined) return process.nextTick(callback);
	var newValue = this.parse(input);
	var oldValue = item.get(this.path);
	if (newValue.isValid()) {
		if (!oldValue || !newValue.isSame(oldValue)) {
			item.set(this.path, newValue.toDate());
		}
	} else if (oldValue) {
		item.set(this.path, null);
	}
	process.nextTick(callback);
};

/* Export Field Type */
module.exports = datetime;
<commit_msg>Datetime field can share validateInput and validateRequiredInput with date<commit_after>var moment = require('moment');
var DateType = require('../date/DateType');
var FieldType = require('../Type');
var util = require('util');
var utils = require('keystone-utils');

var parseFormats = ['YYYY-MM-DD', 'YYYY-MM-DD h:m:s a', 'YYYY-MM-DD h:m a', 'YYYY-MM-DD H:m:s', 'YYYY-MM-DD H:m'];

/**
 * DateTime FieldType Constructor
 * @extends Field
 * @api public
 */
function datetime (list, path, options) {
	this._nativeType = Date;
	this._underscoreMethods = ['format', 'moment', 'parse'];
	this._fixedSize = 'full';
	this._properties = ['formatString', 'isUTC'];
	this.typeDescription = 'date and time';
	this.parseFormatString = options.parseFormat || parseFormats;
	this.formatString = (options.format === false) ? false : (options.format || 'YYYY-MM-DD h:m:s a');
	this.isUTC = options.utc || false;
	if (this.formatString && typeof this.formatString !== 'string') {
		throw new Error('FieldType.DateTime: options.format must be a string.');
	}
	datetime.super_.call(this, list, path, options);
	this.paths = {
		date: this._path.append('_date'),
		time: this._path.append('_time'),
	};
}
util.inherits(datetime, FieldType);

/* Inherit from DateType prototype */
datetime.prototype.addFilterToQuery = DateType.prototype.addFilterToQuery;
datetime.prototype.format = DateType.prototype.format;
datetime.prototype.moment = DateType.prototype.moment;
datetime.prototype.validateInput = DateType.prototype.validateInput;
datetime.prototype.validateRequiredInput = DateType.prototype.validateRequiredInput;

/**
 * Get the value from a data object; may be simple or a pair of fields
 */
datetime.prototype.getInputFromData = function (data) {
	var dateValue = this.getValueFromData(data, '_date');
	var timeValue = this.getValueFromData(data, '_time');
	if (dateValue && timeValue) {
		return dateValue + ' ' + timeValue;
	}
	return this.getValueFromData(data);
};

/**
 * Parses input with the correct moment version (normal or utc) and uses
 * either the provided input format or the default set
 */
datetime.prototype.parse = function (input, format) {
	var m = this.isUTC ? moment.utc : moment;
	return m(input, format || parseFormats);
};

/**
 * Checks that a valid date has been provided in a data object
 * An empty value clears the stored value and is considered valid
 *
 * Deprecated
 */
datetime.prototype.inputIsValid = function (data, required, item) {
	if (!(this.path in data && !(this.paths.date in data && this.paths.time in data)) && item && item.get(this.path)) return true;
	var newValue = moment(this.getInputFromData(data), parseFormats);
	if (required && (!newValue || !newValue.isValid())) {
		return false;
	} else if (this.getInputFromData(data) && newValue && !newValue.isValid()) {
		return false;
	} else {
		return true;
	}
};

/**
 * Updates the value for this field in the item from a data object
 */
datetime.prototype.updateItem = function (item, data, callback) {
	var input = this.getInputFromData(data);
	if (input === undefined) return process.nextTick(callback);
	var newValue = this.parse(input);
	var oldValue = item.get(this.path);
	if (newValue.isValid()) {
		if (!oldValue || !newValue.isSame(oldValue)) {
			item.set(this.path, newValue.toDate());
		}
	} else if (oldValue) {
		item.set(this.path, null);
	}
	process.nextTick(callback);
};

/* Export Field Type */
module.exports = datetime;
<|endoftext|>


<commit_before>/*
 * CMS.js v1.0.0
 * Copyright 2015 Chris Diana
 * www.cdmedia.github.io/cms.js
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 */

var CMS = {

	settings: {
		siteName: 'CMS.js',
		siteTagline: 'Your site tagline',
		siteEmail: 'your_email@example.com',
		siteAuthor: 'Your Name',
		siteUrl: '',
		siteNavItems: [
			{ name: 'Github', href: '#', newWindow: false},
			{ name: 'About' }
		],
		pagination: 3,
		postsFolder: 'posts',
		postSnippetLength: 120,
		pagesFolder: 'pages',
		fadeSpeed: 300,
		mainContainer: $('.cms_main'),
		footerContainer: $('.cms_footer'),
		footerText: '© ' + new Date().getFullYear() + ' All Rights Reserved.',
		parseSeperator: '---',
		loader: '
Loading...
',
		get siteAttributes() {
			return [
				{ attr: 'title', value: CMS.settings.siteName },
				{ attr: '.cms_sitename', value: CMS.settings.siteName},
				{ attr: '.cms_tagline', value: CMS.settings.siteTagline},
				{ attr: '.cms_footer_text', value: CMS.settings.footerText}
			];
		},
		mode: 'Github',
		githubUserSettings: {
			username: 'yourusername',
			repo: 'yourrepo',
		},
		githubSettings: {
			branch: 'gh-pages',
			host: 'https://api.github.com'
		}
	},

	posts: [],
	pages: [],
	loaded: {},

	extend: function (target, opts, callback) {
		var next;
		if (typeof opts === "undefined") {
			opts = target;
			target = CMS;
		}
		for (next in opts) {
			if (Object.prototype.hasOwnProperty.call(opts, next)) {
				target[next] = opts[next];
			}
		}
		callback(); // check user config options
		return target;
	},

	render: function (url) {
		CMS.settings.mainContainer.html('').fadeOut(CMS.settings.fadeSpeed);
		CMS.settings.footerContainer.hide();

		var type = url.split('/')[0];
		var map = {

			// Main view
			'' : function () {
				CMS.renderPosts();
			},

			// Post view
			'#post' : function() {
				var id = url.split('#post/')[1].trim();
				CMS.renderPost(id);
			},

			// Post view
			'#page' : function() {
				var title = url.split('#page/')[1].trim();
				CMS.renderPage(title);
			}

		};

		if (map[type]) {
			map[type]();
		} else {
			var errorMsg = 'Error loading page.';
			CMS.renderError(errorMsg);
		}
	},

	renderPage: function(title) {
		CMS.pages.forEach(function(page){
			if(page.title == title) {

				var tpl = $('#page-template').html(),
					$tpl = $(tpl);

				$tpl.find('.page-title').html(page.title);
				$tpl.find('.page-content').html(page.contentData);

				CMS.settings.mainContainer.html($tpl).hide().fadeIn(CMS.settings.fadeSpeed);
			}
		});
		CMS.renderFooter();
	},

	renderPost: function(id) {
		CMS.posts.forEach(function(post){
			if(post.id == id) {

				var tpl = $('#post-template').html(),
					$tpl = $(tpl);

				$tpl.find('.post-title').html(post.title);
				$tpl.find('.post-date').html((post.date.getMonth() + 1) + '/' + post.date.getDate() + '/' +  post.date.getFullYear());
				$tpl.find('.post-content').html(post.contentData);

				CMS.settings.mainContainer.html($tpl).hide().fadeIn(CMS.settings.fadeSpeed);

				emojify.run();
			}
		});
		CMS.renderFooter();
	},

	renderPosts: function() {
		CMS.posts.forEach(function(post){
			var tpl = $('#post-template').html(),
				$tpl = $(tpl);

			var title = '' + post.title + '',
				date = (post.date.getMonth() + 1) + '/' + post.date.getDate() + '/' +  post.date.getFullYear(),
				snippet = post.contentData.split('.')[0] + '.';

			var postLink = $tpl.find('.post-title'),
				postDate = $tpl.find('.post-date'),
				postSnippet = $tpl.find('.post-content');

			postLink.on('click', function (e) {
				e.preventDefault();
				window.location.hash = 'post/' + post.id;
			});

			postLink.html(title);
			postSnippet.html(snippet);
			postDate.html(date);
			CMS.settings.mainContainer.append($tpl).hide().fadeIn(CMS.settings.fadeSpeed);
		});
		CMS.renderFooter();
	},

	renderFooter: function() {
		// Load footer later so things dont look weird loading ajax stuff
		setTimeout(function () {
			CMS.settings.footerContainer.fadeIn(CMS.settings.fadeSpeed);
		}, 800);
	},

	renderError: function(msg) {
		var tpl = $('#error-template').html(),
			$tpl = $(tpl);

		$tpl.find('.error_text').html(msg);

		CMS.settings.mainContainer.html('').fadeOut(CMS.settings.fadeSpeed, function(){
			CMS.settings.mainContainer.html($tpl).fadeIn(CMS.settings.fadeSpeed);
		});
	},

	contentLoaded: function(type) {

		CMS.loaded[type] = true;

		if(CMS.loaded.page && CMS.loaded.post) {

			// Set navigation
			this.setNavigation();

	        // Manually trigger on initial load
			$(window).trigger('hashchange');
		}
	},

	parseContent: function(content, type, file, counter, numFiles) {

		var data = content.split(CMS.settings.parseSeperator),
			contentObj = {},
			id = counter,
			date = file.date;

		contentObj.id = id;
		contentObj.date = date;

		// Get content info
		var infoData = data[1].split('\n');

		$.each(infoData, function(k, v) {
			if(v.length) {
				v.replace(/^\s+|\s+$/g, '').trim();
				var i = v.split(':');
				var val = i[1];
				k = i[0];
				contentObj[k] = val.trim();
			}
		});

		// Drop stuff we dont need
		data.splice(0,2);

		// Put everything back together if broken
		var contentData = data.join();
		//contentObj.contentData = marked(contentData);
		contentObj.contentData = micromarkdown.parse(contentData);

		if(type == 'post') {
			CMS.posts.push(contentObj);
		} else if (type == 'page') {
			CMS.pages.push(contentObj);
		}

		// Execute after all content is loaded
		if(counter === numFiles) {
			CMS.contentLoaded(type);
		}
	},

	getContent: function(type, file, counter, numFiles) {

		var urlFolder = '';

		switch(type) {
			case 'post':
				urlFolder = CMS.settings.postsFolder;
				break;
			case 'page':
				urlFolder = CMS.settings.pagesFolder;
				break;
		}

		if(CMS.settings.mode == 'Github') {
			url = file.link;
		} else {
			url = urlFolder + '/' + file.name;
		}

		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'html',
			success: function(content) {
				CMS.parseContent(content, type, file, counter, numFiles);
			},
			error: function() {
				var errorMsg = 'Error loading ' + type + ' content';
				CMS.renderError(errorMsg);
			}
		});
	},

	getFiles: function(type) {

		var folder = '',
			url = '';

		switch(type) {
			case 'post':
				folder = CMS.settings.postsFolder;
				break;
			case 'page':
				folder = CMS.settings.pagesFolder;
				break;
		}

		if(CMS.settings.mode == 'Github') {
			var gus = CMS.settings.githubUserSettings,
				gs = CMS.settings.githubSettings;
			url = gs.host + '/repos/' + gus.username + '/' + gus.repo + '/contents/' + folder + '?ref=' + gs.branch;
		} else {
			url = folder;
		}

		$.ajax({
			url: url,
			success: function(data) {

				var files = [],
					linkFiles;

				if(CMS.settings.mode == 'Github') {
					linkFiles = data;
				} else {
					linkFiles = $(data).find("a");
				}

				$(linkFiles).each(function(k, f) {

					var filename,
						downloadLink;

					if(CMS.settings.mode == 'Github') {
						filename = f.name;
						downloadLink = f.download_url;
					} else {
						filename = $(f).attr("href");
					}

					if(filename.endsWith('.md')) {
						var file = {};
						file.date = new Date(filename.substring(0, 10));
						file.name = filename;
						if(downloadLink) {
							file.link = downloadLink;
						}
						files.push(file);
					}

				});

				var counter = 0,
					numFiles = files.length;

				if(files.length > 0) {
					$(files).each(function(k, file) {
						counter++;
						CMS.getContent(type, file, counter, numFiles);
					});
				} else {
					var errorMsg = 'Error loading ' + type + 's in directory. Make sure ' +
						'there are Markdown ' + type + 's in the ' + type + 's folder.';
					CMS.renderError(errorMsg);
				}
			},
			error: function() {
				var errorMsg;
				if(CMS.settings.mode == 'Github') {
					errorMsg = 'Error loading ' + type + 's directory. Make sure ' +
						'your Github settings are correctly set in your config.js file.';
				} else {
					errorMsg = 'Error loading ' + type + 's directory. Make sure ' +
						type + 's directory is set correctly in config and .htaccess is in ' +
						type + 's directory with Apache "Options Indexes" set on.';
				}
				CMS.renderError(errorMsg);
			}
		});
	},

	setNavigation: function() {

		var nav = '
';
		CMS.settings.siteNavItems.forEach(function(navItem) {
			if(navItem.hasOwnProperty('href')) {
				nav += '
' + navItem.name + '
';
			} else {
				CMS.pages.forEach(function(page) {
					if(navItem.name == page.title) {
						nav += '
' + navItem.name + '
';
					}
				});
			}
		});
		nav += '
';

		$('.cms_nav').html(nav).hide().fadeIn(CMS.settings.fadeSpeed);

		// Set onclicks for nav links
		$.each($('.cms_nav_link'), function(k, link) {
			var title =  $(this).attr("id");
			$(this).on('click', function (e) {
				e.preventDefault();
				window.location.hash = 'page/' + title;
			});

		});
	},

	setSiteAttributes: function() {
		CMS.settings.siteAttributes.forEach(function(attribute) {

			var value;

			// Set brand
			if(attribute.attr == '.cms_sitename') {
				if (attribute.value.match(/\.(jpeg|jpg|gif|png)$/)) {
		            value = '';
		        } else {
		            value = attribute.value;
		        }
			} else {
				value = attribute.value;
			}
			$(attribute.attr).html(value).hide().fadeIn(CMS.settings.fadeSpeed);
		});
	},

	generateSite: function() {

		this.setSiteAttributes();

		var types = ['post', 'page'];

		types.forEach(function(type){
			CMS.getFiles(type);
		});

		// Check for hash changes
        $(window).on('hashchange', function () {
            CMS.render(window.location.hash);
        });
	},

	init: function (options) {
		if ($.isPlainObject(options)) {
			return this.extend(this.settings, options, function () {
				CMS.generateSite();
			});
		}
	}

};<commit_msg>-- Converted Branch --<commit_after>/*
 * CMS.js v1.0.0
 * Copyright 2015 Chris Diana
 * www.cdmedia.github.io/cms.js
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 */

var CMS = {

	settings: {
		siteName: 'CMS.js',
		siteTagline: 'Your site tagline',
		siteEmail: 'your_email@example.com',
		siteAuthor: 'Your Name',
		siteUrl: '',
		siteNavItems: [
			{ name: 'Github', href: '#', newWindow: false},
			{ name: 'About' }
		],
		pagination: 3,
		postsFolder: 'posts',
		postSnippetLength: 120,
		pagesFolder: 'pages',
		fadeSpeed: 300,
		mainContainer: $('.cms_main'),
		footerContainer: $('.cms_footer'),
		footerText: '© ' + new Date().getFullYear() + ' All Rights Reserved.',
		parseSeperator: '---',
		loader: '
Loading...
',
		get siteAttributes() {
			return [
				{ attr: 'title', value: CMS.settings.siteName },
				{ attr: '.cms_sitename', value: CMS.settings.siteName},
				{ attr: '.cms_tagline', value: CMS.settings.siteTagline},
				{ attr: '.cms_footer_text', value: CMS.settings.footerText}
			];
		},
		mode: 'Github',
		githubUserSettings: {
			username: 'yourusername',
			repo: 'yourrepo',
		},
		githubSettings: {
			branch: 'master',
			host: 'https://api.github.com'
		}
	},

	posts: [],
	pages: [],
	loaded: {},

	extend: function (target, opts, callback) {
		var next;
		if (typeof opts === "undefined") {
			opts = target;
			target = CMS;
		}
		for (next in opts) {
			if (Object.prototype.hasOwnProperty.call(opts, next)) {
				target[next] = opts[next];
			}
		}
		callback(); // check user config options
		return target;
	},

	render: function (url) {
		CMS.settings.mainContainer.html('').fadeOut(CMS.settings.fadeSpeed);
		CMS.settings.footerContainer.hide();

		var type = url.split('/')[0];
		var map = {

			// Main view
			'' : function () {
				CMS.renderPosts();
			},

			// Post view
			'#post' : function() {
				var id = url.split('#post/')[1].trim();
				CMS.renderPost(id);
			},

			// Post view
			'#page' : function() {
				var title = url.split('#page/')[1].trim();
				CMS.renderPage(title);
			}

		};

		if (map[type]) {
			map[type]();
		} else {
			var errorMsg = 'Error loading page.';
			CMS.renderError(errorMsg);
		}
	},

	renderPage: function(title) {
		CMS.pages.forEach(function(page){
			if(page.title == title) {

				var tpl = $('#page-template').html(),
					$tpl = $(tpl);

				$tpl.find('.page-title').html(page.title);
				$tpl.find('.page-content').html(page.contentData);

				CMS.settings.mainContainer.html($tpl).hide().fadeIn(CMS.settings.fadeSpeed);
			}
		});
		CMS.renderFooter();
	},

	renderPost: function(id) {
		CMS.posts.forEach(function(post){
			if(post.id == id) {

				var tpl = $('#post-template').html(),
					$tpl = $(tpl);

				$tpl.find('.post-title').html(post.title);
				$tpl.find('.post-date').html((post.date.getMonth() + 1) + '/' + post.date.getDate() + '/' +  post.date.getFullYear());
				$tpl.find('.post-content').html(post.contentData);

				CMS.settings.mainContainer.html($tpl).hide().fadeIn(CMS.settings.fadeSpeed);

				emojify.run();
			}
		});
		CMS.renderFooter();
	},

	renderPosts: function() {
		CMS.posts.forEach(function(post){
			var tpl = $('#post-template').html(),
				$tpl = $(tpl);

			var title = '' + post.title + '',
				date = (post.date.getMonth() + 1) + '/' + post.date.getDate() + '/' +  post.date.getFullYear(),
				snippet = post.contentData.split('.')[0] + '.';

			var postLink = $tpl.find('.post-title'),
				postDate = $tpl.find('.post-date'),
				postSnippet = $tpl.find('.post-content');

			postLink.on('click', function (e) {
				e.preventDefault();
				window.location.hash = 'post/' + post.id;
			});

			postLink.html(title);
			postSnippet.html(snippet);
			postDate.html(date);
			CMS.settings.mainContainer.append($tpl).hide().fadeIn(CMS.settings.fadeSpeed);
		});
		CMS.renderFooter();
	},

	renderFooter: function() {
		// Load footer later so things dont look weird loading ajax stuff
		setTimeout(function () {
			CMS.settings.footerContainer.fadeIn(CMS.settings.fadeSpeed);
		}, 800);
	},

	renderError: function(msg) {
		var tpl = $('#error-template').html(),
			$tpl = $(tpl);

		$tpl.find('.error_text').html(msg);

		CMS.settings.mainContainer.html('').fadeOut(CMS.settings.fadeSpeed, function(){
			CMS.settings.mainContainer.html($tpl).fadeIn(CMS.settings.fadeSpeed);
		});
	},

	contentLoaded: function(type) {

		CMS.loaded[type] = true;

		if(CMS.loaded.page && CMS.loaded.post) {

			// Set navigation
			this.setNavigation();

	        // Manually trigger on initial load
			$(window).trigger('hashchange');
		}
	},

	parseContent: function(content, type, file, counter, numFiles) {

		var data = content.split(CMS.settings.parseSeperator),
			contentObj = {},
			id = counter,
			date = file.date;

		contentObj.id = id;
		contentObj.date = date;

		// Get content info
		var infoData = data[1].split('\n');

		$.each(infoData, function(k, v) {
			if(v.length) {
				v.replace(/^\s+|\s+$/g, '').trim();
				var i = v.split(':');
				var val = i[1];
				k = i[0];
				contentObj[k] = val.trim();
			}
		});

		// Drop stuff we dont need
		data.splice(0,2);

		// Put everything back together if broken
		var contentData = data.join();
		//contentObj.contentData = marked(contentData);
		contentObj.contentData = micromarkdown.parse(contentData);

		if(type == 'post') {
			CMS.posts.push(contentObj);
		} else if (type == 'page') {
			CMS.pages.push(contentObj);
		}

		// Execute after all content is loaded
		if(counter === numFiles) {
			CMS.contentLoaded(type);
		}
	},

	getContent: function(type, file, counter, numFiles) {

		var urlFolder = '';

		switch(type) {
			case 'post':
				urlFolder = CMS.settings.postsFolder;
				break;
			case 'page':
				urlFolder = CMS.settings.pagesFolder;
				break;
		}

		if(CMS.settings.mode == 'Github') {
			url = file.link;
		} else {
			url = urlFolder + '/' + file.name;
		}

		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'html',
			success: function(content) {
				CMS.parseContent(content, type, file, counter, numFiles);
			},
			error: function() {
				var errorMsg = 'Error loading ' + type + ' content';
				CMS.renderError(errorMsg);
			}
		});
	},

	getFiles: function(type) {

		var folder = '',
			url = '';

		switch(type) {
			case 'post':
				folder = CMS.settings.postsFolder;
				break;
			case 'page':
				folder = CMS.settings.pagesFolder;
				break;
		}

		if(CMS.settings.mode == 'Github') {
			var gus = CMS.settings.githubUserSettings,
				gs = CMS.settings.githubSettings;
			url = gs.host + '/repos/' + gus.username + '/' + gus.repo + '/contents/' + folder + '?ref=' + gs.branch;
		} else {
			url = folder;
		}

		$.ajax({
			url: url,
			success: function(data) {

				var files = [],
					linkFiles;

				if(CMS.settings.mode == 'Github') {
					linkFiles = data;
				} else {
					linkFiles = $(data).find("a");
				}

				$(linkFiles).each(function(k, f) {

					var filename,
						downloadLink;

					if(CMS.settings.mode == 'Github') {
						filename = f.name;
						downloadLink = f.download_url;
					} else {
						filename = $(f).attr("href");
					}

					if(filename.endsWith('.md')) {
						var file = {};
						file.date = new Date(filename.substring(0, 10));
						file.name = filename;
						if(downloadLink) {
							file.link = downloadLink;
						}
						files.push(file);
					}

				});

				var counter = 0,
					numFiles = files.length;

				if(files.length > 0) {
					$(files).each(function(k, file) {
						counter++;
						CMS.getContent(type, file, counter, numFiles);
					});
				} else {
					var errorMsg = 'Error loading ' + type + 's in directory. Make sure ' +
						'there are Markdown ' + type + 's in the ' + type + 's folder.';
					CMS.renderError(errorMsg);
				}
			},
			error: function() {
				var errorMsg;
				if(CMS.settings.mode == 'Github') {
					errorMsg = 'Error loading ' + type + 's directory. Make sure ' +
						'your Github settings are correctly set in your config.js file.';
				} else {
					errorMsg = 'Error loading ' + type + 's directory. Make sure ' +
						type + 's directory is set correctly in config and .htaccess is in ' +
						type + 's directory with Apache "Options Indexes" set on.';
				}
				CMS.renderError(errorMsg);
			}
		});
	},

	setNavigation: function() {

		var nav = '
';
		CMS.settings.siteNavItems.forEach(function(navItem) {
			if(navItem.hasOwnProperty('href')) {
				nav += '
' + navItem.name + '
';
			} else {
				CMS.pages.forEach(function(page) {
					if(navItem.name == page.title) {
						nav += '
' + navItem.name + '
';
					}
				});
			}
		});
		nav += '
';

		$('.cms_nav').html(nav).hide().fadeIn(CMS.settings.fadeSpeed);

		// Set onclicks for nav links
		$.each($('.cms_nav_link'), function(k, link) {
			var title =  $(this).attr("id");
			$(this).on('click', function (e) {
				e.preventDefault();
				window.location.hash = 'page/' + title;
			});

		});
	},

	setSiteAttributes: function() {
		CMS.settings.siteAttributes.forEach(function(attribute) {

			var value;

			// Set brand
			if(attribute.attr == '.cms_sitename') {
				if (attribute.value.match(/\.(jpeg|jpg|gif|png)$/)) {
		            value = '';
		        } else {
		            value = attribute.value;
		        }
			} else {
				value = attribute.value;
			}
			$(attribute.attr).html(value).hide().fadeIn(CMS.settings.fadeSpeed);
		});
	},

	generateSite: function() {

		this.setSiteAttributes();

		var types = ['post', 'page'];

		types.forEach(function(type){
			CMS.getFiles(type);
		});

		// Check for hash changes
        $(window).on('hashchange', function () {
            CMS.render(window.location.hash);
        });
	},

	init: function (options) {
		if ($.isPlainObject(options)) {
			return this.extend(this.settings, options, function () {
				CMS.generateSite();
			});
		}
	}

};<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('18.0.0');
		this.setClientTag('node:22-03-06');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('18.0.0');
		this.setClientTag('node:22-03-07');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>/*!
 * Module dependencies.
 */

var _ = require('underscore'),
	util = require('util'),
	super_ = require('../Type');

var REGEXP_LNGLAT = /^\s*(\-?\d+(?:\.\d+)?)\s*\,\s*(\-?\d+(?:\.\d+)?)\s*$/;

/**
 * Geo FieldType Constructor
 * @extends Field
 * @api public
 */

function geopoint(list, path, options) {

	this._fixedSize = 'medium';

	// TODO: implement filtering, hard-coded as disabled for now
	options.nofilter = true;
	geopoint.super_.call(this, list, path, options);

}

/*!
 * Inherit from Field
 */

util.inherits(geopoint, super_);

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * Adds a 2dsphere indexed lat/lng pair
 *
 * @api public
 */

geopoint.prototype.addToSchema = function() {
	this.list.schema.path(this.path, _.defaults({ type: [Number], index: '2dsphere' }, this.options));
	this.bindUnderscoreMethods();
};

/**
 * Gets the field's data from an Item, as used by the React components
 */

geopoint.prototype.getData = function(item) {
	var points = item.get(this.path);
	return (points && points.length === 2) ? points : [];
};

/**
 * Formats the field value
 *
 * @api public
 */

geopoint.prototype.format = function(item) {
	return item.get(this.path).join(', ');
};

/**
 * Validates that a value for this field has been provided in a data object
 *
 * @api public
 */

geopoint.prototype.validateInput = function(data, required, item) {

	// Input is valid if the field is not required, and not present
	if (!this.path in data && !required) return true;

	var values = data[this.path];

	if (_.isArray(values)) {
		values = _.compact(values).join(',');
	}

	if (values === '' && !required) return true;

	return REGEXP_LNGLAT.test(values);

};

/**
 * Updates the value for this field in the item from a data object
 *
 * @api public
 */

geopoint.prototype.updateItem = function(item, data) {

	if (!_.isObject(data)) return;

	if (this.path in data && _.isString(data[this.path])) {

		// Value should be formatted lng,lat
		var values = REGEXP_LNGLAT.exec(data[this.path]);

		if (values) {
			item.set(this.path, [values[1], values[2]]);
		} else {
			item.set(this.path, undefined);
		}

	} else if (this.path in data && _.isArray(data[this.path])) {

		var values = data[this.path];

		if (values.length === 2 && REGEXP_LNGLAT.test(_.compact(values).join(','))) {
			item.set(this.path, values);
		} else {
			item.set(this.path, undefined);
		}

	}

};

/*!
 * Export class
 */

exports = module.exports = geopoint;
<commit_msg>Fix unary using the incorrect expression in GeoPointType - fixes #997<commit_after>/*!
 * Module dependencies.
 */

var _ = require('underscore'),
	util = require('util'),
	super_ = require('../Type');

var REGEXP_LNGLAT = /^\s*(\-?\d+(?:\.\d+)?)\s*\,\s*(\-?\d+(?:\.\d+)?)\s*$/;

/**
 * Geo FieldType Constructor
 * @extends Field
 * @api public
 */

function geopoint(list, path, options) {

	this._fixedSize = 'medium';

	// TODO: implement filtering, hard-coded as disabled for now
	options.nofilter = true;
	geopoint.super_.call(this, list, path, options);

}

/*!
 * Inherit from Field
 */

util.inherits(geopoint, super_);

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * Adds a 2dsphere indexed lat/lng pair
 *
 * @api public
 */

geopoint.prototype.addToSchema = function() {
	this.list.schema.path(this.path, _.defaults({ type: [Number], index: '2dsphere' }, this.options));
	this.bindUnderscoreMethods();
};

/**
 * Gets the field's data from an Item, as used by the React components
 */

geopoint.prototype.getData = function(item) {
	var points = item.get(this.path);
	return (points && points.length === 2) ? points : [];
};

/**
 * Formats the field value
 *
 * @api public
 */

geopoint.prototype.format = function(item) {
	return item.get(this.path).join(', ');
};

/**
 * Validates that a value for this field has been provided in a data object
 *
 * @api public
 */

geopoint.prototype.validateInput = function(data, required, item) {

	// Input is valid if the field is not required, and not present
	if (!(this.path in data) && !required) return true;

	var values = data[this.path];

	if (_.isArray(values)) {
		values = _.compact(values).join(',');
	}

	if (values === '' && !required) return true;

	return REGEXP_LNGLAT.test(values);

};

/**
 * Updates the value for this field in the item from a data object
 *
 * @api public
 */

geopoint.prototype.updateItem = function(item, data) {

	if (!_.isObject(data)) return;

	if (this.path in data && _.isString(data[this.path])) {

		// Value should be formatted lng,lat
		var values = REGEXP_LNGLAT.exec(data[this.path]);

		if (values) {
			item.set(this.path, [values[1], values[2]]);
		} else {
			item.set(this.path, undefined);
		}

	} else if (this.path in data && _.isArray(data[this.path])) {

		var values = data[this.path];

		if (values.length === 2 && REGEXP_LNGLAT.test(_.compact(values).join(','))) {
			item.set(this.path, values);
		} else {
			item.set(this.path, undefined);
		}

	}

};

/*!
 * Export class
 */

exports = module.exports = geopoint;
<|endoftext|>


<commit_before>var expect = require('chai').expect;

describe('nodex-login-mfa-auth0', function() {

  describe('package.json', function() {
    var json = require('../package.json');

    it('should have assembly metadata', function() {
      expect(json.assembly.namespace).to.equal('mfa/auth0');

      expect(json.assembly.components).to.have.length(9);
      expect(json.assembly.components).to.include('oob/verify');
    });
  });

  it('should throw if required', function() {
    expect(function() {
      var pkg = require('..');
    }).to.throw(Error).with.property('code', 'MODULE_NOT_FOUND');
  });

});
<commit_msg>Fix tests.<commit_after>var expect = require('chai').expect;

describe('nodex-login-mfa-auth0', function() {

  describe('package.json', function() {
    var json = require('../package.json');

    it('should have assembly metadata', function() {
      expect(json.assembly.namespace).to.equal('mfa/auth0');

      expect(json.assembly.components).to.have.length(8);
      expect(json.assembly.components).to.include('oob/verify');
    });
  });

  it('should throw if required', function() {
    expect(function() {
      var pkg = require('..');
    }).to.throw(Error).with.property('code', 'MODULE_NOT_FOUND');
  });

});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

define(["util"], function (util) {
  var assert = util.assert;
  var Deferred = util.Deferred;
  var DEFAULT_SETTINGS = {
    name: "",
    defaultName: "",
    avatar: null,
    stickyShare: null,
    color: null,
    seenIntroDialog: false,
    seenWalkthrough: false,
    dontShowRtcInfo: false
  };

  var DEBUG_STORAGE = false;

  var Storage = util.Class({
    constructor: function (name, storage, prefix) {
      this.name = name;
      this.storage = storage;
      this.prefix = prefix;
    },

    get: function (key, defaultValue) {
      var self = this;
      return Deferred(function (def) {
        // Strictly this isn't necessary, but eventually I want to move to something more
        // async for the storage, and this simulates that much better.
        setTimeout(util.resolver(def, function () {
          key = self.prefix + key;
          var value = self.storage.getItem(key);
          if (! value) {
            value = defaultValue;
            if (DEBUG_STORAGE) {
              console.debug("Get storage", key, "defaults to", value);
            }
          } else {
            value = JSON.parse(value);
            if (DEBUG_STORAGE) {
              console.debug("Get storage", key, "=", value);
            }
          }
          return value;
        }));
      });
    },

    set: function (key, value) {
      var self = this;
      if (value !== undefined) {
        value = JSON.stringify(value);
      }
      return Deferred(function (def) {
          key = self.prefix + key;
          if (value === undefined) {
            self.storage.removeItem(key);
            if (DEBUG_STORAGE) {
              console.debug("Delete storage", key);
            }
          } else {
            self.storage.setItem(key, value);
            if (DEBUG_STORAGE) {
              console.debug("Set storage", key, value);
            }
          }
          setTimeout(def.resolve);
      });
    },

    clear: function () {
      var self = this;
      var promises = [];
      return Deferred((function (def) {
        this.keys().then(function (keys) {
          keys.forEach(function (key) {
            // FIXME: technically we're ignoring the promise returned by all
            // these sets:
            promises.push(self.set(key, undefined));
          });
          util.resolveMany(promises).then(function () {
            def.resolve();
          });
        });
      }).bind(this));
    },

    keys: function (prefix, excludePrefix) {
      // Returns a list of keys, potentially with the given prefix
      var self = this;
      return Deferred(function (def) {
        setTimeout(util.resolver(def, function () {
          prefix = prefix || "";
          var result = [];
          for (var i=0; i<self.storage.length; i++) {
            var key = self.storage.key(i);
            if (key.indexOf(self.prefix + prefix) === 0) {
              var shortKey = key.substr(self.prefix.length);
              if (excludePrefix) {
                shortKey = shortKey.substr(prefix.length);
              }
              result.push(shortKey);
            }
          }
          return result;
        }));
      });
    },

    toString: function () {
      return '[storage for ' + this.name + ']';
    }

  });

  var namePrefix = TogetherJS.getConfig("storagePrefix");

  var storage = Storage('localStorage', localStorage, namePrefix + ".");

  storage.settings = util.mixinEvents({
    defaults: DEFAULT_SETTINGS,

    get: function (name) {
      assert(storage.settings.defaults.hasOwnProperty(name), "Unknown setting:", name);
      return storage.get("settings." + name, storage.settings.defaults[name]);
    },

    set: function (name, value) {
      assert(storage.settings.defaults.hasOwnProperty(name), "Unknown setting:", name);
      return storage.set("settings." + name, value);
    }

  });

  storage.tab = Storage('sessionStorage', sessionStorage, namePrefix + "-session.");

  return storage;
});
<commit_msg>formatting storage.js<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

define(["util"], function (util) {
  var assert = util.assert;
  var Deferred = util.Deferred;
  var DEFAULT_SETTINGS = {
    name: "",
    defaultName: "",
    avatar: null,
    stickyShare: null,
    color: null,
    seenIntroDialog: false,
    seenWalkthrough: false,
    dontShowRtcInfo: false
  };

  var DEBUG_STORAGE = false;

  var Storage = util.Class({
    constructor: function (name, storage, prefix) {
      this.name = name;
      this.storage = storage;
      this.prefix = prefix;
    },

    get: function (key, defaultValue) {
      var self = this;
      return Deferred(function (def) {
        // Strictly this isn't necessary, but eventually I want to move to something more
        // async for the storage, and this simulates that much better.
        setTimeout(util.resolver(def, function () {
          key = self.prefix + key;
          var value = self.storage.getItem(key);
          if (! value) {
            value = defaultValue;
            if (DEBUG_STORAGE) {
              console.debug("Get storage", key, "defaults to", value);
            }
          } else {
            value = JSON.parse(value);
            if (DEBUG_STORAGE) {
              console.debug("Get storage", key, "=", value);
            }
          }
          return value;
        }));
      });
    },

    set: function (key, value) {
      var self = this;
      if (value !== undefined) {
        value = JSON.stringify(value);
      }
      return Deferred(function (def) {
        key = self.prefix + key;
        if (value === undefined) {
          self.storage.removeItem(key);
          if (DEBUG_STORAGE) {
            console.debug("Delete storage", key);
          }
        } else {
          self.storage.setItem(key, value);
          if (DEBUG_STORAGE) {
            console.debug("Set storage", key, value);
          }
        }
        setTimeout(def.resolve);
      });
    },

    clear: function () {
      var self = this;
      var promises = [];
      return Deferred((function (def) {
        this.keys().then(function (keys) {
          keys.forEach(function (key) {
            // FIXME: technically we're ignoring the promise returned by all
            // these sets:
            promises.push(self.set(key, undefined));
          });
          util.resolveMany(promises).then(function () {
            def.resolve();
          });
        });
      }).bind(this));
    },

    keys: function (prefix, excludePrefix) {
      // Returns a list of keys, potentially with the given prefix
      var self = this;
      return Deferred(function (def) {
        setTimeout(util.resolver(def, function () {
          prefix = prefix || "";
          var result = [];
          for (var i = 0; i < self.storage.length; i++) {
            var key = self.storage.key(i);
            if (key.indexOf(self.prefix + prefix) === 0) {
              var shortKey = key.substr(self.prefix.length);
              if (excludePrefix) {
                shortKey = shortKey.substr(prefix.length);
              }
              result.push(shortKey);
            }
          }
          return result;
        }));
      });
    },

    toString: function () {
      return '[storage for ' + this.name + ']';
    }

  });

  var namePrefix = TogetherJS.getConfig("storagePrefix");

  var storage = Storage('localStorage', localStorage, namePrefix + ".");

  storage.settings = util.mixinEvents({
    defaults: DEFAULT_SETTINGS,

    get: function (name) {
      assert(storage.settings.defaults.hasOwnProperty(name), "Unknown setting:", name);
      return storage.get("settings." + name, storage.settings.defaults[name]);
    },

    set: function (name, value) {
      assert(storage.settings.defaults.hasOwnProperty(name), "Unknown setting:", name);
      return storage.set("settings." + name, value);
    }

  });

  storage.tab = Storage('sessionStorage', sessionStorage, namePrefix + "-session.");

  return storage;
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    // Any plugin buttons using pwg-icon class should also use glyphicon class for correct display
    //$('.pwg-icon').addClass('glyphicon');

    // Grid view button click
    $('#btn-grid').click(function() {
        $.cookie('view', 'grid');
        $('#btn-grid').addClass('active');
        $('#btn-list').removeClass('active');
        $('#content')
            .removeClass('content-list')
            .addClass('content-grid')
            .height('auto')
            .find('.col-outer').each(function() {
                $(this).removeClass('col-lg-12 col-md-12 col-sm-12 col-xs-12')
                    .addClass($(this).data('grid-classes'))
                    .one(
                        'webkitTransitionEnd',
                        function () {
                            $('#content').find('.col-inner').equalHeights();
                        })
            })
            .find('.col-inner')
                .height('auto');
    });

    // List view button click
    $('#btn-list').click(function() {
        $.cookie('view', 'list');
        $('#btn-list').addClass('active');
        $('#btn-grid').removeClass('active');
        $('#content')
            .removeClass('content-grid')
            .addClass('content-list')
            .height('auto')
            .find('.col-outer').each(function() {
                $(this).removeClass($(this).data('grid-classes'))
                    .addClass('col-lg-12 col-md-12 col-sm-12 col-xs-12')
                    .one(
                    'webkitTransitionEnd',
                    function () {
                        $('#content').find('.col-inner').equalHeights();
                    })
            })
            .find('.col-inner')
                .height('auto');
    });

    // Side bar
    $('#sidebar').css('top', $('#theImage').offset().top + 'px');
    $('#info-link').click(function () {
        var sidebar = $('#sidebar');
        if (parseInt(sidebar.css('right')) < 0) {
            sidebar.animate({right: "+=250"}, 500);
        } else {
            sidebar.animate({right: "-=250"}, 500);
        }
        return false;
    });

});
<commit_msg>fix sidebar js<commit_after>$(document).ready(function() {
    // Any plugin buttons using pwg-icon class should also use glyphicon class for correct display
    //$('.pwg-icon').addClass('glyphicon');

    // Grid view button click
    $('#btn-grid').click(function() {
        $.cookie('view', 'grid');
        $('#btn-grid').addClass('active');
        $('#btn-list').removeClass('active');
        $('#content')
            .removeClass('content-list')
            .addClass('content-grid')
            .height('auto')
            .find('.col-outer').each(function() {
                $(this).removeClass('col-lg-12 col-md-12 col-sm-12 col-xs-12')
                    .addClass($(this).data('grid-classes'))
                    .one(
                        'webkitTransitionEnd',
                        function () {
                            $('#content').find('.col-inner').equalHeights();
                        })
            })
            .find('.col-inner')
                .height('auto');
    });

    // List view button click
    $('#btn-list').click(function() {
        $.cookie('view', 'list');
        $('#btn-list').addClass('active');
        $('#btn-grid').removeClass('active');
        $('#content')
            .removeClass('content-grid')
            .addClass('content-list')
            .height('auto')
            .find('.col-outer').each(function() {
                $(this).removeClass($(this).data('grid-classes'))
                    .addClass('col-lg-12 col-md-12 col-sm-12 col-xs-12')
                    .one(
                    'webkitTransitionEnd',
                    function () {
                        $('#content').find('.col-inner').equalHeights();
                    })
            })
            .find('.col-inner')
                .height('auto');
    });

    // Side bar
    var sidebar = $("#sidebar");
    var theImage = $('#theImage')
    if (sidebar.length && theImage.length) {
        sidebar.css('top', theImage.offset().top + 'px');
        $('#info-link').click(function () {
            var sidebar = $('#sidebar');
            if (parseInt(sidebar.css('right')) < 0) {
                sidebar.animate({right: "+=250"}, 500);
            } else {
                sidebar.animate({right: "-=250"}, 500);
            }
            return false;
        });
    }

});
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:18-01-26');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:18-01-27');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>var http = require('http');
var url = require('url');
var path = require('path');
var spawn = require('child_process').spawn;
var querystring = require('querystring');
var fs = require('fs');

// 0 == node, 1 == [this script]
var git = process.argv[2];
var base = process.argv[3];

process.chdir(base);

var headers = {
    'Content-Type': 'text/plain',
};

function labeledArray(l, a) {
    return "---- " + l + " ----\n" + a.join('') + "\n----\n";
}

function getFullPath(section) {
    return path.join(process.cwd(), section);
}

function logCommand(name, child) {
    var stdout = [], stderr = [];
    child.stdout.on('data', function (data) { stdout.push(data); });
    child.stderr.on('data', function (data) { stderr.push(data); });
    child.on('exit', function (code) {
                 console.log('Completed execution of ' + name + ': ' + code);
                 if (code != 0) {
                     console.log(labeledArray('stderr', stderr));
                     console.log(labeledArray('stdout', stdout));
                     }
                 });
}

function spawnIfExists(cb, path, cmd, args, stdin, cmdOpts) {
    fs.stat(path, function(err, stats) {
        if (err) {
            cb();
        } else {
            console.log("Running " + cmd);
            var child = spawn(cmd, args, cmdOpts);
            if (stdin) {
                child.stdin.write(stdin);
                child.stdin.end();
            }
            logCommand(cmd, child);
            child.on('exit', cb);
        }
    });
}

function runSequence(functions) {
    var current = 0;
    function theCallback() {
        var prev = current;
        if (prev >= functions.length) {
            return;
        }
        ++current;
        functions[prev](theCallback);
    }
    theCallback();
}

function runHooks(section, payload) {
    var thePath = getFullPath(section);
    var payloadString = payload ? JSON.stringify(payload) : "";

    var functions = [
        function(cb) {
            spawnIfExists(cb, thePath, git, ['gc', '--auto'],
                undefined, {'cwd': thePath});
        },
        function(cb) {
            var fullPath = path.join(thePath, 'hooks/post-fetch');
            spawnIfExists(cb, fullPath, fullPath, [],
                          payloadString, {'cwd': thePath});
        },
        function(cb) {
            var fullPath = path.resolve('bin/post-fetch');
            spawnIfExists(cb, fullPath, fullPath, [],
                          payloadString, {'cwd': thePath});
        }
    ];

    runSequence(functions);
}

function handleComplete(res, child, section, backgrounded, payload) {
    var stdout = [], stderr = [];
    child.stdout.on('data', function (data) { stdout.push(data); });
    child.stderr.on('data', function (data) { stderr.push(data); });
    if (backgrounded) {
        res.writeHead(202, headers);
        res.end();
        child.on('exit', function (code) {
                     console.log('bg child process updating ' + section
                                 + ' completed with exit code ' + code);
                     if (code != 0) {
                         console.log(labeledArray('stderr', stderr));
                         console.log(labeledArray('stdout', stdout));
                     }
                 });
    } else {
        child.on('exit', function (code) {
                     console.log('fg child process updating ' + section
                                 + ' completed with exit code ' + code);
                     res.writeHead(code == 0 ? 200 : 500, headers);
                     res.end(labeledArray('stderr', stderr)
                             + labeledArray('stdout', stdout));
                 });
    }
    child.on('exit', function(code) { runHooks(section, payload); });
}

function gitUpdate(res, section, backgrounded, payload) {
    var child = spawn(git, ["remote", "update", "-p"],
			         {'cwd': getFullPath(section)});
    handleComplete(res, child, section, backgrounded, payload);
}

function createRepo(res, section, backgrounded, payload) {
    var repo = "git://github.com/" + payload.repository.owner.name +
        "/" + payload.repository.name + ".git";
    if (payload.repository.private) {
        repo = "git@github.com:" + payload.repository.owner.name +
            "/" + payload.repository.name + ".git";
    }
    var child = spawn(git, ["clone", "--mirror", "--bare", repo, getFullPath(section)]);
    handleComplete(res, child, section, backgrounded, payload);
}

function githubPost(res, section, backgrounded, payload) {
    console.log("Processing " + payload.repository.owner.name + "/"
                + payload.repository.name);
    fs.stat(getFullPath(section), function(err, stats) {
                if (err || !stats.isDirectory()) {
                    createRepo(res, section, backgrounded, payload);
                } else {
                    gitUpdate(res, section, backgrounded, payload);
                }
            });
}

function handleReq(req, res) {
    var preq = url.parse(req.url, true);
    var section = path.normalize(preq.pathname.substring(1));
    if (section[0] == ".") {
        res.writeHead(403, headers);
        res.end("You're doing it wrong\n");
    } else {
        var backgrounded = (preq.query && preq.query.bg == 'false') ? false : true;
        if (req.method === "GET") {
            gitUpdate(res, section, backgrounded);
        } else if (req.method === "POST") {
            req.content = '';
            req.addListener("data", function(chunk) { req.content += chunk; });
            req.addListener("end", function() {
                                var query = querystring.parse(req.content);
                                if (query.payload) {
                                    githubPost(res, section, backgrounded,
                                               JSON.parse(query.payload));
                                } else {
                                    gitUpdate(res, section, backgrounded);
                                }
	                        });
        }
    }
}

http.createServer(handleReq).listen(8124, "0.0.0.0");
console.log('Server running at http://0.0.0.0:8124/');
<commit_msg>Unconditionally close stdin to children.<commit_after>var http = require('http');
var url = require('url');
var path = require('path');
var spawn = require('child_process').spawn;
var querystring = require('querystring');
var fs = require('fs');

// 0 == node, 1 == [this script]
var git = process.argv[2];
var base = process.argv[3];

process.chdir(base);

var headers = {
    'Content-Type': 'text/plain',
};

function labeledArray(l, a) {
    return "---- " + l + " ----\n" + a.join('') + "\n----\n";
}

function getFullPath(section) {
    return path.join(process.cwd(), section);
}

function logCommand(name, child) {
    var stdout = [], stderr = [];
    child.stdout.on('data', function (data) { stdout.push(data); });
    child.stderr.on('data', function (data) { stderr.push(data); });
    child.on('exit', function (code) {
                 console.log('Completed execution of ' + name + ': ' + code);
                 if (code != 0) {
                     console.log(labeledArray('stderr', stderr));
                     console.log(labeledArray('stdout', stdout));
                     }
                 });
}

function spawnIfExists(cb, path, cmd, args, stdin, cmdOpts) {
    fs.stat(path, function(err, stats) {
        if (err) {
            cb();
        } else {
            console.log("Running " + cmd);
            var child = spawn(cmd, args, cmdOpts);
            if (stdin) {
                child.stdin.write(stdin);
            }
            child.stdin.end();
            logCommand(cmd, child);
            child.on('exit', cb);
        }
    });
}

function runSequence(functions) {
    var current = 0;
    function theCallback() {
        var prev = current;
        if (prev >= functions.length) {
            return;
        }
        ++current;
        functions[prev](theCallback);
    }
    theCallback();
}

function runHooks(section, payload) {
    var thePath = getFullPath(section);
    var payloadString = payload ? JSON.stringify(payload) : "";

    var functions = [
        function(cb) {
            spawnIfExists(cb, thePath, git, ['gc', '--auto'],
                undefined, {'cwd': thePath});
        },
        function(cb) {
            var fullPath = path.join(thePath, 'hooks/post-fetch');
            spawnIfExists(cb, fullPath, fullPath, [],
                          payloadString, {'cwd': thePath});
        },
        function(cb) {
            var fullPath = path.resolve('bin/post-fetch');
            spawnIfExists(cb, fullPath, fullPath, [],
                          payloadString, {'cwd': thePath});
        }
    ];

    runSequence(functions);
}

function handleComplete(res, child, section, backgrounded, payload) {
    var stdout = [], stderr = [];
    child.stdout.on('data', function (data) { stdout.push(data); });
    child.stderr.on('data', function (data) { stderr.push(data); });
    if (backgrounded) {
        res.writeHead(202, headers);
        res.end();
        child.on('exit', function (code) {
                     console.log('bg child process updating ' + section
                                 + ' completed with exit code ' + code);
                     if (code != 0) {
                         console.log(labeledArray('stderr', stderr));
                         console.log(labeledArray('stdout', stdout));
                     }
                 });
    } else {
        child.on('exit', function (code) {
                     console.log('fg child process updating ' + section
                                 + ' completed with exit code ' + code);
                     res.writeHead(code == 0 ? 200 : 500, headers);
                     res.end(labeledArray('stderr', stderr)
                             + labeledArray('stdout', stdout));
                 });
    }
    child.on('exit', function(code) { runHooks(section, payload); });
}

function gitUpdate(res, section, backgrounded, payload) {
    var child = spawn(git, ["remote", "update", "-p"],
			         {'cwd': getFullPath(section)});
    handleComplete(res, child, section, backgrounded, payload);
}

function createRepo(res, section, backgrounded, payload) {
    var repo = "git://github.com/" + payload.repository.owner.name +
        "/" + payload.repository.name + ".git";
    if (payload.repository.private) {
        repo = "git@github.com:" + payload.repository.owner.name +
            "/" + payload.repository.name + ".git";
    }
    var child = spawn(git, ["clone", "--mirror", "--bare", repo, getFullPath(section)]);
    handleComplete(res, child, section, backgrounded, payload);
}

function githubPost(res, section, backgrounded, payload) {
    console.log("Processing " + payload.repository.owner.name + "/"
                + payload.repository.name);
    fs.stat(getFullPath(section), function(err, stats) {
                if (err || !stats.isDirectory()) {
                    createRepo(res, section, backgrounded, payload);
                } else {
                    gitUpdate(res, section, backgrounded, payload);
                }
            });
}

function handleReq(req, res) {
    var preq = url.parse(req.url, true);
    var section = path.normalize(preq.pathname.substring(1));
    if (section[0] == ".") {
        res.writeHead(403, headers);
        res.end("You're doing it wrong\n");
    } else {
        var backgrounded = (preq.query && preq.query.bg == 'false') ? false : true;
        if (req.method === "GET") {
            gitUpdate(res, section, backgrounded);
        } else if (req.method === "POST") {
            req.content = '';
            req.addListener("data", function(chunk) { req.content += chunk; });
            req.addListener("end", function() {
                                var query = querystring.parse(req.content);
                                if (query.payload) {
                                    githubPost(res, section, backgrounded,
                                               JSON.parse(query.payload));
                                } else {
                                    gitUpdate(res, section, backgrounded);
                                }
	                        });
        }
    }
}

http.createServer(handleReq).listen(8124, "0.0.0.0");
console.log('Server running at http://0.0.0.0:8124/');
<|endoftext|>


<commit_before>/*! Copyright (c) 2016, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *      Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 *      Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *      Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software
 *      without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
angular.module("argus.urlConfig", [])
.constant('CONFIG', {
    version: '4.0-SNAPSHOT',
    wsUrl: 'http://localhost:8080/argusws/',
    emailUrl: 'https://mail.google.com/mail/?view=cm&fs=1&tf=1&to=argus-dev@mycompany.com',
    feedUrl: 'https://groups.google.com/a/mycompany.com/forum/?hl=en#!forum/argus-user',
    wikiUrl: 'https://sites.google.com/a/mycompany.com/argus',
    issueUrl: 'https://groups.google.com/a/mycompany.com/forum/?hl=en#!forum/argus-dev',
    templatePath: '/app/views/argus_custom_directives/templates/'
});
<commit_msg>wiki url<commit_after>/*! Copyright (c) 2016, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *      Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 *      Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *      Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software
 *      without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
angular.module("argus.urlConfig", [])
.constant('CONFIG', {
    version: '2.2.0-SNAPSHOT',
    wsUrl: 'http://localhost:8080/argusws/',
    emailUrl: 'https://mail.google.com/mail/?view=cm&fs=1&tf=1&to=argus-dev@mycompany.com',
    feedUrl: 'https://groups.google.com/a/mycompany.com/forum/?hl=en#!forum/argus-user',
    wikiUrl: 'https://github.com/SalesforceEng/Argus/wiki',
    issueUrl: 'https://groups.google.com/a/mycompany.com/forum/?hl=en#!forum/argus-dev',
    templatePath: '/app/views/argus_custom_directives/templates/'
});
<|endoftext|>