<commit_before>var _ = require('underscore');
var keystone = require('../../../');
var util = require('util');
var cloudinary = require('cloudinary');
var utils = require('keystone-utils');
var super_ = require('../Type');
var async = require('async');

/**
 * CloudinaryImages FieldType Constructor
 * @extends Field
 * @api public
 */
function cloudinaryimages (list, path, options) {

	this._underscoreMethods = ['format'];
	this._fixedSize = 'full';
	this._properties = ['select', 'selectPrefix', 'autoCleanup', 'publicID', 'folder', 'filenameAsPublicID'];

	// TODO: implement filtering, usage disabled for now
	options.nofilter = true;
	// TODO: implement initial form, usage disabled for now
	if (options.initial) {
		throw new Error('Invalid Configuration\n\n'
			+ 'CloudinaryImages fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
	}

	cloudinaryimages.super_.call(this, list, path, options);

	// validate cloudinary config
	if (!keystone.get('cloudinary config')) {
		throw new Error('Invalid Configuration\n\n'
			+ 'CloudinaryImages fields (' + list.key + '.' + this.path + ') require the "cloudinary config" option to be set.\n\n'
			+ 'See http://keystonejs.com/docs/configuration/#services-cloudinary for more information.\n');
	}

}

/*!
 * Inherit from Field
 */
util.inherits(cloudinaryimages, super_);

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * @api public
 */
cloudinaryimages.prototype.addToSchema = function () {

	var mongoose = keystone.mongoose;

	var field = this;
	var schema = this.list.schema;

	this.paths = {
		// virtuals
		folder: this._path.append('.folder'),
		// form paths
		upload: this._path.append('_upload'),
		uploads: this._path.append('_uploads'),
		action: this._path.append('_action'),
		order: this._path.append('_order'),
	};

	var ImageSchema = new mongoose.Schema({
		public_id: String,
		version: Number,
		signature: String,
		format: String,
		resource_type: String,
		url: String,
		width: Number,
		height: Number,
		secure_url: String,
	});

	// Generate cloudinary folder used to upload/select images
	var folder = function (item) { // eslint-disable-line no-unused-vars
		var folderValue = '';

		if (keystone.get('cloudinary folders')) {
			if (field.options.folder) {
				folderValue = field.options.folder;
			} else {
				var folderList = keystone.get('cloudinary prefix') ? [keystone.get('cloudinary prefix')] : [];
				folderList.push(field.list.path);
				folderList.push(field.path);
				folderValue = folderList.join('/');
			}
		}

		return folderValue;
	};

	// The .folder virtual returns the cloudinary folder used to upload/select images
	schema.virtual(field.paths.folder).get(function () {
		return folder(this);
	});

	var src = function (img, options) {
		if (keystone.get('cloudinary secure')) {
			options = options || {};
			options.secure = true;
		}
		return img.public_id ? cloudinary.url(img.public_id + '.' + img.format, options) : '';
	};

	var addSize = function (options, width, height, other) {
		if (width) options.width = width;
		if (height) options.height = height;
		if (typeof other === 'object') {
			Object.assign(options, other);
		}
		return options;
	};

	ImageSchema.method('src', function (options) {
		return src(this, options);
	});

	ImageSchema.method('scale', function (width, height, options) {
		return src(this, addSize({ crop: 'scale' }, width, height, options));
	});

	ImageSchema.method('fill', function (width, height, options) {
		return src(this, addSize({ crop: 'fill', gravity: 'faces' }, width, height, options));
	});

	ImageSchema.method('lfill', function (width, height, options) {
		return src(this, addSize({ crop: 'lfill', gravity: 'faces' }, width, height, options));
	});

	ImageSchema.method('fit', function (width, height, options) {
		return src(this, addSize({ crop: 'fit' }, width, height, options));
	});

	ImageSchema.method('limit', function (width, height, options) {
		return src(this, addSize({ crop: 'limit' }, width, height, options));
	});

	ImageSchema.method('pad', function (width, height, options) {
		return src(this, addSize({ crop: 'pad' }, width, height, options));
	});

	ImageSchema.method('lpad', function (width, height, options) {
		return src(this, addSize({ crop: 'lpad' }, width, height, options));
	});

	ImageSchema.method('crop', function (width, height, options) {
		return src(this, addSize({ crop: 'crop', gravity: 'faces' }, width, height, options));
	});

	ImageSchema.method('thumbnail', function (width, height, options) {
		return src(this, addSize({ crop: 'thumb', gravity: 'faces' }, width, height, options));
	});

	schema.add(this._path.addTo({}, [ImageSchema]));

	this.removeImage = function (item, id, method, callback) {
		var images = item.get(field.path);
		if (typeof id !== 'number') {
			for (var i = 0; i < images.length; i++) {
				if (images[i].public_id === id) {
					id = i;
					break;
				}
			}
		}
		var img = images[id];
		if (!img) return;
		if (method === 'delete') {
			cloudinary.uploader.destroy(img.public_id, function () {});
		}
		images.splice(id, 1);
		if (callback) {
			item.save((typeof callback !== 'function') ? callback : undefined);
		}
	};

	this.underscoreMethod('remove', function (id, callback) {
		field.removeImage(this, id, 'remove', callback);
	});

	this.underscoreMethod('delete', function (id, callback) {
		field.removeImage(this, id, 'delete', callback);
	});

	this.bindUnderscoreMethods();
};

/**
 * Formats the field value
 *
 * @api public
 */
cloudinaryimages.prototype.format = function (item) {
	return _.map(item.get(this.path), function (img) {
		return img.src();
	}).join(', ');
};

/**
 * Detects whether the field has been modified
 *
 * @api public
 */
cloudinaryimages.prototype.isModified = function (item) { // eslint-disable-line no-unused-vars
	// TODO - how should this be detected?
	return true;
};

/**
 * Validates that a value for this field has been provided in a data object
 *
 * @api public
 */
cloudinaryimages.prototype.inputIsValid = function (data) { // eslint-disable-line no-unused-vars
	// TODO - how should image field input be validated?
	return true;
};

/**
 * Updates the value for this field in the item from a data object
 *
 * @api public
 */
cloudinaryimages.prototype.updateItem = function (item, data, callback) { // eslint-disable-line no-unused-vars
	// TODO - direct updating of data (not via upload)
	process.nextTick(callback);
};

/**
 * Returns a callback that handles a standard form submission for the field
 *
 * Expected form parts are
 * - `field.paths.action` in `req.body` in syntax `delete:public_id,public_id|remove:public_id,public_id`
 * - `field.paths.upload` in `req.files` (uploads the images to cloudinary)
 *
 * @api public
 */
cloudinaryimages.prototype.getRequestHandler = function (item, req, paths, callback) {

	var field = this;

	if (utils.isFunction(paths)) {
		callback = paths;
		paths = field.paths;
	} else if (!paths) {
		paths = field.paths;
	}

	callback = callback || function () {};

	return function () {

		// Order
		if (req.body[paths.order]) {
			var images = item.get(field.path);
			var newOrder = req.body[paths.order].split(',');

			images.sort(function (a, b) {
				return (newOrder.indexOf(a.public_id) > newOrder.indexOf(b.public_id)) ? 1 : -1;
			});
		}

		// Removals & Deletes
		if (req.body && req.body[paths.action]) {
			var actions = req.body[paths.action].split('|');

			actions.forEach(function (action) {
				action = action.split(':');
				var method = action[0];
				var ids = action[1];

				if (!method.match(/^(remove|delete)$/) || !ids) return;

				ids.split(',').forEach(function (id) {
					field.removeImage(item, id, method);
				});
			});
		}

		// Upload References (direct uploading)
		if (req.body[paths.uploads]) {
			var uploads = JSON.parse(req.body[paths.uploads]);

			uploads.forEach(function (file) {
				item.get(field.path).push(file);
			});
		}

		// Upload Data (form submissions)
		if (req.files && req.files[paths.upload]) {
			var files = [].concat(req.files[paths.upload]);

			var tp = keystone.get('cloudinary prefix') || '';

			if (tp.length) {
				tp += '_';
			}

			var uploadOptions = {
				tags: [tp + field.list.path + '_' + field.path, tp + field.list.path + '_' + field.path + '_' + item.id],
			};

			if (keystone.get('cloudinary folders')) {
				uploadOptions.folder = item.get(paths.folder);
			}

			if (keystone.get('cloudinary prefix')) {
				uploadOptions.tags.push(keystone.get('cloudinary prefix'));
			}

			if (keystone.get('env') !== 'production') {
				uploadOptions.tags.push(tp + 'dev');
			}

			async.each(files, function (file, next) {

				if (!file.size) return next();

				if (field.options.filenameAsPublicID) {
					uploadOptions.public_id = file.originalname.substring(0, file.originalname.lastIndexOf('.'));
				}

				cloudinary.uploader.upload(file.path, function (result) {
					if (result.error) {
						return next(result.error);
					} else {
						item.get(field.path).push(result);
						return next();
					}
				}, uploadOptions);

			}, function (err) {
				return callback(err);
			});
		} else {
			return callback();
		}
	};
};

/**
 * Immediately handles a standard form submission for the field (see `getRequestHandler()`)
 *
 * @api public
 */
cloudinaryimages.prototype.handleRequest = function (item, req, paths, callback) {
	this.getRequestHandler(item, req, paths, callback)();
};

/*!
 * Export class
 */
module.exports = cloudinaryimages;
<commit_msg>Use the default path modified check for cloudinaryimages<commit_after>var _ = require('underscore');
var keystone = require('../../../');
var util = require('util');
var cloudinary = require('cloudinary');
var utils = require('keystone-utils');
var super_ = require('../Type');
var async = require('async');

/**
 * CloudinaryImages FieldType Constructor
 * @extends Field
 * @api public
 */
function cloudinaryimages (list, path, options) {

	this._underscoreMethods = ['format'];
	this._fixedSize = 'full';
	this._properties = ['select', 'selectPrefix', 'autoCleanup', 'publicID', 'folder', 'filenameAsPublicID'];

	// TODO: implement filtering, usage disabled for now
	options.nofilter = true;
	// TODO: implement initial form, usage disabled for now
	if (options.initial) {
		throw new Error('Invalid Configuration\n\n'
			+ 'CloudinaryImages fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
	}

	cloudinaryimages.super_.call(this, list, path, options);

	// validate cloudinary config
	if (!keystone.get('cloudinary config')) {
		throw new Error('Invalid Configuration\n\n'
			+ 'CloudinaryImages fields (' + list.key + '.' + this.path + ') require the "cloudinary config" option to be set.\n\n'
			+ 'See http://keystonejs.com/docs/configuration/#services-cloudinary for more information.\n');
	}

}

/*!
 * Inherit from Field
 */
util.inherits(cloudinaryimages, super_);

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * @api public
 */
cloudinaryimages.prototype.addToSchema = function () {

	var mongoose = keystone.mongoose;

	var field = this;
	var schema = this.list.schema;

	this.paths = {
		// virtuals
		folder: this._path.append('.folder'),
		// form paths
		upload: this._path.append('_upload'),
		uploads: this._path.append('_uploads'),
		action: this._path.append('_action'),
		order: this._path.append('_order'),
	};

	var ImageSchema = new mongoose.Schema({
		public_id: String,
		version: Number,
		signature: String,
		format: String,
		resource_type: String,
		url: String,
		width: Number,
		height: Number,
		secure_url: String,
	});

	// Generate cloudinary folder used to upload/select images
	var folder = function (item) { // eslint-disable-line no-unused-vars
		var folderValue = '';

		if (keystone.get('cloudinary folders')) {
			if (field.options.folder) {
				folderValue = field.options.folder;
			} else {
				var folderList = keystone.get('cloudinary prefix') ? [keystone.get('cloudinary prefix')] : [];
				folderList.push(field.list.path);
				folderList.push(field.path);
				folderValue = folderList.join('/');
			}
		}

		return folderValue;
	};

	// The .folder virtual returns the cloudinary folder used to upload/select images
	schema.virtual(field.paths.folder).get(function () {
		return folder(this);
	});

	var src = function (img, options) {
		if (keystone.get('cloudinary secure')) {
			options = options || {};
			options.secure = true;
		}
		return img.public_id ? cloudinary.url(img.public_id + '.' + img.format, options) : '';
	};

	var addSize = function (options, width, height, other) {
		if (width) options.width = width;
		if (height) options.height = height;
		if (typeof other === 'object') {
			Object.assign(options, other);
		}
		return options;
	};

	ImageSchema.method('src', function (options) {
		return src(this, options);
	});

	ImageSchema.method('scale', function (width, height, options) {
		return src(this, addSize({ crop: 'scale' }, width, height, options));
	});

	ImageSchema.method('fill', function (width, height, options) {
		return src(this, addSize({ crop: 'fill', gravity: 'faces' }, width, height, options));
	});

	ImageSchema.method('lfill', function (width, height, options) {
		return src(this, addSize({ crop: 'lfill', gravity: 'faces' }, width, height, options));
	});

	ImageSchema.method('fit', function (width, height, options) {
		return src(this, addSize({ crop: 'fit' }, width, height, options));
	});

	ImageSchema.method('limit', function (width, height, options) {
		return src(this, addSize({ crop: 'limit' }, width, height, options));
	});

	ImageSchema.method('pad', function (width, height, options) {
		return src(this, addSize({ crop: 'pad' }, width, height, options));
	});

	ImageSchema.method('lpad', function (width, height, options) {
		return src(this, addSize({ crop: 'lpad' }, width, height, options));
	});

	ImageSchema.method('crop', function (width, height, options) {
		return src(this, addSize({ crop: 'crop', gravity: 'faces' }, width, height, options));
	});

	ImageSchema.method('thumbnail', function (width, height, options) {
		return src(this, addSize({ crop: 'thumb', gravity: 'faces' }, width, height, options));
	});

	schema.add(this._path.addTo({}, [ImageSchema]));

	this.removeImage = function (item, id, method, callback) {
		var images = item.get(field.path);
		if (typeof id !== 'number') {
			for (var i = 0; i < images.length; i++) {
				if (images[i].public_id === id) {
					id = i;
					break;
				}
			}
		}
		var img = images[id];
		if (!img) return;
		if (method === 'delete') {
			cloudinary.uploader.destroy(img.public_id, function () {});
		}
		images.splice(id, 1);
		if (callback) {
			item.save((typeof callback !== 'function') ? callback : undefined);
		}
	};

	this.underscoreMethod('remove', function (id, callback) {
		field.removeImage(this, id, 'remove', callback);
	});

	this.underscoreMethod('delete', function (id, callback) {
		field.removeImage(this, id, 'delete', callback);
	});

	this.bindUnderscoreMethods();
};

/**
 * Formats the field value
 *
 * @api public
 */
cloudinaryimages.prototype.format = function (item) {
	return _.map(item.get(this.path), function (img) {
		return img.src();
	}).join(', ');
};

/**
 * Validates that a value for this field has been provided in a data object
 *
 * @api public
 */
cloudinaryimages.prototype.inputIsValid = function (data) { // eslint-disable-line no-unused-vars
	// TODO - how should image field input be validated?
	return true;
};

/**
 * Updates the value for this field in the item from a data object
 *
 * @api public
 */
cloudinaryimages.prototype.updateItem = function (item, data, callback) { // eslint-disable-line no-unused-vars
	// TODO - direct updating of data (not via upload)
	process.nextTick(callback);
};

/**
 * Returns a callback that handles a standard form submission for the field
 *
 * Expected form parts are
 * - `field.paths.action` in `req.body` in syntax `delete:public_id,public_id|remove:public_id,public_id`
 * - `field.paths.upload` in `req.files` (uploads the images to cloudinary)
 *
 * @api public
 */
cloudinaryimages.prototype.getRequestHandler = function (item, req, paths, callback) {

	var field = this;

	if (utils.isFunction(paths)) {
		callback = paths;
		paths = field.paths;
	} else if (!paths) {
		paths = field.paths;
	}

	callback = callback || function () {};

	return function () {

		// Order
		if (req.body[paths.order]) {
			var images = item.get(field.path);
			var newOrder = req.body[paths.order].split(',');

			images.sort(function (a, b) {
				return (newOrder.indexOf(a.public_id) > newOrder.indexOf(b.public_id)) ? 1 : -1;
			});
		}

		// Removals & Deletes
		if (req.body && req.body[paths.action]) {
			var actions = req.body[paths.action].split('|');

			actions.forEach(function (action) {
				action = action.split(':');
				var method = action[0];
				var ids = action[1];

				if (!method.match(/^(remove|delete)$/) || !ids) return;

				ids.split(',').forEach(function (id) {
					field.removeImage(item, id, method);
				});
			});
		}

		// Upload References (direct uploading)
		if (req.body[paths.uploads]) {
			var uploads = JSON.parse(req.body[paths.uploads]);

			uploads.forEach(function (file) {
				item.get(field.path).push(file);
			});
		}

		// Upload Data (form submissions)
		if (req.files && req.files[paths.upload]) {
			var files = [].concat(req.files[paths.upload]);

			var tp = keystone.get('cloudinary prefix') || '';

			if (tp.length) {
				tp += '_';
			}

			var uploadOptions = {
				tags: [tp + field.list.path + '_' + field.path, tp + field.list.path + '_' + field.path + '_' + item.id],
			};

			if (keystone.get('cloudinary folders')) {
				uploadOptions.folder = item.get(paths.folder);
			}

			if (keystone.get('cloudinary prefix')) {
				uploadOptions.tags.push(keystone.get('cloudinary prefix'));
			}

			if (keystone.get('env') !== 'production') {
				uploadOptions.tags.push(tp + 'dev');
			}

			async.each(files, function (file, next) {

				if (!file.size) return next();

				if (field.options.filenameAsPublicID) {
					uploadOptions.public_id = file.originalname.substring(0, file.originalname.lastIndexOf('.'));
				}

				cloudinary.uploader.upload(file.path, function (result) {
					if (result.error) {
						return next(result.error);
					} else {
						item.get(field.path).push(result);
						return next();
					}
				}, uploadOptions);

			}, function (err) {
				return callback(err);
			});
		} else {
			return callback();
		}
	};
};

/**
 * Immediately handles a standard form submission for the field (see `getRequestHandler()`)
 *
 * @api public
 */
cloudinaryimages.prototype.handleRequest = function (item, req, paths, callback) {
	this.getRequestHandler(item, req, paths, callback)();
};

/*!
 * Export class
 */
module.exports = cloudinaryimages;
<|endoftext|>


<commit_before>var Player = React.createClass({

  setVolume: function(volume){
    this.refs.audio.volume = volume;
  },

  getPlayer: function(){
    return this.refs.audio;
  },

  render: function() {
    return (

          <Controls getPlayerRef={ this.getPlayer }/>

                  <audio id="barmaglot-player" preload="none" ref="audio">
                      <source src="http://195.248.234.62:8000/radioskovoroda" type="audio/mpeg"/>
                  </audio>

              <Volume volumeHandle={ this.setVolume }/>

    );}
});

var Controls = React.createClass({
  getInitialState: function() {
      return { showPause: false, showPlay: true };
  },
  displayPause: function(e){
    this.setState({ showPause: true , showPlay: false });
    var player = this.props.getPlayerRef();
    player.play();
  },
  displayPlay: function(e){
    this.setState({ showPause: false , showPlay: true });
    var player = this.props.getPlayerRef();
    player.pause();
  },
  render: function() {
    return (

                  { this.state.showPause ?

 : null }

                  { this.state.showPlay ?

 : null }

    )
  }
});

var Volume = React.createClass({

  propTypes: {
      classes: React.PropTypes.array,
      volumes: React.PropTypes.object
  },

  getDefaultProps: function() {
    return {
      classes: ['one', 'two', 'three', 'four', 'five'],
      volumes: {'one': 0.2, 'two': 0.4, 'three': 0.6, 'four': 0.8, 'five': 1}
    };
  },

  soundHandler: function(bar, event) {
    var soundValue = this.props.volumes[bar];
    console.log(soundValue);
    this.props.volumeHandle(soundValue)
  },

  render: function () {
    var getClass = function(i){
      return 'volume-bar ' + i;
    };

    var _soundHandler = function(bar, event){
        this.soundHandller(bar);
    };

    var _this = this, bars = this.props.classes.map(function(i) {
      return

;
    });

    return (

pink floyd - wish you where here

              {bars}

    )
  }
});

ReactDOM.render(
  <Player />,
  document.getElementById('barmaglot-player')
);<commit_msg>removed obsolete method<commit_after>var Player = React.createClass({

  setVolume: function(volume){
    this.refs.audio.volume = volume;
  },

  getPlayer: function(){
    return this.refs.audio;
  },

  render: function() {
    return (

          <Controls getPlayerRef={ this.getPlayer }/>

                  <audio id="barmaglot-player" preload="none" ref="audio">
                      <source src="http://195.248.234.62:8000/radioskovoroda" type="audio/mpeg"/>
                  </audio>

              <Volume volumeHandle={ this.setVolume }/>

    );}
});

var Controls = React.createClass({
  getInitialState: function() {
      return { showPause: false, showPlay: true };
  },
  displayPause: function(e){
    this.setState({ showPause: true , showPlay: false });
    var player = this.props.getPlayerRef();
    player.play();
  },
  displayPlay: function(e){
    this.setState({ showPause: false , showPlay: true });
    var player = this.props.getPlayerRef();
    player.pause();
  },
  render: function() {
    return (

                  { this.state.showPause ?

 : null }

                  { this.state.showPlay ?

 : null }

    )
  }
});

var Volume = React.createClass({

  propTypes: {
      classes: React.PropTypes.array,
      volumes: React.PropTypes.object
  },

  getDefaultProps: function() {
    return {
      classes: ['one', 'two', 'three', 'four', 'five'],
      volumes: {'one': 0.2, 'two': 0.4, 'three': 0.6, 'four': 0.8, 'five': 1}
    };
  },

  soundHandler: function(bar, event) {
    var soundValue = this.props.volumes[bar];
    console.log(soundValue);
    this.props.volumeHandle(soundValue)
  },

  render: function () {
    var getClass = function(i){
      return 'volume-bar ' + i;
    };

    var _this = this, bars = this.props.classes.map(function(i) {
      return

;
    });

    return (

pink floyd - wish you where here

              {bars}

    )
  }
});

ReactDOM.render(
  <Player />,
  document.getElementById('barmaglot-player')
);<|endoftext|>


<commit_before>/**
 * Manage files associated with content
 * @param collectionId
 * @param data
 * @param field - JSON data key
 * @param idField - HTML id for the template
 */

function addFile(collectionId, data, field, idField) {
  var list = data[field];
  var downloadExtensions, header, button;
  if (field === 'supplementaryFiles') {
    header = 'Supplementary files';
    button = 'supplementary file';
  } else if (field === 'pdfTable') {
    header = 'PDF Table';
    button = 'pdf';
  } else {
    header = 'Upload files';
    button = 'file';
  }
  var dataTemplate = {list: list, idField: idField, header: header, button: button};
  var html = templates.editorDownloads(dataTemplate);
  $('#' + idField).replaceWith(html);
  var uriUpload;

  $(".workspace-edit").scrollTop(Florence.globalVars.pagePos);

  //Edit
  if (!data[field] || data[field].length === 0) {
    var lastIndex = 0;
  } else {
    $(data[field]).each(function (index) {
      // Delete
      $('#' + idField + '-delete_' + index).click(function () {
        fileDelete(collectionId, data, field, index);
      });
    });
  }

  //Add
  if (data.type === 'static_adhoc') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'static_qmi') {
    downloadExtensions = /\.pdf$/;
  } else if (data.type === 'article_download' || data.type === 'static_methodology_download') {
    downloadExtensions = /\.pdf$/;
  } else if (data.type === 'static_foi') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'static_page') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'static_article') {
    downloadExtensions = /\.xls$|.pdf$/;
  } else if (data.type === 'dataset' || data.type === 'timeseries_dataset') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'article' || data.type === 'bulletin') {
    downloadExtensions = /\.pdf$/;
  } else {
    sweetAlert("This file type is not valid", "Contact an administrator if you need to add this type of file in this document", "info");
  }

  $('#add-' + idField).one('click', function () {
    if ((data.type === 'article' || data.type === 'bulletin') && (data[field] && data[field].length > 0)) {
      sweetAlert("You can upload only one file here");
      return false;
    } else {
      if (!data[field]) {
        data[field] = [];
      }
      uploadFile(collectionId, data, field, idField, lastIndex, downloadExtensions, addFile);
    }
  });

  $(function () {
    $('.add-tooltip').tooltip({
      items: '.add-tooltip',
      content: 'Type title here and click Save to add it to the page',
      show: "slideDown", // show immediately
      open: function (event, ui) {
        ui.tooltip.hover(
          function () {
            $(this).fadeTo("slow", 0.5);
          });
      }
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable({
      stop: function () {
        $('#' + idField + ' .edit-section__sortable-item--counter').each(function (index) {
          $(this).empty().append(index + 1);
        });
      }
    });
  }

  sortable();
}

<commit_msg>Add zip to static article<commit_after>/**
 * Manage files associated with content
 * @param collectionId
 * @param data
 * @param field - JSON data key
 * @param idField - HTML id for the template
 */

function addFile(collectionId, data, field, idField) {
  var list = data[field];
  var downloadExtensions, header, button;
  if (field === 'supplementaryFiles') {
    header = 'Supplementary files';
    button = 'supplementary file';
  } else if (field === 'pdfTable') {
    header = 'PDF Table';
    button = 'pdf';
  } else {
    header = 'Upload files';
    button = 'file';
  }
  var dataTemplate = {list: list, idField: idField, header: header, button: button};
  var html = templates.editorDownloads(dataTemplate);
  $('#' + idField).replaceWith(html);
  var uriUpload;

  $(".workspace-edit").scrollTop(Florence.globalVars.pagePos);

  //Edit
  if (!data[field] || data[field].length === 0) {
    var lastIndex = 0;
  } else {
    $(data[field]).each(function (index) {
      // Delete
      $('#' + idField + '-delete_' + index).click(function () {
        fileDelete(collectionId, data, field, index);
      });
    });
  }

  //Add
  if (data.type === 'static_adhoc') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'static_qmi') {
    downloadExtensions = /\.pdf$/;
  } else if (data.type === 'article_download' || data.type === 'static_methodology_download') {
    downloadExtensions = /\.pdf$/;
  } else if (data.type === 'static_foi') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'static_page') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'static_article') {
    downloadExtensions = /\.xls$|.pdf$|.zip$/;
  } else if (data.type === 'dataset' || data.type === 'timeseries_dataset') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'article' || data.type === 'bulletin') {
    downloadExtensions = /\.pdf$/;
  } else {
    sweetAlert("This file type is not valid", "Contact an administrator if you need to add this type of file in this document", "info");
  }

  $('#add-' + idField).one('click', function () {
    if ((data.type === 'article' || data.type === 'bulletin') && (data[field] && data[field].length > 0)) {
      sweetAlert("You can upload only one file here");
      return false;
    } else {
      if (!data[field]) {
        data[field] = [];
      }
      uploadFile(collectionId, data, field, idField, lastIndex, downloadExtensions, addFile);
    }
  });

  $(function () {
    $('.add-tooltip').tooltip({
      items: '.add-tooltip',
      content: 'Type title here and click Save to add it to the page',
      show: "slideDown", // show immediately
      open: function (event, ui) {
        ui.tooltip.hover(
          function () {
            $(this).fadeTo("slow", 0.5);
          });
      }
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable({
      stop: function () {
        $('#' + idField + ' .edit-section__sortable-item--counter').each(function (index) {
          $(this).empty().append(index + 1);
        });
      }
    });
  }

  sortable();
}

<|endoftext|>


<commit_before>function Spiral(graphType) {
  this.graphType = graphType || "points";
  this.numberOfPoints = null,
  this.period = null,
  this.tickMarkNumber = 0,
  this.margin = {
    top: 10,
    right: 10,
    bottom: 10,
    left: 10
  },
  this.svgHeight = 0,
  this.svgWidth = 0,
  this.spacing = 1,
  this.lineWidth = 50,
  this.targetElement = '#chart',
  this.width = this.svgWidth - this.margin.left - this.margin.right,
  this.height = this.svgHeight - this.margin.top - this.margin.bottom,
  this.data = [],
  this.x = d3.scale.linear().range([0, 730]).domain([-750, 750]),
  this.y = d3.scale.linear().range([480, 0]).domain([-500, 500]),
  this.cartesian = function(radius, angle, size, startAngle, endAngle) {
    var size = size || 1;
    var xPos = this.x(radius * Math.cos(angle));
    var yPos = this.y(radius * Math.sin(angle));
    return [xPos, yPos, size, radius, angle, startAngle, endAngle];
  },
  this.render = function() {
    var spiralContext = this;

    var svg = d3.select(spiralContext.targetElement)
      .append("svg")
      .attr("width", spiralContext.svgWidth)
      .attr("height", spiralContext.svgHeight)

    if (spiralContext.graphType === "points") {
      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");

      svg.selectAll("g").selectAll("dot")
        .data(spiralContext.data)
          .enter().append("circle")
            .attr("r", function(d) { return d[2]; })
            .attr("cx", function(d) { return d[0]; })
            .attr("cy", function(d) { return d[1]; });
    } else if (spiralContext.graphType === "custom-path") {
      spiralContext.data.forEach(function(datum, t, dataSet){
        var start = startAngle(t, spiralContext.period);
        var end = endAngle(t, spiralContext.period);

        var startInnerRadius = radius(spiralContext.spacing, start) - spiralContext.lineWidth*0.5;
        var startOuterRadius = radius(spiralContext.spacing, start) + spiralContext.lineWidth*0.5;
        var endInnerRadius = radius(spiralContext.spacing, end) - spiralContext.lineWidth*0.5;
        var endOuterRadius = radius(spiralContext.spacing, end) + spiralContext.lineWidth*0.5;

        var ctrlInnerRad = 0.01; // Use to adjust arc inner radius
        var ctrlOuterRad = 0.01; // Use to adjust arc outer radius
        var innerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) - spiralContext.lineWidth*0.5 + ctrlInnerRad, theta(t, spiralContext.period));
        var outerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) + spiralContext.lineWidth*0.5 + ctrlOuterRad, theta(t, spiralContext.period));

        var startPoint = spiralContext.cartesian(startInnerRadius, start); // Bottom right of arc
        var point2 = spiralContext.cartesian(startOuterRadius, start); // Top right of arc
        var point3 = spiralContext.cartesian(endOuterRadius, end); // Top left of arc
        var point4 = spiralContext.cartesian(endInnerRadius, end); // Bottom left of arc
        var arcPath = "M" + startPoint[0] + " " + startPoint[1] + "L" + point2[0] + " " + point2[1];
        arcPath += "Q" + outerControlPoint[0] + " " + outerControlPoint[1] + " " + point3[0] + " " + point3[1];
        arcPath += "L" + point4[0] + " " + point4[1];
        arcPath += "Q" + innerControlPoint[0] + " " + innerControlPoint[1] + " " + startPoint[0] + " " + startPoint[1] + "Z";
        datum[1] = arcPath
      });

      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");
      svg.selectAll("g").selectAll("path")
        .data(spiralContext.data.slice(100))
        .enter().append("path")
          .style("fill", function(d) { return "black"; })
          .style("opacity", function(d) {return d[2]/9})
          .attr("d", function(d) { return d[1]});
    } else if (spiralContext.graphType === "non-spiral") {
      // --------------------vvv Standard Line Graph vvv---------------------------
      var x2 = d3.scale.linear().range([0, 730]);
      var y2 = d3.scale.linear().range([480, 0]);
      x2.domain(d3.extent(spiralContext.data, function(d) { return d[0]; }));
      y2.domain(d3.extent(spiralContext.data, function(d) { return d[1]; }));

      var xAxis = d3.svg.axis().scale(x2)
        .orient("bottom").ticks(5);

      var yAxis = d3.svg.axis().scale(y2)
        .orient("left").ticks(5);

      var line = d3.svg.line()
        .x(function(d) { return x2(d[0]); })
        .y(function(d) { return y2(d[1]); });

      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate("+spiralContext.margin.left+"," + 480 + ")")
        .call(xAxis)
        .append("text")
          .attr("x", 710)
          .attr("y", -3)
          .attr("dy", "-.35em")
          .style("text-anchor", "middle")
          .text("time");

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate("+spiralContext.margin.left+",0)")
        .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Signal (a.u.)");

      svg.append("path")
        .datum(spiralContext.data)
        .attr("class", "line")
        .attr("d", line)
        .attr("fill", "none")
        .attr("stroke-width", "1")
        .attr("stroke", "steelblue")
        .attr("transform", "translate("+spiralContext.margin.left+",0)")
    }
  },
  this.randomData = function() {
    this.data = [];
    for (var i=0; i<this.numberOfPoints; i++){
      var angle = theta(i, this.period);
      var rad = radius(this.spacing, angle);
      var size = 1 + Math.random()*1.5;
      if (i % 10 === 0) {
        size = 5.5 + Math.random()*3;
      }

      if (this.graphType === 'non-spiral') {
        this.data.push([i, size*this.period, 2])
      } else {
        this.data.push(this.cartesian(rad, angle, size, startAngle(i, this.period), endAngle(i, this.period)));
      }
    }
  },
  this.setParam = function(param, value) {
    var spiralContext = this;
    spiralContext[param] = value;
    if (['svgHeight', 'svgWidth', 'margin.top', 'margin.right', 'margin.bottom', , 'margin.left'].indexOf(param) > -1) {
      spiralContext.width = spiralContext.svgWidth - spiralContext.margin.left - spiralContext.margin.right;
      spiralContext.height = spiralContext.svgHeight - spiralContext.margin.top - spiralContext.margin.bottom;
      spiralContext.x = d3.scale.linear().range([0, spiralContext.width]).domain([-spiralContext.svgWidth, spiralContext.svgWidth]);
      spiralContext.y = d3.scale.linear().range([spiralContext.height, 0]).domain([-spiralContext.svgHeight, spiralContext.svgHeight]);
    }
  },
  this.redraw = function() {
    var spiralContext = this;
    var graphContainer = document.getElementById(spiralContext.targetElement.substr(1));
    while (graphContainer.firstChild) {
      graphContainer.removeChild(graphContainer.firstChild)
    }
    spiralContext.render();
  },
  this.autocorrelate = function() {}
}

// For time point #t, calculate the angle to the center of the arc
// period is the number of time points per revolution (2 PI)
function theta(t, period) {
  return 2 * Math.PI / (period) * t;
}

function startAngle(t, period) {
  return (theta(t-1, period) + theta(t, period))/2;
}

function endAngle(t, period) {
  return (theta(t+1, period) + theta(t, period))/2;
}

function radius(spacing, angle) {
  return spacing * angle;
}
<commit_msg>Begin refactor: move params to graphParams property<commit_after>function Spiral(graphType) {
  this.graphParams = {
    graphType: graphType || "points",
  },
  this.numberOfPoints = null,
  this.period = null,
  this.tickMarkNumber = 0,
  this.margin = {
    top: 10,
    right: 10,
    bottom: 10,
    left: 10
  },
  this.svgHeight = 0,
  this.svgWidth = 0,
  this.spacing = 1,
  this.lineWidth = 50,
  this.targetElement = '#chart',
  this.width = this.svgWidth - this.margin.left - this.margin.right,
  this.height = this.svgHeight - this.margin.top - this.margin.bottom,
  this.data = [],
  this.x = d3.scale.linear().range([0, 730]).domain([-750, 750]),
  this.y = d3.scale.linear().range([480, 0]).domain([-500, 500]),
  this.cartesian = function(radius, angle, size, startAngle, endAngle) {
    var size = size || 1;
    var xPos = this.x(radius * Math.cos(angle));
    var yPos = this.y(radius * Math.sin(angle));
    return [xPos, yPos, size, radius, angle, startAngle, endAngle];
  },
  this.render = function() {
    var spiralContext = this;

    var svg = d3.select(spiralContext.targetElement)
      .append("svg")
      .attr("width", spiralContext.svgWidth)
      .attr("height", spiralContext.svgHeight)

    if (spiralContext.graphParams.graphType === "points") {
      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");

      svg.selectAll("g").selectAll("dot")
        .data(spiralContext.data)
          .enter().append("circle")
            .attr("r", function(d) { return d[2]; })
            .attr("cx", function(d) { return d[0]; })
            .attr("cy", function(d) { return d[1]; });
    } else if (spiralContext.graphParams.graphType === "custom-path") {
      spiralContext.data.forEach(function(datum, t, dataSet){
        var start = startAngle(t, spiralContext.period);
        var end = endAngle(t, spiralContext.period);

        var startInnerRadius = radius(spiralContext.spacing, start) - spiralContext.lineWidth*0.5;
        var startOuterRadius = radius(spiralContext.spacing, start) + spiralContext.lineWidth*0.5;
        var endInnerRadius = radius(spiralContext.spacing, end) - spiralContext.lineWidth*0.5;
        var endOuterRadius = radius(spiralContext.spacing, end) + spiralContext.lineWidth*0.5;

        var ctrlInnerRad = 0.01; // Use to adjust arc inner radius
        var ctrlOuterRad = 0.01; // Use to adjust arc outer radius
        var innerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) - spiralContext.lineWidth*0.5 + ctrlInnerRad, theta(t, spiralContext.period));
        var outerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) + spiralContext.lineWidth*0.5 + ctrlOuterRad, theta(t, spiralContext.period));

        var startPoint = spiralContext.cartesian(startInnerRadius, start); // Bottom right of arc
        var point2 = spiralContext.cartesian(startOuterRadius, start); // Top right of arc
        var point3 = spiralContext.cartesian(endOuterRadius, end); // Top left of arc
        var point4 = spiralContext.cartesian(endInnerRadius, end); // Bottom left of arc
        var arcPath = "M" + startPoint[0] + " " + startPoint[1] + "L" + point2[0] + " " + point2[1];
        arcPath += "Q" + outerControlPoint[0] + " " + outerControlPoint[1] + " " + point3[0] + " " + point3[1];
        arcPath += "L" + point4[0] + " " + point4[1];
        arcPath += "Q" + innerControlPoint[0] + " " + innerControlPoint[1] + " " + startPoint[0] + " " + startPoint[1] + "Z";
        datum[1] = arcPath
      });

      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");
      svg.selectAll("g").selectAll("path")
        .data(spiralContext.data.slice(100))
        .enter().append("path")
          .style("fill", function(d) { return "black"; })
          .style("opacity", function(d) {return d[2]/9})
          .attr("d", function(d) { return d[1]});
    } else if (spiralContext.graphParams.graphType === "non-spiral") {
      // --------------------vvv Standard Line Graph vvv---------------------------
      var x2 = d3.scale.linear().range([0, 730]);
      var y2 = d3.scale.linear().range([480, 0]);
      x2.domain(d3.extent(spiralContext.data, function(d) { return d[0]; }));
      y2.domain(d3.extent(spiralContext.data, function(d) { return d[1]; }));

      var xAxis = d3.svg.axis().scale(x2)
        .orient("bottom").ticks(5);

      var yAxis = d3.svg.axis().scale(y2)
        .orient("left").ticks(5);

      var line = d3.svg.line()
        .x(function(d) { return x2(d[0]); })
        .y(function(d) { return y2(d[1]); });

      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate("+spiralContext.margin.left+"," + 480 + ")")
        .call(xAxis)
        .append("text")
          .attr("x", 710)
          .attr("y", -3)
          .attr("dy", "-.35em")
          .style("text-anchor", "middle")
          .text("time");

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate("+spiralContext.margin.left+",0)")
        .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Signal (a.u.)");

      svg.append("path")
        .datum(spiralContext.data)
        .attr("class", "line")
        .attr("d", line)
        .attr("fill", "none")
        .attr("stroke-width", "1")
        .attr("stroke", "steelblue")
        .attr("transform", "translate("+spiralContext.margin.left+",0)")
    }
  },
  this.randomData = function() {
    this.data = [];
    for (var i=0; i<this.numberOfPoints; i++){
      var angle = theta(i, this.period);
      var rad = radius(this.spacing, angle);
      var size = 1 + Math.random()*1.5;
      if (i % 10 === 0) {
        size = 5.5 + Math.random()*3;
      }

      if (this.graphParams.graphType === 'non-spiral') {
        this.data.push([i, size*this.period, 2])
      } else {
        this.data.push(this.cartesian(rad, angle, size, startAngle(i, this.period), endAngle(i, this.period)));
      }
    }
  },
  this.setParam = function(param, value) {
    var spiralContext = this;
    spiralContext[param] = value;
    if (['svgHeight', 'svgWidth', 'margin.top', 'margin.right', 'margin.bottom', , 'margin.left'].indexOf(param) > -1) {
      spiralContext.width = spiralContext.svgWidth - spiralContext.margin.left - spiralContext.margin.right;
      spiralContext.height = spiralContext.svgHeight - spiralContext.margin.top - spiralContext.margin.bottom;
      spiralContext.x = d3.scale.linear().range([0, spiralContext.width]).domain([-spiralContext.svgWidth, spiralContext.svgWidth]);
      spiralContext.y = d3.scale.linear().range([spiralContext.height, 0]).domain([-spiralContext.svgHeight, spiralContext.svgHeight]);
    }
  },
  this.redraw = function() {
    var spiralContext = this;
    var graphContainer = document.getElementById(spiralContext.targetElement.substr(1));
    while (graphContainer.firstChild) {
      graphContainer.removeChild(graphContainer.firstChild)
    }
    spiralContext.render();
  },
  this.autocorrelate = function() {}
}

// For time point #t, calculate the angle to the center of the arc
// period is the number of time points per revolution (2 PI)
function theta(t, period) {
  return 2 * Math.PI / (period) * t;
}

function startAngle(t, period) {
  return (theta(t-1, period) + theta(t, period))/2;
}

function endAngle(t, period) {
  return (theta(t+1, period) + theta(t, period))/2;
}

function radius(spacing, angle) {
  return spacing * angle;
}
<|endoftext|>


<commit_before>"use strict";

const FoldDict = require("./fold_dict").FoldDict;
const people = require("./people");

const partners = new Set();

exports.set_partner = function (user_id) {
    partners.add(user_id);
};

exports.is_partner = function (user_id) {
    return partners.has(user_id);
};

class RecentPrivateMessages {
    // This data structure keeps track of the sets of users you've had
    // recent conversations with, sorted by time (implemented via
    // `message_id` sorting, since that's how we time-sort messages).
    recent_message_ids = new FoldDict(); // key is user_ids_string
    recent_private_messages = [];

    insert(user_ids, message_id) {
        if (user_ids.length === 0) {
            // The server sends [] for self-PMs.
            user_ids = [people.my_current_user_id()];
        }
        user_ids.sort((a, b) => a - b);

        const user_ids_string = user_ids.join(",");
        let conversation = this.recent_message_ids.get(user_ids_string);

        if (conversation === undefined) {
            // This is a new user, so create a new object.
            conversation = {
                user_ids_string,
                max_message_id: message_id,
            };
            this.recent_message_ids.set(user_ids_string, conversation);

            // Optimistically insert the new message at the front, since that
            // is usually where it belongs, but we'll re-sort.
            this.recent_private_messages.unshift(conversation);
        } else {
            if (conversation.max_message_id >= message_id) {
                // don't backdate our conversation.  This is the
                // common code path after initialization when
                // processing old messages, since we'll already have
                // the latest message_id for the conversation from
                // initialization.
                return;
            }

            // update our latest message_id
            conversation.max_message_id = message_id;
        }

        this.recent_private_messages.sort((a, b) => b.max_message_id - a.max_message_id);
    }

    get() {
        // returns array of structs with user_ids_string and
        // message_id
        return this.recent_private_messages;
    }

    get_strings() {
        // returns array of structs with user_ids_string and
        // message_id
        return this.recent_private_messages.map((conversation) => conversation.user_ids_string);
    }

    initialize(params) {
        for (const conversation of params.recent_private_conversations) {
            this.insert(conversation.user_ids, conversation.max_message_id);
        }
    }
}

exports.recent = new RecentPrivateMessages();
<commit_msg>js: Convert pm_conversations module to ES6.<commit_after>import {FoldDict} from "./fold_dict";
import * as people from "./people";

const partners = new Set();

export function set_partner(user_id) {
    partners.add(user_id);
}

export function is_partner(user_id) {
    return partners.has(user_id);
}

class RecentPrivateMessages {
    // This data structure keeps track of the sets of users you've had
    // recent conversations with, sorted by time (implemented via
    // `message_id` sorting, since that's how we time-sort messages).
    recent_message_ids = new FoldDict(); // key is user_ids_string
    recent_private_messages = [];

    insert(user_ids, message_id) {
        if (user_ids.length === 0) {
            // The server sends [] for self-PMs.
            user_ids = [people.my_current_user_id()];
        }
        user_ids.sort((a, b) => a - b);

        const user_ids_string = user_ids.join(",");
        let conversation = this.recent_message_ids.get(user_ids_string);

        if (conversation === undefined) {
            // This is a new user, so create a new object.
            conversation = {
                user_ids_string,
                max_message_id: message_id,
            };
            this.recent_message_ids.set(user_ids_string, conversation);

            // Optimistically insert the new message at the front, since that
            // is usually where it belongs, but we'll re-sort.
            this.recent_private_messages.unshift(conversation);
        } else {
            if (conversation.max_message_id >= message_id) {
                // don't backdate our conversation.  This is the
                // common code path after initialization when
                // processing old messages, since we'll already have
                // the latest message_id for the conversation from
                // initialization.
                return;
            }

            // update our latest message_id
            conversation.max_message_id = message_id;
        }

        this.recent_private_messages.sort((a, b) => b.max_message_id - a.max_message_id);
    }

    get() {
        // returns array of structs with user_ids_string and
        // message_id
        return this.recent_private_messages;
    }

    get_strings() {
        // returns array of structs with user_ids_string and
        // message_id
        return this.recent_private_messages.map((conversation) => conversation.user_ids_string);
    }

    initialize(params) {
        for (const conversation of params.recent_private_conversations) {
            this.insert(conversation.user_ids, conversation.max_message_id);
        }
    }
}

export const recent = new RecentPrivateMessages();
<|endoftext|>


<commit_before>function addFile(collectionId, data, field, idField) {
  var list = data[field];
  var downloadExtensions;
  var dataTemplate = {list: list, idField: idField};
  var html = templates.editorDownloads(dataTemplate);
  $('#' + idField).replaceWith(html);
  var uriUpload;
  // Edit
  if (!data[field] || data[field].length === 0) {
    var lastIndex = 0;
  } else {
    $(data[field]).each(function (index) {
      // Delete
      $('#' + idField + '-delete_' + index).click(function () {
        var result = confirm("Are you sure you want to delete this file?");
        if (result === true) {
          var position = $(".workspace-edit").scrollTop();
          Florence.globalVars.pagePos = position + 200;
          $(this).parent().remove();
          $.ajax({
            url: "/zebedee/content/" + collectionId + "?uri=" + data[field][index].file,
            type: "DELETE",
            success: function (res) {
              console.log(res);
            },
            error: function (res) {
              console.log(res);
            }
          });
          data[field].splice(index, 1);
          updateContent(collectionId, data.uri, JSON.stringify(data));
        }
      });
      // Edit
      $('#' + idField + '-edit_' + index).click(function () {
        var editedSectionValue = {
          "markdown": $('#' + idField + '-title_' + index).val(),
        };
        var saveContent = function (updatedContent) {
          data[field][index].markdown = updatedContent;
          updateContent(collectionId, data.uri, JSON.stringify(data));
        };
        loadMarkdownEditor(editedSectionValue, saveContent, data);
      });
    });
  }

  //Add
  if (data.type === 'dataset') {
    downloadExtensions = /\.csv$|.xls$|.csdb$|.zip$/;
  } else if (data.type === 'static_adhoc') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'static_qmi') {
    downloadExtensions = /\.pdf$/;
  } else if (data.type === 'static_foi') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else {
    alert('This file type is not valid. Contact an administrator to add this type of file in this document');
  }

  $('#add-' + idField).one('click', function () {
      var position = $(".workspace-edit").scrollTop();
      Florence.globalVars.pagePos = position + 200;
      $('#sortable-' + idField).append(
        '
' +
        '  <form id="UploadForm">' +
        '    <input type="file" title="Select a file and click Submit" name="files">' +
        '
' +
        '    <button type="submit" form="UploadForm" value="submit">Submit</button>' +
        '    <button class="btn-page-cancel" id="file-cancel">Cancel</button>' +
        '  </form>' +
        '

' +
        '

' +
        '
');

      $('#file-cancel').one('click', function (e) {
        e.preventDefault();
        $('#' + lastIndex).remove();
        addFile(collectionId, data, field, idField);
      });

      $('#UploadForm').submit(function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();
        var formdata = new FormData();

        function showUploadedItem(source) {
          $('#list').append(source);
        }

        document.getElementById("response").innerHTML = "Uploading . . .";

        var file = this[0].files[0];
        uriUpload = data.uri + "/" + file.name;
        var safeUriUpload = checkPathSlashes(uriUpload);

        if (data[field].length > 0) {
          $(data[field]).each(function (i, filesUploaded) {
            if (filesUploaded.file == safeUriUpload) {
              alert('This file already exists');
              $('#' + lastIndex).remove();
              addFile(collectionId, data, field, idField);
              return;
            }
          });
        }
        if (!!file.name.match(downloadExtensions)) {
          showUploadedItem(file.name);
          if (formdata) {
            formdata.append("name", file);
          }
        } else {
          alert('This file type is not supported');
          $('#' + lastIndex).remove();
          addFile(collectionId, data, field, idField);
          return;
        }

        if (formdata) {
          $.ajax({
            url: "/zebedee/content/" + collectionId + "?uri=" + safeUriUpload,
            type: "POST",
            data: formdata,
            cache: false,
            processData: false,
            contentType: false,
            success: function (res) {
              document.getElementById("response").innerHTML = "File uploaded successfully";
              data[field].push({title: '', file: safeUriUpload});
              updateContent(collectionId, data.uri, JSON.stringify(data));
            }
          });
        }
      });
    }
  );

  $(function () {
    $('.add-tooltip').tooltip({
      items: '.add-tooltip',
      content: 'Type title here and click Save to add it to the page',
      show: "slideDown", // show immediately
      open: function (event, ui) {
        ui.tooltip.hover(
          function () {
            $(this).fadeTo("slow", 0.5);
          });
      }
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable();
  }

  sortable();
}

<commit_msg>Limit dataset type uploads. Add csdb to timeseries dataset type<commit_after>function addFile(collectionId, data, field, idField) {
  var list = data[field];
  var downloadExtensions;
  var dataTemplate = {list: list, idField: idField};
  var html = templates.editorDownloads(dataTemplate);
  $('#' + idField).replaceWith(html);
  var uriUpload;
  // Edit
  if (!data[field] || data[field].length === 0) {
    var lastIndex = 0;
  } else {
    $(data[field]).each(function (index) {
      // Delete
      $('#' + idField + '-delete_' + index).click(function () {
        var result = confirm("Are you sure you want to delete this file?");
        if (result === true) {
          var position = $(".workspace-edit").scrollTop();
          Florence.globalVars.pagePos = position + 200;
          $(this).parent().remove();
          $.ajax({
            url: "/zebedee/content/" + collectionId + "?uri=" + data[field][index].file,
            type: "DELETE",
            success: function (res) {
              console.log(res);
            },
            error: function (res) {
              console.log(res);
            }
          });
          data[field].splice(index, 1);
          updateContent(collectionId, data.uri, JSON.stringify(data));
        }
      });
      // Edit
      $('#' + idField + '-edit_' + index).click(function () {
        var editedSectionValue = {
          "markdown": $('#' + idField + '-title_' + index).val(),
        };
        var saveContent = function (updatedContent) {
          data[field][index].markdown = updatedContent;
          updateContent(collectionId, data.uri, JSON.stringify(data));
        };
        loadMarkdownEditor(editedSectionValue, saveContent, data);
      });
    });
  }

  //Add
  if (data.type === 'dataset') {
    downloadExtensions = /\.csv$|.xls$|.zip$/;
  }  else if (data.type === 'timeseries_dataset') {
    downloadExtensions = /\.csdb$/;
  }  else if (data.type === 'static_adhoc') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else if (data.type === 'static_qmi') {
    downloadExtensions = /\.pdf$/;
  } else if (data.type === 'static_foi') {
    downloadExtensions = /\.csv$|.xls$|.doc$|.pdf$|.zip$/;
  } else {
    alert('This file type is not valid. Contact an administrator to add this type of file in this document');
  }

  $('#add-' + idField).one('click', function () {
      var position = $(".workspace-edit").scrollTop();
      Florence.globalVars.pagePos = position + 200;
      $('#sortable-' + idField).append(
        '
' +
        '  <form id="UploadForm">' +
        '    <input type="file" title="Select a file and click Submit" name="files">' +
        '
' +
        '    <button type="submit" form="UploadForm" value="submit">Submit</button>' +
        '    <button class="btn-page-cancel" id="file-cancel">Cancel</button>' +
        '  </form>' +
        '

' +
        '

' +
        '
');

      $('#file-cancel').one('click', function (e) {
        e.preventDefault();
        $('#' + lastIndex).remove();
        addFile(collectionId, data, field, idField);
      });

      $('#UploadForm').submit(function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();
        var formdata = new FormData();

        function showUploadedItem(source) {
          $('#list').append(source);
        }

        document.getElementById("response").innerHTML = "Uploading . . .";

        var file = this[0].files[0];
        uriUpload = data.uri + "/" + file.name;
        var safeUriUpload = checkPathSlashes(uriUpload);

        if (data[field].length > 0) {
          $(data[field]).each(function (i, filesUploaded) {
            if (filesUploaded.file == safeUriUpload) {
              alert('This file already exists');
              $('#' + lastIndex).remove();
              addFile(collectionId, data, field, idField);
              return;
            }
          });
        }
        if (!!file.name.match(downloadExtensions)) {
          showUploadedItem(file.name);
          if (formdata) {
            formdata.append("name", file);
          }
        } else {
          alert('This file type is not supported');
          $('#' + lastIndex).remove();
          addFile(collectionId, data, field, idField);
          return;
        }

        if (formdata) {
          $.ajax({
            url: "/zebedee/content/" + collectionId + "?uri=" + safeUriUpload,
            type: "POST",
            data: formdata,
            cache: false,
            processData: false,
            contentType: false,
            success: function (res) {
              document.getElementById("response").innerHTML = "File uploaded successfully";
              data[field].push({title: '', file: safeUriUpload});
              updateContent(collectionId, data.uri, JSON.stringify(data));
            }
          });
        }
      });
    }
  );

  $(function () {
    $('.add-tooltip').tooltip({
      items: '.add-tooltip',
      content: 'Type title here and click Save to add it to the page',
      show: "slideDown", // show immediately
      open: function (event, ui) {
        ui.tooltip.hover(
          function () {
            $(this).fadeTo("slow", 0.5);
          });
      }
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable();
  }

  sortable();
}

<|endoftext|>


<commit_before>function viewReports() {
  var manual = '[manual collection]';

  $.ajax({
    url: "/zebedee/publishedcollections",
    type: "get",
    crossDomain: true,
    success: function (collections) {
      $(collections).each(function (i) {
        collections[i].order = i;
      });
      populatePublishTable(collections);
    },
    error: function (response) {
      handleApiError(response);
    }
  });

  function populatePublishTable(collections) {

    //var collectionsByDate = _.chain(collections)
    //  .filter(function (collection) {
    //    return collection.publishResults[collection.publishResults.length - 1].transaction.startDate;
    //  })
    //  .sortBy('startDate')
    //  .value();

    //$(collectionsByDate).each(function (n, coll) {
    $(collections).each(function (n, coll) {
      if(coll.publishResults && coll.publishResults.length > 0) {
        var date = coll.publishResults[coll.publishResults.length - 1].transaction.startDate;

        //collectionsByDate[n].formattedDate = StringUtils.formatIsoFull(date);
        collections[n].formattedDate = StringUtils.formatIsoFull(date);
      }
    });

    //var reportList = templates.reportList(collectionsByDate);
    var reportList = templates.reportList(collections);
    $('.section').html(reportList);

    $('.publish-select-table tbody tr').click(function () {
      var i = $(this).attr('data-collections-order');
      viewReportDetails(collections[i]);

      $('.publish-select-table tbody tr').removeClass('selected');
      $(this).addClass('selected');
      $('.publish-selected').animate({right: "0%"}, 800);
      $('.publish-select').animate({marginLeft: "0%"}, 500);
    });
  }
}
<commit_msg>Filtering published collections that do not have any publish results<commit_after>function viewReports() {
  var manual = '[manual collection]';

  $.ajax({
    url: "/zebedee/publishedcollections",
    type: "get",
    crossDomain: true,
    success: function (collections) {

      populatePublishTable(collections);
    },
    error: function (response) {
      handleApiError(response);
    }
  });

  function populatePublishTable(collections) {

    var filteredCollections = _.chain(collections)
      .filter(function (collection) {
        return collection.publishResults && collection.publishResults.length > 0;
      })
      //.sortBy('startDate')
      .value();

    $(filteredCollections).each(function (i) {
      filteredCollections[i].order = i;
    });

    //$(collectionsByDate).each(function (n, coll) {
    $(filteredCollections).each(function (n, coll) {
      if(coll.publishResults && coll.publishResults.length > 0) {
        var date = coll.publishResults[coll.publishResults.length - 1].transaction.startDate;

        //collectionsByDate[n].formattedDate = StringUtils.formatIsoFull(date);
        filteredCollections[n].formattedDate = StringUtils.formatIsoFull(date);
      }
    });

    //var reportList = templates.reportList(collectionsByDate);
    var reportList = templates.reportList(filteredCollections);
    $('.section').html(reportList);

    $('.publish-select-table tbody tr').click(function () {
      var i = $(this).attr('data-collections-order');
      viewReportDetails(filteredCollections[i]);

      $('.publish-select-table tbody tr').removeClass('selected');
      $(this).addClass('selected');
      $('.publish-selected').animate({right: "0%"}, 800);
      $('.publish-select').animate({marginLeft: "0%"}, 500);
    });
  }
}
<|endoftext|>


<commit_before>function Spiral(graphType) {
  this.graphType = graphType || "points";
  this.numberOfPoints = null,
  this.period = null,
  this.margin = {
    top: 10,
    right: 10,
    bottom: 10,
    left: 10
  },
  this.svgHeight = 0,
  this.svgWidth = 0,
  this.spacing = 1,
  this.lineWidth = 50,
  this.targetElement = '#chart',
  this.width = this.svgWidth - this.margin.left - this.margin.right,
  this.height = this.svgHeight - this.margin.top - this.margin.bottom,
  this.data = [],
  this.x = d3.scale.linear().range([0, 730]).domain([-750, 750]),
  this.y = d3.scale.linear().range([480, 0]).domain([-500, 500]),
  this.cartesian = function(radius, angle, size, startAngle, endAngle) {
    var size = size || 1;
    var xPos = this.x(radius * Math.cos(angle));
    var yPos = this.y(radius * Math.sin(angle));
    return [xPos, yPos, size, radius, angle, startAngle, endAngle];
  },
  this.render = function() {
    var spiralContext = this;

    var svg = d3.select(spiralContext.targetElement)
      .append("svg")
      .attr("width", spiralContext.svgWidth)
      .attr("height", spiralContext.svgHeight)

    if (spiralContext.graphType === "points") {
      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");

      svg.selectAll("g").selectAll("dot")
        .data(spiralContext.data)
          .enter().append("circle")
            .attr("r", function(d) { return d[2]; })
            .attr("cx", function(d) { return d[0]; })
            .attr("cy", function(d) { return d[1]; });
    } else if (spiralContext.graphType === "custom-path") {
      spiralContext.data.forEach(function(datum, t, dataSet){
        var start = startAngle(t, spiralContext.period);
        var end = endAngle(t, spiralContext.period);

        var startInnerRadius = radius(spiralContext.spacing, start) - spiralContext.lineWidth*0.5;
        var startOuterRadius = radius(spiralContext.spacing, start) + spiralContext.lineWidth*0.5;
        var endInnerRadius = radius(spiralContext.spacing, end) - spiralContext.lineWidth*0.5;
        var endOuterRadius = radius(spiralContext.spacing, end) + spiralContext.lineWidth*0.5;

        var ctrlInnerRad = 0.01; // Use to adjust arc inner radius
        var ctrlOuterRad = 0.01; // Use to adjust arc outer radius
        var innerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) - spiralContext.lineWidth*0.5 + ctrlInnerRad, theta(t, spiralContext.period));
        var outerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) + spiralContext.lineWidth*0.5 + ctrlOuterRad, theta(t, spiralContext.period));

        var startPoint = spiralContext.cartesian(startInnerRadius, start); // Bottom right of arc
        var point2 = spiralContext.cartesian(startOuterRadius, start); // Top right of arc
        var point3 = spiralContext.cartesian(endOuterRadius, end); // Top left of arc
        var point4 = spiralContext.cartesian(endInnerRadius, end); // Bottom left of arc
        var arcPath = "M" + startPoint[0] + " " + startPoint[1] + "L" + point2[0] + " " + point2[1];
        arcPath += "Q" + outerControlPoint[0] + " " + outerControlPoint[1] + " " + point3[0] + " " + point3[1];
        arcPath += "L" + point4[0] + " " + point4[1];
        arcPath += "Q" + innerControlPoint[0] + " " + innerControlPoint[1] + " " + startPoint[0] + " " + startPoint[1] + "Z";
        datum[1] = arcPath
      });

      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");
      svg.selectAll("g").selectAll("path")
        .data(spiralContext.data.slice(100))
        .enter().append("path")
          .style("fill", function(d) { return "black"; })
          .style("opacity", function(d) {return d[2]/9})
          .attr("d", function(d) { return d[1]});
    } else if (spiralContext.graphType === "non-spiral") {
      // --------------------vvv Standard Line Graph vvv---------------------------
      var x2 = d3.scale.linear().range([0, 730]);
      var y2 = d3.scale.linear().range([480, 0]);
      x2.domain(d3.extent(spiralContext.data, function(d) { return d[0]; }));
      y2.domain(d3.extent(spiralContext.data, function(d) { return d[1]; }));

      var xAxis = d3.svg.axis().scale(x2)
        .orient("bottom").ticks(5);

      var yAxis = d3.svg.axis().scale(y2)
        .orient("left").ticks(5);

      var line = d3.svg.line()
        .x(function(d) { return x2(d[0]); })
        .y(function(d) { return y2(d[1]); });

      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate("+spiralContext.margin.left+"," + 480 + ")")
        .call(xAxis)
        .append("text")
          .attr("x", 710)
          .attr("y", -3)
          .attr("dy", "-.35em")
          .style("text-anchor", "middle")
          .text("time");

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate("+spiralContext.margin.left+",0)")
        .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Signal (a.u.)");

      svg.append("path")
        .datum(spiralContext.data)
        .attr("class", "line")
        .attr("d", line)
        .attr("fill", "none")
        .attr("stroke-width", "1")
        .attr("stroke", "steelblue")
        .attr("transform", "translate("+spiralContext.margin.left+",0)")
    }
  },
  this.randomData = function() {
    this.data = [];
    for (var i=0; i<this.numberOfPoints; i++){
      var angle = theta(i, this.period);
      var rad = radius(this.spacing, angle);
      var size = 1 + Math.random()*1.5;
      if (i % 10 === 0) {
        size = 5.5 + Math.random()*3;
      }

      if (this.graphType === 'non-spiral') {
        this.data.push([i, size*this.period, 2])
      } else {
        this.data.push(this.cartesian(rad, angle, size, startAngle(i, this.period), endAngle(i, this.period)));
      }
    }
  },
  this.setParam = function(param, value) {
    var spiralContext = this;
    spiralContext[param] = value;
    if (['svgHeight', 'svgWidth', 'margin.top', 'margin.right', 'margin.bottom', , 'margin.left'].indexOf(param) > -1) {
      spiralContext.width = spiralContext.svgWidth - spiralContext.margin.left - spiralContext.margin.right;
      spiralContext.height = spiralContext.svgHeight - spiralContext.margin.top - spiralContext.margin.bottom;
      spiralContext.x = d3.scale.linear().range([0, spiralContext.width]).domain([-spiralContext.svgWidth, spiralContext.svgWidth]);
      spiralContext.y = d3.scale.linear().range([spiralContext.height, 0]).domain([-spiralContext.svgHeight, spiralContext.svgHeight]);
    }
  },
  this.redraw = function() {
    var spiralContext = this;
    var graphContainer = document.getElementById(spiralContext.targetElement.substr(1));
    while (graphContainer.firstChild) {
      graphContainer.removeChild(graphContainer.firstChild)
    }
    spiralContext.render();
  }
}

// For time point #t, calculate the angle to the center of the arc
// period is the number of time points per revolution (2 PI)
function theta(t, period) {
  return 2 * Math.PI / (period) * t;
}

function startAngle(t, period) {
  return (theta(t-1, period) + theta(t, period))/2;
}

function endAngle(t, period) {
  return (theta(t+1, period) + theta(t, period))/2;
}

function radius(spacing, angle) {
  return spacing * angle;
}<commit_msg>Begin refactor: move params to graphParams property<commit_after>function Spiral(graphType) {
  this.graphParams = {
    graphType: graphType || "points",
  },
  this.numberOfPoints = null,
  this.period = null,
  this.margin = {
    top: 10,
    right: 10,
    bottom: 10,
    left: 10
  },
  this.svgHeight = 0,
  this.svgWidth = 0,
  this.spacing = 1,
  this.lineWidth = 50,
  this.targetElement = '#chart',
  this.width = this.svgWidth - this.margin.left - this.margin.right,
  this.height = this.svgHeight - this.margin.top - this.margin.bottom,
  this.data = [],
  this.x = d3.scale.linear().range([0, 730]).domain([-750, 750]),
  this.y = d3.scale.linear().range([480, 0]).domain([-500, 500]),
  this.cartesian = function(radius, angle, size, startAngle, endAngle) {
    var size = size || 1;
    var xPos = this.x(radius * Math.cos(angle));
    var yPos = this.y(radius * Math.sin(angle));
    return [xPos, yPos, size, radius, angle, startAngle, endAngle];
  },
  this.render = function() {
    var spiralContext = this;

    var svg = d3.select(spiralContext.targetElement)
      .append("svg")
      .attr("width", spiralContext.svgWidth)
      .attr("height", spiralContext.svgHeight)

    if (spiralContext.graphParams.graphType === "points") {
      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");

      svg.selectAll("g").selectAll("dot")
        .data(spiralContext.data)
          .enter().append("circle")
            .attr("r", function(d) { return d[2]; })
            .attr("cx", function(d) { return d[0]; })
            .attr("cy", function(d) { return d[1]; });
    } else if (spiralContext.graphParams.graphType === "custom-path") {
      spiralContext.data.forEach(function(datum, t, dataSet){
        var start = startAngle(t, spiralContext.period);
        var end = endAngle(t, spiralContext.period);

        var startInnerRadius = radius(spiralContext.spacing, start) - spiralContext.lineWidth*0.5;
        var startOuterRadius = radius(spiralContext.spacing, start) + spiralContext.lineWidth*0.5;
        var endInnerRadius = radius(spiralContext.spacing, end) - spiralContext.lineWidth*0.5;
        var endOuterRadius = radius(spiralContext.spacing, end) + spiralContext.lineWidth*0.5;

        var ctrlInnerRad = 0.01; // Use to adjust arc inner radius
        var ctrlOuterRad = 0.01; // Use to adjust arc outer radius
        var innerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) - spiralContext.lineWidth*0.5 + ctrlInnerRad, theta(t, spiralContext.period));
        var outerControlPoint = spiralContext.cartesian(radius(spiralContext.spacing, theta(t, spiralContext.period)) + spiralContext.lineWidth*0.5 + ctrlOuterRad, theta(t, spiralContext.period));

        var startPoint = spiralContext.cartesian(startInnerRadius, start); // Bottom right of arc
        var point2 = spiralContext.cartesian(startOuterRadius, start); // Top right of arc
        var point3 = spiralContext.cartesian(endOuterRadius, end); // Top left of arc
        var point4 = spiralContext.cartesian(endInnerRadius, end); // Bottom left of arc
        var arcPath = "M" + startPoint[0] + " " + startPoint[1] + "L" + point2[0] + " " + point2[1];
        arcPath += "Q" + outerControlPoint[0] + " " + outerControlPoint[1] + " " + point3[0] + " " + point3[1];
        arcPath += "L" + point4[0] + " " + point4[1];
        arcPath += "Q" + innerControlPoint[0] + " " + innerControlPoint[1] + " " + startPoint[0] + " " + startPoint[1] + "Z";
        datum[1] = arcPath
      });

      svg.append("g")
        .attr("transform", "translate(" + spiralContext.margin.left + "," + spiralContext.margin.top + ")");
      svg.selectAll("g").selectAll("path")
        .data(spiralContext.data.slice(100))
        .enter().append("path")
          .style("fill", function(d) { return "black"; })
          .style("opacity", function(d) {return d[2]/9})
          .attr("d", function(d) { return d[1]});
    } else if (spiralContext.graphParams.graphType === "non-spiral") {
      // --------------------vvv Standard Line Graph vvv---------------------------
      var x2 = d3.scale.linear().range([0, 730]);
      var y2 = d3.scale.linear().range([480, 0]);
      x2.domain(d3.extent(spiralContext.data, function(d) { return d[0]; }));
      y2.domain(d3.extent(spiralContext.data, function(d) { return d[1]; }));

      var xAxis = d3.svg.axis().scale(x2)
        .orient("bottom").ticks(5);

      var yAxis = d3.svg.axis().scale(y2)
        .orient("left").ticks(5);

      var line = d3.svg.line()
        .x(function(d) { return x2(d[0]); })
        .y(function(d) { return y2(d[1]); });

      // Add the X Axis
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate("+spiralContext.margin.left+"," + 480 + ")")
        .call(xAxis)
        .append("text")
          .attr("x", 710)
          .attr("y", -3)
          .attr("dy", "-.35em")
          .style("text-anchor", "middle")
          .text("time");

      // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate("+spiralContext.margin.left+",0)")
        .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Signal (a.u.)");

      svg.append("path")
        .datum(spiralContext.data)
        .attr("class", "line")
        .attr("d", line)
        .attr("fill", "none")
        .attr("stroke-width", "1")
        .attr("stroke", "steelblue")
        .attr("transform", "translate("+spiralContext.margin.left+",0)")
    }
  },
  this.randomData = function() {
    this.data = [];
    for (var i=0; i<this.numberOfPoints; i++){
      var angle = theta(i, this.period);
      var rad = radius(this.spacing, angle);
      var size = 1 + Math.random()*1.5;
      if (i % 10 === 0) {
        size = 5.5 + Math.random()*3;
      }

      if (this.graphParams.graphType === 'non-spiral') {
        this.data.push([i, size*this.period, 2])
      } else {
        this.data.push(this.cartesian(rad, angle, size, startAngle(i, this.period), endAngle(i, this.period)));
      }
    }
  },
  this.setParam = function(param, value) {
    var spiralContext = this;
    spiralContext[param] = value;
    if (['svgHeight', 'svgWidth', 'margin.top', 'margin.right', 'margin.bottom', , 'margin.left'].indexOf(param) > -1) {
      spiralContext.width = spiralContext.svgWidth - spiralContext.margin.left - spiralContext.margin.right;
      spiralContext.height = spiralContext.svgHeight - spiralContext.margin.top - spiralContext.margin.bottom;
      spiralContext.x = d3.scale.linear().range([0, spiralContext.width]).domain([-spiralContext.svgWidth, spiralContext.svgWidth]);
      spiralContext.y = d3.scale.linear().range([spiralContext.height, 0]).domain([-spiralContext.svgHeight, spiralContext.svgHeight]);
    }
  },
  this.redraw = function() {
    var spiralContext = this;
    var graphContainer = document.getElementById(spiralContext.targetElement.substr(1));
    while (graphContainer.firstChild) {
      graphContainer.removeChild(graphContainer.firstChild)
    }
    spiralContext.render();
  }
}

// For time point #t, calculate the angle to the center of the arc
// period is the number of time points per revolution (2 PI)
function theta(t, period) {
  return 2 * Math.PI / (period) * t;
}

function startAngle(t, period) {
  return (theta(t-1, period) + theta(t, period))/2;
}

function endAngle(t, period) {
  return (theta(t+1, period) + theta(t, period))/2;
}

function radius(spacing, angle) {
  return spacing * angle;
}<|endoftext|>


<commit_before>describe('String Template Engine', function () {
    this.prepareTestElement('

');

    beforeEach(function() {
        this.engine = new ko.stringTemplateEngine();
    });

    it('Should "ko.stringTemplateEngine.instance" exist and be an instanse of ko.stringTemplateEngine', function() {
        expect(ko.stringTemplateEngine.instance).toBeDefined();
        expect(ko.stringTemplateEngine.instance).toEqual(jasmine.any(ko.stringTemplateEngine));
    });

    it('Should add new string template to string template engine', function() {
        this.engine.addTemplate('test', 'text');

        expect(this.engine.isTemplateExist('test')).toBeTruthy();
    });

    it('Should remove template from template engine', function () {
        this.engine.addTemplate('test', 'text');

        expect(this.engine.isTemplateExist('test')).toBeTruthy();
        this.engine.removeTemplate('test');
        expect(this.engine.isTemplateExist('test')).toBeFalsy();
    });

    it('Should render element with added string template', function () {
        this.engine.addTemplate('test', 'test text');

        var vm = {
            templ: { name: 'test', templateEngine: this.engine }
        };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement).toContainText('test text');
    });

    it('Should not render element with string template engine', function () {
        this.engine.addTemplate('test', 'string template engine');
        this.testElement.after('');

        var vm = {
            templ: { name: 'test' }
        };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement).not.toContainText('string template engine');
        $('#test-template').remove();
    });

    it('Should throw exception, if trying to remove template without name', function () {
        expect(function() {
            this.engine.removeTemplate();
        }).toThrow();
    });

    it('Should throw exception, if trying to add undefined template', function () {
        expect(function () {
            this.engine.addTemplate('test');
        }).toThrow();
    });
});<commit_msg>Updated tests for string template engine<commit_after>describe('String Template Engine', function () {
    this.prepareTestElement('

');

    beforeEach(function() {
        this.engine = new ko.stringTemplateEngine();
    });

    it('Should "ko.stringTemplateEngine.instance" exist and be an instanse of ko.stringTemplateEngine', function() {
        expect(ko.stringTemplateEngine.instance).toBeDefined();
        expect(ko.stringTemplateEngine.instance).toEqual(jasmine.any(ko.stringTemplateEngine));
    });

    it('Should add new string template to string template engine', function() {
        this.engine.addTemplate('test', 'text');

        expect(this.engine.isTemplateExist('test')).toBeTruthy();
    });

    it('Should get added template from string template engine', function () {
        this.engine.addTemplate('test', 'text');

        expect(this.engine.getTemplate('test')).toEqual('text');
    });

    it('Should remove template from template engine', function () {
        this.engine.addTemplate('test', 'text');

        expect(this.engine.isTemplateExist('test')).toBeTruthy();
        this.engine.removeTemplate('test');
        expect(this.engine.isTemplateExist('test')).toBeFalsy();
    });

    it('Should render element with added string template', function () {
        this.engine.addTemplate('test', 'test text');

        var vm = {
            templ: { name: 'test', templateEngine: this.engine }
        };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement).toContainText('test text');
    });

    it('Should not render element with string template engine', function () {
        this.engine.addTemplate('test', 'string template engine');
        this.testElement.after('');

        var vm = {
            templ: { name: 'test' }
        };

        ko.applyBindings(vm, this.testElement[0]);

        expect(this.testElement).not.toContainText('string template engine');
        $('#test-template').remove();
    });

    it('Should throw exception, if trying to remove template without name', function () {
        expect(function() {
            this.engine.removeTemplate();
        }).toThrow();
    });

    it('Should throw exception, if trying to add undefined template', function () {
        expect(function () {
            this.engine.addTemplate('test');
        }).toThrow();
    });
});<|endoftext|>


<commit_before>/*!
 * Validator v0.11.9 for Bootstrap 3, by @1000hz
 * Copyright 2017 Cina Saffary
 * Licensed under http://opensource.org/licenses/MIT
 *
 * https://github.com/1000hz/bootstrap-validator
 */

+function(a){"use strict";function b(b){return b.is('[type="checkbox"]')?b.prop("checked"):b.is('[type="radio"]')?!!a('[name="'+b.attr("name")+'"]:checked').length:b.is("select[multiple]")?(b.val()||[]).length:b.val()}function c(b){return this.each(function(){var c=a(this),e=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b),f=c.data("bs.validator");(f||"destroy"!=b)&&(f||c.data("bs.validator",f=new d(this,e)),"string"==typeof b&&f[b]())})}var d=function(c,e){this.options=e,this.validators=a.extend({},d.VALIDATORS,e.custom),this.$element=a(c),this.$btn=a('button[type="submit"], input[type="submit"]').filter('[form="'+this.$element.attr("id")+'"]').add(this.$element.find('input[type="submit"], button[type="submit"]')),this.update(),this.$element.on("input.bs.validator change.bs.validator focusout.bs.validator",a.proxy(this.onInput,this)),this.$element.on("submit.bs.validator",a.proxy(this.onSubmit,this)),this.$element.on("reset.bs.validator",a.proxy(this.reset,this)),this.$element.find("[data-match]").each(function(){var c=a(this),d=c.attr("data-match");a(d).on("input.bs.validator",function(){b(c)&&c.trigger("input.bs.validator")})}),this.$inputs.filter(function(){return b(a(this))&&!a(this).closest(".has-error").length}).trigger("focusout"),this.$element.attr("novalidate",!0)};d.VERSION="0.11.9",d.INPUT_SELECTOR=':input:not([type="hidden"], [type="submit"], [type="reset"], button)',d.FOCUS_OFFSET=20,d.DEFAULTS={delay:500,html:!1,disable:!0,focus:!0,custom:{},errors:{match:"Does not match",minlength:"Not long enough"},feedback:{success:"glyphicon-ok",error:"glyphicon-remove"}},d.VALIDATORS={"native":function(a){var b=a[0];return b.checkValidity?!b.checkValidity()&&!b.validity.valid&&(b.validationMessage||"error!"):void 0},match:function(b){var c=b.attr("data-match");return b.val()!==a(c).val()&&d.DEFAULTS.errors.match},minlength:function(a){var b=a.attr("data-minlength");return a.val().length<b&&d.DEFAULTS.errors.minlength}},d.prototype.update=function(){var b=this;return this.$inputs=this.$element.find(d.INPUT_SELECTOR).add(this.$element.find('[data-validate="true"]')).not(this.$element.find('[data-validate="false"]').each(function(){b.clearErrors(a(this))})),this.toggleSubmit(),this},d.prototype.onInput=function(b){var c=this,d=a(b.target),e="focusout"!==b.type;this.$inputs.is(d)&&this.validateInput(d,e).done(function(){c.toggleSubmit()})},d.prototype.validateInput=function(c,d){var e=(b(c),c.data("bs.validator.errors"));c.is('[type="radio"]')&&(c=this.$element.find('input[name="'+c.attr("name")+'"]'));var f=a.Event("validate.bs.validator",{relatedTarget:c[0]});if(this.$element.trigger(f),!f.isDefaultPrevented()){var g=this;return this.runValidators(c).done(function(b){c.data("bs.validator.errors",b),b.length?d?g.defer(c,g.showErrors):g.showErrors(c):g.clearErrors(c),e&&b.toString()===e.toString()||(f=b.length?a.Event("invalid.bs.validator",{relatedTarget:c[0],detail:b}):a.Event("valid.bs.validator",{relatedTarget:c[0],detail:e}),g.$element.trigger(f)),g.toggleSubmit(),g.$element.trigger(a.Event("validated.bs.validator",{relatedTarget:c[0]}))})}},d.prototype.runValidators=function(c){function d(a){return c.attr("data-"+a+"-error")}function e(){var a=c[0].validity;return a.typeMismatch?c.attr("data-type-error"):a.patternMismatch?c.attr("data-pattern-error"):a.stepMismatch?c.attr("data-step-error"):a.rangeOverflow?c.attr("data-max-error"):a.rangeUnderflow?c.attr("data-min-error"):a.valueMissing?c.attr("data-required-error"):null}function f(){return c.attr("data-error")}function g(a){return d(a)||e()||f()}var h=[],i=a.Deferred();return c.data("bs.validator.deferred")&&c.data("bs.validator.deferred").reject(),c.data("bs.validator.deferred",i),a.each(this.validators,a.proxy(function(a,d){var e=null;!b(c)&&!c.attr("required")||void 0===c.attr("data-"+a)&&"native"!=a||!(e=d.call(this,c))||(e=g(a)||e,!~h.indexOf(e)&&h.push(e))},this)),!h.length&&b(c)&&c.attr("data-remote")?this.defer(c,function(){var d={};d[c.attr("name")]=b(c),a.get(c.attr("data-remote"),d).fail(function(a,b,c){h.push(g("remote")||c)}).always(function(){i.resolve(h)})}):i.resolve(h),i.promise()},d.prototype.validate=function(){var b=this;return a.when(this.$inputs.map(function(){return b.validateInput(a(this),!1)})).then(function(){b.toggleSubmit(),b.focusError()}),this},d.prototype.focusError=function(){if(this.options.focus){var b=this.$element.find(".has-error :input:first");0!==b.length&&(a("html, body").animate({scrollTop:b.offset().top-d.FOCUS_OFFSET},250),b.focus())}},d.prototype.showErrors=function(b){var c=this.options.html?"html":"text",d=b.data("bs.validator.errors"),e=b.closest(".form-group"),f=e.find(".help-block.with-errors"),g=e.find(".form-control-feedback");d.length&&(d=a("<ul/>").addClass("list-unstyled").append(a.map(d,function(b){return a("<li/>")[c](b)})),void 0===f.data("bs.validator.originalContent")&&f.data("bs.validator.originalContent",f.html()),f.empty().append(d),e.addClass("has-error has-danger"),e.hasClass("has-feedback")&&g.removeClass(this.options.feedback.success)&&g.addClass(this.options.feedback.error)&&e.removeClass("has-success"))},d.prototype.clearErrors=function(a){var c=a.closest(".form-group"),d=c.find(".help-block.with-errors"),e=c.find(".form-control-feedback");d.html(d.data("bs.validator.originalContent")),c.removeClass("has-error has-danger has-success"),c.hasClass("has-feedback")&&e.removeClass(this.options.feedback.error)&&e.removeClass(this.options.feedback.success)&&b(a)&&e.addClass(this.options.feedback.success)&&c.addClass("has-success")},d.prototype.hasErrors=function(){function b(){return!!(a(this).data("bs.validator.errors")||[]).length}return!!this.$inputs.filter(b).length},d.prototype.isIncomplete=function(){function c(){var c=b(a(this));return!("string"==typeof c?a.trim(c):c)}return!!this.$inputs.filter("[required]").filter(c).length},d.prototype.onSubmit=function(a){this.validate(),(this.isIncomplete()||this.hasErrors())&&a.preventDefault()},d.prototype.toggleSubmit=function(){this.options.disable&&this.$btn.toggleClass("disabled",this.isIncomplete()||this.hasErrors())},d.prototype.defer=function(b,c){return c=a.proxy(c,this,b),this.options.delay?(window.clearTimeout(b.data("bs.validator.timeout")),void b.data("bs.validator.timeout",window.setTimeout(c,this.options.delay))):c()},d.prototype.reset=function(){return this.$element.find(".form-control-feedback").removeClass(this.options.feedback.error).removeClass(this.options.feedback.success),this.$inputs.removeData(["bs.validator.errors","bs.validator.deferred"]).each(function(){var b=a(this),c=b.data("bs.validator.timeout");window.clearTimeout(c)&&b.removeData("bs.validator.timeout")}),this.$element.find(".help-block.with-errors").each(function(){var b=a(this),c=b.data("bs.validator.originalContent");b.removeData("bs.validator.originalContent").html(c)}),this.$btn.removeClass("disabled"),this.$element.find(".has-error, .has-danger, .has-success").removeClass("has-error has-danger has-success"),this},d.prototype.destroy=function(){return this.reset(),this.$element.removeAttr("novalidate").removeData("bs.validator").off(".bs.validator"),this.$inputs.off(".bs.validator"),this.options=null,this.validators=null,this.$element=null,this.$btn=null,this.$inputs=null,this};var e=a.fn.validator;a.fn.validator=c,a.fn.validator.Constructor=d,a.fn.validator.noConflict=function(){return a.fn.validator=e,this},a(window).on("load",function(){a('form[data-toggle="validator"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery);<commit_msg>Delete validator.min.js<commit_after><|endoftext|>