<commit_before>import classNames from 'classnames/dedupe';
import React, {PropTypes} from 'react';

import BindMixin from '../Mixin/BindMixin';
import FormControl from './FormControl';
import Util from '../Util/Util';

// Find a the options for a particular field in the form.
function findFieldOption(options, field) {
  let flattenedOptions = Util.flatten(options);
  return Util.find(flattenedOptions, function (fieldOption) {
    var isField = fieldOption.name === field;
    if (fieldOption.fieldType === 'object' && !isField) {
      return findFieldOption(fieldOption.definition, field);
    }

    return isField;
  });
}

function mergeNewModel(stateModel, currentDefinitionModel, nextDefinitionModel) {
  let newModel = {};
  let stateModelClone = Util.extend({}, stateModel);

  // This allows us to remove fields on the model, if we remove that field from
  // the definition.
  Object.keys(stateModelClone).forEach(function (modelKey) {
    if (!nextDefinitionModel.hasOwnProperty(modelKey)) {
      delete stateModelClone[modelKey];
    }
  });

  // This makes sure we only update the keys that are different.
  Object.keys(nextDefinitionModel).forEach(function (key) {
    if (currentDefinitionModel[key] !== nextDefinitionModel[key]) {
      newModel[key] = nextDefinitionModel[key];
    }
  });

  return Util.extend({}, stateModelClone, newModel);
}

class Form extends Util.mixin(BindMixin) {
  get methodsToBind() {
    return [
      'getBlurChange',
      'getOnFocusChange',
      'getValueChange',
      'handleEvent',
      'handleSubmit'
    ];
  }

  constructor() {
    super();

    this.state = {
      model: {},
      editingField: '',
      erroredFields: {}
    };

    this.submitMap = {};
  }

  componentWillMount() {
    super.componentWillMount();

    if (this.props.triggerSubmit) {
      this.props.triggerSubmit(this.handleSubmit);
    }

    this.setState({
      model: this.buildStateObj(this.props.definition, 'value'),
      erroredFields: this.buildStateObj(this.props.definition, 'showError')
    });
  }

  componentWillReceiveProps(nextProps) {
    super.componentWillReceiveProps();

    let props = this.props;
    let state = this.state;
    let nextState = {};
    let currentModel = this.buildStateObj(props.definition, 'value');
    let nextModel = this.buildStateObj(nextProps.definition, 'value');
    if (!Util.isEqual(currentModel, nextModel)) {
      nextState.model = mergeNewModel(state.model, currentModel, nextModel);
    }

    let currentErrors = this.buildStateObj(props.definition, 'showError');
    let nextErrors = this.buildStateObj(nextProps.definition, 'showError');
    if (!Util.isEqual(currentErrors, nextErrors)) {
      nextState.erroredFields = mergeNewModel(
        state.erroredFields,
        currentErrors,
        nextErrors
      );
    }

    this.setState(nextState);
  }

  handleEvent(eventType, fieldName, fieldValue, event, ...rest) {
    let eventObj = {eventType, fieldName, fieldValue, event};
    let newState = {};

    switch (eventType) {
      case 'blur':
        newState = this.getBlurChange(fieldName);
        break;
      case 'change':
        newState = this.getValueChange(fieldName, fieldValue);
        break;
      case 'focus':
        newState = this.getOnFocusChange(fieldName);
        break;
      case 'multipleChange':
        newState = this.getMultipleChange(fieldName, fieldValue);
    }

    // If there is no change to the model, just return the old one
    let newModel = newState.model || this.state.model;
    this.props.onChange(newModel, eventObj, ...rest);
    if (Object.keys(newState).length) {
      this.setState(newState);
    }
  }

  getTriggerSubmit(formKey, triggerSubmit) {
    this.submitMap[formKey] = triggerSubmit;
  }

  handleSubSubmit(formKey, model) {
    this.state.model[formKey] = model;
  }

  handleSubmit(event) {
    if (event) {
      event.preventDefault();
    }

    let model = this.state.model;
    let props = this.props;
    let validated = this.validateSubmit(
      model, props.definition
    );

    Object.keys(this.submitMap).forEach((formKey) => {
      this.submitMap[formKey]();
    });

    if (!validated) {
      props.onError();
    }

    if (validated && props.onSubmit) {
      props.onSubmit(model);
    }
  }

  getValueChange(field, value) {
    let model = Util.clone(this.state.model);
    model[field] = value;

    return {model};
  }

  getMultipleChange(field, values) {
    let model = Util.clone(this.state.model);
    model[field].forEach(function (item) {
      let {name} = item;
      if (Util.isArray(values)) {
        values.forEach(function (value) {
          // Update value in field
          if (name === value.name) {
            Util.extend(item, value);
          }
        });
      } else if (name === values.name) {
        Util.extend(item, values);
      }
    });

    return {model};
  }

  getBlurChange(field) {
    let options = findFieldOption(this.props.definition, field);

    if (options.writeType === 'input') {
      return {};
    }

    this.handleSubmit();
    return {editingField: null};
  }

  getOnFocusChange(name) {
    let fieldOption = findFieldOption(this.props.definition, name);

    if (fieldOption.writeType === 'edit') {
      return {editingField: name};
    }

    return {};
  }

  validateValue(field, value, definition) {
    let options = findFieldOption(definition, field);

    if (options == null || options.validation == null) {
      return true;
    }

    let {validation} = options;

    if (typeof validation === 'function') {
      return validation(value);
    }

    return validation.test(value);
  }

  validateSubmit(model, definition) {
    let erroredFields = {};
    let submitValidated = true;

    Object.keys(model).forEach((name) => {
      let options = findFieldOption(definition, name);
      if (options == null) {
        return true;
      }

      let fieldValue = model[name];
      let validated = this.validateValue(
        name, fieldValue, definition
      );

      if (!validated) {
        erroredFields[name] = options.validationErrorText;
        submitValidated = false;
        return;
      }

      if (options.required && (fieldValue == null || fieldValue === '')) {
        erroredFields[name] = 'Field cannot be empty.';
        submitValidated = false;
      }
    });

    erroredFields = Util.extend(
      {}, this.buildStateObj(this.props.definition, 'showError'), erroredFields
    );

    // Set the errored fields into state so we can render correctly.
    this.setState({erroredFields});

    return submitValidated;
  }

  buildStateObj(definition, fieldProp) {
    let stateObj = {};
    Util.flatten(definition).forEach((formControlOption) => {
      // If the element is a React element, then we don't want to add it to the
      // state object, which represents the form values.
      if (React.isValidElement(formControlOption)
        || formControlOption.render
        || formControlOption.fieldType === 'submit') {
        return;
      }

      if (formControlOption.fieldType === 'object') {
        stateObj[formControlOption.name] = this.buildStateObj(
          formControlOption.definition, fieldProp
        );

        return;
      }

      stateObj[formControlOption.name] = formControlOption[fieldProp] || null;
    });

    return stateObj;
  }

  buildFormPropObj(formControlOption, stateObj) {
    let name = formControlOption.name;
    let propObj = {};

    if (Util.isArray(formControlOption)) {
      formControlOption.forEach(function (option) {
        propObj[option.name] = stateObj[option.name];
      });
    } else {
      propObj[name] = stateObj[name];
    }

    return propObj;
  }

  getFormControls(definition) {
    let {props, state} = this;
    let classes = {
      formGroupClass: 'form-group',
      formGroupErrorClass: 'form-group-error',
      formRowClass: 'row',
      helpBlockClass: 'form-help-block',
      inlineIconClass: 'form-element-inline-icon',
      inlineTextClass: 'form-element-inline-text',
      inputClass: 'form-control',
      readClass: 'read-only'
    };

    Object.keys(classes).forEach(function (className) {
      classes[className] = classNames(classes[className], props[className]);
    });

    return definition.map((formControlOption, i) => {
      // If it's a React element, we just want to return it. We need to add a
      // key to the object because we're iterating over a list of items.
      if (React.isValidElement(formControlOption)) {
        return (
          <span key={i}>
            {formControlOption}
          </span>
        );
      }

      if (formControlOption.render && !formControlOption.definition) {
        return formControlOption.render();
      }

      if (formControlOption.fieldType === 'object') {
        let nestedDefinition = [formControlOption.render()]
          .concat(formControlOption.definition);

        return (
          <Form
            className={this.props.className}
            key={i}
            definition={nestedDefinition}
            triggerSubmit={this.getTriggerSubmit.bind(this, formControlOption.name)}
            onChange={this.props.onChange}
            onSubmit={this.handleSubSubmit.bind(this, formControlOption.name)}
            formTag="div" />
        );
      }

      // Map each field to showError boolean
      let showError =
        this.buildFormPropObj(formControlOption, state.erroredFields);

      // Map each field to it's current value.
      let currentValue =
        this.buildFormPropObj(formControlOption, state.model);

      return (
        <FormControl
          key={i}
          definition={formControlOption}
          editing={state.editingField}
          validationError={showError}
          currentValue={currentValue}
          handleEvent={this.handleEvent}
          handleSubmit={this.handleSubmit}
          maxColumnWidth={props.maxColumnWidth}
          {...classes} />
      );
    });
  }

  render() {
    let {className, definition, key} = this.props;
    /* eslint-disable react/jsx-no-undef */
    return (
      <this.props.formTag
        key={key}
        onSubmit={this.handleSubmit}
        className={classNames('form flush-bottom', className)}>
        {this.getFormControls(definition)}
      </this.props.formTag>
    );
    /* eslint-enable react/jsx-no-undef */
  }
}

let classPropType = React.PropTypes.oneOfType([
  React.PropTypes.array,
  React.PropTypes.object,
  React.PropTypes.string
]);

Form.defaultProps = {
  definition: {},
  formTag: 'form',
  key: '',
  maxColumnWidth: 12,
  onChange: function () {},
  onError: function () {},
  onSubmit: function () {},
  triggerSubmit: function () {}
};

Form.propTypes = {
  // Classes.
  className: classPropType,
  formGroupClass: classPropType,
  formGroupErrorClass: classPropType,
  formRowClass: classPropType,
  helpBlockClass: classPropType,
  inlineIconClass: classPropType,
  inlineTextClass: classPropType,
  inputClass: classPropType,
  readClass: classPropType,
  sharedClass: classPropType,

  formTag: PropTypes.string,
  key: PropTypes.node,

  // Form definition to build the form from. Contains either:
  // 1. Array of field definitions will be created on same row
  // 2. Field definition (object) will create a single field in that row
  definition: PropTypes.arrayOf(
    React.PropTypes.oneOfType([
      React.PropTypes.object,
      React.PropTypes.array
    ])
  ),

  // Optional number of columns in the grid
  maxColumnWidth: PropTypes.number,
  // Optional function to call on error
  onError: PropTypes.func,
  // Optional function to call on change
  onChange: PropTypes.func,
  // Optional function to call on submit
  onSubmit: PropTypes.func,
  // Optional function. Will receive a trigger function.
  // Call the trigger function, when a submit needs to be triggered externally
  triggerSubmit: PropTypes.func
};

module.exports = Form;
<commit_msg>Add useExternalErrors prop to Form<commit_after>import classNames from 'classnames/dedupe';
import React, {PropTypes} from 'react';

import BindMixin from '../Mixin/BindMixin';
import FormControl from './FormControl';
import Util from '../Util/Util';

// Find a the options for a particular field in the form.
function findFieldOption(options, field) {
  let flattenedOptions = Util.flatten(options);
  return Util.find(flattenedOptions, function (fieldOption) {
    var isField = fieldOption.name === field;
    if (fieldOption.fieldType === 'object' && !isField) {
      return findFieldOption(fieldOption.definition, field);
    }

    return isField;
  });
}

function mergeNewModel(stateModel, currentDefinitionModel, nextDefinitionModel) {
  let newModel = {};
  let stateModelClone = Util.extend({}, stateModel);

  // This allows us to remove fields on the model, if we remove that field from
  // the definition.
  Object.keys(stateModelClone).forEach(function (modelKey) {
    if (!nextDefinitionModel.hasOwnProperty(modelKey)) {
      delete stateModelClone[modelKey];
    }
  });

  // This makes sure we only update the keys that are different.
  Object.keys(nextDefinitionModel).forEach(function (key) {
    if (currentDefinitionModel[key] !== nextDefinitionModel[key]) {
      newModel[key] = nextDefinitionModel[key];
    }
  });

  return Util.extend({}, stateModelClone, newModel);
}

class Form extends Util.mixin(BindMixin) {
  get methodsToBind() {
    return [
      'getBlurChange',
      'getOnFocusChange',
      'getValueChange',
      'handleEvent',
      'handleSubmit'
    ];
  }

  constructor() {
    super();

    this.state = {
      model: {},
      editingField: '',
      erroredFields: {}
    };

    this.submitMap = {};
  }

  componentWillMount() {
    super.componentWillMount();

    if (this.props.triggerSubmit) {
      this.props.triggerSubmit(this.handleSubmit);
    }

    this.setState({
      model: this.buildStateObj(this.props.definition, 'value'),
      erroredFields: this.buildStateObj(this.props.definition, 'showError')
    });
  }

  componentWillReceiveProps(nextProps) {
    super.componentWillReceiveProps();

    let props = this.props;
    let state = this.state;
    let nextState = {};
    let currentModel = this.buildStateObj(props.definition, 'value');
    let nextModel = this.buildStateObj(nextProps.definition, 'value');
    if (!Util.isEqual(currentModel, nextModel)) {
      nextState.model = mergeNewModel(state.model, currentModel, nextModel);
    }

    if (this.props.useExternalErrors) {
      nextState.erroredFields = this.buildStateObj(nextProps.definition, 'showError');
    } else {
      let currentErrors = this.buildStateObj(props.definition, 'showError');
      let nextErrors = this.buildStateObj(nextProps.definition, 'showError');
      if (!Util.isEqual(currentErrors, nextErrors)) {
        nextState.erroredFields = mergeNewModel(
          state.erroredFields,
          currentErrors,
          nextErrors
        );
      }
    }

    this.setState(nextState);
  }

  handleEvent(eventType, fieldName, fieldValue, event, ...rest) {
    let eventObj = {eventType, fieldName, fieldValue, event};
    let newState = {};

    switch (eventType) {
      case 'blur':
        newState = this.getBlurChange(fieldName);
        break;
      case 'change':
        newState = this.getValueChange(fieldName, fieldValue);
        break;
      case 'focus':
        newState = this.getOnFocusChange(fieldName);
        break;
      case 'multipleChange':
        newState = this.getMultipleChange(fieldName, fieldValue);
    }

    // If there is no change to the model, just return the old one
    let newModel = newState.model || this.state.model;
    this.props.onChange(newModel, eventObj, ...rest);
    if (Object.keys(newState).length) {
      this.setState(newState);
    }
  }

  getTriggerSubmit(formKey, triggerSubmit) {
    this.submitMap[formKey] = triggerSubmit;
  }

  handleSubSubmit(formKey, model) {
    this.state.model[formKey] = model;
  }

  handleSubmit(event) {
    if (event) {
      event.preventDefault();
    }

    let model = this.state.model;
    let props = this.props;
    let validated = this.validateSubmit(
      model, props.definition
    );

    Object.keys(this.submitMap).forEach((formKey) => {
      this.submitMap[formKey]();
    });

    if (!validated) {
      props.onError();
    }

    if (validated && props.onSubmit) {
      props.onSubmit(model);
    }
  }

  getValueChange(field, value) {
    let model = Util.clone(this.state.model);
    model[field] = value;

    return {model};
  }

  getMultipleChange(field, values) {
    let model = Util.clone(this.state.model);
    model[field].forEach(function (item) {
      let {name} = item;
      if (Util.isArray(values)) {
        values.forEach(function (value) {
          // Update value in field
          if (name === value.name) {
            Util.extend(item, value);
          }
        });
      } else if (name === values.name) {
        Util.extend(item, values);
      }
    });

    return {model};
  }

  getBlurChange(field) {
    let options = findFieldOption(this.props.definition, field);

    if (options.writeType === 'input') {
      return {};
    }

    this.handleSubmit();
    return {editingField: null};
  }

  getOnFocusChange(name) {
    let fieldOption = findFieldOption(this.props.definition, name);

    if (fieldOption.writeType === 'edit') {
      return {editingField: name};
    }

    return {};
  }

  validateValue(field, value, definition) {
    let options = findFieldOption(definition, field);

    if (options == null || options.validation == null) {
      return true;
    }

    let {validation} = options;

    if (typeof validation === 'function') {
      return validation(value);
    }

    return validation.test(value);
  }

  validateSubmit(model, definition) {
    let erroredFields = {};
    let submitValidated = true;

    Object.keys(model).forEach((name) => {
      let options = findFieldOption(definition, name);
      if (options == null) {
        return true;
      }

      let fieldValue = model[name];
      let validated = this.validateValue(
        name, fieldValue, definition
      );

      if (!validated) {
        erroredFields[name] = options.validationErrorText;
        submitValidated = false;
        return;
      }

      if (options.required && (fieldValue == null || fieldValue === '')) {
        erroredFields[name] = 'Field cannot be empty.';
        submitValidated = false;
      }
    });

    erroredFields = Util.extend(
      {}, this.buildStateObj(this.props.definition, 'showError'), erroredFields
    );

    // Set the errored fields into state so we can render correctly.
    this.setState({erroredFields});

    return submitValidated;
  }

  buildStateObj(definition, fieldProp) {
    let stateObj = {};
    Util.flatten(definition).forEach((formControlOption) => {
      // If the element is a React element, then we don't want to add it to the
      // state object, which represents the form values.
      if (React.isValidElement(formControlOption)
        || formControlOption.render
        || formControlOption.fieldType === 'submit') {
        return;
      }

      if (formControlOption.fieldType === 'object') {
        stateObj[formControlOption.name] = this.buildStateObj(
          formControlOption.definition, fieldProp
        );

        return;
      }

      stateObj[formControlOption.name] = formControlOption[fieldProp] || null;
    });

    return stateObj;
  }

  buildFormPropObj(formControlOption, stateObj) {
    let name = formControlOption.name;
    let propObj = {};

    if (Util.isArray(formControlOption)) {
      formControlOption.forEach(function (option) {
        propObj[option.name] = stateObj[option.name];
      });
    } else {
      propObj[name] = stateObj[name];
    }

    return propObj;
  }

  getFormControls(definition) {
    let {props, state} = this;
    let classes = {
      formGroupClass: 'form-group',
      formGroupErrorClass: 'form-group-error',
      formRowClass: 'row',
      helpBlockClass: 'form-help-block',
      inlineIconClass: 'form-element-inline-icon',
      inlineTextClass: 'form-element-inline-text',
      inputClass: 'form-control',
      readClass: 'read-only'
    };

    Object.keys(classes).forEach(function (className) {
      classes[className] = classNames(classes[className], props[className]);
    });

    return definition.map((formControlOption, i) => {
      // If it's a React element, we just want to return it. We need to add a
      // key to the object because we're iterating over a list of items.
      if (React.isValidElement(formControlOption)) {
        return (
          <span key={i}>
            {formControlOption}
          </span>
        );
      }

      if (formControlOption.render && !formControlOption.definition) {
        return formControlOption.render();
      }

      if (formControlOption.fieldType === 'object') {
        let nestedDefinition = [formControlOption.render()]
          .concat(formControlOption.definition);

        return (
          <Form
            className={this.props.className}
            key={i}
            definition={nestedDefinition}
            triggerSubmit={this.getTriggerSubmit.bind(this, formControlOption.name)}
            onChange={this.props.onChange}
            onSubmit={this.handleSubSubmit.bind(this, formControlOption.name)}
            formTag="div" />
        );
      }

      // Map each field to showError boolean
      let showError =
        this.buildFormPropObj(formControlOption, state.erroredFields);

      // Map each field to it's current value.
      let currentValue =
        this.buildFormPropObj(formControlOption, state.model);

      return (
        <FormControl
          key={i}
          definition={formControlOption}
          editing={state.editingField}
          validationError={showError}
          currentValue={currentValue}
          handleEvent={this.handleEvent}
          handleSubmit={this.handleSubmit}
          maxColumnWidth={props.maxColumnWidth}
          {...classes} />
      );
    });
  }

  render() {
    let {className, definition, key} = this.props;
    /* eslint-disable react/jsx-no-undef */
    return (
      <this.props.formTag
        key={key}
        onSubmit={this.handleSubmit}
        className={classNames('form flush-bottom', className)}>
        {this.getFormControls(definition)}
      </this.props.formTag>
    );
    /* eslint-enable react/jsx-no-undef */
  }
}

let classPropType = React.PropTypes.oneOfType([
  React.PropTypes.array,
  React.PropTypes.object,
  React.PropTypes.string
]);

Form.defaultProps = {
  definition: {},
  formTag: 'form',
  key: '',
  maxColumnWidth: 12,
  onChange: function () {},
  onError: function () {},
  onSubmit: function () {},
  triggerSubmit: function () {}
};

Form.propTypes = {
  // Classes.
  className: classPropType,
  formGroupClass: classPropType,
  formGroupErrorClass: classPropType,
  formRowClass: classPropType,
  helpBlockClass: classPropType,
  inlineIconClass: classPropType,
  inlineTextClass: classPropType,
  inputClass: classPropType,
  readClass: classPropType,
  sharedClass: classPropType,

  formTag: PropTypes.string,
  key: PropTypes.node,

  // Form definition to build the form from. Contains either:
  // 1. Array of field definitions will be created on same row
  // 2. Field definition (object) will create a single field in that row
  definition: PropTypes.arrayOf(
    React.PropTypes.oneOfType([
      React.PropTypes.object,
      React.PropTypes.array
    ])
  ),

  // Optional number of columns in the grid
  maxColumnWidth: PropTypes.number,
  // Optional function to call on error
  onError: PropTypes.func,
  // Optional function to call on change
  onChange: PropTypes.func,
  // Optional function to call on submit
  onSubmit: PropTypes.func,
  // Optional function. Will receive a trigger function.
  // Call the trigger function, when a submit needs to be triggered externally
  triggerSubmit: PropTypes.func,
  // If set to true, errors will be completely driven from the form definition.
  useExternalErrors: PropTypes.bool
};

module.exports = Form;
<|endoftext|>


<commit_before>var currentTestName = "";
var currentSteps = [];
var currentStepIndex = 0;

var testCases = [];
var currentlyExecutingTest = 0;

var testMode = "manual";      // can be "auto", "recursive"
var runMode = "interactive";  // can be "batch"

var snapshotPrefix = "";
var snapshotIndex = 0;

var advanceKey = "n";

TestCase = function (name, path, func) {
    this.name = name;
    this.path = path;
    this.func = func;
}

var currentTestCase = null;
var usePrimaryCamera = false;
var currentRecursiveTestCompleted = false;

//returns n as a string, padded to length characters with the character ch
function pad(n, length, ch) {
  ch = ch || '0';  // default is '0'
  n += '';         // convert n to string

  // returns n as is, if it is too long
  return (n.length >= length) ? n : new Array(length - n.length + 1).join(ch) + n;
}

var runOneStep = function (stepFunctor, stepIndex) {
    print("Running step " + (stepIndex + 1) + "/" + (currentSteps.length) +": " + stepFunctor.name);
    Window.displayAnnouncement("Running step " + (stepIndex + 1) + "/" + (currentSteps.length) +": " + stepFunctor.name);

    if (stepFunctor.func !== undefined) {
        stepFunctor.func();
    }

    // Not quite sure this is the definitive solution here because of the snapshot bug latency issue.
    // but this seems to work ok if the snapshot is a separate step
    if ((stepFunctor.snap !== undefined) && stepFunctor.snap) {
        print("Taking snapshot " + (stepIndex + 1));

        // Image numbers are padded to 5 digits
        // Changing this number requires changing the auto-tester C++ code!
        var NUM_DIGITS = 5;
        var currentSnapshotName = snapshotPrefix + pad(snapshotIndex, NUM_DIGITS, '0');;
        usePrimaryCamera ? Window.takeSnapshot(false, false, 0.0, currentSnapshotName) : Window.takeSecondaryCameraSnapshot(currentSnapshotName);
        ++snapshotIndex;
    }
}

var runNextStep = function () {
    // Run next step and increment only if there is one more
    if (currentStepIndex < currentSteps.length) {
        runOneStep(currentSteps[currentStepIndex], currentStepIndex);
        currentStepIndex++;
    }

    // Return true to go on or false if done
    return (currentStepIndex < currentSteps.length);
}

var testOver = function() {
    if (testMode === "manual") {
        Controller.keyPressEvent.disconnect(onKeyPressEventNextStep);
        Window.displayAnnouncement("Test " + currentTestName + " have been completed");
    }

    print("Test is over: " + currentTestName);

    currentSteps = [];
    currentStepIndex = 0;
    currentTestName = "";
    currentTestCase = null;

    print("runmode: " + runMode);
    print("testmode: " + testMode);

    if (runMode === "batch" && testMode === "auto") {
        print("Waiting to die");
        Script.setTimeout(function () { Test.quit(); }, 2000);
    } else if (testMode === "manual" || testMode === "auto") {
        Script.stop();
    } else { // testMode === "recursive"
        currentRecursiveTestCompleted = true;
    }
}

var autoTimeStep = 2000;

var onRunAutoNext = function() {
    // run the step...
    if (!runNextStep()) {
        testOver();
        return;
    }

    // and call itself after next timer
    Script.setTimeout(
        onRunAutoNext,
        autoTimeStep
    );
}

var onRunAuto = function() {
    // run the next step after next timer
    var STEP_TIME = 2000;
    Script.setTimeout(
        onRunAutoNext,
        STEP_TIME
    );
}

var onKeyPressEventNextStep = function (event) {
    if (String.fromCharCode(event.key) == advanceKey.toUpperCase()) {
        if (!runNextStep()) {
            testOver();
        }
    }
}

var onRunManual = function() {
    Window.displayAnnouncement(
        "Ready to run test " + currentTestName + "\n" +
        currentSteps.length + " steps\nPress " + "'" + advanceKey + "'" + " for next steps");

    Controller.keyPressEvent.connect( onKeyPressEventNextStep );
}

// Add Steps to the test case
var doAddStep = function (name, stepFunction, snapshot) {
    currentSteps.push({"index": currentSteps.length, "name": name, "func": stepFunction, "snap": snapshot })
    print("PUSHING STEP" + currentSteps.length);
}

// The following are exported methods, accessible to test scripts

// Perform is the main method of a test
//      testName - name of the test
//      testPath - path the test is executing in
//      testMain - a function that creates the test
//
// The method creates a test case in currentTestCase.
// If the test mode is manual or auto then its execution is started
module.exports.perform = function (testName, testPath, testMain) {
    currentTestCase = new TestCase(testName, testPath, testMain);

    // Manual and auto tests are run immediately, recursive tests are stored in a queue
    if (testMode === "manual") {
        print("Begin manual test:" + testName);
        currentTestCase.func("manual");
    } else if (testMode === "auto") {
        print("Begin auto test:" + testName);
        currentTestCase.func("auto");
    } else {
        print("Not running yet - in recursive mode");
        testCases.push(currentTestCase);
    }
}

module.exports.setupTest = function (primaryCamera) {
    if (currentTestCase === null) {
        return;
    }

    // Clear the test case steps
    currentSteps = [];
    currentStepIndex = 0;
    currentTestName = currentTestCase.name;

    print("Setup test - " + currentTestName);

    // Hide the avatar
    MyAvatar.setEnableMeshVisible(false);

    // Zero the head position
    MyAvatar.bodyYaw =   0.0;
    MyAvatar.bodyPitch = 0.0;
    MyAvatar.bodyRoll =  0.0;
    MyAvatar.headYaw =   0.0;
    MyAvatar.headPitch = 0.0;
    MyAvatar.headRoll =  0.0;

    // resolvePath(".") returns a string that looks like "file:/" + <current folder>
    // We need the current folder
    var path = currentTestCase.path.substring(currentTestCase.path.indexOf(":") + 4);
    var pathParts = path.split("/");

    // Snapshots are saved in the user-selected folder
    // For a test running from D:/GitHub/hifi-tests/tests/content/entity/zone/create/tests.js
    // the tests are named D_GitHub_hifi-tests_tests_content_entity_zone_create_0.jpg and so on
    // Date and time are not used as part of the name, to keep the path lengths to a minimum
    // (the Windows API limit is 260 characters).
    //
    snapshotPrefix = "";

    // On Windows the first part is <disk>: - this is changed
    var str = pathParts[0];
    if (str.indexOf(":") !== -1) {
        snapshotPrefix = str.replace(":", "").toUpperCase();
    }

    for (var i = 1; i < pathParts.length; ++i) {
        str = pathParts[i];

        // Replace any spaces
        str = str.replace(" ", "__");

        snapshotPrefix += "_" + str;
    }

    snapshotIndex = 0;

    var spectatorCameraConfig = Render.getConfig("SecondaryCamera");
    spectatorCameraConfig.enableSecondaryCameraRenderConfigs(true);
    spectatorCameraConfig.resetSizeSpectatorCamera(1920, 1080);
    spectatorCameraConfig.vFoV = 45;
    Render.getConfig("SecondaryCameraJob.ToneMapping").curve = 0;

    // Configure the secondary camera
    spectatorCameraConfig.position = {x: MyAvatar.position.x, y: MyAvatar.position.y + 0.6, z: MyAvatar.position.z};
    spectatorCameraConfig.orientation = MyAvatar.orientation;

    if (primaryCamera) {
        usePrimaryCamera = true;
    }

    return spectatorCameraConfig;
}

// Add steps to the test case, take snapshot if 3rd parameter is true
module.exports.addStep = function (name, stepFunction) {
    doAddStep(name, stepFunction, false);
}

// Add steps to the test case, take snapshot
module.exports.addStepSnapshot = function (name, stepFunction) {
    doAddStep(name, stepFunction, true);
}

// The default mode is manual
// The default time between test steps may be modified through these methods
module.exports.enableAuto = function (timeStep) {
    testMode = "auto";
    if (timeStep) {
        autoTimeStep = timeStep;
    }
    print("TEST MODE AUTO SELECTED");
}

module.exports.enableRecursive = function (timeStep) {
    testMode = "recursive";
    if (timeStep) {
        autoTimeStep = timeStep;
    }
    print("TEST MODE RECURSIVE SELECTED");
}

module.exports.enableBatch = function () {
    runMode = "batch";
}

// Steps is an array of functions; each function being a test step
module.exports.runTest = function (testType) {
    // In recursive mode, this call is ignored
    if (testType  === "auto") {
        onRunAuto();
    } else if (testType === "manual") {
        onRunManual();
    }
}

module.exports.runRecursive = function () {
    print("Starting recursive tests");

    currentRecursiveTestCompleted = true;
    var STEP_TIME = 2000;
    Script.setInterval(
        function () {
            if (currentRecursiveTestCompleted) {
                currentRecursiveTestCompleted = false;
                if (testCases.length > 0) {
                    currentTestCase = testCases.pop();
                    currentTestCase.func("auto");
                } else {
                    print("Recursive tests complete");
                    Script.stop();
                }
            }
        },
        STEP_TIME
    );
}

//module.exports.assertPlatform = function (listOfRequiredPlatforms) {
//    // Find our OS
//    var platform = "Unknown";
//    if (Window.isWindows64()) {
//        platform = "WINDOWS64";
//    } else if (Window.isMacOs()) {
//        platform = "MACOS";
//    } else if (Window.isLinux()) {
//        platform = "LINUX";
//    } else if (Window.isAndroid()) {
//        platform = "ANDROID";
//    }
//
//    // requiredPlatforms will contain the list of required platforms, and possibly some extra spaces
//    // (the spaces have no effect)
//    var requiredPlatforms = listOfRequiredPlatforms.split(" ");
//
//    var platformOK = false;
//    for (var requiredPlatform in requiredPlatforms) {
//        if (requiredPlatform.toUpperCase() === platform) {
//            platformOK = true;
//            break;
//        }
//    }
//
//    if (!platformOK) {
//        var errorMessage = "TEST IS NOT SUPPORTED ON THIS PLATFORM!!!";
//        print(errorMessage);
//        Window.displayAnnouncement(errorMessage);
//        Script.stop();
//    }
//}
//
//module.exports.assertDisplay = function (listOfRequiredDisplays) {
//    // Find our display
//    var display = "DESKTOP";
//    if (Window.hasRift()) {
//        display = "RIFT";
//    } else if (Window.hasVive()) {
//        display = "VIVE";
//    }
//
//    // requiredDisplays will contain the list of required displays, and possibly some extra spaces
//    // (the spaces have no effect)
//    var requiredDisplays = listOfRequiredDisplays.split(" ");
//
//    var displayOK = false;
//    for (var requiredDisplay in requiredDisplays) {
//        // The Rift is often called by the manufacturer's name
//        if (requiredDisplay.toUpperCase() == "OCULUS") {
//            requiredDisplay = "RIFT";
//        }
//
//        if (requiredDisplay.toUpperCase() === display) {
//            displayOK = true;
//            break;
//        }
//    }
//
//    if (!displayOK) {
//        var errorMessage = "TEST IS NOT SUPPORTED ON THIS DISPLAY!!!";
//        print(errorMessage);
//        Window.displayAnnouncement(errorMessage);
//        Script.stop();
//    }
//}
//
//module.exports.assertCPUType = function (listOfRequiredCPUs) {
//    // Find our CPU
//    var CPU = "I5";
//    if (Window.isI7()) {
//        CPU = "I7";
//    }
//
//    // requiredCPUs will contain the list of required displays, and possibly some extra spaces
//    // (the spaces have no effect)
//    var requiredCPUs = listOfRequiredCPUs.split(" ");
//
//    var cpuOK = false;
//    for (var requiredCPU in requiredCPUs) {
//        if (requiredCPU === CPU) {
//            cpuOK = true;
//            break;
//        }
//    }
//
//    if (!cpuOK) {
//        var errorMessage = "TEST IS NOT SUPPORTED ON THIS CPU!!!";
//        print(errorMessage);
//        Window.displayAnnouncement(errorMessage);
//        Script.stop();
//    }
//}
//
//module.exports.assertGPUType = function (listOfRequiredGPUs) {
//    // Find our GPU
//    var GPU = "AMD";
//    if (Window.isNvidia()) {
//        GPU = "I7";
//    }
//
//    // requiredGPUs will contain the list of required GPUs, and possibly some extra spaces
//    // (the spaces have no effect)
//    var requiredGPUs = listOfRequiredGPUs.split(" ");
//
//    var gpuOK = false;
//    for (var requiredGPU in requiredGPUs) {
//        if (requiredGPU.toUpperCase() === GPU) {
//            gpuOK = true;
//            break;
//        }
//    }
//
//    if (!gpuOK) {
//        var errorMessage = "TEST IS NOT SUPPORTED ON THIS GPU!!!";
//        print(errorMessage);
//        Window.displayAnnouncement(errorMessage);
//        Script.stop();
//    }
//}
<commit_msg>Separated recursive and auto modes.<commit_after>var currentTestName = "";
var currentSteps = [];
var currentStepIndex = 0;

var testCases = [];
var currentlyExecutingTest = 0;

var testMode = "manual";      // can be "auto"
var runMode = "interactive";  // can be "batch"
var isRecursive = false;

var snapshotPrefix = "";
var snapshotIndex = 0;

var advanceKey = "n";

TestCase = function (name, path, func) {
    this.name = name;
    this.path = path;
    this.func = func;
}

var currentTestCase = null;
var usePrimaryCamera = false;
var currentRecursiveTestCompleted = false;

//returns n as a string, padded to length characters with the character ch
function pad(n, length, ch) {
  ch = ch || '0';  // default is '0'
  n += '';         // convert n to string

  // returns n as is, if it is too long
  return (n.length >= length) ? n : new Array(length - n.length + 1).join(ch) + n;
}

var runOneStep = function (stepFunctor, stepIndex) {
    print("Running step " + (stepIndex + 1) + "/" + (currentSteps.length) +": " + stepFunctor.name);
    Window.displayAnnouncement("Running step " + (stepIndex + 1) + "/" + (currentSteps.length) +": " + stepFunctor.name);

    if (stepFunctor.func !== undefined) {
        stepFunctor.func();
    }

    // Not quite sure this is the definitive solution here because of the snapshot bug latency issue.
    // but this seems to work ok if the snapshot is a separate step
    if ((stepFunctor.snap !== undefined) && stepFunctor.snap) {
        print("Taking snapshot " + (stepIndex + 1));

        // Image numbers are padded to 5 digits
        // Changing this number requires changing the auto-tester C++ code!
        var NUM_DIGITS = 5;
        var currentSnapshotName = snapshotPrefix + pad(snapshotIndex, NUM_DIGITS, '0');;
        usePrimaryCamera ? Window.takeSnapshot(false, false, 0.0, currentSnapshotName) : Window.takeSecondaryCameraSnapshot(currentSnapshotName);
        ++snapshotIndex;
    }
}

var runNextStep = function () {
    // Run next step and increment only if there is one more
    if (currentStepIndex < currentSteps.length) {
        runOneStep(currentSteps[currentStepIndex], currentStepIndex);
        currentStepIndex++;
    }

    // Return true to go on or false if done
    return (currentStepIndex < currentSteps.length);
}

var testOver = function() {
    if (testMode === "manual") {
        Controller.keyPressEvent.disconnect(onKeyPressEventNextStep);
        Window.displayAnnouncement("Test " + currentTestName + " have been completed");
    }

    print("Test is over: " + currentTestName);

    currentSteps = [];
    currentStepIndex = 0;
    currentTestName = "";
    currentTestCase = null;

    if (isRecursive) {
        currentRecursiveTestCompleted = true;
    } else if (runMode === "batch" && testMode === "auto") {
        // Exit interface
        print("Waiting to die");
        Script.setTimeout(function () { Test.quit(); }, 2000);
    } else {
        // Just stop the script
        Script.stop();
    }
}

var autoTimeStep = 2000;

var onRunAutoNext = function() {
    // run the step...
    if (!runNextStep()) {
        testOver();
        return;
    }

    // and call itself after next timer
    Script.setTimeout(
        onRunAutoNext,
        autoTimeStep
    );
}

var onRunAuto = function() {
    // run the next step after next timer
    var STEP_TIME = 2000;
    Script.setTimeout(
        onRunAutoNext,
        STEP_TIME
    );
}

var onKeyPressEventNextStep = function (event) {
    if (String.fromCharCode(event.key) == advanceKey.toUpperCase()) {
        if (!runNextStep()) {
            testOver();
        }
    }
}

var onRunManual = function() {
    Window.displayAnnouncement(
        "Ready to run test " + currentTestName + "\n" +
        currentSteps.length + " steps\nPress " + "'" + advanceKey + "'" + " for next steps");

    Controller.keyPressEvent.connect( onKeyPressEventNextStep );
}

// Add Steps to the test case
var doAddStep = function (name, stepFunction, snapshot) {
    currentSteps.push({"index": currentSteps.length, "name": name, "func": stepFunction, "snap": snapshot })
    print("PUSHING STEP" + currentSteps.length);
}

// The following are exported methods, accessible to test scripts

// Perform is the main method of a test
//      testName - name of the test
//      testPath - path the test is executing in
//      testMain - a function that creates the test
//
// The method creates a test case in currentTestCase.
// If the test mode is manual or auto then its execution is started
module.exports.perform = function (testName, testPath, testMain) {
    currentTestCase = new TestCase(testName, testPath, testMain);

    // Manual and auto tests are run immediately, recursive tests are stored in a queue
    if (isRecursive) {
        print("Not running yet - in recursive mode");
        testCases.push(currentTestCase);
    } else if (testMode === "manual") {
        print("Begin manual test:" + testName);
        currentTestCase.func("manual");
    } else { // testMode === "auto"
        print("Begin auto test:" + testName);
        currentTestCase.func("auto");
    }
}

module.exports.setupTest = function (primaryCamera) {
    if (currentTestCase === null) {
        return;
    }

    // Clear the test case steps
    currentSteps = [];
    currentStepIndex = 0;
    currentTestName = currentTestCase.name;

    print("Setup test - " + currentTestName);

    // Hide the avatar
    MyAvatar.setEnableMeshVisible(false);

    // Zero the head position
    MyAvatar.bodyYaw =   0.0;
    MyAvatar.bodyPitch = 0.0;
    MyAvatar.bodyRoll =  0.0;
    MyAvatar.headYaw =   0.0;
    MyAvatar.headPitch = 0.0;
    MyAvatar.headRoll =  0.0;

    // resolvePath(".") returns a string that looks like "file:/" + <current folder>
    // We need the current folder
    var path = currentTestCase.path.substring(currentTestCase.path.indexOf(":") + 4);
    var pathParts = path.split("/");

    // Snapshots are saved in the user-selected folder
    // For a test running from D:/GitHub/hifi-tests/tests/content/entity/zone/create/tests.js
    // the tests are named D_GitHub_hifi-tests_tests_content_entity_zone_create_0.jpg and so on
    // Date and time are not used as part of the name, to keep the path lengths to a minimum
    // (the Windows API limit is 260 characters).
    //
    snapshotPrefix = "";

    // On Windows the first part is <disk>: - this is changed
    var str = pathParts[0];
    if (str.indexOf(":") !== -1) {
        snapshotPrefix = str.replace(":", "").toUpperCase();
    }

    for (var i = 1; i < pathParts.length; ++i) {
        str = pathParts[i];

        // Replace any spaces
        str = str.replace(" ", "__");

        snapshotPrefix += "_" + str;
    }

    snapshotIndex = 0;

    var spectatorCameraConfig = Render.getConfig("SecondaryCamera");
    spectatorCameraConfig.enableSecondaryCameraRenderConfigs(true);
    spectatorCameraConfig.resetSizeSpectatorCamera(1920, 1080);
    spectatorCameraConfig.vFoV = 45;
    Render.getConfig("SecondaryCameraJob.ToneMapping").curve = 0;

    // Configure the secondary camera
    spectatorCameraConfig.position = {x: MyAvatar.position.x, y: MyAvatar.position.y + 0.6, z: MyAvatar.position.z};
    spectatorCameraConfig.orientation = MyAvatar.orientation;

    if (primaryCamera) {
        usePrimaryCamera = true;
    }

    return spectatorCameraConfig;
}

// Add steps to the test case, take snapshot if 3rd parameter is true
module.exports.addStep = function (name, stepFunction) {
    doAddStep(name, stepFunction, false);
}

// Add steps to the test case, take snapshot
module.exports.addStepSnapshot = function (name, stepFunction) {
    doAddStep(name, stepFunction, true);
}

// The default mode is manual
// The default time between test steps may be modified through these methods
module.exports.enableAuto = function (timeStep) {
    testMode = "auto";
    if (timeStep) {
        autoTimeStep = timeStep;
    }
    print("TEST MODE AUTO SELECTED");
}

module.exports.enableRecursive = function (timeStep) {
    isRecursive = true;
    if (timeStep) {
        autoTimeStep = timeStep;
    }
    print("TEST MODE RECURSIVE SELECTED");
}

module.exports.enableBatch = function () {
    runMode = "batch";
}

// Steps is an array of functions; each function being a test step
module.exports.runTest = function (testType) {
    // In recursive mode, this call is ignored
    if (isRecursive) {
        return;
    }

    if (testType  === "auto") {
        onRunAuto();
    } else if (testType === "manual") {
        onRunManual();
    }
}

module.exports.runRecursive = function () {
    print("Starting recursive tests");

    currentRecursiveTestCompleted = true;
    var STEP_TIME = 2000;
    Script.setInterval(
        function () {
            if (currentRecursiveTestCompleted) {
                currentRecursiveTestCompleted = false;
                if (testCases.length > 0) {
                    currentTestCase = testCases.pop();
                    currentTestCase.func("auto");
                } else {
                    print("Recursive tests complete");
                    Script.stop();
                }
            }
        },
        STEP_TIME
    );
}

//module.exports.assertPlatform = function (listOfRequiredPlatforms) {
//    // Find our OS
//    var platform = "Unknown";
//    if (Window.isWindows64()) {
//        platform = "WINDOWS64";
//    } else if (Window.isMacOs()) {
//        platform = "MACOS";
//    } else if (Window.isLinux()) {
//        platform = "LINUX";
//    } else if (Window.isAndroid()) {
//        platform = "ANDROID";
//    }
//
//    // requiredPlatforms will contain the list of required platforms, and possibly some extra spaces
//    // (the spaces have no effect)
//    var requiredPlatforms = listOfRequiredPlatforms.split(" ");
//
//    var platformOK = false;
//    for (var requiredPlatform in requiredPlatforms) {
//        if (requiredPlatform.toUpperCase() === platform) {
//            platformOK = true;
//            break;
//        }
//    }
//
//    if (!platformOK) {
//        var errorMessage = "TEST IS NOT SUPPORTED ON THIS PLATFORM!!!";
//        print(errorMessage);
//        Window.displayAnnouncement(errorMessage);
//        Script.stop();
//    }
//}
//
//module.exports.assertDisplay = function (listOfRequiredDisplays) {
//    // Find our display
//    var display = "DESKTOP";
//    if (Window.hasRift()) {
//        display = "RIFT";
//    } else if (Window.hasVive()) {
//        display = "VIVE";
//    }
//
//    // requiredDisplays will contain the list of required displays, and possibly some extra spaces
//    // (the spaces have no effect)
//    var requiredDisplays = listOfRequiredDisplays.split(" ");
//
//    var displayOK = false;
//    for (var requiredDisplay in requiredDisplays) {
//        // The Rift is often called by the manufacturer's name
//        if (requiredDisplay.toUpperCase() == "OCULUS") {
//            requiredDisplay = "RIFT";
//        }
//
//        if (requiredDisplay.toUpperCase() === display) {
//            displayOK = true;
//            break;
//        }
//    }
//
//    if (!displayOK) {
//        var errorMessage = "TEST IS NOT SUPPORTED ON THIS DISPLAY!!!";
//        print(errorMessage);
//        Window.displayAnnouncement(errorMessage);
//        Script.stop();
//    }
//}
//
//module.exports.assertCPUType = function (listOfRequiredCPUs) {
//    // Find our CPU
//    var CPU = "I5";
//    if (Window.isI7()) {
//        CPU = "I7";
//    }
//
//    // requiredCPUs will contain the list of required displays, and possibly some extra spaces
//    // (the spaces have no effect)
//    var requiredCPUs = listOfRequiredCPUs.split(" ");
//
//    var cpuOK = false;
//    for (var requiredCPU in requiredCPUs) {
//        if (requiredCPU === CPU) {
//            cpuOK = true;
//            break;
//        }
//    }
//
//    if (!cpuOK) {
//        var errorMessage = "TEST IS NOT SUPPORTED ON THIS CPU!!!";
//        print(errorMessage);
//        Window.displayAnnouncement(errorMessage);
//        Script.stop();
//    }
//}
//
//module.exports.assertGPUType = function (listOfRequiredGPUs) {
//    // Find our GPU
//    var GPU = "AMD";
//    if (Window.isNvidia()) {
//        GPU = "I7";
//    }
//
//    // requiredGPUs will contain the list of required GPUs, and possibly some extra spaces
//    // (the spaces have no effect)
//    var requiredGPUs = listOfRequiredGPUs.split(" ");
//
//    var gpuOK = false;
//    for (var requiredGPU in requiredGPUs) {
//        if (requiredGPU.toUpperCase() === GPU) {
//            gpuOK = true;
//            break;
//        }
//    }
//
//    if (!gpuOK) {
//        var errorMessage = "TEST IS NOT SUPPORTED ON THIS GPU!!!";
//        print(errorMessage);
//        Window.displayAnnouncement(errorMessage);
//        Script.stop();
//    }
//}
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache 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
//
//     https://www.apache.org/licenses/LICENSE-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.

'use strict';

function main(projectId = 'YOUR_PROJECT_ID', location = 'global') {
  // [START translate_v3_get_supported_languages]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate');

  // Instantiates a client
  const translationClient = new TranslationServiceClient();

  async function getSupportedLanguages() {
    // Construct request
    const request = {
      parent: `projects/${projectId}/locations/${location}`,
    };

    // Get supported languages
    const [response] = await translationClient.getSupportedLanguages(request);

    for (const language of response.languages) {
      // Supported language code, generally consisting of its ISO 639-1 identifier, for
      // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
      // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
      console.log(`Language - Language Code: ${language.languageCode}`);
      // Human readable name of the language localized in the display language specified
      // in the request.
      console.log(`Language - Display Name: ${language.displayName}`);
      // Can be used as source language.
      console.log(`Language - Support Source: ${language.supportSource}`);
      // Can be used as target language.
      console.log(`Language - Support Target: ${language.supportTarget}`);
    }
  }

  getSupportedLanguages();
  // [END translate_v3_get_supported_languages]
}

main(...process.argv.slice(2));
<commit_msg>fix: removed display_name from sample<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache 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
//
//     https://www.apache.org/licenses/LICENSE-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.

'use strict';

function main(projectId = 'YOUR_PROJECT_ID', location = 'global') {
  // [START translate_v3_get_supported_languages]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'global';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate');

  // Instantiates a client
  const translationClient = new TranslationServiceClient();

  async function getSupportedLanguages() {
    // Construct request
    const request = {
      parent: `projects/${projectId}/locations/${location}`,
    };

    // Get supported languages
    const [response] = await translationClient.getSupportedLanguages(request);

    for (const language of response.languages) {
      // Supported language code, generally consisting of its ISO 639-1 identifier, for
      // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
      // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
      console.log(`Language - Language Code: ${language.languageCode}`);
      // Can be used as source language.
      console.log(`Language - Support Source: ${language.supportSource}`);
      // Can be used as target language.
      console.log(`Language - Support Target: ${language.supportTarget}`);
    }
  }

  getSupportedLanguages();
  // [END translate_v3_get_supported_languages]
}

main(...process.argv.slice(2));
<|endoftext|>


<commit_before>const appId = "r4yeksa5";

window.intercomSettings = {
  app_id: appId
};

(function(){
  var w=window;
  var ic=w.Intercom;
  if(typeof ic==="function") {
    ic('reattach_activator');
    ic('update',intercomSettings);
  }else{
    var d=document;
    var i=function(){i.c(arguments)};
    i.q=[];
    i.c=function(args){i.q.push(args)};
    w.Intercom=i;
    function l(){
      var s=d.createElement('script');
      s.type='text/javascript';
      s.async=true;
      s.src='https://widget.intercom.io/widget/' + appId;
      var x=d.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s,x);
    }
    if(w.attachEvent){w.attachEvent('onload',l);
  }
  else{
    w.addEventListener('load',l,false);}
  }
})();

window.Intercom('boot', window.intercomSettings);
<commit_msg>Updated Javascript function<commit_after>const appId = "r4yeksa5";

window.intercomSettings = {
  app_id: appId
};

(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/' + appId;var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()

window.Intercom('boot', window.intercomSettings);
<|endoftext|>


<commit_before>/*
 *
 * A simple constraint satisfaction problem solver in Javascript.
 *
 */
module('users.timfelgentreff.csp.csp').requires().toRun(function() {

JSLoader.loadJs(module('users.timfelgentreff.csp.underscore-min').uri());

var util = {
    mixin: function(target, src) {
      for (var name in src) {
        if (src.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
          target[name] = src[name];
        }
      }
    },
    hashcopy: function(obj) {
      var ret = obj.constructor();
      for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
          ret[p] = obj[p];
        }
      }
      return ret;
    }
};

  /*
   * Variable
   */
  var Variable = function(name,domain) {
    this.name = name;
    this.domain = domain;
  };

  Variable.prototype.toString = function() {
    return "" + this.name + " => [" + this.domain.toString() + "]";
  };

  /*
   * Constraint
   */
  var Constraint = function(variables, fn) {
    this.fn = fn;
    this.variables = variables;
  };

  Constraint.prototype.toString = function() {
    return "(" + this.variables.toString() + ") => " + this.fn.toString();
  };

  /*
   * Problem
   */
  var Problem = function() {
    this.solver = new RecursiveBacktrackingSolver();
    this.variables = {};
    this.constraints = [];
  };

  Problem.prototype.addVariable = function(name, domain) {
    this.variables[name] = new Variable(name,domain);
  };

  Problem.prototype.removeVariable = function(vari) {
	  var vars = this.variables;
	  delete vars[vari];
  };

  Problem.prototype.addConstraint = function(variables, fn) {
    this.constraints.push(new Constraint(variables, fn));
  };

  Problem.prototype.removeConstraint = function(constraint) {
	var index = this.constraints.indexOf(constraint);
	if(index > -1) {
	    this.constraints.splice(index, 1);
	} else {
		throw "attempt to removed a non-existing element";
	}
  };

  Problem.prototype.setSolver = function(solver) {
    this.solver = solver;
  };

  Problem.prototype.getSolution = function(restrictedDomains) {
    return this.solver.getSolution(this, restrictedDomains);
  };

  Problem.prototype.getAssignmentFor = function(name) {
    return this.solver.getAssignmentFor(name);
  };

  /*
   * Solver
   */
  var RecursiveBacktrackingSolver = function() {
    this.assignments = {};
  };

  RecursiveBacktrackingSolver.prototype.getSolution = function(csp, restrictedDomains) {
    var satisfiable = this.solve(csp.variables, csp.constraints, restrictedDomains);

    return satisfiable;
  };

  RecursiveBacktrackingSolver.prototype.getAssignmentFor = function(name) {
    return this.assignments[name];
  };

  RecursiveBacktrackingSolver.prototype.solve = function(variables, constraints, restrictedDomains) {
	  var domainByName = this.prepareSolving(variables, restrictedDomains);

	  var fulfilled = this.recursiveSolve(constraints, domainByName);

	  return fulfilled;
  };

  RecursiveBacktrackingSolver.prototype.prepareSolving = function(variables, restrictedDomains) {
	  var domainByName = _.defaults(restrictedDomains, variables);

	  return domainByName;
  };

	RecursiveBacktrackingSolver.prototype.recursiveSolve = function(constraints, domainByName) {
		if(_.size(domainByName) === 0) {
			var fulfilled = this.checkAssignments(constraints);
			return fulfilled;
		} else {
			var current = _.chain(domainByName)
				.keys()
				.first()
				.value();
			var remainingDomain = _.omit(domainByName, current);
			var currentDomain = domainByName[current].domain;
			var fulfillingValue = _.find(currentDomain, function(val) {
				this.assignments[current] = val;
				var fulfilled = this.recursiveSolve(constraints, remainingDomain);
				return fulfilled;
			}, this);
			return typeof fulfillingValue !== "undefined";
		};
	};

	RecursiveBacktrackingSolver.prototype.checkAssignments = function(constraints) {
		var constraintsFulfilled =_.every(constraints, function(constraint) {
			return constraint.fn();
		}, this);

		if(constraintsFulfilled) {
			this.summitSolution();
		}

		return constraintsFulfilled;
	};

	RecursiveBacktrackingSolver.prototype.summitSolution = function() {};

/*
 * Public API
 */
Object.subclass("_csp", {});
Object.extend(_csp, {
	version: "0.1",
    DiscreteProblem: Problem
});

});<commit_msg>return created constraints<commit_after>/*
 *
 * A simple constraint satisfaction problem solver in Javascript.
 *
 */
module('users.timfelgentreff.csp.csp').requires().toRun(function() {

JSLoader.loadJs(module('users.timfelgentreff.csp.underscore-min').uri());

var util = {
    mixin: function(target, src) {
      for (var name in src) {
        if (src.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
          target[name] = src[name];
        }
      }
    },
    hashcopy: function(obj) {
      var ret = obj.constructor();
      for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
          ret[p] = obj[p];
        }
      }
      return ret;
    }
};

  /*
   * Variable
   */
  var Variable = function(name,domain) {
    this.name = name;
    this.domain = domain;
  };

  Variable.prototype.toString = function() {
    return "" + this.name + " => [" + this.domain.toString() + "]";
  };

  /*
   * Constraint
   */
  var Constraint = function(variables, fn) {
    this.fn = fn;
    this.variables = variables;
  };

  Constraint.prototype.toString = function() {
    return "(" + this.variables.toString() + ") => " + this.fn.toString();
  };

  /*
   * Problem
   */
  var Problem = function() {
    this.solver = new RecursiveBacktrackingSolver();
    this.variables = {};
    this.constraints = [];
  };

  Problem.prototype.addVariable = function(name, domain) {
    this.variables[name] = new Variable(name,domain);
  };

  Problem.prototype.removeVariable = function(vari) {
	  var vars = this.variables;
	  delete vars[vari];
  };

  Problem.prototype.addConstraint = function(variables, fn) {
	var constraint = new Constraint(variables, fn);
    this.constraints.push(constraint);
    return constraint;
  };

  Problem.prototype.removeConstraint = function(constraint) {
	var index = this.constraints.indexOf(constraint);
	if(index > -1) {
	    this.constraints.splice(index, 1);
	} else {
		throw "attempt to removed a non-existing element";
	}
  };

  Problem.prototype.setSolver = function(solver) {
    this.solver = solver;
  };

  Problem.prototype.getSolution = function(restrictedDomains) {
    return this.solver.getSolution(this, restrictedDomains);
  };

  Problem.prototype.getAssignmentFor = function(name) {
    return this.solver.getAssignmentFor(name);
  };

  /*
   * Solver
   */
  var RecursiveBacktrackingSolver = function() {
    this.assignments = {};
  };

  RecursiveBacktrackingSolver.prototype.getSolution = function(csp, restrictedDomains) {
    var satisfiable = this.solve(csp.variables, csp.constraints, restrictedDomains);

    return satisfiable;
  };

  RecursiveBacktrackingSolver.prototype.getAssignmentFor = function(name) {
    return this.assignments[name];
  };

  RecursiveBacktrackingSolver.prototype.solve = function(variables, constraints, restrictedDomains) {
	  var domainByName = this.prepareSolving(variables, restrictedDomains);

	  var fulfilled = this.recursiveSolve(constraints, domainByName);

	  return fulfilled;
  };

  RecursiveBacktrackingSolver.prototype.prepareSolving = function(variables, restrictedDomains) {
	  var domainByName = _.defaults(restrictedDomains, variables);

	  return domainByName;
  };

	RecursiveBacktrackingSolver.prototype.recursiveSolve = function(constraints, domainByName) {
		if(_.size(domainByName) === 0) {
			var fulfilled = this.checkAssignments(constraints);
			return fulfilled;
		} else {
			var current = _.chain(domainByName)
				.keys()
				.first()
				.value();
			var remainingDomain = _.omit(domainByName, current);
			var currentDomain = domainByName[current].domain;
			var fulfillingValue = _.find(currentDomain, function(val) {
				this.assignments[current] = val;
				var fulfilled = this.recursiveSolve(constraints, remainingDomain);
				return fulfilled;
			}, this);
			return typeof fulfillingValue !== "undefined";
		};
	};

	RecursiveBacktrackingSolver.prototype.checkAssignments = function(constraints) {
		var constraintsFulfilled =_.every(constraints, function(constraint) {
			return constraint.fn();
		}, this);

		if(constraintsFulfilled) {
			this.summitSolution();
		}

		return constraintsFulfilled;
	};

	RecursiveBacktrackingSolver.prototype.summitSolution = function() {};

/*
 * Public API
 */
Object.subclass("_csp", {});
Object.extend(_csp, {
	version: "0.1",
    DiscreteProblem: Problem
});

});<|endoftext|>


<commit_before>import copyToClipboard from 'copy-to-clipboard'
import React, { Component } from 'react'
import _ from 'lodash/fp'
import { SUI, leven } from 'src/lib'
import {
  Form,
  Grid,
  Header,
  Icon,
  Message,
  Popup,
} from 'src'

const gridStyle = {
  background: '#fff',
}

const iconKeyToHeaderMap = {
  WEB_CONTENT_ICONS: 'Web Content',
  USER_ACTIONS_ICONS: 'User Actions',
  MESSAGES_ICONS: 'Messages',
  USERS_ICONS: 'Users',
  GENDER_SEXUALITY_ICONS: 'Gender & Sexuality',
  ACCESSIBILITY_ICONS: 'Accessibility',
  VIEW_ADJUSTMENT_ICONS: 'View Adjustment',
  LITERAL_OBJECTS_ICONS: 'Literal Objects',
  SHAPES_ICONS: 'Shapes',
  ITEM_SELECTION_ICONS: 'Item Selection',
  MEDIA_ICONS: 'Media',
  POINTERS_ICONS: 'Pointers',
  MOBILE_ICONS: 'Mobile',
  COMPUTER_ICONS: 'Computer',
  FILE_SYSTEM_ICONS: 'File System',
  TECHNOLOGIES_ICONS: 'Technologies',
  RATING_ICONS: 'Rating',
  AUDIO_ICONS: 'Audio',
  MAP_LOCATIONS_TRANSPORTATION_ICONS: 'Map, Locations & Transportation',
  TABLES_ICONS: 'Tables',
  TEXT_EDITOR_ICONS: 'Text Editor',
  CURRENCY_ICONS: 'Currency',
  PAYMENT_OPTIONS_ICONS: 'Payment Options',
  NETWORKS_AND_WEBSITE_ICONS: 'Networks And Website',
  ICON_ALIASES: 'Icon Aliases',
}

const similarityScore = (strA, strB) => {
  const aWords = strA.trim().split(' ')
  const bWords = strB.trim().split(' ')

  return _.flow(
    _.map(a => _.map(b => leven(a, b), bWords)),
    _.map(_.min),
    _.sum
  )(aWords)
}
export default class IconSearch extends Component {
  state = { search: '', includeSimilar: true }

  componentDidMount() {
    const input = document.querySelector('#docs-icon-set-input input')
    input.focus()
  }

  handleChange = _.debounce(100, (e, { value }) => this.setState({ search: value }))

  handleIncludeSimilarChange = (e, { checked }) => this.setState({ includeSimilar: checked })

  copy = (text) => () => {
    copyToClipboard(text)
    this.setState({ copied: true })
    setTimeout(() => this.setState({ copied: false }), 1000)
  }

  renderIconColumn = (name) => (
    <Popup
      key={name}
      mouseEnterDelay={1000}
      inverted
      closeOnTriggerClick={false}
      closeOnRootNodeClick={false}
      closeOnDocumentClick={false}
      style={{ width: '8em', textAlign: 'center' }}
      size='mini'
      position='top center'
      content={this.state.copied ? 'Copied!' : 'Click to copy'}
      trigger={(
        <Grid.Column className='docs-icon-set-column' onClick={this.copy(name)}>
          <Icon name={name} size='big' />

{name}

        </Grid.Column>
      )}
    />
  )

  renderIcons = () => {
    const { includeSimilar, search } = this.state
    const query = search.trim().toLowerCase()
    const iconKeys = Object.keys(iconKeyToHeaderMap)

    // no search
    if (!query) {
      return iconKeys.map(iconKey => (
        <Grid key={iconKey} columns={5} doubling>
          <Grid.Column width={16}>

              {iconKeyToHeaderMap[iconKey]}

          </Grid.Column>
          {SUI[iconKey].map(this.renderIconColumn)}
        </Grid>
      ))
    }

    const iconSearchMatches = SUI.ICONS_AND_ALIASES
      .filter(name => {
        // contains
        if (name.indexOf(query) !== -1) return true

        // similar
        return includeSimilar && similarityScore(name, query) <= 2
      })
      .map(this.renderIconColumn)

    // no results
    if (iconSearchMatches.length === 0) {
      return (
        <Grid>
          <Grid.Column textAlign='left'>
            <Message
              info
              icon='search'
              content={`There is no icon name or alias ${includeSimilar ? 'similar' : 'that contains'} to "${query}".`}
              header='No Results'
            />
          </Grid.Column>
        </Grid>
      )
    }

    // results
    return <Grid columns={5} doubling>{iconSearchMatches}</Grid>
  }

  render() {
    const { includeSimilar } = this.state
    return (
      <Grid columns={1} padded textAlign='center' style={gridStyle}>
        <Grid.Column>
          <Form onSubmit={(e) => e.preventDefault()}>
            <Form.Group inline>
              <Form.Input
                id='docs-icon-set-input'
                placeholder='Search...'
                icon='search'
                onChange={this.handleChange}
              />
              <Form.Checkbox
                toggle
                label='Show similar'
                checked={includeSimilar}
                onChange={this.handleIncludeSimilarChange}
              />
            </Form.Group>
          </Form>
        </Grid.Column>
        <Grid.Column>
          {this.renderIcons()}
        </Grid.Column>
      </Grid>
    )
  }
}
<commit_msg>docs(Icon): fix selector for input (#1714)<commit_after>import copyToClipboard from 'copy-to-clipboard'
import React, { Component } from 'react'
import _ from 'lodash/fp'
import { SUI, leven } from 'src/lib'
import {
  Form,
  Grid,
  Header,
  Icon,
  Message,
  Popup,
} from 'src'

const gridStyle = {
  background: '#fff',
}

const iconKeyToHeaderMap = {
  WEB_CONTENT_ICONS: 'Web Content',
  USER_ACTIONS_ICONS: 'User Actions',
  MESSAGES_ICONS: 'Messages',
  USERS_ICONS: 'Users',
  GENDER_SEXUALITY_ICONS: 'Gender & Sexuality',
  ACCESSIBILITY_ICONS: 'Accessibility',
  VIEW_ADJUSTMENT_ICONS: 'View Adjustment',
  LITERAL_OBJECTS_ICONS: 'Literal Objects',
  SHAPES_ICONS: 'Shapes',
  ITEM_SELECTION_ICONS: 'Item Selection',
  MEDIA_ICONS: 'Media',
  POINTERS_ICONS: 'Pointers',
  MOBILE_ICONS: 'Mobile',
  COMPUTER_ICONS: 'Computer',
  FILE_SYSTEM_ICONS: 'File System',
  TECHNOLOGIES_ICONS: 'Technologies',
  RATING_ICONS: 'Rating',
  AUDIO_ICONS: 'Audio',
  MAP_LOCATIONS_TRANSPORTATION_ICONS: 'Map, Locations & Transportation',
  TABLES_ICONS: 'Tables',
  TEXT_EDITOR_ICONS: 'Text Editor',
  CURRENCY_ICONS: 'Currency',
  PAYMENT_OPTIONS_ICONS: 'Payment Options',
  NETWORKS_AND_WEBSITE_ICONS: 'Networks And Website',
  ICON_ALIASES: 'Icon Aliases',
}

const similarityScore = (strA, strB) => {
  const aWords = strA.trim().split(' ')
  const bWords = strB.trim().split(' ')

  return _.flow(
    _.map(a => _.map(b => leven(a, b), bWords)),
    _.map(_.min),
    _.sum
  )(aWords)
}
export default class IconSearch extends Component {
  state = { search: '', includeSimilar: true }

  componentDidMount() {
    const input = document.querySelector('#docs-icon-set-input')
    input.focus()
  }

  handleChange = _.debounce(100, (e, { value }) => this.setState({ search: value }))

  handleIncludeSimilarChange = (e, { checked }) => this.setState({ includeSimilar: checked })

  copy = (text) => () => {
    copyToClipboard(text)
    this.setState({ copied: true })
    setTimeout(() => this.setState({ copied: false }), 1000)
  }

  renderIconColumn = (name) => (
    <Popup
      key={name}
      mouseEnterDelay={1000}
      inverted
      closeOnTriggerClick={false}
      closeOnRootNodeClick={false}
      closeOnDocumentClick={false}
      style={{ width: '8em', textAlign: 'center' }}
      size='mini'
      position='top center'
      content={this.state.copied ? 'Copied!' : 'Click to copy'}
      trigger={(
        <Grid.Column className='docs-icon-set-column' onClick={this.copy(name)}>
          <Icon name={name} size='big' />

{name}

        </Grid.Column>
      )}
    />
  )

  renderIcons = () => {
    const { includeSimilar, search } = this.state
    const query = search.trim().toLowerCase()
    const iconKeys = Object.keys(iconKeyToHeaderMap)

    // no search
    if (!query) {
      return iconKeys.map(iconKey => (
        <Grid key={iconKey} columns={5} doubling>
          <Grid.Column width={16}>

              {iconKeyToHeaderMap[iconKey]}

          </Grid.Column>
          {SUI[iconKey].map(this.renderIconColumn)}
        </Grid>
      ))
    }

    const iconSearchMatches = SUI.ICONS_AND_ALIASES
      .filter(name => {
        // contains
        if (name.indexOf(query) !== -1) return true

        // similar
        return includeSimilar && similarityScore(name, query) <= 2
      })
      .map(this.renderIconColumn)

    // no results
    if (iconSearchMatches.length === 0) {
      return (
        <Grid>
          <Grid.Column textAlign='left'>
            <Message
              info
              icon='search'
              content={`There is no icon name or alias ${includeSimilar ? 'similar' : 'that contains'} to "${query}".`}
              header='No Results'
            />
          </Grid.Column>
        </Grid>
      )
    }

    // results
    return <Grid columns={5} doubling>{iconSearchMatches}</Grid>
  }

  render() {
    const { includeSimilar } = this.state
    return (
      <Grid columns={1} padded textAlign='center' style={gridStyle}>
        <Grid.Column>
          <Form onSubmit={(e) => e.preventDefault()}>
            <Form.Group inline>
              <Form.Input
                id='docs-icon-set-input'
                placeholder='Search...'
                icon='search'
                onChange={this.handleChange}
              />
              <Form.Checkbox
                toggle
                label='Show similar'
                checked={includeSimilar}
                onChange={this.handleIncludeSimilarChange}
              />
            </Form.Group>
          </Form>
        </Grid.Column>
        <Grid.Column>
          {this.renderIcons()}
        </Grid.Column>
      </Grid>
    )
  }
}
<|endoftext|>


<commit_before>/**
 * @file Ingress-ICE, the main script
 * @author Nikitakun (https://github.com/nibogd)
 * @version 4.3.0
 * @license MIT
 * @see {@link https://github.com/nibogd/ingress-ice|GitHub }
 * @see {@link https://ingress.netlify.com/|Website }
 */

"use strict";

/*global phantom */
/*global require */
/*global ice */

var system    = require('system');
var args      = system.args;
var fs        = require('fs');
var version   = '4.3.0';
var filename  = 'ice.js';
var iceFolder = args[0].substring(0, args[0].length - filename.length) + 'modules/';
var iceModules= fs.list(iceFolder);

/*
 * Loads all scripts in the 'modules' folder
 */
function loadModules() {
  for(var i = 0; i < iceModules.length; i++) {
    var file = iceFolder + iceModules[i];
    if(fs.isFile(file)){
      phantom.injectJs(file);
    }
  }
}

loadModules();
window.setTimeout(ice, 1000);
<commit_msg>Version bump to 4.4.0<commit_after>/**
 * @file Ingress-ICE, the main script
 * @author Nikitakun (https://github.com/nibogd)
 * @version 4.4.0
 * @license MIT
 * @see {@link https://github.com/nibogd/ingress-ice|GitHub }
 * @see {@link https://ingress.netlify.com/|Website }
 */

"use strict";

/*global phantom */
/*global require */
/*global ice */

var system    = require('system');
var args      = system.args;
var fs        = require('fs');
var version   = '4.4.0';
var filename  = 'ice.js';
var iceFolder = args[0].substring(0, args[0].length - filename.length) + 'modules/';
var iceModules= fs.list(iceFolder);

/*
 * Loads all scripts in the 'modules' folder
 */
function loadModules() {
  for(var i = 0; i < iceModules.length; i++) {
    var file = iceFolder + iceModules[i];
    if(fs.isFile(file)){
      phantom.injectJs(file);
    }
  }
}

loadModules();
window.setTimeout(ice, 1000);
<|endoftext|>


<commit_before>/* eslint-disable */

import React from 'react'
//
import ReactStory, { defaultProps } from 'react-story'
import CodeSandbox from './CodeSandbox.js'
import './stories/utils/prism.css'
import '../../react-table.css'

import Readme from './stories/Readme.js'
import HOCReadme from './stories/HOCReadme.js'

// import Test from './stories/test.js'

// import Tester from './examples/expander';

const stories = [
  { name: 'Readme', component: Readme },
  { name: 'HOC Readme', component: HOCReadme },

  // { name: 'Tester', component: Tester },
  { name: 'Simple Table', component: CodeSandbox('X6npLXPRW') },
  {
    name: 'Cell Renderers & Custom Components',
    component: CodeSandbox('OyRL04Z4Y'),
  },
  { name: 'Default Sorting', component: CodeSandbox('gLwmmjzA3') },
  {
    name: 'Custom Sorting',
    component: CodeSandbox('VGx67J35'),
  },
  { name: 'Custom Column Widths', component: CodeSandbox('o2OORXNXN') },
  { name: 'Custom Component Props', component: CodeSandbox('nZW3L0wp4') },
  { name: 'Server-side Data', component: CodeSandbox('wjrn8wy3R') },
  { name: 'Sub Components', component: CodeSandbox('n2gqAxl7') },
  { name: 'Pivoting & Aggregation', component: CodeSandbox('oNY9z8xN') },
  {
    name: 'Pivoting & Aggregation w/ Sub Components',
    component: CodeSandbox('p0kEVBgQ'),
  },
  {
    name: '100k Rows w/ Pivoting & Sub Components',
    component: CodeSandbox('DRmKj0XyK'),
  },
  { name: 'Pivoting Options', component: CodeSandbox('kZKmNBK6r') },
  { name: 'Functional Rendering', component: CodeSandbox('VPZ0Bzv8X') },
  {
    name: 'Custom Expander Position',
    component: CodeSandbox('1jj2XrPEV'),
  },
  { name: 'Custom "No Data" Text', component: CodeSandbox('RgRpRDv80') },
  { name: 'Footers', component: CodeSandbox('KOqQXn3p8') },
  { name: 'Custom Filtering', component: CodeSandbox('5Eyxxxyx') },
  { name: 'Controlled Component', component: CodeSandbox('r7XEZRK2') },
  { name: 'Editable Table', component: CodeSandbox('n5r19gzQP') },
  {
    name: 'Fixed Header w/ Vertical Scroll',
    component: CodeSandbox('7LY0gjA8O'),
  },
  {
    name: 'Multiple Pagers (Top and Bottom)',
    component: CodeSandbox('VEZ8OgvX'),
  },
  { name: 'Tree Table (HOC)', component: CodeSandbox('lxmr4wynzq') },
  { name: 'Select Table (HOC)', component: CodeSandbox('7yq5ylw09j') },
  { name: 'Select Tree Table (HOC)', component: CodeSandbox('2p7jp4klwp') },
]

export default class App extends React.Component {
  render () {
    return (
      <ReactStory
        style={{
          display: 'block',
          width: '100%',
          height: '100%',
        }}
        pathPrefix='story/'
        StoryWrapper={props =>
          <defaultProps.StoryWrapper
            css={{
              padding: 0,
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            <a
              href='//github.com/react-tools/react-table'
              style={{
                display: 'block',
                textAlign: 'center',
                borderBottom: 'solid 3px #cccccc',
              }}
            >
              <img
                src='https://github.com/react-tools/media/raw/master/logo-react-table.png'
                alt='React Table Logo'
                style={{
                  width: '150px',
                  padding: '10px',
                }}
              />
            </a>
            <div
              {...props}
              style={{
                flex: '1 0 auto',
                position: 'relative',
              }}
            />
          </defaultProps.StoryWrapper>}
        stories={stories}
      />
    )
  }
}
<commit_msg>Comment out<commit_after>/* eslint-disable */

import React from 'react'
//
import ReactStory, { defaultProps } from 'react-story'
import CodeSandbox from './CodeSandbox.js'
import './stories/utils/prism.css'
import '../../react-table.css'

import Readme from './stories/Readme.js'
import HOCReadme from './stories/HOCReadme.js'

// import Test from './stories/test.js'

// import Tester from './examples/expander';

const stories = [
  { name: 'Readme', component: Readme },
  { name: 'HOC Readme', component: HOCReadme },

  // { name: 'Tester', component: Test },
  { name: 'Simple Table', component: CodeSandbox('X6npLXPRW') },
  {
    name: 'Cell Renderers & Custom Components',
    component: CodeSandbox('OyRL04Z4Y'),
  },
  { name: 'Default Sorting', component: CodeSandbox('gLwmmjzA3') },
  {
    name: 'Custom Sorting',
    component: CodeSandbox('VGx67J35'),
  },
  { name: 'Custom Column Widths', component: CodeSandbox('o2OORXNXN') },
  { name: 'Custom Component Props', component: CodeSandbox('nZW3L0wp4') },
  { name: 'Server-side Data', component: CodeSandbox('wjrn8wy3R') },
  { name: 'Sub Components', component: CodeSandbox('n2gqAxl7') },
  { name: 'Pivoting & Aggregation', component: CodeSandbox('oNY9z8xN') },
  {
    name: 'Pivoting & Aggregation w/ Sub Components',
    component: CodeSandbox('p0kEVBgQ'),
  },
  {
    name: '100k Rows w/ Pivoting & Sub Components',
    component: CodeSandbox('DRmKj0XyK'),
  },
  { name: 'Pivoting Options', component: CodeSandbox('kZKmNBK6r') },
  { name: 'Functional Rendering', component: CodeSandbox('VPZ0Bzv8X') },
  {
    name: 'Custom Expander Position',
    component: CodeSandbox('1jj2XrPEV'),
  },
  { name: 'Custom "No Data" Text', component: CodeSandbox('RgRpRDv80') },
  { name: 'Footers', component: CodeSandbox('KOqQXn3p8') },
  { name: 'Custom Filtering', component: CodeSandbox('5Eyxxxyx') },
  { name: 'Controlled Component', component: CodeSandbox('r7XEZRK2') },
  { name: 'Editable Table', component: CodeSandbox('n5r19gzQP') },
  {
    name: 'Fixed Header w/ Vertical Scroll',
    component: CodeSandbox('7LY0gjA8O'),
  },
  {
    name: 'Multiple Pagers (Top and Bottom)',
    component: CodeSandbox('VEZ8OgvX'),
  },
  { name: 'Tree Table (HOC)', component: CodeSandbox('lxmr4wynzq') },
  { name: 'Select Table (HOC)', component: CodeSandbox('7yq5ylw09j') },
  { name: 'Select Tree Table (HOC)', component: CodeSandbox('2p7jp4klwp') },
]

export default class App extends React.Component {
  render () {
    return (
      <ReactStory
        style={{
          display: 'block',
          width: '100%',
          height: '100%',
        }}
        pathPrefix='story/'
        StoryWrapper={props =>
          <defaultProps.StoryWrapper
            css={{
              padding: 0,
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            <a
              href='//github.com/react-tools/react-table'
              style={{
                display: 'block',
                textAlign: 'center',
                borderBottom: 'solid 3px #cccccc',
              }}
            >
              <img
                src='https://github.com/react-tools/media/raw/master/logo-react-table.png'
                alt='React Table Logo'
                style={{
                  width: '150px',
                  padding: '10px',
                }}
              />
            </a>
            <div
              {...props}
              style={{
                flex: '1 0 auto',
                position: 'relative',
              }}
            />
          </defaultProps.StoryWrapper>}
        stories={stories}
      />
    )
  }
}
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache 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
//
//     https://www.apache.org/licenses/LICENSE-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.

'use strict';

async function setEndpoint(projectId) {
  // [START automl_set_endpoint]
  const automl = require('@google-cloud/automl').v1beta1;

  // You must first create a dataset, using the `eu` endpoint, before you can
  // call other operations such as: list, get, import, delete, etc.
  const clientOptions = {apiEndpoint: 'eu-automl.googleapis.com'};

  // Instantiates a client
  const client = new automl.AutoMlClient(clientOptions);

  // A resource that represents Google Cloud Platform location.
  const projectLocation = client.locationPath(projectId, 'eu');
  // [END automl_set_endpoint]
  console.log(projectLocation);

  // Grabs the list of datasets in a given project location.
  // Note: create a dataset in `eu` before calling `listDatasets`.
  const responses = await client.listDatasets({parent: projectLocation});

  // Prints out each dataset.
  const datasets = responses[0];
  datasets.forEach(dataset => {
    console.log(dataset);
  });
}

setEndpoint(...process.argv.slice(2)).catch(err => {
  console.error(err);
  process.exitCode = 1;
});
<commit_msg>fix(samples): remove extra print statement and "setEndpoint.js" from linkinator (#261)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache 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
//
//     https://www.apache.org/licenses/LICENSE-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.

'use strict';

async function setEndpoint(projectId) {
  // [START automl_set_endpoint]
  const automl = require('@google-cloud/automl').v1beta1;

  // You must first create a dataset, using the `eu` endpoint, before you can
  // call other operations such as: list, get, import, delete, etc.
  const clientOptions = {apiEndpoint: 'eu-automl.googleapis.com'};

  // Instantiates a client
  const client = new automl.AutoMlClient(clientOptions);

  // A resource that represents Google Cloud Platform location.
  const projectLocation = client.locationPath(projectId, 'eu');
  // [END automl_set_endpoint]

  // Grabs the list of datasets in a given project location.
  // Note: create a dataset in `eu` before calling `listDatasets`.
  const responses = await client.listDatasets({parent: projectLocation});

  // Prints out each dataset.
  const datasets = responses[0];
  datasets.forEach(dataset => {
    console.log(dataset);
  });
}

setEndpoint(...process.argv.slice(2)).catch(err => {
  console.error(err);
  process.exitCode = 1;
});
<|endoftext|>


<commit_before>/**
* Geo-OV - applicatie voor het registreren van KAR meldpunten
*
* Copyright (C) 2009-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * Form voor editen instellingen die worden opgeslagen in het gebruikersprofiel.
 */

var savedProfile = Ext.JSON.encode(profile);

function saveProfile() {
    setTimeout(checkSaveProfile, 500);
}

function checkSaveProfile() {
    var encodedProfile = Ext.JSON.encode(profile);

    if(encodedProfile != savedProfile) {
        savedProfile = encodedProfile;
        Ext.Ajax.request({
            url: profileActionBeanUrl,
            method: 'POST',
            scope: this,
            params: {settings: Ext.JSON.encode(profile)},
            failure: function (response){
                Ext.MessageBox.show({title: "Ajax fout", msg: response.responseText, buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
            }
        });
    }
}

Ext.define("SettingsForm", {

    editor: null,

    window: null,

    /* XXX move to common place */
    karAttributes: [
        {n: 2, label: "Vehicle type", range: "0 - 99", desc: "0 - no information\n1 - bus\n2 - tram\netc."},
        {n: 3, label: "Line number PT", range: "0 - 9999", desc: "Line-number (internal line number PT-company)"},
        {n: 6, label: "Vehicle id", range: "0 - 32767", desc: "0 - no information\nFor public transport the grootwagennummer is used (practially in range 1 to 9999)"},
        {n: 7, label: "Direction at intersection/signal group number", range: "0 - 255", desc: "For the direction selection \n" +
                "at the intersection, it is suggested to use the signal group number. If this signal group number " +
                "is not available a right/left/straigt ahead switch may be used:\n" +
                "0 = no information\n1-200 = signal group number\n201 = right\n202 = left\n203 = straight ahead\n204-255 = reserved"},
        {n: 8, label: "Vehicle status", range: "0 - 99", desc: "0 = no information\n1 = driving\n2 = stopping\n" +
                "3 = departure from stop (start door close)\n4 = stand still (stop, not at bus stop)\n" +
                "5 - 99 = reserved"},
        {n: 11, label: "Punctuality [s]", range: "-3600 - +3600", desc: "- early (<0)\nlate (>0)"},
        {n: 13, label: "Actual vehicle speed [m/s]", range: "0 - 99", desc: "Actual speed when te message is sent [m/s]"},
        {n: 15, label: "Driving time till passage stop line", range: "0 - 255", desc: "Expected time until passage stop line " +
            "(without delay for other traffic, for example wait-row) in seconds for th efirst Traffic Light Controller on the route"},
        {n: 19, label: "Type of command", range: "0 - 99", desc: "0 - reserved\n1 - entering announcement\n" +
                "2 - leave announcement\n3 - pre-announcement\n4..99 - reserved"}
    ],

    constructor: function(editor) {
        this.editor = editor;
    },

    show: function() {
        if(this.window != null) {
            this.window.destroy();
            this.window = null;
        }
        var me = this;
        me.window = Ext.create('Ext.window.Window', {
            title: 'Instellingen',
            height: 600,
            width: 550,
            modal: true,
            layout: 'fit',
            items: {
                xtype: 'form',
                bodyStyle: 'padding: 5px 5px 0',
                fieldDefaults: {
                    msgTarget: 'side',
                    labelWidth: 150
                },
                defaultType: 'textfield',
                defaults: {
                    anchor: '100%'
                },
                items: [{
                    fieldLabel: 'Test',
                    name: 'test',
                    value: profile.test
                }],
                buttons: [{
                    text: 'Opslaan',
                    handler: function() {
                        var form = this.up('form').getForm();
                        if(!form.isValid()) {
                            Ext.Msg.alert('Ongeldige gegevens', 'Controleer aub de geldigheid van de ingevulde gegevens.')
                            return;
                        }

                        Ext.Object.merge(profile, form.getValues());

                        saveProfile();

                        //me.editor.fireEvent("profileUpdated", rseq);

                        me.window.destroy();
                        me.window = null;
                    }
                },{
                    text: 'Annuleren',
                    handler: function() {
                        me.window.destroy();
                        me.window = null;
                    }
                }]
            }
        }).show();
    }
});<commit_msg>instellen default kar attributen; default alles aan<commit_after>/**
* Geo-OV - applicatie voor het registreren van KAR meldpunten
*
* Copyright (C) 2009-2013 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * Form voor editen instellingen die worden opgeslagen in het gebruikersprofiel.
 */

var savedProfile = Ext.JSON.encode(profile);

function saveProfile() {
    setTimeout(checkSaveProfile, 500);
}

function checkSaveProfile() {
    var encodedProfile = Ext.JSON.encode(profile);

    if(encodedProfile != savedProfile) {
        savedProfile = encodedProfile;
        Ext.Ajax.request({
            url: profileActionBeanUrl,
            method: 'POST',
            scope: this,
            params: {settings: Ext.JSON.encode(profile)},
            failure: function (response){
                Ext.MessageBox.show({title: "Ajax fout", msg: response.responseText, buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
            }
        });
    }
}

Ext.define("SettingsForm", {

    editor: null,

    window: null,

    newDefaultKarAttributes: null,

    /* XXX move to common place */
    karAttributes: [
        {n: 2, label: "Vehicle type", range: "0 - 99", desc: "0 - no information\n1 - bus\n2 - tram\netc."},
        {n: 3, label: "Line number PT", range: "0 - 9999", desc: "Line-number (internal line number PT-company)"},
        {n: 6, label: "Vehicle id", range: "0 - 32767", desc: "0 - no information\nFor public transport the grootwagennummer is used (practially in range 1 to 9999)"},
        {n: 7, label: "Direction at intersection/signal group number", range: "0 - 255", desc: "For the direction selection \n" +
                "at the intersection, it is suggested to use the signal group number. If this signal group number " +
                "is not available a right/left/straigt ahead switch may be used:\n" +
                "0 = no information\n1-200 = signal group number\n201 = right\n202 = left\n203 = straight ahead\n204-255 = reserved"},
        {n: 8, label: "Vehicle status", range: "0 - 99", desc: "0 = no information\n1 = driving\n2 = stopping\n" +
                "3 = departure from stop (start door close)\n4 = stand still (stop, not at bus stop)\n" +
                "5 - 99 = reserved"},
        {n: 11, label: "Punctuality [s]", range: "-3600 - +3600", desc: "- early (<0)\nlate (>0)"},
        {n: 13, label: "Actual vehicle speed [m/s]", range: "0 - 99", desc: "Actual speed when te message is sent [m/s]"},
        {n: 15, label: "Driving time till passage stop line", range: "0 - 255", desc: "Expected time until passage stop line " +
            "(without delay for other traffic, for example wait-row) in seconds for th efirst Traffic Light Controller on the route"},
        {n: 19, label: "Type of command", range: "0 - 99", desc: "0 - reserved\n1 - entering announcement\n" +
                "2 - leave announcement\n3 - pre-announcement\n4..99 - reserved"}
    ],

    constructor: function(editor) {
        this.editor = editor;
    },

    show: function() {
        if(this.window != null) {
            this.window.destroy();
            this.window = null;
        }
        var me = this;
        me.window = Ext.create('Ext.window.Window', {
            title: 'Instellingen',
            height: 600,
            width: 550,
            modal: true,
            layout: 'fit',
            items: {
                xtype: 'form',
                bodyStyle: 'padding: 5px 5px 0',
                fieldDefaults: {
                    msgTarget: 'side',
                    labelWidth: 150
                },
                defaultType: 'textfield',
                defaults: {
                    anchor: '100%'
                },
                items: [{
                    fieldLabel: 'Test',
                    name: 'test',
                    value: profile.test
                },{
                    xtype: 'button',
                    text: 'Standaard KAR attributen voor nieuw verkeerssysteem',
                    handler: function() {

                        if(!profile.defaultKarAttributes) {
                            profile.defaultKarAttributes = { "ES": [ [], [], [] ], "PT": [ [], [], [] ], "OT": [ [], [], [] ]};
                            var vts = ["ES","PT","OT"];
                            for(var i in vts) {
                                var vt = vts[i];
                                for(var j = 0; j < 24; j++) {
                                    profile.defaultKarAttributes[vt][0].push(true);
                                    profile.defaultKarAttributes[vt][1].push(true);
                                    profile.defaultKarAttributes[vt][2].push(true);
                                }
                            }
                        }

                        Ext.create(KarAttributesEditWindow,
                            "Standaard KAR attributen voor nieuw verkeersysteem",
                            "In dit scherm kan worden aangegeven welke KAR attributen standaard " +
                                "voor nieuw aangemaakte verkeerssystemen moeten worden aangevinkt.",
                            profile.defaultKarAttributes,
                            function(atts) {
                                me.newDefaultKarAttributes = atts;
                            }
                        ).show();
                    }
                }],
                buttons: [{
                    text: 'Opslaan',
                    handler: function() {
                        var form = this.up('form').getForm();
                        if(!form.isValid()) {
                            Ext.Msg.alert('Ongeldige gegevens', 'Controleer aub de geldigheid van de ingevulde gegevens.')
                            return;
                        }

                        Ext.Object.merge(profile, form.getValues());

                        if(me.newDefaultKarAttributes != null) {
                            profile.defaultKarAttributes = me.newDefaultKarAttributes;
                        }
                        saveProfile();

                        //me.editor.fireEvent("profileUpdated", rseq);

                        me.window.destroy();
                        me.window = null;
                    }
                },{
                    text: 'Annuleren',
                    handler: function() {
                        me.window.destroy();
                        me.window = null;
                    }
                }]
            }
        }).show();
    }
});<|endoftext|>