<commit_before>/**
* This file kicks off the build process for the application.  It also attaches
* the Lore singleton to the window, so you can access it from the command line
* in case you need to play with it or want to manually kick off actions or check
* the reducer state (through `lore.actions.xyz`, `lore.reducers.xyz`,
* `lore.models.xyz`, etc.)
**/

import lore from 'lore';
import _ from 'lodash';

// Allows you to access your lore app globally as well as from within
// the console. Remove this line if you don't want to be able to do that.
window.lore = lore;

// Hooks
import auth from 'lore-hook-auth';
import actions from 'lore-hook-actions';
import bindActions from 'lore-hook-bind-actions';
import collections from 'lore-hook-collections';
import connections from 'lore-hook-connections';
import connect from 'lore-hook-connect';
import models from 'lore-hook-models';
import polling from 'lore-hook-polling';
import react from 'lore-hook-react';
import reducers from 'lore-hook-reducers';
import redux from 'lore-hook-redux';
import router from 'lore-hook-router';

// Summon the app!
lore.summon({
  hooks: {
    auth,
    actions,
    bindActions,
    collections,
    connections,
    connect,
    models,
    polling,
    react,
    reducers,
    redux: _.extend(redux, {
      dependencies: ['reducers', 'auth']
    }),
    router
  }
});
<commit_msg>[lore-generate-new] remove polling hook from es6 template<commit_after>/**
* This file kicks off the build process for the application.  It also attaches
* the Lore singleton to the window, so you can access it from the command line
* in case you need to play with it or want to manually kick off actions or check
* the reducer state (through `lore.actions.xyz`, `lore.reducers.xyz`,
* `lore.models.xyz`, etc.)
**/

import lore from 'lore';
import _ from 'lodash';

// Allows you to access your lore app globally as well as from within
// the console. Remove this line if you don't want to be able to do that.
window.lore = lore;

// Hooks
import auth from 'lore-hook-auth';
import actions from 'lore-hook-actions';
import bindActions from 'lore-hook-bind-actions';
import collections from 'lore-hook-collections';
import connections from 'lore-hook-connections';
import connect from 'lore-hook-connect';
import models from 'lore-hook-models';
import react from 'lore-hook-react';
import reducers from 'lore-hook-reducers';
import redux from 'lore-hook-redux';
import router from 'lore-hook-router';

// Summon the app!
lore.summon({
  hooks: {
    auth,
    actions,
    bindActions,
    collections,
    connections,
    connect,
    models,
    react,
    reducers,
    redux: _.extend(redux, {
      dependencies: ['reducers', 'auth']
    }),
    router
  }
});
<|endoftext|>


<commit_before>import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import Typography from '../Typography';

export const styles = {
  /* Styles applied to the root element. */
  root: {
    display: 'flex',
    alignItems: 'center',
    padding: 16,
  },
  /* Styles applied to the avatar element. */
  avatar: {
    flex: '0 0 auto',
    marginRight: 16,
  },
  /* Styles applied to the action element. */
  action: {
    flex: '0 0 auto',
    alignSelf: 'flex-start',
    marginTop: -4,
    marginRight: -8,
    marginBottom: -4,
  },
  /* Styles applied to the content wrapper element. */
  content: {
    flex: '1 1 auto',
  },
  /* Styles applied to the title Typography element. */
  title: {},
  /* Styles applied to the subheader Typography element. */
  subheader: {},
};

const CardHeader = React.forwardRef(function CardHeader(props, ref) {
  const {
    action,
    avatar,
    classes,
    className,
    component: Component = 'div',
    disableTypography = false,
    subheader: subheaderProp,
    subheaderTypographyProps,
    title: titleProp,
    titleTypographyProps,
    ...other
  } = props;

  let title = titleProp;
  if (title != null && title.type !== Typography && !disableTypography) {
    title = (
      <Typography
        variant={avatar ? 'body2' : 'h5'}
        className={classes.title}
        component="span"
        display="block"
        {...titleTypographyProps}
      >
        {title}
      </Typography>
    );
  }

  let subheader = subheaderProp;
  if (subheader != null && subheader.type !== Typography && !disableTypography) {
    subheader = (
      <Typography
        variant={avatar ? 'body2' : 'body1'}
        className={classes.subheader}
        color="textSecondary"
        component="span"
        display="block"
        {...subheaderTypographyProps}
      >
        {subheader}
      </Typography>
    );
  }

  return (
    <Component className={clsx(classes.root, className)} ref={ref} {...other}>
      {avatar &&
{avatar}
}

        {title}
        {subheader}

      {action &&
{action}
}
    </Component>
  );
});

CardHeader.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The action to display in the card header.
   */
  action: PropTypes.node,
  /**
   * The Avatar for the Card Header.
   */
  avatar: PropTypes.node,
  /**
   * @ignore
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes /* @typescript-to-proptypes-ignore */.elementType,
  /**
   * If `true`, `subheader` and `title` won't be wrapped by a Typography component.
   * This can be useful to render an alternative Typography variant by wrapping
   * the `title` text, and optional `subheader` text
   * with the Typography component.
   * @default false
   */
  disableTypography: PropTypes.bool,
  /**
   * The content of the component.
   */
  subheader: PropTypes.node,
  /**
   * These props will be forwarded to the subheader
   * (as long as disableTypography is not `true`).
   */
  subheaderTypographyProps: PropTypes.object,
  /**
   * The content of the Card Title.
   */
  title: PropTypes.node,
  /**
   * These props will be forwarded to the title
   * (as long as disableTypography is not `true`).
   */
  titleTypographyProps: PropTypes.object,
};

export default withStyles(styles, { name: 'MuiCardHeader' })(CardHeader);
<commit_msg>[Card] Use flex display for CardHeader.avatar (#23169)<commit_after>import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import Typography from '../Typography';

export const styles = {
  /* Styles applied to the root element. */
  root: {
    display: 'flex',
    alignItems: 'center',
    padding: 16,
  },
  /* Styles applied to the avatar element. */
  avatar: {
    display: 'flex',
    flex: '0 0 auto',
    marginRight: 16,
  },
  /* Styles applied to the action element. */
  action: {
    flex: '0 0 auto',
    alignSelf: 'flex-start',
    marginTop: -4,
    marginRight: -8,
    marginBottom: -4,
  },
  /* Styles applied to the content wrapper element. */
  content: {
    flex: '1 1 auto',
  },
  /* Styles applied to the title Typography element. */
  title: {},
  /* Styles applied to the subheader Typography element. */
  subheader: {},
};

const CardHeader = React.forwardRef(function CardHeader(props, ref) {
  const {
    action,
    avatar,
    classes,
    className,
    component: Component = 'div',
    disableTypography = false,
    subheader: subheaderProp,
    subheaderTypographyProps,
    title: titleProp,
    titleTypographyProps,
    ...other
  } = props;

  let title = titleProp;
  if (title != null && title.type !== Typography && !disableTypography) {
    title = (
      <Typography
        variant={avatar ? 'body2' : 'h5'}
        className={classes.title}
        component="span"
        display="block"
        {...titleTypographyProps}
      >
        {title}
      </Typography>
    );
  }

  let subheader = subheaderProp;
  if (subheader != null && subheader.type !== Typography && !disableTypography) {
    subheader = (
      <Typography
        variant={avatar ? 'body2' : 'body1'}
        className={classes.subheader}
        color="textSecondary"
        component="span"
        display="block"
        {...subheaderTypographyProps}
      >
        {subheader}
      </Typography>
    );
  }

  return (
    <Component className={clsx(classes.root, className)} ref={ref} {...other}>
      {avatar &&
{avatar}
}

        {title}
        {subheader}

      {action &&
{action}
}
    </Component>
  );
});

CardHeader.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------
  /**
   * The action to display in the card header.
   */
  action: PropTypes.node,
  /**
   * The Avatar for the Card Header.
   */
  avatar: PropTypes.node,
  /**
   * @ignore
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes /* @typescript-to-proptypes-ignore */.elementType,
  /**
   * If `true`, `subheader` and `title` won't be wrapped by a Typography component.
   * This can be useful to render an alternative Typography variant by wrapping
   * the `title` text, and optional `subheader` text
   * with the Typography component.
   * @default false
   */
  disableTypography: PropTypes.bool,
  /**
   * The content of the component.
   */
  subheader: PropTypes.node,
  /**
   * These props will be forwarded to the subheader
   * (as long as disableTypography is not `true`).
   */
  subheaderTypographyProps: PropTypes.object,
  /**
   * The content of the Card Title.
   */
  title: PropTypes.node,
  /**
   * These props will be forwarded to the title
   * (as long as disableTypography is not `true`).
   */
  titleTypographyProps: PropTypes.object,
};

export default withStyles(styles, { name: 'MuiCardHeader' })(CardHeader);
<|endoftext|>


<commit_before>define([
	'jquery',
	'underscore',
	'backbone',
	'config',
	'utils',
	'text!templates/data-import.html',
	'views/modal-view'
], function($, _, Backbone, config, utils, templateHtml, ModalView) {
	var DataImportView = ModalView.extend({

	    tagName: 'div',
		className: 'data-import-view modal fade',

	    events: {
	    	'change .step.source input': 'sourceInputChanged',
			'click .import-run': 'importButtonClicked',
			'click .source-submit': 'sourceSubmitButtonClicked',
			'click .back': 'backButtonClicked',
			'click .from-field .remove' : 'fromFieldRemoveClicked',
	    },

	    initialize: function(options) {
		    this.template = _.template(templateHtml);
			this.vent = options.vent;
			this.responseData = null;
			this.dataTitle = '';
			this.dataDescription = '';
			this.maxPreview = 30;
			this.inspectedSource;
			this.fromFieldColors = ['#a52a2a', '#f89406', '#46a546', '#62cffc', '#ff7f50', '#87ceeb', '#daa520', '#b8860b', '#c43c35', '#556b2f'];

			this.toFields = {
				'loc': 'Point X,Y',
				'val': 'Point Value',
				'datetime':'Date',
				'label': 'Point Label',
				'attributes': 'Attributes'
			};
	    },

	    canImport: function()
	    {
	    	return !this.isLoading
	    		&& this.$('input[name=url]').val().length;
	    },

	    sourceSubmitButtonClicked: function()
	    {
	    	var self = this;
	    	if (!this.canImport()) return false;
	    	console.log('sourceSubmit');
			this.runImport({inspect: true, max: this.maxPreview}, {
				success: function(responseData) {
					if (responseData.items && responseData.items.length) {
						self.initSourceForMapping(responseData);
						self.setStep('mapping');
					}
				}
			});
			return false;
	    },

	    backButtonClicked: function()
	    {
	    	this.setStep('source');
	    },

	    sourceInputChanged: function()
	    {
	    	var prev = this.$('input[name=url]').data('prevVal'),
	    		cur = this.$('input[name=url]').val();
	    	this.$('input[name=url]').data('prevVal', cur);
	    	if (1/*!prev || !prev.length*/) { // TODO detect a 100% change
	    		cur = cur.replace(/^https:\/\/www.dropbox.com\//,
	    			'https://dl.dropbox.com/');
	    		this.$('input[name=url]').val(cur);
	    	}
	    	this.$('.btn.source-submit').attr('disabled', !this.canImport());
	    },

		importButtonClicked: function()
		{
			var self = this;
			if (!this.canImport()) return false;
			this.runImport({background: true}, {
				success: function(responseData) {
					app.saveNewMapLayer(responseData.collection._id);
					self.setStep('source');
					self.close();
				}
			});
			return false;
		},

		initSourceForMapping: function(data)
		{
			var self = this;
			this.inspectedSource = data;
			this.fromFields = {};
			_.each(this.inspectedSource.items[0], function(value, key) {
				self.fromFields[key] = key;
			});

			this.$('.from-data thead').empty();
			this.$('.from-data tbody').empty();
			this.$('.to-data thead').empty();
			this.$('.to-data tbody').empty();

			var i = 0;
			for (var k in this.fromFields) {
				var f = this.fromFieldTemplate.clone();
				f.removeClass('element-template');
				$('.field-name', f).text(k);
				$('.label', f).css('background-color', this.fromFieldColors[i % this.fromFieldColors.length]);
				$('.from-field', f).attr('data-from', k);
				this.$('.from-data thead').append(f).show();
				i++;
			}

			// add source row preview
			_.each(this.inspectedSource.items, function(row) {
				var tds = '';
				_.each(self.fromFields, function(tmp, key) {
					tds += '' + row[key] + '	';
				});
				self.$('.from-data tbody').append('
' + tds + '
');
			});

			var initClickHandler = function(f) {
				$('.show-field-settings', f).hide();
				// solve with popover
				/*$('.show-field-settings', f).click(function() {
					$('.field-settings', f).toggle();
					return false;
				});*/
			};

			this.updateHandleStates();

			for (var k in this.toFields) {
				var f = this.toFieldTemplate.clone();
				f.removeClass('element-template');
				$('.field-title', f).text(this.toFields[k]);
				$('.to-field', f).attr('data-to', k);
				$('.field-settings', f).hide();
				initClickHandler(f);
				this.$('.to-data thead').append(f).show();
			}
			this.$('.to-field').sortable({
				connectWith: '.to-field',
				stop: function(event, ui) {
					// prevent double loading since dropping from draggable into the sortable
					// will also fire this event, but draggable.stop fires later than this one.
					if (self.preventSortableEvents) return;
					self.loadImportPreview();
				}
			});

			this.$('.from-field').draggable({
				revert: "invalid",
				helper: "clone",
				connectToSortable: '.to-field',
				stack: '.drag.label',
				start: function(event, ui) {
					self.preventSortableEvents = true;
					$(ui.helper).removeClass('half-opacity');
					self.$('.to-field').addClass('highlight');
				},
				stop: function(event, ui) {
					self.preventSortableEvents = false;
					self.$('.to-field').removeClass('highlight');
					self.$('.to-data .from-field').removeClass('half-opacity');
					self.updateHandleStates();
					self.loadImportPreview();
				}
			});

		},

	    render: function()
	    {
	    	var self = this;

			$(this.el).html(this.template());
			var self = this;

			this.spinner = this.$('.spinner').html(new Spinner({radius:6,length:0,width:6,color:'#333',lines:7,speed:1.5}).spin().el).hide();

			this.setStep('source');

			if (DEV) {
				this.$('[name=url]').val('https://dl.dropbox.com/s/cb4blktkkelwg1n/nuclear_reactors.csv');
				self.sourceSubmitButtonClicked();
			}

			this.sourceInputChanged();

			this.fromFieldTemplate = this.$('.from-data thead .element-template');
			this.toFieldTemplate = this.$('.to-data thead .element-template');
			this.$('.element-template').remove();

			this.$("input.text").click(function() {
			   $(this).select();
			});

	        return this;
	    },

	    setStep: function(step)
	    {
	    	this.setAlert();
	    	this.$('.step').each(function() {
	    		$(this).toggle($(this).is('.' + step));
	    	});
	    },

	    updateHandleStates: function()
	    {
	    	var self = this,
	    		mapped = this.$('.to-data .from-field');
	    	this.$('.from-data .from-field').each(function() {
	    		for (var i = 0; i < mapped.length; i++) {
	    			if ($(mapped[i]).attr('data-from') == $(this).attr('data-from')) {
		    			$(this).addClass('half-opacity');
		    			return;
	    			}
	    		}
    			$(this).removeClass('half-opacity');
	    	});
	    	this.$('.target').toggleClass('mapped', mapped.length > 0);
	    },

	    fromFieldRemoveClicked: function(event) {
			$(event.currentTarget).closest('.from-field').remove();
			this.updateHandleStates();
			this.previousFieldDefs = null;
			this.loadImportPreview();
			return false;
	    },

	    setAlert: function(html) {
	    	if (!html) {
				this.$('.modal-body .alert').hide();
	    	} else {
				this.$('.modal-body .alert').show();
				this.$('.modal-body .alert').html(html);
	    	}
	    },

	    getFieldDefs: function()
	    {
			var defs = {},
				valid = false;
			for (var k in this.toFields) {
				//console.log(this.$('.to-field[data-to=' + k +'] .from-field'));
				var fromFields = this.$('.to-field[data-to=' + k +'] .from-field'),
					def = {
						fromFields: []
					};
				for (var i = 0; i < fromFields.length; i++) {
					def.fromFields.push($(fromFields[i]).attr('data-from'));
				}
				if (def.fromFields.length) {
					defs[k] = def;
					valid = true;
				}
			}

			var errors = [];

			// move validation to server
			/*if (!defs.loc.fromFields.length) {
				errors.push('Point X,Y is required');
			}*/

			return {fieldDefs: defs, errors: errors, valid: valid};
	    },

		runImport: function(params, options)
		{
			var self = this,
				defs, fieldDefs,
				options = options || {};

			if (!params.inspect) {
				defs = this.getFieldDefs();
				fieldDefs = defs.fieldDefs || [];

				if (defs.errors.length) {
					if (!options.silent) {
						this.setAlert('

' + defs.errors.join('

') + '

');
					}
					if (!params.preview) {
						return false;
					}
				}

				if (!defs.valid && params.preview) {
					self.updateImportPreview([]);
					return;
				}
			}

			this.previousFieldDefs = fieldDefs;

			var params = _.extend({
				url: this.$('input[name=url]').val(),
				fields: fieldDefs,
			}, params);
			console.log('Requesting import', params);
			this.setAlert();
			this.setLoading(true);
			if (this.request) {
//				this.request.abort();
			}
			this.request = $.ajax({
				type: 'POST',
				url: '/api/import/',
				data: params,
				success: function(responseData) {
					console.log('import response', responseData);
					self.setLoading(false);
					if (params.preview) {
						self.updateImportPreview(responseData.items);
					}
					if (options.success) {
						options.success(responseData);
					}
				},
				error: function(jqXHR, textStatus, errorThrown) {
					self.setLoading(false);
					var data = $.parseJSON(jqXHR.responseText),
						errors = data && data.errors ? data.errors : data.error ? {'': data} : null;
					console.error('import failed', errors);
					var lis = '';
					if (errors) {
						for (var k in errors) {
							lis += '
 ' + errors[k].message + '
';
						}
						if (!options.silent) {
							self.setAlert('
' + lis + '
');
						}
					}
					if (params.preview) {
						self.updateImportPreview([]);
					}
					if (options.error) {
						options.error(responseData);
					}
				}
			});
		},

		setLoading: function(isLoading)
		{
			this.isLoading = isLoading;
			this.$('.import-run').attr('disabled', isLoading);
			this.$('.source-submit').attr('disabled', isLoading);
			if (isLoading) {
				this.spinner.show();
			} else {
				this.spinner.hide();
			}
		},

		loadImportPreview: function()
		{
			if (this.previousFieldDefs && _.isEqual(this.previousFieldDefs, this.getFieldDefs().fieldDefs)) return;
			this.runImport({preview: true, max: this.maxPreview}, {silent: true});
		},

		updateImportPreview: function(items)
		{
			var self = this;
			var rows = items.reduce(function(rows, current) {
				var row = ''
				if (current) {
					for (var k in self.toFields) {
						var val = undefined, tdclass = undefined;
						if (typeof current[k] == 'object' && current[k].error) {
							tdclass = 'conversion-error';
							switch (current[k].name){
								case 'ValueSkippedError':
									//val = 'skipped';
									val = current[k].message;
									break;
								default:
									val = current[k].message;
							}
						} else {
							switch (k) {
								default:
									val = current[k];
									break;
								case 'datetime':
									if (current[k]) {
										val = new Date(current[k]);
										if (val) {
											val = val.format(locale.formats.DATE_TIME);
										}
									}
							}
							if (val == undefined ||
								((typeof val == 'string' || Array.isArray(val)) && !val.length)) {
									tdclass = 'conversion-blank';
									val = 'blank';
							}
						}
						row += '' + val + '	';
					}
				}
				rows.push('
' + row + '
');
				return rows;
			}, []);
			this.$('.to-data tbody').html(rows.join(''));
		}

	});

	return DataImportView;
});
<commit_msg>Updated target fields<commit_after>define([
	'jquery',
	'underscore',
	'backbone',
	'config',
	'utils',
	'text!templates/data-import.html',
	'views/modal-view'
], function($, _, Backbone, config, utils, templateHtml, ModalView) {
	var DataImportView = ModalView.extend({

	    tagName: 'div',
		className: 'data-import-view modal fade',

	    events: {
	    	'change .step.source input': 'sourceInputChanged',
			'click .import-run': 'importButtonClicked',
			'click .source-submit': 'sourceSubmitButtonClicked',
			'click .back': 'backButtonClicked',
			'click .from-field .remove' : 'fromFieldRemoveClicked',
	    },

	    initialize: function(options) {
		    this.template = _.template(templateHtml);
			this.vent = options.vent;
			this.responseData = null;
			this.dataTitle = '';
			this.dataDescription = '';
			this.maxPreview = 30;
			this.inspectedSource;
			this.fromFieldColors = ['#a52a2a', '#f89406', '#46a546', '#62cffc', '#ff7f50', '#87ceeb', '#daa520', '#b8860b', '#c43c35', '#556b2f'];

			this.toFields = {
				'geometry.coordinates': 'Point X,Y',
				'properties.val': 'Point Value',
				'properties.datetime':'Date',
				'properties.label': 'Point Label',
				//'properties.mixed': 'Mixed'
			};
	    },

	    canImport: function()
	    {
	    	return !this.isLoading
	    		&& this.$('input[name=url]').val().length;
	    },

	    sourceSubmitButtonClicked: function()
	    {
	    	var self = this;
	    	if (!this.canImport()) return false;
	    	console.log('sourceSubmit');
			this.runImport({inspect: true, max: this.maxPreview}, {
				success: function(responseData) {
					if (responseData.items && responseData.items.length) {
						self.initSourceForMapping(responseData);
						self.setStep('mapping');
					}
				}
			});
			return false;
	    },

	    backButtonClicked: function()
	    {
	    	this.setStep('source');
	    },

	    sourceInputChanged: function()
	    {
	    	var prev = this.$('input[name=url]').data('prevVal'),
	    		cur = this.$('input[name=url]').val();
	    	this.$('input[name=url]').data('prevVal', cur);
	    	if (1/*!prev || !prev.length*/) { // TODO detect a 100% change
	    		cur = cur.replace(/^https:\/\/www.dropbox.com\//,
	    			'https://dl.dropbox.com/');
	    		this.$('input[name=url]').val(cur);
	    	}
	    	this.$('.btn.source-submit').attr('disabled', !this.canImport());
	    },

		importButtonClicked: function()
		{
			var self = this;
			if (!this.canImport()) return false;
			this.runImport({background: true}, {
				success: function(responseData) {
					app.saveNewMapLayer(responseData.collection._id);
					self.setStep('source');
					self.close();
				}
			});
			return false;
		},

		initSourceForMapping: function(data)
		{
			var self = this;
			this.inspectedSource = data;
			this.fromFields = {};
			_.each(this.inspectedSource.items[0], function(value, key) {
				self.fromFields[key] = key;
			});

			this.$('.from-data thead').empty();
			this.$('.from-data tbody').empty();
			this.$('.to-data thead').empty();
			this.$('.to-data tbody').empty();

			var i = 0;
			for (var k in this.fromFields) {
				var f = this.fromFieldTemplate.clone();
				f.removeClass('element-template');
				$('.field-name', f).text(k);
				$('.label', f).css('background-color', this.fromFieldColors[i % this.fromFieldColors.length]);
				$('.from-field', f).attr('data-from', k);
				this.$('.from-data thead').append(f).show();
				i++;
			}

			// add source row preview
			_.each(this.inspectedSource.items, function(row) {
				var tds = '';
				_.each(self.fromFields, function(tmp, key) {
					tds += '' + row[key] + '	';
				});
				self.$('.from-data tbody').append('
' + tds + '
');
			});

			var initClickHandler = function(f) {
				$('.show-field-settings', f).hide();
				// solve with popover
				/*$('.show-field-settings', f).click(function() {
					$('.field-settings', f).toggle();
					return false;
				});*/
			};

			this.updateHandleStates();

			for (var k in this.toFields) {
				var f = this.toFieldTemplate.clone();
				f.removeClass('element-template');
				$('.field-title', f).text(this.toFields[k]);
				$('.to-field', f).attr('data-to', k);
				$('.field-settings', f).hide();
				initClickHandler(f);
				this.$('.to-data thead').append(f).show();
			}
			this.$('.to-field').sortable({
				connectWith: '.to-field',
				stop: function(event, ui) {
					// prevent double loading since dropping from draggable into the sortable
					// will also fire this event, but draggable.stop fires later than this one.
					if (self.preventSortableEvents) return;
					self.loadImportPreview();
				}
			});

			this.$('.from-field').draggable({
				revert: "invalid",
				helper: "clone",
				connectToSortable: '.to-field',
				stack: '.drag.label',
				start: function(event, ui) {
					self.preventSortableEvents = true;
					$(ui.helper).removeClass('half-opacity');
					self.$('.to-field').addClass('highlight');
				},
				stop: function(event, ui) {
					self.preventSortableEvents = false;
					self.$('.to-field').removeClass('highlight');
					self.$('.to-data .from-field').removeClass('half-opacity');
					self.updateHandleStates();
					self.loadImportPreview();
				}
			});

		},

	    render: function()
	    {
	    	var self = this;

			$(this.el).html(this.template());
			var self = this;

			this.spinner = this.$('.spinner').html(new Spinner({radius:6,length:0,width:6,color:'#333',lines:7,speed:1.5}).spin().el).hide();

			this.setStep('source');

			if (DEV) {
				this.$('[name=url]').val('https://dl.dropbox.com/s/cb4blktkkelwg1n/nuclear_reactors.csv');
				self.sourceSubmitButtonClicked();
			}

			this.sourceInputChanged();

			this.fromFieldTemplate = this.$('.from-data thead .element-template');
			this.toFieldTemplate = this.$('.to-data thead .element-template');
			this.$('.element-template').remove();

			this.$("input.text").click(function() {
			   $(this).select();
			});

	        return this;
	    },

	    setStep: function(step)
	    {
	    	this.setAlert();
	    	this.$('.step').each(function() {
	    		$(this).toggle($(this).is('.' + step));
	    	});
	    },

	    updateHandleStates: function()
	    {
	    	var self = this,
	    		mapped = this.$('.to-data .from-field');
	    	this.$('.from-data .from-field').each(function() {
	    		for (var i = 0; i < mapped.length; i++) {
	    			if ($(mapped[i]).attr('data-from') == $(this).attr('data-from')) {
		    			$(this).addClass('half-opacity');
		    			return;
	    			}
	    		}
    			$(this).removeClass('half-opacity');
	    	});
	    	this.$('.target').toggleClass('mapped', mapped.length > 0);
	    },

	    fromFieldRemoveClicked: function(event) {
			$(event.currentTarget).closest('.from-field').remove();
			this.updateHandleStates();
			this.previousFieldDefs = null;
			this.loadImportPreview();
			return false;
	    },

	    setAlert: function(html) {
	    	if (!html) {
				this.$('.modal-body .alert').hide();
	    	} else {
				this.$('.modal-body .alert').show();
				this.$('.modal-body .alert').html(html);
	    	}
	    },

	    getFieldDefs: function()
	    {
			var defs = {},
				valid = false;
			for (var k in this.toFields) {
				//console.log(this.$('.to-field[data-to=' + k +'] .from-field'));
				var fromFields = this.$('.to-field[data-to="' + k +'"] .from-field'),
					def = {
						fromFields: []
					};
				for (var i = 0; i < fromFields.length; i++) {
					def.fromFields.push($(fromFields[i]).attr('data-from'));
				}
				if (def.fromFields.length) {
					defs[k] = def;
					valid = true;
				}
			}

			var errors = [];

			// move validation to server
			/*if (!defs.loc.fromFields.length) {
				errors.push('Point X,Y is required');
			}*/

			return {fieldDefs: defs, errors: errors, valid: valid};
	    },

		runImport: function(params, options)
		{
			var self = this,
				defs, fieldDefs,
				options = options || {};

			if (!params.inspect) {
				defs = this.getFieldDefs();
				fieldDefs = defs.fieldDefs || [];

				if (defs.errors.length) {
					if (!options.silent) {
						this.setAlert('

' + defs.errors.join('

') + '

');
					}
					if (!params.preview) {
						return false;
					}
				}

				if (!defs.valid && params.preview) {
					self.updateImportPreview([]);
					return;
				}
			}

			this.previousFieldDefs = fieldDefs;

			var params = _.extend({
				url: this.$('input[name=url]').val(),
				fields: fieldDefs,
			}, params);
			console.log('Requesting import', params);
			this.setAlert();
			this.setLoading(true);
			if (this.request) {
//				this.request.abort();
			}
			this.request = $.ajax({
				type: 'POST',
				url: '/api/import/',
				data: params,
				success: function(responseData) {
					console.log('import response', responseData);
					self.setLoading(false);
					if (params.preview) {
						self.updateImportPreview(responseData.items);
					}
					if (options.success) {
						options.success(responseData);
					}
				},
				error: function(jqXHR, textStatus, errorThrown) {
					self.setLoading(false);
					var data = $.parseJSON(jqXHR.responseText),
						errors = data && data.errors ? data.errors : data.error ? {'': data} : null;
					console.error('import failed', errors);
					var lis = '';
					if (errors) {
						for (var k in errors) {
							lis += '
 ' + errors[k].message + '
';
						}
						if (!options.silent) {
							self.setAlert('
' + lis + '
');
						}
					}
					if (params.preview) {
						self.updateImportPreview([]);
					}
					if (options.error) {
						options.error(responseData);
					}
				}
			});
		},

		setLoading: function(isLoading)
		{
			this.isLoading = isLoading;
			this.$('.import-run').attr('disabled', isLoading);
			this.$('.source-submit').attr('disabled', isLoading);
			if (isLoading) {
				this.spinner.show();
			} else {
				this.spinner.hide();
			}
		},

		loadImportPreview: function()
		{
			if (this.previousFieldDefs && _.isEqual(this.previousFieldDefs, this.getFieldDefs().fieldDefs)) return;
			this.runImport({preview: true, max: this.maxPreview}, {silent: true});
		},

		updateImportPreview: function(items)
		{
			var self = this;
			var rows = items.reduce(function(rows, current) {
				var row = ''
				if (current) {
					for (var k in self.toFields) {
						var val = undefined, tdclass = undefined;
						if (typeof current[k] == 'object' && current[k].error) {
							tdclass = 'conversion-error';
							switch (current[k].name){
								case 'ValueSkippedError':
									//val = 'skipped';
									val = current[k].message;
									break;
								default:
									val = current[k].message;
							}
						} else {
							switch (k) {
								default:
									val = current[k];
									break;
								case 'datetime':
									if (current[k]) {
										val = new Date(current[k]);
										if (val) {
											val = val.format(locale.formats.DATE_TIME);
										}
									}
							}
							if (val == undefined ||
								((typeof val == 'string' || Array.isArray(val)) && !val.length)) {
									tdclass = 'conversion-blank';
									val = 'blank';
							}
						}
						row += '' + val + '	';
					}
				}
				rows.push('
' + row + '
');
				return rows;
			}, []);
			this.$('.to-data tbody').html(rows.join(''));
		}

	});

	return DataImportView;
});
<|endoftext|>


<commit_before>'use strict';

/**
* merkurClientApp.services Module
*
* Provides services and constants for Merkur-Client
*/
var merkurClientAppServices = angular.module('merkurClientApp.services', []);

// Stomp service
merkurClientAppServices.service('stompService', ['messages.serverWebsocketEndpoint', function (messagesServerWebsocketEndpoint) {
  var socket = new SockJS(messagesServerWebsocketEndpoint);
  this.client = Stomp.over(socket);
}]);

// endpoint address for websocket server
merkurClientAppServices.value('messages.serverWebsocketEndpoint', 'http://localhost:8080/merkur-server/socket');

// number of maximum entries shown
merkurClientAppServices.value('messages.maxEntriesShown', 10);

// topic of messages fetched from stomp client
// TODO : Über GUI konfigurierbar machen
merkurClientAppServices. value('messages.topic', '/topic/price.stock.*');
// merkurClientAppServices. value('messages.topic', '/topic/counter');
// merkurClientAppServices. value('messages.topic', '/topic/uuid');<commit_msg>Routing-Key angepasst.<commit_after>'use strict';

/**
* merkurClientApp.services Module
*
* Provides services and constants for Merkur-Client
*/
var merkurClientAppServices = angular.module('merkurClientApp.services', []);

// Stomp service
merkurClientAppServices.service('stompService', ['messages.serverWebsocketEndpoint', function (messagesServerWebsocketEndpoint) {
  var socket = new SockJS(messagesServerWebsocketEndpoint);
  this.client = Stomp.over(socket);
}]);

// endpoint address for websocket server
merkurClientAppServices.value('messages.serverWebsocketEndpoint', 'http://localhost:8080/merkur-server/socket');

// number of maximum entries shown
merkurClientAppServices.value('messages.maxEntriesShown', 10);

// topic of messages fetched from stomp client
// TODO : Über GUI konfigurierbar machen
merkurClientAppServices. value('messages.topic', '/topic/de.#');
// merkurClientAppServices. value('messages.topic', '/topic/counter');
// merkurClientAppServices. value('messages.topic', '/topic/uuid');<|endoftext|>


<commit_before>import { $t } from 'element-ui/src/locale';

var CONFIRM_TEXT = $t('el.messagebox.confirm');
var CANCEL_TEXT = $t('el.messagebox.cancel');

var defaults = {
  title: '提示',
  message: '',
  type: '',
  showInput: false,
  showClose: true,
  modalFade: true,
  lockScroll: true,
  closeOnClickModal: true,
  inputValue: null,
  inputPlaceholder: '',
  inputPattern: null,
  inputValidator: null,
  inputErrorMessage: '',
  showConfirmButton: true,
  showCancelButton: false,
  confirmButtonPosition: 'right',
  confirmButtonHighlight: false,
  cancelButtonHighlight: false,
  confirmButtonText: CONFIRM_TEXT,
  cancelButtonText: CANCEL_TEXT,
  confirmButtonClass: '',
  cancelButtonClass: ''
};

import Vue from 'vue';
import msgboxVue from './main.vue';

var merge = function(target) {
  for (var i = 1, j = arguments.length; i < j; i++) {
    var source = arguments[i];
    for (var prop in source) {
      if (source.hasOwnProperty(prop)) {
        var value = source[prop];
        if (value !== undefined) {
          target[prop] = value;
        }
      }
    }
  }

  return target;
};

var MessageBoxConstructor = Vue.extend(msgboxVue);

var currentMsg, instance;
var msgQueue = [];

var initInstance = function() {
  instance = new MessageBoxConstructor({
    el: document.createElement('div')
  });

  instance.callback = function(action) {
    if (currentMsg) {
      var callback = currentMsg.callback;
      if (typeof callback === 'function') {
        if (instance.showInput) {
          callback(instance.inputValue, action);
        } else {
          callback(action);
        }
      }
      if (currentMsg.resolve) {
        var $type = currentMsg.options.$type;
        if ($type === 'confirm' || $type === 'prompt') {
          if (action === 'confirm') {
            if (instance.showInput) {
              currentMsg.resolve({ value: instance.inputValue, action });
            } else {
              currentMsg.resolve(action);
            }
          } else if (action === 'cancel' && currentMsg.reject) {
            currentMsg.reject(action);
          }
        } else {
          currentMsg.resolve(action);
        }
      }
    }
  };
};

var showNextMsg = function() {
  if (!instance) {
    initInstance();
  }

  if (!instance.value || instance.closeTimer) {
    if (msgQueue.length > 0) {
      currentMsg = msgQueue.shift();

      var options = currentMsg.options;
      for (var prop in options) {
        if (options.hasOwnProperty(prop)) {
          instance[prop] = options[prop];
        }
      }
      ['modal', 'showClose', 'closeOnClickModal', 'closeOnPressEscape'].forEach(prop => {
        if (instance[prop] === undefined) {
          instance[prop] = true;
        }
      });
      document.body.appendChild(instance.$el);

      Vue.nextTick(() => {
        instance.value = true;
      });
    }
  }
};

var MessageBox = function(options, callback) {
  if (typeof options === 'string') {
    options = {
      title: options
    };
    if (arguments[1]) {
      options.message = arguments[1];
    }
    if (arguments[2]) {
      options.type = arguments[2];
    }
  } else if (options.callback && !callback) {
    callback = options.callback;
  }

  if (typeof Promise !== 'undefined') {
    return new Promise(function(resolve, reject) { // eslint-disable-line
      msgQueue.push({
        options: merge({}, defaults, MessageBox.defaults || {}, options),
        callback: callback,
        resolve: resolve,
        reject: reject
      });

      showNextMsg();
    });
  } else {
    msgQueue.push({
      options: merge({}, defaults, MessageBox.defaults || {}, options),
      callback: callback
    });

    showNextMsg();
  }
};

MessageBox.setDefaults = function(defaults) {
  MessageBox.defaults = defaults;
};

MessageBox.alert = function(message, title, options) {
  if (typeof title === 'object') {
    options = title;
    title = '';
  }
  return MessageBox(merge({
    title: title,
    message: message,
    $type: 'alert',
    closeOnPressEscape: false,
    closeOnClickModal: false
  }, options));
};

MessageBox.confirm = function(message, title, options) {
  if (typeof title === 'object') {
    options = title;
    title = '';
  }
  return MessageBox(merge({
    title: title,
    message: message,
    $type: 'confirm',
    showCancelButton: true
  }, options));
};

MessageBox.prompt = function(message, title, options) {
  if (typeof title === 'object') {
    options = title;
    title = '';
  }
  return MessageBox(merge({
    title: title,
    message: message,
    showCancelButton: true,
    showInput: true,
    $type: 'prompt'
  }, options));
};

MessageBox.close = function() {
  instance.value = false;
  msgQueue = [];
  currentMsg = null;
};

export default MessageBox;
export { MessageBox };
<commit_msg>MessageBox: fix a callback overwriting bug<commit_after>import { $t } from 'element-ui/src/locale';

const CONFIRM_TEXT = $t('el.messagebox.confirm');
const CANCEL_TEXT = $t('el.messagebox.cancel');

const defaults = {
  title: '提示',
  message: '',
  type: '',
  showInput: false,
  showClose: true,
  modalFade: true,
  lockScroll: true,
  closeOnClickModal: true,
  inputValue: null,
  inputPlaceholder: '',
  inputPattern: null,
  inputValidator: null,
  inputErrorMessage: '',
  showConfirmButton: true,
  showCancelButton: false,
  confirmButtonPosition: 'right',
  confirmButtonHighlight: false,
  cancelButtonHighlight: false,
  confirmButtonText: CONFIRM_TEXT,
  cancelButtonText: CANCEL_TEXT,
  confirmButtonClass: '',
  cancelButtonClass: ''
};

import Vue from 'vue';
import msgboxVue from './main.vue';

const merge = function(target) {
  for (let i = 1, j = arguments.length; i < j; i++) {
    let source = arguments[i];
    for (let prop in source) {
      if (source.hasOwnProperty(prop)) {
        let value = source[prop];
        if (value !== undefined) {
          target[prop] = value;
        }
      }
    }
  }

  return target;
};

const MessageBoxConstructor = Vue.extend(msgboxVue);

let currentMsg, instance;
let msgQueue = [];

const defaultCallback = action => {
  if (currentMsg) {
    let callback = currentMsg.callback;
    if (typeof callback === 'function') {
      if (instance.showInput) {
        callback(instance.inputValue, action);
      } else {
        callback(action);
      }
    }
    if (currentMsg.resolve) {
      let $type = currentMsg.options.$type;
      if ($type === 'confirm' || $type === 'prompt') {
        if (action === 'confirm') {
          if (instance.showInput) {
            currentMsg.resolve({ value: instance.inputValue, action });
          } else {
            currentMsg.resolve(action);
          }
        } else if (action === 'cancel' && currentMsg.reject) {
          currentMsg.reject(action);
        }
      } else {
        currentMsg.resolve(action);
      }
    }
  }
};

const initInstance = () => {
  instance = new MessageBoxConstructor({
    el: document.createElement('div')
  });

  instance.callback = defaultCallback;
};

const showNextMsg = () => {
  if (!instance) {
    initInstance();
  }

  if (!instance.value || instance.closeTimer) {
    if (msgQueue.length > 0) {
      currentMsg = msgQueue.shift();

      let options = currentMsg.options;
      for (let prop in options) {
        if (options.hasOwnProperty(prop)) {
          instance[prop] = options[prop];
        }
      }
      if (options.callback === undefined) {
        instance.callback = defaultCallback;
      }
      ['modal', 'showClose', 'closeOnClickModal', 'closeOnPressEscape'].forEach(prop => {
        if (instance[prop] === undefined) {
          instance[prop] = true;
        }
      });
      document.body.appendChild(instance.$el);

      Vue.nextTick(() => {
        instance.value = true;
      });
    }
  }
};

const MessageBox = function(options, callback) {
  if (typeof options === 'string') {
    options = {
      title: options
    };
    if (arguments[1]) {
      options.message = arguments[1];
    }
    if (arguments[2]) {
      options.type = arguments[2];
    }
  } else if (options.callback && !callback) {
    callback = options.callback;
  }

  if (typeof Promise !== 'undefined') {
    return new Promise((resolve, reject) => { // eslint-disable-line
      msgQueue.push({
        options: merge({}, defaults, MessageBox.defaults || {}, options),
        callback: callback,
        resolve: resolve,
        reject: reject
      });

      showNextMsg();
    });
  } else {
    msgQueue.push({
      options: merge({}, defaults, MessageBox.defaults || {}, options),
      callback: callback
    });

    showNextMsg();
  }
};

MessageBox.setDefaults = defaults => {
  MessageBox.defaults = defaults;
};

MessageBox.alert = (message, title, options) => {
  if (typeof title === 'object') {
    options = title;
    title = '';
  }
  return MessageBox(merge({
    title: title,
    message: message,
    $type: 'alert',
    closeOnPressEscape: false,
    closeOnClickModal: false
  }, options));
};

MessageBox.confirm = (message, title, options) => {
  if (typeof title === 'object') {
    options = title;
    title = '';
  }
  return MessageBox(merge({
    title: title,
    message: message,
    $type: 'confirm',
    showCancelButton: true
  }, options));
};

MessageBox.prompt = (message, title, options) => {
  if (typeof title === 'object') {
    options = title;
    title = '';
  }
  return MessageBox(merge({
    title: title,
    message: message,
    showCancelButton: true,
    showInput: true,
    $type: 'prompt'
  }, options));
};

MessageBox.close = () => {
  instance.value = false;
  msgQueue = [];
  currentMsg = null;
};

export default MessageBox;
export { MessageBox };
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import Helmet from 'react-helmet'
import kellieLogo from '../images/kellie_logo.svg'
import kellieSocials from '../images/kellie_socials.png'
import './index.css'

const TemplateWrapper = ({ children }) =>

    <Helmet
      title="Tangles Hair Extensions and More"
      meta={[
        { name: 'Tangles Hair Extensions and More', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { name: 'keywords', content: 'hair, hair extensions, coloring, ombre, balayage, brazilian blowouts, keratin treatments' },
        { name: 'description', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { name: 'image', content: kellieLogo },
        { itemprop: 'name', content: 'Tangles Hair Extensions and More' },
        { itemprop: 'description', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { itemprop: 'image', content: kellieLogo },
        { name: 'twitter:card', content: 'summary_large_image' },
        { name: 'twitter:title', content: 'Tangles Hair Extensions and More' },
        { name: 'twitter:description', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { name: 'twitter:image', content: kellieLogo },
        { name: 'og:title', content: 'Tangles Hair Extensions and More' },
        { name: 'og:image', content: kellieSocials },
        { name: 'og:description', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { name: 'og:site_name', content: 'Tangles Hair Extensions and More' },
        { name: 'fb:admins', content: '238806386155182' },
        { name: 'og:type', content: 'website' },
      ]}
    >
      <link rel="shortcut icon" type="image/svg" href={kellieLogo} />
      <link rel="stylesheet" href="https://unpkg.com/tachyons@4.8.0/css/tachyons.min.css"/>
    </Helmet>

      {children()}

TemplateWrapper.propTypes = {
  children: PropTypes.func,
}

export default TemplateWrapper
<commit_msg>Editing twitter card data<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import Helmet from 'react-helmet'
import kellieLogo from '../images/kellie_logo.svg'
import kellieSocials from '../images/kellie_socials.png'
import './index.css'

const TemplateWrapper = ({ children }) =>

    <Helmet
      title="Tangles Hair Extensions and More"
      meta={[
        { name: 'Tangles Hair Extensions and More', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { name: 'keywords', content: 'hair, hair extensions, coloring, ombre, balayage, brazilian blowouts, keratin treatments' },
        { name: 'description', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { name: 'image', content: kellieLogo },
        { itemprop: 'name', content: 'Tangles Hair Extensions and More' },
        { itemprop: 'description', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { itemprop: 'image', content: kellieLogo },
        { name: 'twitter:card', content: 'summary_large_image' },
        { name: 'twitter:title', content: 'Tangles Hair Extensions and More' },
        { name: 'twitter:description', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { name: 'twitter:image', content: kellieSocials },
        { name: 'og:title', content: 'Tangles Hair Extensions and More' },
        { name: 'og:image', content: kellieSocials },
        { name: 'og:description', content: 'Tangles Hair Extensions and More. Where genuinely caring about your hair is a wonderful experience' },
        { name: 'og:site_name', content: 'Tangles Hair Extensions and More' },
        { name: 'fb:admins', content: '238806386155182' },
        { name: 'og:type', content: 'website' },
      ]}
    >
      <link rel="shortcut icon" type="image/svg" href={kellieLogo} />
      <link rel="stylesheet" href="https://unpkg.com/tachyons@4.8.0/css/tachyons.min.css"/>
    </Helmet>

      {children()}

TemplateWrapper.propTypes = {
  children: PropTypes.func,
}

export default TemplateWrapper
<|endoftext|>


<commit_before>/**
 * Modules dependencies
 */

var mocha = require('mocha'),
	figc = require('figc'),
	assert = require('chai').assert,
	libPath = process.env['SOLR_CLIENT_COV'] ? '../../lib-cov' : '../../lib',
	solr = require( libPath + '/solr'),
	sassert = require('../sassert');

// Test suite
var config = figc(__dirname + '/config.json');
var client = solr.createClient(config.client);
var basePath = [config.client.path, config.client.core].join('/').replace(/\/$/,"");

//TO-DO: add test for collectionConfigName, routerField, async, createNodeSet, createNodeSetShuffle
describe('Collection',function(){
	describe('#createCollection',function(){
		it('should create one new Collection',function(done){
			this.timeout(10000);
			var collection = client.collection();
			collection.create(
				{
					name: 'solrCollectionTest1',
					numShards: 2,
					replicationFactor: 1,
					maxShardsPerNode: 1,
					autoAddReplicas: 'false'
				}
			);
			client.executeCollection(collection,function(err,data){
				//sassert.ok(err,data);
				assert.equal(data.responseHeader.status,0);
				done();
			});
		});
                it('should create one new Collection, two shards, with array of shard names',function(done){
			this.timeout(10000);
                        var collection = client.collection();
                        collection.create(
                                {
                                        name: 'solrCollectionTest2',
                                        routerName: 'compositeId',
                                        numShards: 2
                                }
                        );
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
				assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
                it('should create one new Collection, with implicit router',function(done){
			this.timeout(10000);
                        var collection = client.collection();
                        collection.create(
                                {
                                        name: 'solrCollectionTest3',
                                        routerName: 'implicit',
                                        shards: ['shard1','shard2']
                                }
                        );
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
				assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

        describe('#reloadCollection',function(){
                it('should reload collection solrCollectionTest1',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.reload('solrCollectionTest1');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

        describe('#splitShard',function(){
		//params `ranges, splitKey not included
                it('should split shard shard1 in solrCollectionTest1',function(done){
                        this.timeout(20000);
                        var collection = client.collection();
                        collection.splitShard({
				collection: 'solrCollectionTest1',
				shard: 'shard1'
			});
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#deleteShard',function(){
                it('should delete shard shard1 in collection solrCollectionTest3',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.deleteShard({
                                collection:'solrCollectionTest3',
                                shard: 'shard1'
                        });
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

        describe('#createShard',function(){
                it('should create shard shardtest1 in collection solrCollectionTest3',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.createShard({
				collection:'solrCollectionTest3',
				shard: 'shard1'
			});
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#createAlias',function(){
                it('should create alias testAlias for collections solrCollectionTest1, solrCollectionTest2',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.createAlias({
                                name:'testAlias',
                                collections: ['solrCollectionTest1', 'solrCollectionTest2']
                        });
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#deleteAlias',function(){
                it('should delete alias testAlias',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.deleteAlias('testAlias');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#deleteCollection',function(){
                it('should delete collection solrCollectionTest1',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.delete('solrCollectionTest1');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
		it('should delete collection solrCollectionTest2',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.delete('solrCollectionTest2');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
		it('should delete collection solrCollectionTest3',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.delete('solrCollectionTest3');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
	});

});
<commit_msg>Added more tests<commit_after>/**
 * Modules dependencies
 */

var mocha = require('mocha'),
	figc = require('figc'),
	assert = require('chai').assert,
	libPath = process.env['SOLR_CLIENT_COV'] ? '../../lib-cov' : '../../lib',
	solr = require( libPath + '/solr'),
	sassert = require('../sassert');

// Test suite
var config = figc(__dirname + '/config.json');
var client = solr.createClient(config.client);
var basePath = [config.client.path, config.client.core].join('/').replace(/\/$/,"");

//TO-DO: add test for collectionConfigName, routerField, async, createNodeSet, createNodeSetShuffle
describe('Collection',function(){
	describe('#createCollection',function(){
		it('should create one new Collection',function(done){
			this.timeout(10000);
			var collection = client.collection();
			collection.create(
				{
					name: 'solrCollectionTest1',
					numShards: 2,
					replicationFactor: 1,
					maxShardsPerNode: 1,
					autoAddReplicas: 'false'
				}
			);
			client.executeCollection(collection,function(err,data){
				//sassert.ok(err,data);
				assert.equal(data.responseHeader.status,0);
				done();
			});
		});
                it('should create one new Collection, one shard, one replicas',function(done){
			this.timeout(10000);
                        var collection = client.collection();
                        collection.create(
                                {
                                        name: 'solrCollectionTest2',
                                        routerName: 'compositeId',
                                        numShards: 1,
					shards: 'shard1',
					replicationFactor: 1
                                }
                        );
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
				assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
                it('should create one new Collection, with implicit router',function(done){
			this.timeout(10000);
                        var collection = client.collection();
                        collection.create(
                                {
                                        name: 'solrCollectionTest3',
                                        routerName: 'implicit',
                                        shards: ['shard1','shard2']
                                }
                        );
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
				assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

        describe('#reloadCollection',function(){
                it('should reload collection solrCollectionTest1',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.reload('solrCollectionTest1');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

        describe('#splitShard',function(){
		//params `ranges, splitKey not included
                it('should split shard shard1 in solrCollectionTest1',function(done){
                        this.timeout(20000);
                        var collection = client.collection();
                        collection.splitShard({
				collection: 'solrCollectionTest1',
				shard: 'shard1'
			});
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#deleteShard',function(){
                it('should delete shard shard1 in collection solrCollectionTest3',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.deleteShard({
                                collection:'solrCollectionTest3',
                                shard: 'shard1'
                        });
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

        describe('#createShard',function(){
                it('should create shard shardtest1 in collection solrCollectionTest3',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.createShard({
				collection:'solrCollectionTest3',
				shard: 'shard1'
			});
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#createAlias',function(){
                it('should create alias testAlias for collections solrCollectionTest1, solrCollectionTest2',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.createAlias({
                                name:'testAlias',
                                collections: ['solrCollectionTest1', 'solrCollectionTest2']
                        });
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#deleteAlias',function(){
                it('should delete alias testAlias',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.deleteAlias('testAlias');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#addReplica',function(){
                it('should add replica to shard2 of solrCollectionTest2',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.addReplica({
                                collection:'solrCollectionTest2',
                                shard: 'shard1'
                        });
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#deleteReplica',function(){
                it('should delete replica1 from shard1 from solrCollectionTest2',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.deleteReplica({
				collection:'solrCollectionTest2',
				shard: 'shard1',
				replica: 'core_node2',
				onlyIfDown: 'false'
			});
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
        });

	describe('#deleteCollection',function(){
                it('should delete collection solrCollectionTest1',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.delete('solrCollectionTest1');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
		it('should delete collection solrCollectionTest2',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.delete('solrCollectionTest2');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
		it('should delete collection solrCollectionTest3',function(done){
                        this.timeout(10000);
                        var collection = client.collection();
                        collection.delete('solrCollectionTest3');
                        client.executeCollection(collection,function(err,data){
                                //sassert.ok(err,data);
                                assert.equal(data.responseHeader.status,0);
                                done();
                        });
                });
	});

});
<|endoftext|>


<commit_before>/**
 * UI and function to add project
 */
'use strict';

require('css/add-project-plugin.css');
var $ = require('jquery');
var m = require('mithril');
var $osf = require('js/osfHelpers');

// XHR configuration to get apiserver connection to work
var xhrconfig = function (xhr) {
    xhr.withCredentials = true;
};

var AddProject = {
    controller : function (options) {
        var self = this;
        self.defaults = {
            buttonTemplate : m('.btn.btn-primary[data-toggle="modal"][data-target="#addProjectModal"]', 'Add new Project'),
            parent : null
        };
        self.viewState = m.prop('form'); // 'processing', 'success', 'error';
        self.options = $.extend(self.defaults, options);
        self.init = function _init () {

        };
        self.newProjectName = m.prop('');
        self.newProjectDesc = m.prop('');
        self.categoryList = [
            { value: 'project', label: 'Project'},
            { value: 'hypothesis', label : 'Hypothesis' },
            { value: 'methods and measures', label :  'Methods and Measures'},
            { value: 'procedure', label:  'Procedure'},
            { value: 'instrumentation', label: 'Instrumentation'},
            { value: 'data', label:  'Data'},
            { value: 'analysis', label: 'Analysis'},
            { value: 'communication',label: 'Communication'},
            { value: 'other', label: 'Other'}
        ];
        self.newProjectCategory = m.prop(self.categoryList[0].value);
        self.goToProjectLink = m.prop('');
        self.errorMessageType = m.prop('unknown');
        self.errorMessage = {
            'unknown' : 'There was an unknown error. Please try again later.'
        };
        self.chooseCategory = function(event){
            self.newProjectCategory = $(this).val();
        };
        self.add = function _add () {
            self.viewState('processing');
            var url = $osf.apiV2Url('nodes/', { query : {}});
            var data = {
                    'data' : {
                        'type': 'nodes',
                        'attributes': {
                            'title': self.newProjectName(),
                            'category': self.newProjectCategory,
                            'description' : self.newProjectDesc()
                        }
                    }
                };
            var success = function _success (result) {
                self.viewState('success');
                console.log('success', result);
                self.goToProjectLink(result.data.links.html);
            };
            var error = function _error (result) {
                self.viewState('error');
                console.log('error', result);
            };
            m.request({method : 'POST', url : url, data : data, config : xhrconfig})
                .then(success, error);
            self.newProjectName('');
            //m.redraw(true);

        };
        self.reset = function _reset(){
            self.newProjectName('');
            self.viewState('form');
            $('.modal').modal('hide');
        };
    },
    view : function (ctrl, options) {
        var templates = {
            form : m('.modal-content', [
                m('.modal-header', [
                    m('button.close[data-dismiss="modal"][aria-label="Close"]',{ onclick : ctrl.reset}, [
                        m('span[aria-hidden="true"]','×'),
                    ]),
                    m('h3.modal-title', 'Add New Project')
                ]),
                m('.modal-body', [
                    m('', [
                        m('.form-group.m-v-sm', [
                            m('label[for="projectName].f-w-lg.text-bigger', 'Project Name'),
                            m('input[type="text"].form-control', {
                                onkeyup: function(ev){
                                    if (ev.which === 13) {
                                         ctrl.add();
                                    }
                                    ctrl.newProjectName($(this).val());
                                },
                                value : ctrl.newProjectName()
                            })
                        ]),
                        m('.form-group.m-v-sm', [
                            m('label[for="projectDesc].f-w-lg.text-bigger', 'Project Description'),
                            m('textarea.form-control', {
                                onkeyup: function(ev){
                                    ctrl.newProjectDesc($(this).val());
                                },
                                value : ctrl.newProjectDesc()
                            })
                        ]),
                        m('.f-w-lg.text-bigger','Category'),
                        m('.category-radio.p-h-md', [
                            ctrl.categoryList.map(function(cat){
                                return m('.radio', m('label', [  m('input', {
                                    type: 'radio',
                                    name: 'projectCategory',
                                    value: cat.value,
                                    checked: ctrl.newProjectCategory() === cat.value,
                                    onchange : m.withAttr('value', ctrl.newProjectCategory)
                                }), cat.label ]));
                            })
                        ])
                    ])
                ]),
                m('.modal-footer', [
                    m('button[type="button"].btn.btn-default[data-dismiss="modal"]', { onclick : ctrl.reset},  'Cancel'),
                    m('button[type="button"].btn.btn-success', { onclick : ctrl.add },'Add')
                ])
            ]),
            processing : m('.modal-content',
                m('.modal-content',
                    m('.modal-header', [
                        m('button.close[data-dismiss="modal"][aria-label="Close"]',{ onclick : ctrl.reset}, [
                            m('span[aria-hidden="true"]','×'),
                        ]),
                    ]),
                    m('.modal-body', [
                            m('.add-project-processing', 'Saving your project...')
                        ]
                    )
                )
            ),
            success : m('.modal-content', [
                m('.modal-content',
                    m('.modal-body', [
                            m('button.close[data-dismiss="modal"][aria-label="Close"]',{ onclick : ctrl.reset}, [
                                m('span[aria-hidden="true"]','×'),
                            ]),
                            m('h4.p-md.add-project-success.text-success', 'Project created successfully!')
                        ]
                    ),
                    m('.modal-footer', [
                        m('button[type="button"].btn.btn-default[data-dismiss="modal"]', { onclick : ctrl.reset },  'Keep Working Here'),
                        m('a.btn.btn-success', { href : ctrl.goToProjectLink() },'Go to New Project')
                    ])
                )
            ]),
            error : m('.modal-content', [
                m('.modal-content',
                    m('.modal-body', [
                            m('button.close[data-dismiss="modal"][aria-label="Close"]',{ onclick : ctrl.reset}, [
                                m('span[aria-hidden="true"]','×'),
                            ]),
                            m('h4.p-md.add-project-error.text-danger', 'Couldn\'t create your project'),
                            m('p', ctrl.errorMessage[ctrl.errorMessageType()])
                        ]
                    )
                )
            ])
        };

        return  m('', [
            ctrl.options.buttonTemplate,
            m('#addProjectModal.modal.fade[tabindex=-1][role="dialog"][aria-labelledby="addProject"][aria-hidden="true"]',
                m('.modal-dialog',
                    templates[ctrl.viewState()]
                )
            )
        ]);
    }
};

module.exports = AddProject;<commit_msg>Use withAttr [skip ci]<commit_after>/**
 * UI and function to add project
 */
'use strict';

require('css/add-project-plugin.css');
var $ = require('jquery');
var m = require('mithril');
var $osf = require('js/osfHelpers');

// XHR configuration to get apiserver connection to work
var xhrconfig = function (xhr) {
    xhr.withCredentials = true;
};

var AddProject = {
    controller : function (options) {
        var self = this;
        self.defaults = {
            buttonTemplate : m('.btn.btn-primary[data-toggle="modal"][data-target="#addProjectModal"]', 'Add new Project'),
            parent : null
        };
        self.viewState = m.prop('form'); // 'processing', 'success', 'error';
        self.options = $.extend(self.defaults, options);
        self.init = function _init () {

        };
        self.newProjectName = m.prop('');
        self.newProjectDesc = m.prop('');
        self.categoryList = [
            { value: 'project', label: 'Project'},
            { value: 'hypothesis', label : 'Hypothesis' },
            { value: 'methods and measures', label :  'Methods and Measures'},
            { value: 'procedure', label:  'Procedure'},
            { value: 'instrumentation', label: 'Instrumentation'},
            { value: 'data', label:  'Data'},
            { value: 'analysis', label: 'Analysis'},
            { value: 'communication',label: 'Communication'},
            { value: 'other', label: 'Other'}
        ];
        self.newProjectCategory = m.prop(self.categoryList[0].value);
        self.goToProjectLink = m.prop('');
        self.errorMessageType = m.prop('unknown');
        self.errorMessage = {
            'unknown' : 'There was an unknown error. Please try again later.'
        };
        self.chooseCategory = function(event){
            self.newProjectCategory = $(this).val();
        };
        self.add = function _add () {
            self.viewState('processing');
            var url = $osf.apiV2Url('nodes/', { query : {}});
            var data = {
                    'data' : {
                        'type': 'nodes',
                        'attributes': {
                            'title': self.newProjectName(),
                            'category': self.newProjectCategory,
                            'description' : self.newProjectDesc()
                        }
                    }
                };
            var success = function _success (result) {
                self.viewState('success');
                console.log('success', result);
                self.goToProjectLink(result.data.links.html);
            };
            var error = function _error (result) {
                self.viewState('error');
                console.log('error', result);
            };
            m.request({method : 'POST', url : url, data : data, config : xhrconfig})
                .then(success, error);
            self.newProjectName('');
            //m.redraw(true);

        };
        self.reset = function _reset(){
            self.newProjectName('');
            self.viewState('form');
            $('.modal').modal('hide');
        };
    },
    view : function (ctrl, options) {
        var templates = {
            form : m('.modal-content', [
                m('.modal-header', [
                    m('button.close[data-dismiss="modal"][aria-label="Close"]',{ onclick : ctrl.reset}, [
                        m('span[aria-hidden="true"]','×'),
                    ]),
                    m('h3.modal-title', 'Add New Project')
                ]),
                m('.modal-body', [
                    m('', [
                        m('.form-group.m-v-sm', [
                            m('label[for="projectName].f-w-lg.text-bigger', 'Project Name'),
                            m('input[type="text"].form-control', {
                                onkeyup: function(ev){
                                    if (ev.which === 13) {
                                         ctrl.add();
                                    }
                                    ctrl.newProjectName($(this).val());
                                },
                                value : ctrl.newProjectName()
                            })
                        ]),
                        m('.form-group.m-v-sm', [
                            m('label[for="projectDesc].f-w-lg.text-bigger', 'Project Description'),
                            m('textarea.form-control', {
                                onkeyup: m.withAttr('value', ctrl.newProjectDesc),
                                value : ctrl.newProjectDesc()
                            })
                        ]),
                        m('.f-w-lg.text-bigger','Category'),
                        m('.category-radio.p-h-md', [
                            ctrl.categoryList.map(function(cat){
                                return m('.radio', m('label', [  m('input', {
                                    type: 'radio',
                                    name: 'projectCategory',
                                    value: cat.value,
                                    checked: ctrl.newProjectCategory() === cat.value,
                                    onchange : m.withAttr('value', ctrl.newProjectCategory)
                                }), cat.label ]));
                            })
                        ])
                    ])
                ]),
                m('.modal-footer', [
                    m('button[type="button"].btn.btn-default[data-dismiss="modal"]', { onclick : ctrl.reset},  'Cancel'),
                    m('button[type="button"].btn.btn-success', { onclick : ctrl.add },'Add')
                ])
            ]),
            processing : m('.modal-content',
                m('.modal-content',
                    m('.modal-header', [
                        m('button.close[data-dismiss="modal"][aria-label="Close"]',{ onclick : ctrl.reset}, [
                            m('span[aria-hidden="true"]','×'),
                        ]),
                    ]),
                    m('.modal-body', [
                            m('.add-project-processing', 'Saving your project...')
                        ]
                    )
                )
            ),
            success : m('.modal-content', [
                m('.modal-content',
                    m('.modal-body', [
                            m('button.close[data-dismiss="modal"][aria-label="Close"]',{ onclick : ctrl.reset}, [
                                m('span[aria-hidden="true"]','×'),
                            ]),
                            m('h4.p-md.add-project-success.text-success', 'Project created successfully!')
                        ]
                    ),
                    m('.modal-footer', [
                        m('button[type="button"].btn.btn-default[data-dismiss="modal"]', { onclick : ctrl.reset },  'Keep Working Here'),
                        m('a.btn.btn-success', { href : ctrl.goToProjectLink() },'Go to New Project')
                    ])
                )
            ]),
            error : m('.modal-content', [
                m('.modal-content',
                    m('.modal-body', [
                            m('button.close[data-dismiss="modal"][aria-label="Close"]',{ onclick : ctrl.reset}, [
                                m('span[aria-hidden="true"]','×'),
                            ]),
                            m('h4.p-md.add-project-error.text-danger', 'Couldn\'t create your project'),
                            m('p', ctrl.errorMessage[ctrl.errorMessageType()])
                        ]
                    )
                )
            ])
        };

        return  m('', [
            ctrl.options.buttonTemplate,
            m('#addProjectModal.modal.fade[tabindex=-1][role="dialog"][aria-labelledby="addProject"][aria-hidden="true"]',
                m('.modal-dialog',
                    templates[ctrl.viewState()]
                )
            )
        ]);
    }
};

module.exports = AddProject;<|endoftext|>