<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import autobind from 'autobind-decorator'

import {Button} from 'react-bootstrap'
import DatePicker from 'react-16-bootstrap-date-picker'

import ValidatableFormWrapper from 'components/ValidatableFormWrapper'
import Fieldset from 'components/Fieldset'
import Autocomplete from 'components/Autocomplete'
import Form from 'components/Form'
import Messages from'components/Messages'
import ButtonToggleGroup from 'components/ButtonToggleGroup'
import DictionaryField from '../../HOC/DictionaryField'

import Settings from 'Settings'
import API from 'api'
import {Organization, Person, Position, Task} from 'models'

import CALENDAR_ICON from 'resources/calendar.png'

import AppContext from 'components/AppContext'
import { withRouter } from 'react-router-dom'
import NavigationWarning from 'components/NavigationWarning'
import { jumpToTop } from 'components/Page'
import utils from 'utils'

const customEnumButtons = (list) => {
	let buttons = []
	for (const key in list) {
		if (list.hasOwnProperty(key)) {
			let value = list[key]
			buttons.push(<Button id="statusActiveButton" key={key} value={key}>{value}</Button>)
		}
	  }
    return buttons
}

class BaseTaskForm extends ValidatableFormWrapper {
	static propTypes = {
		task: PropTypes.object.isRequired,
		original: PropTypes.object.isRequired,
		edit: PropTypes.bool,
		currentUser: PropTypes.instanceOf(Person),
	}

	constructor(props) {
		super(props)
		this.TaskCustomFieldRef1 = DictionaryField(Form.Field)
		this.TaskCustomField = DictionaryField(Form.Field)
		this.PlannedCompletionField = DictionaryField(Form.Field)
		this.ProjectedCompletionField = DictionaryField(Form.Field)
		this.TaskCustomFieldEnum1 = DictionaryField(Form.Field)
		this.TaskCustomFieldEnum2 = DictionaryField(Form.Field)

		this.state = {
			success: null,
			error: null,
			isBlocking: false,
		}
	}

	render() {
		const { task, edit, currentUser } = this.props
		const taskShortLabel = Settings.fields.task.shortLabel
		const customFieldRef1 = Settings.fields.task.customFieldRef1
		const customFieldEnum1 = Settings.fields.task.customFieldEnum1
		const customFieldEnum2 = Settings.fields.task.customFieldEnum2
		const plannedCompletion = Settings.fields.task.plannedCompletion
		const projectedCompletion = Settings.fields.task.projectedCompletion
		const orgSearchQuery = {status: Organization.STATUS.ACTIVE}

		orgSearchQuery.type = Organization.TYPE.ADVISOR_ORG
		if (currentUser && currentUser.position && currentUser.position.type === Position.TYPE.SUPER_USER) {
			orgSearchQuery.parentOrgUuid = currentUser.position.organization.uuid
			orgSearchQuery.parentOrgRecursively = true
		}
		const {ValidatableForm, RequiredField} = this
		return (

				<NavigationWarning isBlocking={this.state.isBlocking} />

				<Messages error={this.state.error} success={this.state.success} />

				<ValidatableForm
					formFor={task}
					onChange={this.onChange}
					onSubmit={this.onSubmit}
					submitText={`Save ${taskShortLabel}`}
					horizontal>

					<Fieldset title={edit ?
						`Edit ${taskShortLabel} ${task.shortName}`
						:
						`Create a new ${taskShortLabel}`
					}>
						<RequiredField id="shortName" label={`${taskShortLabel} number`} />
						<RequiredField id="longName" label={`${taskShortLabel} description`} />

						<RequiredField id="status" >
							<ButtonToggleGroup>
								<Button id="statusActiveButton" value={ Task.STATUS.ACTIVE }>Active</Button>
								<Button id="statusInactiveButton" value={ Task.STATUS.INACTIVE }>Inactive</Button>
							</ButtonToggleGroup>
						</RequiredField>

						<Form.Field id="responsibleOrg" label="Responsible organization">
							<Autocomplete
								objectType={Organization}
								valueKey="shortName"
								fields={Organization.autocompleteQuery}
								placeholder={`Select a responsible organization for this ${taskShortLabel}`}
								queryParams={orgSearchQuery}
							/>
						</Form.Field>

						{customFieldRef1 &&
							<this.TaskCustomFieldRef1 dictProps={customFieldRef1} id="customFieldRef1">
								<Autocomplete
									objectType={Task}
									valueKey="shortName"
									fields={Task.autocompleteQuery}
									template={Task.autocompleteTemplate}
									placeholder={customFieldRef1.placeholder}
									queryParams={{}}
								/>
							</this.TaskCustomFieldRef1>
						}

						<this.TaskCustomField dictProps={Settings.fields.task.customField} id="customField"/>

						{plannedCompletion &&
							<this.PlannedCompletionField dictProps={plannedCompletion} id="plannedCompletion" addon={CALENDAR_ICON}>
								<DatePicker showTodayButton placeholder={plannedCompletion.placeholder} dateFormat="DD/MM/YYYY" showClearButton={false} />
							</this.PlannedCompletionField>
						}

						{projectedCompletion &&
							<this.ProjectedCompletionField dictProps={projectedCompletion} id="projectedCompletion" addon={CALENDAR_ICON}>
								<DatePicker showTodayButton placeholder={projectedCompletion.placeholder} dateFormat="DD/MM/YYYY" showClearButton={false} />
							</this.ProjectedCompletionField>
						}

						{customFieldEnum1 &&
							<this.TaskCustomFieldEnum1  dictProps={Object.without(customFieldEnum1, 'enum')} id="customFieldEnum1">
								<ButtonToggleGroup>
									{customEnumButtons(customFieldEnum1.enum)}
								</ButtonToggleGroup>
							</this.TaskCustomFieldEnum1>
						}

						{customFieldEnum2 &&
							<this.TaskCustomFieldEnum2  dictProps={Object.without(customFieldEnum2, 'enum')} id="customFieldEnum2">
								<ButtonToggleGroup>
									{customEnumButtons(customFieldEnum2.enum)}
								</ButtonToggleGroup>
							</this.TaskCustomFieldEnum2>
						}

						</Fieldset>
				</ValidatableForm>

		)
	}

	@autobind
	onChange() {
		this.setState({
			isBlocking: this.formHasUnsavedChanges(this.props.task, this.props.original),
		})
	}

	@autobind
	onSubmit(event) {
		let {task, edit} = this.props
		task.responsibleOrg = utils.getReference(task.responsibleOrg)
		task.customFieldRef1 = utils.getReference(task.customFieldRef1)
		const operation = edit ? 'updateTask' : 'createTask'
		let graphql = operation + '(task: $task)'
		graphql += edit ? '' : ' { uuid }'
		const variables = { task: task }
		const variableDef = '($task: TaskInput!)'
		this.setState({isBlocking: false})
		API.mutation(graphql, variables, variableDef, {disableSubmits: true})
			.then(data => {
				if (data[operation].uuid) {
					task.uuid = data[operation].uuid
				}
				this.props.history.replace(Task.pathForEdit(task))
				this.props.history.push({
					pathname: Task.pathFor(task),
					state: {
						success: 'Task saved',
					}
				})
			}).catch(error => {
				this.setState({success: null, error: error})
				jumpToTop()
			})
	}
}

const TaskForm = (props) => (
	<AppContext.Consumer>
		{context =>
			<BaseTaskForm currentUser={context.currentUser} {...props} />
		}
	</AppContext.Consumer>
)

export default withRouter(TaskForm)
<commit_msg>NCI-Agency/anet#917: Use Formik for tasks form<commit_after>import PropTypes from 'prop-types'
import React, { Component } from 'react'

import {Button} from 'react-bootstrap'
import DatePicker from 'react-16-bootstrap-date-picker'

import { Formik, Form, Field } from 'formik'
import * as FieldHelper from 'components/FieldHelper'

import Fieldset from 'components/Fieldset'
import NewAutocomplete from 'components/NewAutocomplete'
import Messages from'components/Messages'
import DictionaryField from '../../HOC/DictionaryField'

import Settings from 'Settings'
import API from 'api'
import {Organization, Person, Task} from 'models'
import _isEmpty from 'lodash/isEmpty'

import CALENDAR_ICON from 'resources/calendar.png'
import ORGANIZATION_ICON from 'resources/organizations.png'
import TASK_ICON from 'resources/tasks.png'

import AppContext from 'components/AppContext'
import { withRouter } from 'react-router-dom'
import NavigationWarning from 'components/NavigationWarning'
import { jumpToTop } from 'components/Page'
import utils from 'utils'

class BaseTaskForm extends Component {
	static propTypes = {
		initialValues: PropTypes.object.isRequired,
		title: PropTypes.string,
		edit: PropTypes.bool,
		currentUser: PropTypes.instanceOf(Person),
	}

	static defaultProps = {
		initialValues: new Task(),
		title: '',
		edit: false,
	}

	statusButtons = [
		{
			id: 'statusActiveButton',
			value: Task.STATUS.ACTIVE,
			label: 'Active',
		},
		{
			id: 'statusInactiveButton',
			value: Task.STATUS.INACTIVE,
			label: 'Inactive'
		},
	]
	TaskCustomFieldRef1 = DictionaryField(Field)
	TaskCustomField = DictionaryField(Field)
	PlannedCompletionField = DictionaryField(Field)
	ProjectedCompletionField = DictionaryField(Field)
	TaskCustomFieldEnum1 = DictionaryField(Field)
	TaskCustomFieldEnum2 = DictionaryField(Field)
	state = {
		error: null,
	}

	render() {
		const { currentUser, edit, title, ...myFormProps } = this.props

		const taskShortLabel = Settings.fields.task.shortLabel
		const customFieldRef1 = Settings.fields.task.customFieldRef1
		const customFieldEnum1 = Settings.fields.task.customFieldEnum1
		const customFieldEnum2 = Settings.fields.task.customFieldEnum2
		const plannedCompletion = Settings.fields.task.plannedCompletion
		const projectedCompletion = Settings.fields.task.projectedCompletion

		const orgSearchQuery = {
			status: Organization.STATUS.ACTIVE,
			type: Organization.TYPE.ADVISOR_ORG,
		}

		if (currentUser && currentUser.isSuperUser() && !currentUser.isAdmin()) {
			Object.assign(orgSearchQuery, {
				parentOrgUuid: currentUser.position.organization.uuid,
				parentOrgRecursively: true,
			})
		}
		return (
			<Formik
				enableReinitialize={true}
				onSubmit={this.onSubmit}
				validate={this.validate}
				isInitialValid={() => this.isValid(this.props.initialValues)}
				{...myFormProps}
			>
			{({
				handleSubmit,
				isSubmitting,
				isValid,
				dirty,
				errors,
				setFieldValue,
				values,
				submitForm
			}) => {
				const action =

					<Button key="submit" bsStyle="primary" type="button" onClick={submitForm} disabled={isSubmitting || !isValid}>Save {taskShortLabel}</Button>

				return

					<NavigationWarning isBlocking={dirty} />
					<Messages error={this.state.error} />
					<Form className="form-horizontal" method="post">
						<Fieldset title={this.props.title} action={action} />
						<Fieldset>
							<Field
								name="shortName"
								label={`${taskShortLabel} number`}
								component={FieldHelper.renderInputField}
							/>

							<Field
								name="longName"
								label={`${taskShortLabel} description`}
								component={FieldHelper.renderInputField}
							/>

							<Field
								name="status"
								component={FieldHelper.renderButtonToggleGroup}
								buttons={this.statusButtons}
							/>

							<Field
								name="responsibleOrg"
								label="Responsible organization"
								component={FieldHelper.renderSpecialField}
								onChange={value => setFieldValue('responsibleOrg', value)}
								addon={ORGANIZATION_ICON}
							>
								<NewAutocomplete
									objectType={Organization}
									valueKey="shortName"
									fields={Organization.autocompleteQuery}
									placeholder={`Select a responsible organization for this ${taskShortLabel}`}
									queryParams={orgSearchQuery}
								/>
							</Field>

							{customFieldRef1 &&
								<this.TaskCustomFieldRef1
									dictProps={customFieldRef1}
									name="customFieldRef1"
									component={FieldHelper.renderSpecialField}
									onChange={value => setFieldValue('customFieldRef1', value)}
									addon={TASK_ICON}
								>
									<NewAutocomplete
										objectType={Task}
										valueKey="shortName"
										fields={Task.autocompleteQuery}
										template={Task.autocompleteTemplate}
										placeholder={customFieldRef1.placeholder}
										queryParams={{}}
									/>
								</this.TaskCustomFieldRef1>
							}

							<this.TaskCustomField
								dictProps={Settings.fields.task.customField}
								name="customField"
								component={FieldHelper.renderInputField}
							/>

							{plannedCompletion &&
								<this.PlannedCompletionField
									dictProps={plannedCompletion}
									name="plannedCompletion"
									component={FieldHelper.renderSpecialField}
									onChange={(value, formattedValue) => setFieldValue('plannedCompletion', value)}
									addon={CALENDAR_ICON}
								>
									<DatePicker showTodayButton placeholder={plannedCompletion.placeholder} dateFormat="DD/MM/YYYY" showClearButton={false} />
								</this.PlannedCompletionField>
							}

							{projectedCompletion &&
								<this.ProjectedCompletionField
									dictProps={projectedCompletion}
									name="projectedCompletion"
									component={FieldHelper.renderSpecialField}
									onChange={(value, formattedValue) => setFieldValue('projectedCompletion', value)}
									addon={CALENDAR_ICON}
								>
									<DatePicker showTodayButton placeholder={projectedCompletion.placeholder} dateFormat="DD/MM/YYYY" showClearButton={false} />
								</this.ProjectedCompletionField>
							}

							{customFieldEnum1 &&
								<this.TaskCustomFieldEnum1
									dictProps={Object.without(customFieldEnum1, 'enum')}
									name="customFieldEnum1"
									component={FieldHelper.renderButtonToggleGroup}
									buttons={this.customEnumButtons(customFieldEnum1.enum)}
								/>
							}

							{customFieldEnum2 &&
								<this.TaskCustomFieldEnum2
									dictProps={Object.without(customFieldEnum2, 'enum')}
									name="customFieldEnum2"
									component={FieldHelper.renderButtonToggleGroup}
									buttons={this.customEnumButtons(customFieldEnum2.enum)}
								/>
							}
						</Fieldset>

								<Button onClick={this.onCancel}>Cancel</Button>

								<Button id="formBottomSubmit" bsStyle="primary" type="button" onClick={submitForm} disabled={isSubmitting || !isValid}>Save {taskShortLabel}</Button>

					</Form>

			}}
			</Formik>
		)
	}

	isValid = (values) => {
		return _isEmpty(this.validate(values))
	}

	validate = (values) => {
		let errors = {}
		if (!values.shortName) {
			errors.shortName = 'Required'
		}
		if (!values.longName) {
			errors.longName = 'Required'
		}
		if (!values.status) {
			errors.status = 'Required'
		}
		if (values.responsibleOrg && (typeof values.responsibleOrg !== 'object')) {
			errors.responsibleOrg =  'Organization not found in database'
		}
		if (values.customFieldRef1 && (typeof values.customFieldRef1 !== 'object')) {
			errors.customFieldRef1 =  'Task not found in database'
		}
		return errors
	}

	customEnumButtons = (list) => {
		const buttons = []
		for (const key in list) {
			if (list.hasOwnProperty(key)) {
				buttons.push({
					id: key,
					value: key,
					label: list[key],
				})
			}
		}
	    return buttons
	}

	onCancel = () => {
		this.props.history.goBack()
	}

	onSubmit = (values, form) => {
		return this.save(values, form)
			.then(response => this.onSubmitSuccess(response, values, form))
			.catch(error => {
				this.setState({error})
				jumpToTop()
			})
	}

	onSubmitSuccess = (response, values, form) => {
		const { edit } = this.props
		const operation = edit ? 'updateTask' : 'createTask'
		const task = new Task({uuid: (response[operation].uuid ? response[operation].uuid : this.props.initialValues.uuid)})
		// After successful submit, reset the form in order to make sure the dirty
		// prop is also reset (otherwise we would get a blocking navigation warning)
		form.resetForm()
		this.props.history.replace(Task.pathForEdit(task))
		this.props.history.push({
			pathname: Task.pathFor(task),
			state: {
				success: 'Task saved',
			}
		})
	}

	save = (values, form) => {
		const task = new Task(values)
		task.responsibleOrg = utils.getReference(task.responsibleOrg)
		task.customFieldRef1 = utils.getReference(task.customFieldRef1)
		const { edit } = this.props
		const operation = edit ? 'updateTask' : 'createTask'
		let graphql = operation + '(task: $task)'
		graphql += edit ? '' : ' { uuid }'
		const variables = { task: task }
		const variableDef = '($task: TaskInput!)'
		return API.mutation(graphql, variables, variableDef)
	}
}

const TaskForm = (props) => (
	<AppContext.Consumer>
		{context =>
			<BaseTaskForm currentUser={context.currentUser} {...props} />
		}
	</AppContext.Consumer>
)

export default withRouter(TaskForm)
<|endoftext|>


<commit_before>/**
 * Copyright Kitware Inc.
 *
 * This is the PhantomJS runtime script that invokes the Girder app in test
 * mode. The test mode page is built with grunt and lives at:
 * clients/web/static/built/testing/testEnv.html. It then executes a Jasmine spec within
 * the context of that test application, and afterwards runs our custom coverage
 * handler on the coverage data.
 */
/* globals phantom, WebPage, jasmine, girderTest */

var system = require('system');
var args = phantom.args ? phantom.args : system.args.slice(1);

if (args && args.length < 2) {
    console.error('Usage: phantomjs phantom_jasmine_runner.js <page> <spec> [<covg_output> [<default jasmine timeout>]');
    console.error('  <page> is the path to the HTML page to load');
    console.error('  <spec> is the path to the Jasmine spec to run.');
    console.error('  <covg_output> is the path to a file to write coverage into.');
    console.error('  <default Jasmine timeout> is in milliseconds.');
    phantom.exit(2);
}

var env = system.env;

var pageUrl = args[0];
var spec = args[1];
var coverageOutput = args[2] || null;
var page = new WebPage();

var fs = require('fs');
require('event-source/global');

try {
    fs.remove(coverageOutput);
} catch (e) {
}

// write coverage results to a file
var reportCoverage = function () {
    if (!coverageOutput) {
        return;
    }

    var cov = page.evaluate(function () {
        return window.__coverage__;
    });

    cov = cov || {};
    fs.write(coverageOutput, JSON.stringify(cov), 'w');
};

// Set decent viewport size for screenshots.
page.viewportSize = {
    width: 1024,
    height: 769
};

page.onConsoleMessage = function (msg) {
    if (msg.indexOf('__SCREENSHOT__') === 0) {
        var imageFile = msg.substring('__SCREENSHOT__'.length) || 'phantom_screenshot.png';
        page.render(imageFile);
        console.log('Created screenshot: ' + imageFile);

        console.log('<DartMeasurementFile name="PhantomScreenshot" type="image/png">' +
            fs.workingDirectory + fs.separator + imageFile + '</DartMeasurementFile>');

        if (env['PHANTOMJS_OUTPUT_AJAX_TRACE'] === undefined ||
            env['PHANTOMJS_OUTPUT_AJAX_TRACE'] === 1 ||
            env['PHANTOMJS_OUTPUT_AJAX_TRACE'] === true) {
            console.log('Dumping ajax trace:');
            console.log(page.evaluate(function () {
                return JSON.stringify(girderTest.ajaxLog(true), null, '  ');
            }));
        }
        return;
    } else if (msg === 'ConsoleReporter finished') {
        var success = this.page.evaluate(function () {
            return window.jasmine_phantom_reporter.status === 'success';
        });
        if (success) {
            reportCoverage();
        }
        phantom.exit(success ? 0 : 1);
    }
};

page.onCallback = function (data) {
    /* Perform an action asked for in the web test and return a result.  An
     * action must be specified in the data object for this to do anything.
     * Available actions are:
     *   uploadFile: upload the file in data.path to the element determined
     * with the selector data.selector.  If no path or an invalid path is
     * specified, and data.size is present, create a temporary file with
     * data.size bytes and upload that.
     *   uploadCleanup: delete any temporary file that was created for uploads.
     * :param data: an object with an 'action', as listed above.
     * :returns: depends on the action.
     */
    var uploadTemp = fs.workingDirectory + fs.separator + 'phantom_temp';
    if (data.suffix) {
        uploadTemp += '_' + data.suffix;
    }
    uploadTemp += '.tmp';
    switch (data.action) {
        case 'fetchEmail':
            if (fs.exists(uploadTemp)) {
                return fs.read(uploadTemp);
            }
            break;
        case 'uploadFile':
            var path = data.path;
            if (!path && data.size !== undefined) {
                path = uploadTemp;
                fs.write(path, new Array(data.size + 1).join('-'), 'wb');
            }
            page.uploadFile(data.selector, path);
            return fs.read(path, {
                mode: 'rb'
            });
        case 'uploadCleanup':
            if (fs.exists(uploadTemp)) {
                fs.remove(uploadTemp);
            }
            break;
        case 'exit':
            // The "Testing Finished" string is magical and causes web_client_test.py not to retry
            console.log('Testing Finished with status=' + data.code);
            phantom.exit(data.code);
    }
};

page.onError = function (msg, trace) {
    var msgStack = ['ERROR: ' + msg];
    if (trace && trace.length) {
        msgStack.push('TRACE:');
        trace.forEach(function (t) {
            msgStack.push(' -> ' + t.file + ': ' + t.line +
                (t.function ? ' (in function "' + t.function + '")' : ''));
        });
    }
    console.error(msgStack.join('\n'));
    console.log('Saved phantom_error_screenshot.png');
    console.log('<DartMeasurementFile name="PhantomErrorScreenshot" type="image/png">' +
        fs.workingDirectory + '/phantom_error_screenshot.png</DartMeasurementFile>');
    page.render('phantom_error_screenshot.png');
    phantom.exit(1);
};

page.onLoadFinished = function (status) {
    if (status !== 'success') {
        console.error('Page load failed');
        // Avoid Unsafe JavaScript attempt to access frame with URL
        // http://stackoverflow.com/a/26688062/250457
        setTimeout(function () {
            phantom.exit(1);
        }, 0);
    } else {
        if (!page.injectJs(spec)) {
            console.error('Could not load test spec into page: ' + spec);
            phantom.exit(1);
        }
        if (args[3]) {
            page.evaluate(function (timeout) {
                if (window.jasmine) {
                    jasmine.getEnv().defaultTimeoutInterval = timeout;
                }
            }, args[3]);
        }
        page.evaluate(function () {
            if (window.girderTest) {
                girderTest.promise.then(function () {
                    jasmine.getEnv().execute();
                });
            }
        });
    }
};

/* Sometimes phantom fails when loading many resources.  I think this is this
 * known issue: https://github.com/ariya/phantomjs/issues/10652.  Adding a
 * resource timeout and then reloading the resource works around the problem.
 */
page.settings.resourceTimeout = 15000;

page.onResourceTimeout = function (request) {
    console.log('Resource timed out.  (#' + request.id + '): ' + JSON.stringify(request));
    console.log('PHANTOM_TIMEOUT');
    /* The exit code doesn't get sent back from here, so setting this to a
     * non-zero value doesn't seem to have any benefit. */
    phantom.exit(0);
};

page.open(pageUrl, function (status) {
    if (status !== 'success') {
        console.error('Could not load page: ' + pageUrl);
        phantom.exit(1);
    }
});
<commit_msg>Adding a necessary console.log because reasons<commit_after>/**
 * Copyright Kitware Inc.
 *
 * This is the PhantomJS runtime script that invokes the Girder app in test
 * mode. The test mode page is built with grunt and lives at:
 * clients/web/static/built/testing/testEnv.html. It then executes a Jasmine spec within
 * the context of that test application, and afterwards runs our custom coverage
 * handler on the coverage data.
 */
/* globals phantom, WebPage, jasmine, girderTest */

var system = require('system');
var args = phantom.args ? phantom.args : system.args.slice(1);

if (args && args.length < 2) {
    console.error('Usage: phantomjs phantom_jasmine_runner.js <page> <spec> [<covg_output> [<default jasmine timeout>]');
    console.error('  <page> is the path to the HTML page to load');
    console.error('  <spec> is the path to the Jasmine spec to run.');
    console.error('  <covg_output> is the path to a file to write coverage into.');
    console.error('  <default Jasmine timeout> is in milliseconds.');
    phantom.exit(2);
}

var env = system.env;

var pageUrl = args[0];
var spec = args[1];
var coverageOutput = args[2] || null;
var page = new WebPage();

var fs = require('fs');
require('event-source/global');

try {
    fs.remove(coverageOutput);
} catch (e) {
}

// write coverage results to a file
var reportCoverage = function () {
    if (!coverageOutput) {
        return;
    }

    var cov = page.evaluate(function () {
        return window.__coverage__;
    });

    cov = cov || {};
    fs.write(coverageOutput, JSON.stringify(cov), 'w');
};

// Set decent viewport size for screenshots.
page.viewportSize = {
    width: 1024,
    height: 769
};

page.onConsoleMessage = function (msg) {
    console.log(msg); // this needs to be here or the tests fail...
    if (msg.indexOf('__SCREENSHOT__') === 0) {
        var imageFile = msg.substring('__SCREENSHOT__'.length) || 'phantom_screenshot.png';
        page.render(imageFile);
        console.log('Created screenshot: ' + imageFile);

        console.log('<DartMeasurementFile name="PhantomScreenshot" type="image/png">' +
            fs.workingDirectory + fs.separator + imageFile + '</DartMeasurementFile>');

        if (env['PHANTOMJS_OUTPUT_AJAX_TRACE'] === undefined ||
            env['PHANTOMJS_OUTPUT_AJAX_TRACE'] === 1 ||
            env['PHANTOMJS_OUTPUT_AJAX_TRACE'] === true) {
            console.log('Dumping ajax trace:');
            console.log(page.evaluate(function () {
                return JSON.stringify(girderTest.ajaxLog(true), null, '  ');
            }));
        }
        return;
    } else if (msg === 'ConsoleReporter finished') {
        var success = this.page.evaluate(function () {
            return window.jasmine_phantom_reporter.status === 'success';
        });
        if (success) {
            reportCoverage();
        }
        phantom.exit(success ? 0 : 1);
    }
};

page.onCallback = function (data) {
    /* Perform an action asked for in the web test and return a result.  An
     * action must be specified in the data object for this to do anything.
     * Available actions are:
     *   uploadFile: upload the file in data.path to the element determined
     * with the selector data.selector.  If no path or an invalid path is
     * specified, and data.size is present, create a temporary file with
     * data.size bytes and upload that.
     *   uploadCleanup: delete any temporary file that was created for uploads.
     * :param data: an object with an 'action', as listed above.
     * :returns: depends on the action.
     */
    var uploadTemp = fs.workingDirectory + fs.separator + 'phantom_temp';
    if (data.suffix) {
        uploadTemp += '_' + data.suffix;
    }
    uploadTemp += '.tmp';
    switch (data.action) {
        case 'fetchEmail':
            if (fs.exists(uploadTemp)) {
                return fs.read(uploadTemp);
            }
            break;
        case 'uploadFile':
            var path = data.path;
            if (!path && data.size !== undefined) {
                path = uploadTemp;
                fs.write(path, new Array(data.size + 1).join('-'), 'wb');
            }
            page.uploadFile(data.selector, path);
            return fs.read(path, {
                mode: 'rb'
            });
        case 'uploadCleanup':
            if (fs.exists(uploadTemp)) {
                fs.remove(uploadTemp);
            }
            break;
        case 'exit':
            // The "Testing Finished" string is magical and causes web_client_test.py not to retry
            console.log('Testing Finished with status=' + data.code);
            phantom.exit(data.code);
    }
};

page.onError = function (msg, trace) {
    var msgStack = ['ERROR: ' + msg];
    if (trace && trace.length) {
        msgStack.push('TRACE:');
        trace.forEach(function (t) {
            msgStack.push(' -> ' + t.file + ': ' + t.line +
                (t.function ? ' (in function "' + t.function + '")' : ''));
        });
    }
    console.error(msgStack.join('\n'));
    console.log('Saved phantom_error_screenshot.png');
    console.log('<DartMeasurementFile name="PhantomErrorScreenshot" type="image/png">' +
        fs.workingDirectory + '/phantom_error_screenshot.png</DartMeasurementFile>');
    page.render('phantom_error_screenshot.png');
    phantom.exit(1);
};

page.onLoadFinished = function (status) {
    if (status !== 'success') {
        console.error('Page load failed');
        // Avoid Unsafe JavaScript attempt to access frame with URL
        // http://stackoverflow.com/a/26688062/250457
        setTimeout(function () {
            phantom.exit(1);
        }, 0);
    } else {
        if (!page.injectJs(spec)) {
            console.error('Could not load test spec into page: ' + spec);
            phantom.exit(1);
        }
        if (args[3]) {
            page.evaluate(function (timeout) {
                if (window.jasmine) {
                    jasmine.getEnv().defaultTimeoutInterval = timeout;
                }
            }, args[3]);
        }
        page.evaluate(function () {
            if (window.girderTest) {
                girderTest.promise.then(function () {
                    jasmine.getEnv().execute();
                });
            }
        });
    }
};

/* Sometimes phantom fails when loading many resources.  I think this is this
 * known issue: https://github.com/ariya/phantomjs/issues/10652.  Adding a
 * resource timeout and then reloading the resource works around the problem.
 */
page.settings.resourceTimeout = 15000;

page.onResourceTimeout = function (request) {
    console.log('Resource timed out.  (#' + request.id + '): ' + JSON.stringify(request));
    console.log('PHANTOM_TIMEOUT');
    /* The exit code doesn't get sent back from here, so setting this to a
     * non-zero value doesn't seem to have any benefit. */
    phantom.exit(0);
};

page.open(pageUrl, function (status) {
    if (status !== 'success') {
        console.error('Could not load page: ' + pageUrl);
        phantom.exit(1);
    }
});
<|endoftext|>


<commit_before>/*
  backgrid-select-all
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong
  Licensed under the MIT @license.
*/
(function (window, $, _, Backbone, Backgrid)  {

  var SelectRowCell = Backgrid.Extension.SelectRowCell = Backbone.View.extend({

    className: "select-row-cell",

    tagName: "td",

    events: {
      "change": "onChange"
    },

    initialize: function (options) {

      this.column = options.column;
      if (!(this.column instanceof Backgrid.Column)) {
        this.column = new Backgrid.Column(this.column);
      }

      this.listenTo(this.model, "select", function (model, selected) {
        this.$el.find(":checkbox").prop("checked", selected).change();
      });

    },

    onChange: function (e) {
      this.model.trigger("selected", this.model, $(e.target).prop("checked"));
    },

    render: function () {
      this.$el.empty().append("<input type='checkbox' />");
      return this;
    }

  });

  Backgrid.Extension.SelectAllHeaderCell = SelectRowCell.extend({

    className: "select-all-header-cell",

    tagName: "th",

    initialize: function (options) {

      this.column = options.column;
      if (!(this.column instanceof Backgrid.Column)) {
        this.column = new Backgrid.Column(this.column);
      }

      this.listenTo(this.collection, "selected", function (model, selected) {
        if (!selected) {
          this.$el.find(":checkbox").prop("checked", selected);
          this.allSelected = selected;
        }
      });

      this.allSelected = false;
    },

    onChange: function (e) {
      var selected = $(e.target).prop("checked");

      this.collection.each(function (model) {
        model.trigger("select", model, selected);
      });

      this.allSelected = selected;
    }

  });

}(window, jQuery, _, Backbone, Backgrid));
<commit_msg>Select all even on page change<commit_after>/*
  backgrid-select-all
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong
  Licensed under the MIT @license.
*/
(function (window, $, _, Backbone, Backgrid)  {

  var SelectRowCell = Backgrid.Extension.SelectRowCell = Backbone.View.extend({

    className: "select-row-cell",

    tagName: "td",

    events: {
      "change": "onChange"
    },

    initialize: function (options) {

      this.column = options.column;
      if (!(this.column instanceof Backgrid.Column)) {
        this.column = new Backgrid.Column(this.column);
      }

      this.listenTo(this.model, "select", function (model, selected) {
        this.$el.find(":checkbox").prop("checked", selected).change();
      });

    },

    onChange: function (e) {
      this.model.trigger("selected", this.model, $(e.target).prop("checked"));
    },

    render: function () {
      this.$el.empty().append("<input type='checkbox' />");
      return this;
    }

  });

  Backgrid.Extension.SelectAllHeaderCell = SelectRowCell.extend({

    className: "select-all-header-cell",

    tagName: "th",

    initialize: function (options) {

      this.column = options.column;
      if (!(this.column instanceof Backgrid.Column)) {
        this.column = new Backgrid.Column(this.column);
      }

      var collection = this.collection;
      this.listenTo(collection, "selected", function (model, selected) {
        if (!selected) {
          this.$el.find(":checkbox").prop("checked", selected);
          this.allSelected = selected;
        }
      });

      this.listenTo(Backbone, "backgrid:refresh", function () {
        if (this.allSelected) {
          collection.each(function (model) {
            model.trigger("select", model, true);
          });
        }
      });

      this.allSelected = false;
    },

    onChange: function (e) {
      var selected = $(e.target).prop("checked");

      this.collection.each(function (model) {
        model.trigger("select", model, selected);
      });

      this.allSelected = selected;
    }

  });

}(window, jQuery, _, Backbone, Backgrid));
<|endoftext|>


<commit_before>/*
  backgrid-select-all
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong
  Licensed under the MIT @license.
*/
(function (window, $, _, Backbone, Backgrid)  {

  var SelectRowCell = Backgrid.Extension.SelectRowCell = Backbone.View.extend({

    className: "select-row-cell",

    tagName: "td",

    events: {
      "change": "onChange"
    },

    initialize: function (options) {

      this.column = options.column;
      if (!(this.column instanceof Backgrid.Column)) {
        this.column = new Backgrid.Column(this.column);
      }

      this.listenTo(this.model, "select", function (model, selected) {
        this.$el.find(":checkbox").prop("checked", selected);
      });

    },

    onChange: function (e) {
      this.model.trigger("selected", this.model, $(e.target).prop("checked"));
    },

    render: function () {
      this.$el.empty().append("<input type='checkbox' />");
      return this;
    }

  });

  Backgrid.Extension.SelectAllHeaderCell = SelectRowCell.extend({

    className: "select-all-header-cell",

    tagName: "th",

    initialize: function (options) {

      this.column = options.column;
      if (!(this.column instanceof Backgrid.Column)) {
        this.column = new Backgrid.Column(this.column);
      }

      this.listenTo(this.collection, "selected", function (model, selected) {
        if (!selected) {
          this.$el.find(":checkbox").prop("checked", selected);
          this.allSelected = selected;
        }
      });

      this.allSelected = false;
    },

    onChange: function (e) {
      var selected = $(e.target).prop("checked");

      this.collection.each(function (model) {
        model.trigger("select", model, selected);
      });

      this.allSelected = selected;
    }

  });

}(window, jQuery, _, Backbone, Backgrid));
<commit_msg>Trigger change event for Webkit browsers<commit_after>/*
  backgrid-select-all
  http://github.com/wyuenho/backgrid

  Copyright (c) 2013 Jimmy Yuen Ho Wong
  Licensed under the MIT @license.
*/
(function (window, $, _, Backbone, Backgrid)  {

  var SelectRowCell = Backgrid.Extension.SelectRowCell = Backbone.View.extend({

    className: "select-row-cell",

    tagName: "td",

    events: {
      "change": "onChange"
    },

    initialize: function (options) {

      this.column = options.column;
      if (!(this.column instanceof Backgrid.Column)) {
        this.column = new Backgrid.Column(this.column);
      }

      this.listenTo(this.model, "select", function (model, selected) {
        this.$el.find(":checkbox").prop("checked", selected).change();
      });

    },

    onChange: function (e) {
      this.model.trigger("selected", this.model, $(e.target).prop("checked"));
    },

    render: function () {
      this.$el.empty().append("<input type='checkbox' />");
      return this;
    }

  });

  Backgrid.Extension.SelectAllHeaderCell = SelectRowCell.extend({

    className: "select-all-header-cell",

    tagName: "th",

    initialize: function (options) {

      this.column = options.column;
      if (!(this.column instanceof Backgrid.Column)) {
        this.column = new Backgrid.Column(this.column);
      }

      this.listenTo(this.collection, "selected", function (model, selected) {
        if (!selected) {
          this.$el.find(":checkbox").prop("checked", selected);
          this.allSelected = selected;
        }
      });

      this.allSelected = false;
    },

    onChange: function (e) {
      var selected = $(e.target).prop("checked");

      this.collection.each(function (model) {
        model.trigger("select", model, selected);
      });

      this.allSelected = selected;
    }

  });

}(window, jQuery, _, Backbone, Backgrid));
<|endoftext|>


<commit_before>/*
 * fis
 * http://web.baidu.com/
 */

'use strict';

exports.name = 'release';
exports.desc = 'build and deploy your project';
exports.register = function(commander, fis){

    function watch(opt){
        var root = fis.project.getProjectPath();
        var isWin = fis.util.isWin();
        var ignored = [];
        [ 'output', fis.project.conf.substring(root.length + 1) ].forEach(function(pattern){
            pattern = isWin ? pattern.replace(/\//g, '\\') : pattern;
            ignored.push('^' + fis.util.escapeReg(pattern) + '\b');
        });
        if(isWin){
            ignored.push(fis.util.escapeReg('\\.'));
        } else {
            ignored.push(fis.util.escapeReg('/.'));
        }
        ignored = new RegExp(ignored.join('|'), 'i');
        var timer = -1;
        var safePathReg = /^[:\\\/ _\-.\w]+$/i;
        function listener(path){
            if(safePathReg.test(path)){
                clearTimeout(timer);
                timer = setTimeout(function(){
                    release(opt);
                }, 500);
            }
        }
        require('chokidar')
            .watch(root, {
                ignored : /\\output\b/i,
                persistent: true
            })
            .on('add', listener)
            .on('change', listener)
            .on('unlink', listener)
            .on('error', function(err){
                fis.log.error(err);
            });
    }

    var lastModified = {};
    var collection = {};
    var deploy = require('./lib/deploy.js');

    function release(opt){
        //write a white space.
        process.stdout.write(' ');
        //compile hooks
        var flag, cost, index = 0;
        opt.beforeEach = function(){
            flag = '.';
            cost = (new Date).getTime();
        };
        opt.afterEach = function(file){
            //cal compile time
            cost = (new Date).getTime() - cost;
            if(cost > 200){
                flag = flag.bold.yellow;
            } else if(cost < 100){
                flag = flag.grey;
            }
            var mtime = file.getMtime().getTime();
            //collect file to deploy
            if((file.cache && file.cache.expired) || lastModified[file.subpath] !== mtime){
                lastModified[file.subpath] = mtime;
                collection[file.subpath] = file;
                if(index > 0 && index % 50 === 0){
                    process.stdout.write('\n ');
                }
                process.stdout.write(flag);
            }
            index++;
        };

        //release
        fis.release(opt, function(ret){
            process.stdout.write('\n');
            fis.util.map(ret.pkg, collection, true);
            deploy(opt.dest, opt.md5, collection, fis);
            collection = {};
        });
    }

    commander
        .option('-d, --dest <names>', 'release output destination', String, 'preview')
        .option('-w, --watch', 'monitor the changes of project')
        .option('-c, --clean', 'clean cache before releasing')
        .option('-t, --type <ext>', 'resouce map type', String, 'php')
        .option('-m, --md5 <level>', 'md5 release option', parseInt, 0)
        .option('-D, --domain', 'add domain', Boolean, false)
        .option('-H, --no-hint', 'without hint', Boolean, true)
        .option('-O, --no-optimize', 'without optimize', Boolean, true)
        .option('-P, --no-pack', 'without package', Boolean, true)
        .option('--debug', 'debug mode', Boolean, false)
        .action(function(options){
            var cwd = fis.util.realpath(process.cwd()),
                filename = fis.config.get('system.conf', fis.project.DEFAULT_CONF_FILE),
                pos = cwd.length, conf;
            do {
                cwd  = cwd.substring(0, pos);
                conf = cwd + '/' + filename;
                if(fis.util.exists(conf)){
                    //merge standard conf
                    fis.config.merge(fis.util.readJSON(__dirname + '/standard.json'));
                    //init project
                    fis.project.init(cwd, conf, function(){

                        //configure log
                        fis.log.level = options.debug ? fis.log.L_ALL : fis.log.level;
                        fis.log.throw = true;

                        //compile setup
                        var tmp = fis.compile.setup({
                            debug    : options.debug,
                            optimize : options.optimize,
                            hint     : options.hint,
                            hash     : options.md5 > 0,
                            domain   : options.domain
                        });

                        if(options.clean){
                            fis.cache.clean(tmp);
                        }

                        if(options.watch){
                            watch(options);
                        } else {
                            release(options);
                        }
                    });
                    return;
                }
            } while(pos > 0);
            fis.log.error('unable to find fis-conf file [' + filename + ']');
        });
};<commit_msg>添加日志监控<commit_after>/*
 * fis
 * http://web.baidu.com/
 */

'use strict';

exports.name = 'release';
exports.desc = 'build and deploy your project';
exports.register = function(commander, fis){

    function watch(opt){
        var root = fis.project.getProjectPath();
        var isWin = fis.util.isWin();
        var ignored = [];
        [ 'output', fis.project.conf.substring(root.length + 1) ].forEach(function(pattern){
            pattern = isWin ? pattern.replace(/\//g, '\\') : pattern;
            ignored.push('^' + fis.util.escapeReg(pattern) + '\b');
        });
        if(isWin){
            ignored.push(fis.util.escapeReg('\\.'));
        } else {
            ignored.push(fis.util.escapeReg('/.'));
        }
        ignored = new RegExp(ignored.join('|'), 'i');
        var timer = -1;
        var safePathReg = /^[:\\\/ _\-.\w]+$/i;
        function listener(path){
            if(safePathReg.test(path)){
                clearTimeout(timer);
                timer = setTimeout(function(){
                    release(opt);
                }, 500);
            }
        }
        require('chokidar')
            .watch(root, {
                ignored : /\\output\b/i,
                persistent: true
            })
            .on('add', listener)
            .on('change', listener)
            .on('unlink', listener)
            .on('error', function(err){
                fis.log.error(err);
            });
    }

    var lastModified = {};
    var collection = {};
    var deploy = require('./lib/deploy.js');

    function release(opt){
        //write a white space.
        process.stdout.write(' ');
        //compile hooks
        var flag, cost, index = 0;
        opt.beforeEach = function(){
            flag = '.';
            cost = (new Date).getTime();
        };
        opt.afterEach = function(file){
            //cal compile time
            cost = (new Date).getTime() - cost;
            if(cost > 200){
                flag = flag.bold.yellow;
            } else if(cost < 100){
                flag = flag.grey;
            }
            var mtime = file.getMtime().getTime();
            //collect file to deploy
            if((file.cache && file.cache.expired) || lastModified[file.subpath] !== mtime){
                lastModified[file.subpath] = mtime;
                collection[file.subpath] = file;
                if(index > 0 && index % 50 === 0){
                    process.stdout.write('\n ');
                }
                process.stdout.write(flag);
                fis.log.debug(file.subpath);
            }
            index++;
        };

        //release
        fis.release(opt, function(ret){
            process.stdout.write('\n');
            fis.util.map(ret.pkg, collection, true);
            deploy(opt.dest, opt.md5, collection, fis);
            collection = {};
        });
    }

    commander
        .option('-d, --dest <names>', 'release output destination', String, 'preview')
        .option('-w, --watch', 'monitor the changes of project')
        .option('-c, --clean', 'clean cache before releasing')
        .option('-t, --type <ext>', 'resouce map type', String, 'php')
        .option('-m, --md5 <level>', 'md5 release option', parseInt, 0)
        .option('-D, --domain', 'add domain', Boolean, false)
        .option('-H, --no-hint', 'without hint', Boolean, true)
        .option('-O, --no-optimize', 'without optimize', Boolean, true)
        .option('-P, --no-pack', 'without package', Boolean, true)
        .option('--debug', 'debug mode', Boolean, false)
        .action(function(options){
            var cwd = fis.util.realpath(process.cwd()),
                filename = fis.config.get('system.conf', fis.project.DEFAULT_CONF_FILE),
                pos = cwd.length, conf;
            do {
                cwd  = cwd.substring(0, pos);
                conf = cwd + '/' + filename;
                if(fis.util.exists(conf)){
                    //merge standard conf
                    fis.config.merge(fis.util.readJSON(__dirname + '/standard.json'));
                    //init project
                    fis.project.init(cwd, conf, function(){

                        //configure log
                        fis.log.level = options.debug ? fis.log.L_ALL : fis.log.level;
                        fis.log.throw = true;

                        //compile setup
                        var tmp = fis.compile.setup({
                            debug    : options.debug,
                            optimize : options.optimize,
                            hint     : options.hint,
                            hash     : options.md5 > 0,
                            domain   : options.domain
                        });

                        if(options.clean){
                            fis.cache.clean(tmp);
                        }

                        if(options.watch){
                            watch(options);
                        } else {
                            release(options);
                        }
                    });
                    return;
                }
            } while(pos > 0);
            fis.log.error('unable to find fis-conf file [' + filename + ']');
        });
};<|endoftext|>


<commit_before>const selectors = require('../../../../selectors')

describe('Company Collections Filter', () => {
  before(() => {
    cy.visit('/companies?sortby=collectionTest')
    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 9)
    cy.get(selectors.entityCollection.collection).should(
      'contain',
      '100,172 companies'
    )
  })

  beforeEach(() => {
    cy.server()
    cy.route('/companies?*').as('filterResults')
  })

  it('should filter by name', () => {
    cy.get(selectors.filter.name).type('FilterByCompany').type('{enter}')

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 1)
    cy.get(selectors.entityCollection.collection).should(
      'contain',
      '1 company matching FilterByCompany'
    )
    cy.get(selectors.entityCollection.collectionRowMessage).should(
      'contain',
      'You can now download this company'
    )
    cy.get(selectors.entityCollection.collectionRowButton).should('be.visible')
  })

  it('should filter by active status', () => {
    cy.get(selectors.filter.statusActive).click()

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        '?sortby=collectionTest&custom=true&name=FilterByCompany&archived=false'
      )
    })

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 1)
  })

  it('should filter by inactive status', () => {
    cy.get(selectors.filter.statusInactive).click()

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        '?sortby=collectionTest&custom=true&name=FilterByCompany&archived=false&archived=true'
      )
    })

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 1)
  })

  it('should filter by last interaction date', () => {
    cy.get(selectors.filter.firstInteractionDate).click()

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain('interaction_between=0')
    })

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 1)
  })

  it('should remove all filters', () => {
    cy.get(selectors.entityCollection.collectionRemoveAllFilter).click()
    cy.get(selectors.entityCollection.collection).should(
      'contain',
      '100,172 companies'
    )
  })

  it('should filter by sector', () => {
    const sector = selectors.filter.sector
    const { typeahead } = selectors.filter
    cy.get(typeahead(sector).selectedOption)
      .click()
      .get(typeahead(sector).textInput)
      .type('Advanced Engineering')
      .get(typeahead(sector).options)
      .should('have.length', 1)
      .get(typeahead(sector).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'sector_descends=af959812-6095-e211-a939-e4115bead28a'
      )
    })
  })

  it('should filter by country', () => {
    const country = selectors.filter.country
    const { typeahead } = selectors.filter

    cy.get(typeahead(country).selectedOption)
      .click()
      .get(typeahead(country).textInput)
      .type('United Kingdom')
      .get(typeahead(country).options)
      .should('have.length', 1)
      .get(typeahead(country).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain('country=80756b9a-5d95-e211-a939-e4115bead28a')
    })
  })

  it('should filter by currently exporting to', () => {
    const exportingTo = selectors.filter.exportingTo
    const { typeahead } = selectors.filter

    cy.get(typeahead(exportingTo).selectedOption)
      .click()
      .get(typeahead(exportingTo).textInput)
      .type('Australia')
      .get(typeahead(exportingTo).options)
      .should('have.length', 1)
      .get(typeahead(exportingTo).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'export_to_countries=9f5f66a0-5d95-e211-a939-e4115bead28a'
      )
    })
  })

  it('should filter by future countries of interest', () => {
    const interestedIn = selectors.filter.interestedIn
    const { typeahead } = selectors.filter

    cy.get(typeahead(interestedIn).selectedOption)
      .click()
      .get(typeahead(interestedIn).textInput)
      .type('Bahamas')
      .get(typeahead(interestedIn).options)
      .should('have.length', 1)
      .get(typeahead(interestedIn).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'future_interest_countries=a25f66a0-5d95-e211-a939-e4115bead28a'
      )
    })
  })

  it('should filter by UK postcode', () => {
    const POSTCODE = 'GL11'

    cy.reload(true)
    cy.get(selectors.filter.ukPostcode).should('be.visible')
    cy.get(selectors.filter.ukPostcode).clear().type(POSTCODE).type('{enter}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(`uk_postcode=${POSTCODE}`)
    })

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 24)
  })

  it('should filter by Lead ITA and Global Account Manager', () => {
    const leadIta = selectors.filter.leadIta
    const { typeahead } = selectors.filter
    cy.get(typeahead(leadIta).selectedOption)
      .click()
      .get(typeahead(leadIta).textInput)
      .type('Shawn Cohen')
      .get(typeahead(leadIta).options)
      .should('have.length', 63)

    cy.get(typeahead(leadIta).selectedOption).type('{enter}').type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'one_list_group_global_account_manager=2c42c516-9898-e211-a939-e4115bead28a'
      )
    })
  })

  it('should filter by uk region', () => {
    const { ukRegion, typeahead } = selectors.filter
    cy.get(typeahead(ukRegion).selectedOption)
      .click()
      .get(typeahead(ukRegion).textInput)
      .type('North West')
      .get(typeahead(ukRegion).options)
      .should('have.length', 1)
      .get(typeahead(ukRegion).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'uk_region=824cd12a-6095-e211-a939-e4115bead28a'
      )
    })
  })
})
<commit_msg>Update companies filter test<commit_after>const selectors = require('../../../../selectors')

describe('Company Collections Filter', () => {
  before(() => {
    cy.visit('/companies?sortby=collectionTest')
    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 9)
    cy.get(selectors.entityCollection.collection).should(
      'contain',
      '100,172 companies'
    )
  })

  beforeEach(() => {
    cy.server()
    cy.route('/companies?*').as('filterResults')
  })

  it('should filter by name', () => {
    cy.get(selectors.filter.name).type('FilterByCompany').type('{enter}')

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 1)
    cy.get(selectors.entityCollection.collection).should(
      'contain',
      '1 company matching FilterByCompany'
    )
    cy.get(selectors.entityCollection.collectionRowMessage).should(
      'contain',
      'You can now download this company'
    )
    cy.get(selectors.entityCollection.collectionRowButton).should('be.visible')
  })

  it('should filter by active status', () => {
    cy.get(selectors.filter.statusActive).click()

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        '?sortby=collectionTest&custom=true&name=FilterByCompany&archived=false'
      )
    })

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 1)
  })

  it('should filter by inactive status', () => {
    cy.get(selectors.filter.statusInactive).click()

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        '?sortby=collectionTest&custom=true&name=FilterByCompany&archived=false&archived=true'
      )
    })

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 1)
  })

  it('should filter by last interaction date', () => {
    cy.get(selectors.filter.firstInteractionDate).click()

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain('interaction_between=0')
    })

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 1)
  })

  it('should remove all filters', () => {
    cy.get(selectors.entityCollection.collectionRemoveAllFilter).click()
    cy.get(selectors.entityCollection.collection).should(
      'contain',
      '100,172 companies'
    )
  })

  it('should filter by sector', () => {
    const sector = selectors.filter.sector
    const { typeahead } = selectors.filter
    cy.get(typeahead(sector).selectedOption)
      .click()
      .get(typeahead(sector).textInput)
      .type('Advanced Engineering')
      .get(typeahead(sector).options)
      .should('have.length', 1)
      .get(typeahead(sector).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'sector_descends=af959812-6095-e211-a939-e4115bead28a'
      )
    })
  })

  it('should filter by country', () => {
    const country = selectors.filter.country
    const { typeahead } = selectors.filter

    cy.get(typeahead(country).selectedOption)
      .click()
      .get(typeahead(country).textInput)
      .type('United Kingdom')
      .get(typeahead(country).options)
      .should('have.length', 1)
      .get(typeahead(country).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain('country=80756b9a-5d95-e211-a939-e4115bead28a')
    })
  })

  it('should filter by currently exporting to', () => {
    const exportingTo = selectors.filter.exportingTo
    const { typeahead } = selectors.filter

    cy.get(typeahead(exportingTo).selectedOption)
      .click()
      .get(typeahead(exportingTo).textInput)
      .type('Australia')
      .get(typeahead(exportingTo).options)
      .should('have.length', 1)
      .get(typeahead(exportingTo).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'export_to_countries=9f5f66a0-5d95-e211-a939-e4115bead28a'
      )
    })
  })

  it('should filter by future countries of interest', () => {
    const interestedIn = selectors.filter.interestedIn
    const { typeahead } = selectors.filter

    cy.get(typeahead(interestedIn).selectedOption)
      .click()
      .get(typeahead(interestedIn).textInput)
      .type('Bahamas')
      .get(typeahead(interestedIn).options)
      .should('have.length', 1)
      .get(typeahead(interestedIn).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'future_interest_countries=a25f66a0-5d95-e211-a939-e4115bead28a'
      )
    })
  })

  it('should filter by UK postcode', () => {
    const POSTCODE = 'GL11'

    cy.reload(true)
    cy.get(selectors.filter.ukPostcode).should('be.visible')
    cy.get(selectors.filter.ukPostcode).clear().type(POSTCODE).type('{enter}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(`uk_postcode=${POSTCODE}`)
    })

    cy.get(selectors.entityCollection.entities)
      .children()
      .should('have.length', 24)
  })

  it('should filter by Lead ITA and Global Account Manager', () => {
    const leadIta = selectors.filter.leadIta
    const { typeahead } = selectors.filter
    cy.get(typeahead(leadIta).selectedOption)
      .click()
      .get(typeahead(leadIta).textInput)
      .type('Shawn Cohen')
      .get(typeahead(leadIta).options)
      .should('have.length', 64)

    cy.get(typeahead(leadIta).selectedOption).type('{enter}').type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'one_list_group_global_account_manager=2c42c516-9898-e211-a939-e4115bead28a'
      )
    })
  })

  it('should filter by uk region', () => {
    const { ukRegion, typeahead } = selectors.filter
    cy.get(typeahead(ukRegion).selectedOption)
      .click()
      .get(typeahead(ukRegion).textInput)
      .type('North West')
      .get(typeahead(ukRegion).options)
      .should('have.length', 1)
      .get(typeahead(ukRegion).textInput)
      .type('{enter}')
      .type('{esc}')

    cy.wait('@filterResults').then((xhr) => {
      expect(xhr.url).to.contain(
        'uk_region=824cd12a-6095-e211-a939-e4115bead28a'
      )
    })
  })
})
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version["enyo-ilib"] = "2.5.2-rc.1";
}
<commit_msg>Update version string to 2.5.2<commit_after>if (enyo && enyo.version) {
	enyo.version["enyo-ilib"] = "2.5.2";
}
<|endoftext|>


<commit_before>/*!
 * Copyright 2013 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var Fields = require('oae-config/lib/fields');

module.exports = {
    'title': 'OAE MediaCore Module',
    'mediacore': {
        'name': 'MediaCore configuration',
        'description': 'Configuration for the MediaCore preview processor',
        'elements': {
            'enabled': new Fields.Bool('Enabled', 'Process videos with MediaCore', false, {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            }),
            'url': new Fields.Text('URL', 'The MediaCore URL', '', {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            }),
            'keyId': new Fields.Text('Key ID', 'The MediaCore Key ID', '', {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            }),
            'secret': new Fields.Text('Secret', 'The MediaCore Secret Key', '', {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            }),
            'collectionId': new Fields.Text('CollectionId', 'The MediaCore Collection Id', '', {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            })
        }
    }
};
<commit_msg>(Issue 686) Suggest an HTTPS link for mediacore url in configuration<commit_after>/*!
 * Copyright 2013 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var Fields = require('oae-config/lib/fields');

module.exports = {
    'title': 'OAE MediaCore Module',
    'mediacore': {
        'name': 'MediaCore Configuration',
        'description': 'Configuration for MediaCore media processing',
        'elements': {
            'enabled': new Fields.Bool('Enabled', 'Process audio and video uploads with MediaCore', false, {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            }),
            'url': new Fields.Text('URL', 'The MediaCore URL (e.g., https://mysite.mediacore.tv)', '', {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            }),
            'keyId': new Fields.Text('Key ID', 'The MediaCore Key ID', '', {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            }),
            'secret': new Fields.Text('Secret', 'The MediaCore Secret Key', '', {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            }),
            'collectionId': new Fields.Text('CollectionId', 'The MediaCore Collection ID', '', {
                'tenantOverride': false,
                'suppress': true,
                'globalAdminOnly': true
            })
        }
    }
};
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version.spotlight = "2.6.0-pre.4";
}
<commit_msg>Update version string to 2.6.0-pre.4.dev<commit_after>if (enyo && enyo.version) {
	enyo.version.spotlight = "2.6.0-pre.4.dev";
}
<|endoftext|>


<commit_before>"use strict";
if (process.env.NODE_ENV === "test") {
  exports.osmbc_version = "1.8.4";
} else {
  exports.osmbc_version = "3.4.2";
}
<commit_msg>Version<commit_after>"use strict";
if (process.env.NODE_ENV === "test") {
  exports.osmbc_version = "1.8.4";
} else {
  exports.osmbc_version = "3.4.3";
}
<|endoftext|>


<commit_before>'use strict';

/**
 *  lib
 **/

/**
 *  lib.stylus
 **/

// stdlib
var path  = require('path');
var fs    = require('fs');

// 3rd-party
var stylus = require('stylus');

////////////////////////////////////////////////////////////////////////////////

// returns list of files under given pathname, but not deeper (no recursion)
function find_files(pathname) {
  var files = [];

  fs.readdirSync(pathname).forEach(function (filename) {
    filename = path.join(pathname, filename);

    if (fs.statSync(filename).isFile()) {
      // we are interested in a first level child files only
      files.push(filename);
      return;
    }
  });

  return files.sort();
}

////////////////////////////////////////////////////////////////////////////////

/**
 *  lib.stylus.import_dir(expr) -> Array
 *
 *  Stylus extensions that allows to mixin all files in the specified directory.
 *
 *
 *  ##### Usage
 *
 *  Assuming `source` is a stylus file:
 *
 *      import-dir('./foobar')
 *
 *  We can define `import-dir` function like this:
 *
 *      stylus(source).define('import-dir', lib.stylus.import_dir);
 **/
module.exports = function import_dir(expr) {
  var block     = this.currentBlock,
      vals      = [stylus.nodes['null']],
      pathname  = path.resolve(path.dirname(this.filename), expr.val);

  find_files(pathname).forEach(function (file) {
    var expr = new stylus.nodes.Expression(),
        node = new stylus.nodes.String(file),
        body;

    expr.push(node);

    body = this.visitImport(new stylus.nodes.Import(expr));
    vals = vals.concat(body.nodes);
  }, this);

  this.mixin(vals, block);
  return vals;
};
<commit_msg>Fix import-dir plugin<commit_after>'use strict';

/**
 *  lib
 **/

/**
 *  lib.stylus
 **/

// stdlib
var path  = require('path');
var fs    = require('fs');

// 3rd-party
var stylus = require('stylus');

////////////////////////////////////////////////////////////////////////////////

// returns list of files under given pathname, but not deeper (no recursion)
function find_files(pathname) {
  var files = [];

  fs.readdirSync(pathname).forEach(function (filename) {
    filename = path.join(pathname, filename);

    // we are interested in a first level child files only
    // and the file must have .styl extension
    if (fs.statSync(filename).isFile() && '.styl' == path.extname(filename)) {
      files.push(filename);
      return;
    }
  });

  return files.sort();
}

////////////////////////////////////////////////////////////////////////////////

/**
 *  lib.stylus.import_dir(expr) -> Array
 *
 *  Stylus extensions that allows to mixin all files in the specified directory.
 *
 *
 *  ##### Usage
 *
 *  Assuming `source` is a stylus file:
 *
 *      import-dir('./foobar')
 *
 *  We can define `import-dir` function like this:
 *
 *      stylus(source).define('import-dir', lib.stylus.import_dir);
 **/
module.exports = function import_dir(expr) {
  var block     = this.currentBlock,
      vals      = [stylus.nodes['null']],
      pathname  = path.resolve(path.dirname(this.filename), expr.val);

  find_files(pathname).forEach(function (file) {
    var expr = new stylus.nodes.Expression(),
        node = new stylus.nodes.String(file),
        body;

    expr.push(node);

    body = this.visitImport(new stylus.nodes.Import(expr));
    vals = vals.concat(body.nodes);
  }, this);

  this.mixin(vals, block);
  return vals;
};
<|endoftext|>


<commit_before>'use strict'

var shimmer = require('shimmer')
var semver = require('semver')
var debug = require('debug')('opbeat')

var SERVER_FNS = ['insert', 'update', 'remove', 'auth']
var CURSOR_FNS_FIRST = ['_find', '_getmore']

module.exports = function (mongodb, agent, version) {
  if (!semver.satisfies(version, '^1.0.0')) {
    debug('mongodb-core version %s not suppoted - aborting...', version)
    return mongodb
  }

  if (mongodb.Server) {
    debug('shimming mongodb-core.Server.prototype.command')
    shimmer.wrap(mongodb.Server.prototype, 'command', wrapCommand)
    debug('shimming mongodb-core.Server.prototype functions:', SERVER_FNS)
    shimmer.massWrap(mongodb.Server.prototype, SERVER_FNS, wrapQuery)
  }

  if (mongodb.Cursor) {
    debug('shimming mongodb-core.Cursor.prototype functions:', CURSOR_FNS_FIRST)
    shimmer.massWrap(mongodb.Cursor.prototype, CURSOR_FNS_FIRST, wrapCursor)
  }

  return mongodb

  function wrapCommand (orig) {
    return function wrappedFunction (ns, cmd) {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Server.prototype.command %o', { uuid: uuid, ns: ns })

      if (trace && arguments.length > 0) {
        var index = arguments.length - 1
        var cb = arguments[index]
        if (typeof cb === 'function') {
          var type
          if (cmd.findAndModify) type = 'findAndModify'
          else if (cmd.createIndexes) type = 'createIndexes'
          else if (cmd.ismaster) type = 'ismaster'
          else if (cmd.count) type = 'count'
          else type = 'command'

          arguments[index] = wrappedCallback
          trace.start(ns + '.' + type, 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Server.prototype.command callback %o', { uuid: uuid })
        trace.end()
        return cb.apply(this, arguments)
      }
    }
  }

  function wrapQuery (orig, name) {
    return function wrappedFunction (ns) {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Server.prototype.%s %o', name, { uuid: uuid, ns: ns })

      if (trace && arguments.length > 0) {
        var index = arguments.length - 1
        var cb = arguments[index]
        if (typeof cb === 'function') {
          arguments[index] = wrappedCallback
          trace.start(ns + '.' + name, 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Server.prototype.%s callback %o', name, { uuid: uuid })
        trace.end()
        return cb.apply(this, arguments)
      }
    }
  }

  function wrapCursor (orig, name) {
    return function wrappedFunction () {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Cursor.prototype.%s %o', name, { uuid: uuid })

      if (trace && arguments.length > 0) {
        var cb = arguments[0]
        if (typeof cb === 'function') {
          arguments[0] = wrappedCallback
          trace.start(this.ns + '.' + (this.cmd.find ? 'find' : name), 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Cursor.prototype.%s callback %o', name, { uuid: uuid })
        trace.end()
        return cb.apply(this, arguments)
      }
    }
  }
}
<commit_msg>Don't try to patch mongodb-core pre version 1.2.7<commit_after>'use strict'

var shimmer = require('shimmer')
var semver = require('semver')
var debug = require('debug')('opbeat')

var SERVER_FNS = ['insert', 'update', 'remove', 'auth']
var CURSOR_FNS_FIRST = ['_find', '_getmore']

module.exports = function (mongodb, agent, version) {
  if (!semver.satisfies(version, '^1.2.7')) {
    debug('mongodb-core version %s not suppoted - aborting...', version)
    return mongodb
  }

  if (mongodb.Server) {
    debug('shimming mongodb-core.Server.prototype.command')
    shimmer.wrap(mongodb.Server.prototype, 'command', wrapCommand)
    debug('shimming mongodb-core.Server.prototype functions:', SERVER_FNS)
    shimmer.massWrap(mongodb.Server.prototype, SERVER_FNS, wrapQuery)
  }

  if (mongodb.Cursor) {
    debug('shimming mongodb-core.Cursor.prototype functions:', CURSOR_FNS_FIRST)
    shimmer.massWrap(mongodb.Cursor.prototype, CURSOR_FNS_FIRST, wrapCursor)
  }

  return mongodb

  function wrapCommand (orig) {
    return function wrappedFunction (ns, cmd) {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Server.prototype.command %o', { uuid: uuid, ns: ns })

      if (trace && arguments.length > 0) {
        var index = arguments.length - 1
        var cb = arguments[index]
        if (typeof cb === 'function') {
          var type
          if (cmd.findAndModify) type = 'findAndModify'
          else if (cmd.createIndexes) type = 'createIndexes'
          else if (cmd.ismaster) type = 'ismaster'
          else if (cmd.count) type = 'count'
          else type = 'command'

          arguments[index] = wrappedCallback
          trace.start(ns + '.' + type, 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Server.prototype.command callback %o', { uuid: uuid })
        trace.end()
        return cb.apply(this, arguments)
      }
    }
  }

  function wrapQuery (orig, name) {
    return function wrappedFunction (ns) {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Server.prototype.%s %o', name, { uuid: uuid, ns: ns })

      if (trace && arguments.length > 0) {
        var index = arguments.length - 1
        var cb = arguments[index]
        if (typeof cb === 'function') {
          arguments[index] = wrappedCallback
          trace.start(ns + '.' + name, 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Server.prototype.%s callback %o', name, { uuid: uuid })
        trace.end()
        return cb.apply(this, arguments)
      }
    }
  }

  function wrapCursor (orig, name) {
    return function wrappedFunction () {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to mongodb-core.Cursor.prototype.%s %o', name, { uuid: uuid })

      if (trace && arguments.length > 0) {
        var cb = arguments[0]
        if (typeof cb === 'function') {
          arguments[0] = wrappedCallback
          trace.start(this.ns + '.' + (this.cmd.find ? 'find' : name), 'db.mongodb.query')
        }
      }

      return orig.apply(this, arguments)

      function wrappedCallback () {
        debug('intercepted mongodb-core.Cursor.prototype.%s callback %o', name, { uuid: uuid })
        trace.end()
        return cb.apply(this, arguments)
      }
    }
  }
}
<|endoftext|>