<commit_before>import React, { Component } from 'react';

import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import IconButton from '@material-ui/core/IconButton';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
import Typography from '@material-ui/core/Typography';

import EditIcon from '@material-ui/icons/Edit';
import DoneIcon from '@material-ui/icons/Done';
import DownloadIcon from '@material-ui/icons/CloudDownload';

import PropTypes from 'prop-types';

import { connect } from 'react-redux'
import _ from 'lodash'

import selectors from '../../redux/selectors';
import { symbols } from '../../elements'
import StructureContainer from '../../containers/structure'
import { approveDataSet } from '../../redux/ducks/upload';
import { setProgress } from '../../redux/ducks/app';

import PageHead from '../page-head';
import PageBody from '../page-body';

import ValidateTable from './validate';
import EditToggle from './editToggle';

import './index.css'
import { CardActions } from '@material-ui/core';
import { push } from 'connected-react-router';
import moment from 'moment';

const tableLabelStyle = {
  fontSize: '18px',
  color: '#9E9E9E'
}

const tableStyle = {
    fontSize: '18px'
  }

const curatorCardStyle = {
  marginTop: '2rem'
}

class Dataset extends Component {

  constructor(props) {
    super(props);
    this.state = {
        approving: false,
        reconstructionMenu: {
          anchor: null,
          open: false
        },
        structureMenu: {
          anchor: null,
          open: false
        },
        projectionMenu: {
          anchor: null,
          open: false
        },
    }
  }

  approve = () => {
    this.props.dispatch(setProgress(true));
    this.props.dispatch(approveDataSet(this.props._id));
    this.setState({
      approving: true
    })
  }

  edit = () => {
    this.props.dispatch(push(`/dataset/${this.props._id}/edit`));
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.public && this.state.approving) {
      this.props.dispatch(setProgress(false));
      this.setState({
        approving: false
      });
    }
  }

  handleClick = (key, anchor) => {
    this.setState({[key]: {anchor: anchor}});
  };

  handleClose = () => {
    this.setState(
      {
        reconstructionMenu:{anchor: null},
        structureMenu: {anchor: null},
        projectionMenu: {anchor: null}
      }
    );
  };

  render = () => {
    const species = this.props.atomicSpecies.map((an) => symbols[an]).join(', ');
    const authors = this.props.authors.join(' and ');
    const mdbId = this.props.mdbId;
    const deposited = this.props.deposited;
    const released = this.props.released;
    const validation = this.props.validation;
    let r1 = 'N/A';
    if (!_.isNil(validation)) {
      r1 = this.props.validation.r1;
    }

    let isPublic = this.props.public;

    let {
      structure, reconstruction, projection, title,
      isCurator, doi, _id, editable, isOwner
    } = this.props;

    editable = _.isNil(editable) ? false : editable;
    let numberOfAtoms = -1;
    let structureUrl =  '';
    if (!_.isNil(structure)) {
        structureUrl = `${window.location.origin}/api/v1/mdb/datasets/_/structures/${structure._id}`;
        numberOfAtoms = structure.numberOfAtoms;
    }

    let reconEmdUrl = '';
    let reconTiffUrl = '';
    if (!_.isNil(reconstruction)) {
      reconEmdUrl = `${window.location.origin}/api/v1/mdb/datasets/_/reconstructions/${reconstruction._id}/emd`
      reconTiffUrl = `${window.location.origin}/api/v1/mdb/datasets/_/reconstructions/${reconstruction._id}/tiff`
    }

    let projEmdUrl = '';
    let projTiffUrl = '';
    if (!_.isNil(projection)) {
      projEmdUrl = `${window.location.origin}/api/v1/mdb/datasets/_/projections/${projection._id}/emd`
      projTiffUrl = `${window.location.origin}/api/v1/mdb/datasets/_/projections/${projection._id}/tiff`
    }

    // Prepare report data
    let jsonReportData = null;
    if (!_.isNil(projection) && !_.isNil(reconstruction)) {
      const data = {...projection, ...reconstruction};
      const jsonReport = encodeURIComponent(JSON.stringify(data,  null, 2));
      jsonReportData = `text/json;charset=utf-8, ${jsonReport}`;
    }

    return (

        <PageHead>
          <Typography  color="inherit" gutterBottom variant="display1">
            {title}
          </Typography>
          <Typography variant="subheading" paragraph color="inherit">
            {authors}
          </Typography>
        </PageHead>
        <PageBody>
          <Card>
            <CardContent>

                <TableBody>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      MDB ID
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {mdbId}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Name of the structure
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {title}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Total number of atoms
                    </TableCell>
                    { numberOfAtoms !== -1 &&
                    <TableCell style={{...tableStyle}}>
                      {numberOfAtoms}
                    </TableCell>
                    }
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      R1 factor
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {r1}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Atomic Species
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {species}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      DOI
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {_.isNil(doi) ? (
                        'N/A'
                      ) : (
                        <a href={`https://dx.doi.org/${doi}`}>
                          {doi}

                      )}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Deposition author(s)
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {authors}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Deposited
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {_.isNil(deposited) ? (
                        'N/A'
                      ) : (
                        moment(deposited).calendar()
                      )}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Released
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {_.isNil(released) ? (
                        'N/A'
                      ) : (
                        moment(released).calendar()
                      )}
                    </TableCell>
                  </TableRow>
                  { ( !_.isNil(projection) &&
                      (!_.isNil(projection.tiffFileId) ||
                       !_.isNil(projection.emdFileId))
                    ) &&
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Tilt series file
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      <IconButton
                        aria-label="More"
                        aria-owns={this.state.projectionMenu.anchor ? 'projection-menu' : null}
                        aria-haspopup="true"
                        onClick={(e) => {this.handleClick('projectionMenu', e.currentTarget)}}
                      >
                        <DownloadIcon />
                      </IconButton>
                      <Menu
                        id="projection-menu"
                        anchorEl={this.state.projectionMenu.anchor}
                        open={Boolean(this.state.projectionMenu.anchor)}
                        onClose={this.handleClose}
                      >
                        { !_.isNil(projection.tiffFileId) &&
                        <MenuItem
                          value="tiff"
                          onClick={this.handleClose}
                        >
                          TIFF
                        </MenuItem>
                        }
                        { !_.isNil(projection.emdFileId) &&
                        <MenuItem
                          value="emd"
                          onClick={this.handleClose}
                        >
                          EMD
                        </MenuItem>
                        }
                      </Menu>
                    </TableCell>
                  </TableRow>
                  }
                  { ( !_.isNil(reconstruction) &&
                     (!_.isNil(reconstruction.tiffFileId) ||
                      !_.isNil(reconstruction.emdFileId))
                    ) &&
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      3D reconstruction file
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      <IconButton
                        aria-label="More"
                        aria-owns={this.state.reconstructionMenu.anchor ? 'reconstruction-menu' : null}
                        aria-haspopup="true"
                        onClick={(e) => {this.handleClick('reconstructionMenu', e.currentTarget)}}
                      >
                        <DownloadIcon />
                      </IconButton>
                      <Menu
                        id="reconstruction-menu"
                        anchorEl={this.state.reconstructionMenu.anchor}
                        open={Boolean(this.state.reconstructionMenu.anchor)}
                        onClose={this.handleClose}
                      >
                        { !_.isNil(reconstruction.tiffFileId) &&
                        <MenuItem
                          value="tiff"
                          onClick={this.handleClose}
                        >
                          TIFF
                        </MenuItem>
                        }
                        { !_.isNil(reconstruction.emdFileId) &&
                        <MenuItem
                          value="emd"
                          onClick={this.handleClose}
                        >
                          EMD
                        </MenuItem>
                        }
                      </Menu>
                    </TableCell>
                  </TableRow>
                  }
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      3D atomic structure file
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      <IconButton
                        aria-label="More"
                        aria-owns={this.state.structureMenu.anchor ? 'structure-menu' : null}
                        aria-haspopup="true"
                        onClick={(e) => {this.handleClick('structureMenu', e.currentTarget)}}
                      >
                        <DownloadIcon />
                      </IconButton>
                      <Menu
                        id="structure-menu"
                        anchorEl={this.state.structureMenu.anchor}
                        open={Boolean(this.state.structureMenu.anchor)}
                        onClose={this.handleClose}
                      >
                        <MenuItem
                          value="xyz"
                          onClick={this.handleClose}
                        >
                          <a href={`${structureUrl}/xyz`}>XYZ
                        </MenuItem>
                        <MenuItem
                          value="cjson"
                          onClick={this.handleClose}
                        >
                          <a href={`${structureUrl}/cjson`}>CJSON
                        </MenuItem>
                        <MenuItem
                          value="cml"
                          onClick={this.handleClose}
                        >
                          <a href={`${structureUrl}/cml`}>CML
                        </MenuItem>
                      </Menu>
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Full report (MatData)
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                    <a href={`data:' + ${jsonReportData}`} download={`${mdbId}.json`}>
                      <IconButton>
                        <DownloadIcon />
                      </IconButton>

                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      License
                    </TableCell>
                    <TableCell style={{...tableStyle}}>

                        CC BY 4

                    </TableCell>
                  </TableRow>
                </TableBody>

                <StructureContainer _id={_id}/>

              { !isPublic &&
              <Typography color="textSecondary" style={{flexGrow: 1}}>* This dataset is awaiting approval.</Typography>
              }
            </CardContent>
            { (isCurator || isOwner) &&
            <CardActions style={{display: 'flex'}}>
              <Button
                style={{marginLeft: 'auto'}}
                variant="contained"
                color="primary"
                disabled={!editable && !isCurator}
                onClick={() => this.edit()}
              >
                <EditIcon/>
                Edit
              </Button>
            </CardActions>
            }
          </Card>
          { isCurator &&

            <Card>
              <CardContent>
                <ValidateTable _id={_id} />
                <EditToggle _id={_id} />
              </CardContent>
              <CardActions style={{display: 'flex'}}>
                { !isPublic &&
                <Button
                  style={{marginLeft: 'auto'}}
                  variant="contained"
                  color="primary"
                  disabled={this.state.approving}
                  onClick={() => this.approve()}
                >
                  <DoneIcon/>
                  Approve
                </Button>
                }
              </CardActions>
            </Card>

          }
        </PageBody>

    );
  }
}

Dataset.propTypes = {
  _id: PropTypes.string,
  userId: PropTypes.string,
  title: PropTypes.string,
  authors: PropTypes.array,
  imageFileId:  PropTypes.string,
  doi:  PropTypes.string,
  isCurator: PropTypes.bool,
  public: PropTypes.bool,
  reconstruction:PropTypes.object,
  projection:PropTypes.object,
  isOwner: PropTypes.bool
}

Dataset.defaultProps = {
  title: '',
  userId: null,
  authors: [],
  imageFileId:  null,
  atomicSpecies: [],
  doi: null,
  isCurator: false,
  public: false,
  reconstruction: {},
  projection: {},
  isOwner: false
}

function mapStateToProps(state, ownProps) {
  let props = {};

  if (!_.isNull(ownProps._id)) {
    let structures = selectors.structures.getStructuresById(state);
    if (_.has(structures, ownProps._id)) {
      // For now we only have a single structure, so just pick the first.
      const structure = structures[ownProps._id][0];
      props = {
        structure,
        public: structure.public
      }
    }

    let reconstructions = selectors.reconstructions.getReconstructionsById(state);
    if (_.has(reconstructions, ownProps._id)) {
      // For now we only have a single reconstruction, so just pick the first.
      const reconstruction = reconstructions[ownProps._id][0];
      props = {...props,
        reconstruction
      }

      if (_.has(reconstruction, 'emdFileId')) {
        props['emdFileId'] = reconstruction.emdFileId
      }

      if (_.has(reconstruction, 'tiffFileId')) {
        props['tiffFileId'] = reconstruction.tiffFileId
      }
    }

    let projections = selectors.projections.getProjectionsById(state);
    if (_.has(projections, ownProps._id)) {
      // For now we only have a single projection, so just pick the first.
      const projection = projections[ownProps._id][0];
      props = {...props,
        projection
      }

      if (_.has(projection, 'emdFileId')) {
        props['emdFileId'] = projection.emdFileId
      }

      if (_.has(projection, 'tiffFileId')) {
        props['tiffFileId'] = projection.tiffFileId
      }
    }
  }

  const me = selectors.girder.getMe(state);

  const curatorGroup = selectors.girder.getCuratorGroup(state);
  if (!_.isNil(curatorGroup)) {
    if (!_.isNil(me)) {
      props['isCurator'] = _.includes(me.groups, curatorGroup['_id'])
    }
  }

  if (!_.isNil(me)) {
    if (me._id === ownProps.userId) {
      props['isOwner'] = true;
    }
  }

  return props;
}

export default connect(mapStateToProps)(Dataset)
<commit_msg>Filter props to include in report<commit_after>import React, { Component } from 'react';

import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import IconButton from '@material-ui/core/IconButton';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
import Typography from '@material-ui/core/Typography';

import EditIcon from '@material-ui/icons/Edit';
import DoneIcon from '@material-ui/icons/Done';
import DownloadIcon from '@material-ui/icons/CloudDownload';

import PropTypes from 'prop-types';

import { connect } from 'react-redux'
import _ from 'lodash'

import selectors from '../../redux/selectors';
import { symbols } from '../../elements'
import StructureContainer from '../../containers/structure'
import { approveDataSet } from '../../redux/ducks/upload';
import { setProgress } from '../../redux/ducks/app';

import PageHead from '../page-head';
import PageBody from '../page-body';

import ValidateTable from './validate';
import EditToggle from './editToggle';
import {
  generalInformationFields,
  dataCollectionFields,
  reconstructionFields
} from '../deposit/fields'

import './index.css'
import { CardActions } from '@material-ui/core';
import { push } from 'connected-react-router';
import moment from 'moment';

const tableLabelStyle = {
  fontSize: '18px',
  color: '#9E9E9E'
}

const tableStyle = {
    fontSize: '18px'
  }

const curatorCardStyle = {
  marginTop: '2rem'
}

class Dataset extends Component {

  constructor(props) {
    super(props);
    this.state = {
        approving: false,
        reconstructionMenu: {
          anchor: null,
          open: false
        },
        structureMenu: {
          anchor: null,
          open: false
        },
        projectionMenu: {
          anchor: null,
          open: false
        },
    }
  }

  approve = () => {
    this.props.dispatch(setProgress(true));
    this.props.dispatch(approveDataSet(this.props._id));
    this.setState({
      approving: true
    })
  }

  edit = () => {
    this.props.dispatch(push(`/dataset/${this.props._id}/edit`));
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.public && this.state.approving) {
      this.props.dispatch(setProgress(false));
      this.setState({
        approving: false
      });
    }
  }

  handleClick = (key, anchor) => {
    this.setState({[key]: {anchor: anchor}});
  };

  handleClose = () => {
    this.setState(
      {
        reconstructionMenu:{anchor: null},
        structureMenu: {anchor: null},
        projectionMenu: {anchor: null}
      }
    );
  };

  render = () => {
    const species = this.props.atomicSpecies.map((an) => symbols[an]).join(', ');
    const authors = this.props.authors.join(' and ');
    const mdbId = this.props.mdbId;
    const deposited = this.props.deposited;
    const released = this.props.released;
    const validation = this.props.validation;
    let r1 = 'N/A';
    if (!_.isNil(validation)) {
      r1 = this.props.validation.r1;
    }

    let isPublic = this.props.public;

    let {
      structure, reconstruction, projection, title,
      isCurator, doi, _id, editable, isOwner
    } = this.props;

    editable = _.isNil(editable) ? false : editable;
    let numberOfAtoms = -1;
    let structureUrl =  '';
    if (!_.isNil(structure)) {
        structureUrl = `${window.location.origin}/api/v1/mdb/datasets/_/structures/${structure._id}`;
        numberOfAtoms = structure.numberOfAtoms;
    }

    let reconEmdUrl = '';
    let reconTiffUrl = '';
    if (!_.isNil(reconstruction)) {
      reconEmdUrl = `${window.location.origin}/api/v1/mdb/datasets/_/reconstructions/${reconstruction._id}/emd`
      reconTiffUrl = `${window.location.origin}/api/v1/mdb/datasets/_/reconstructions/${reconstruction._id}/tiff`
    }

    let projEmdUrl = '';
    let projTiffUrl = '';
    if (!_.isNil(projection)) {
      projEmdUrl = `${window.location.origin}/api/v1/mdb/datasets/_/projections/${projection._id}/emd`
      projTiffUrl = `${window.location.origin}/api/v1/mdb/datasets/_/projections/${projection._id}/tiff`
    }

    // Prepare report data
    let jsonReportData = null;
    if (!_.isNil(projection) && !_.isNil(reconstruction)) {
      // Filter the ones we want
      const dataSetProps = _.pick(this.props, Object.keys(generalInformationFields()));
      const projectionProps = _.pick(projection, Object.keys(dataCollectionFields()));
      const reconstructionProps = _.pick(reconstruction, Object.keys(reconstructionFields()));

      // Combine and encode
      const data = {...dataSetProps, ...projectionProps, ...reconstructionProps};
      const jsonReport = encodeURIComponent(JSON.stringify(data,  null, 2));
      jsonReportData = `text/json;charset=utf-8, ${jsonReport}`;
    }

    return (

        <PageHead>
          <Typography  color="inherit" gutterBottom variant="display1">
            {title}
          </Typography>
          <Typography variant="subheading" paragraph color="inherit">
            {authors}
          </Typography>
        </PageHead>
        <PageBody>
          <Card>
            <CardContent>

                <TableBody>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      MDB ID
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {mdbId}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Name of the structure
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {title}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Total number of atoms
                    </TableCell>
                    { numberOfAtoms !== -1 &&
                    <TableCell style={{...tableStyle}}>
                      {numberOfAtoms}
                    </TableCell>
                    }
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      R1 factor
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {r1}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Atomic Species
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {species}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      DOI
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {_.isNil(doi) ? (
                        'N/A'
                      ) : (
                        <a href={`https://dx.doi.org/${doi}`}>
                          {doi}

                      )}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Deposition author(s)
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {authors}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Deposited
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {_.isNil(deposited) ? (
                        'N/A'
                      ) : (
                        moment(deposited).calendar()
                      )}
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Released
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      {_.isNil(released) ? (
                        'N/A'
                      ) : (
                        moment(released).calendar()
                      )}
                    </TableCell>
                  </TableRow>
                  { ( !_.isNil(projection) &&
                      (!_.isNil(projection.tiffFileId) ||
                       !_.isNil(projection.emdFileId))
                    ) &&
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Tilt series file
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      <IconButton
                        aria-label="More"
                        aria-owns={this.state.projectionMenu.anchor ? 'projection-menu' : null}
                        aria-haspopup="true"
                        onClick={(e) => {this.handleClick('projectionMenu', e.currentTarget)}}
                      >
                        <DownloadIcon />
                      </IconButton>
                      <Menu
                        id="projection-menu"
                        anchorEl={this.state.projectionMenu.anchor}
                        open={Boolean(this.state.projectionMenu.anchor)}
                        onClose={this.handleClose}
                      >
                        { !_.isNil(projection.tiffFileId) &&
                        <MenuItem
                          value="tiff"
                          onClick={this.handleClose}
                        >
                          TIFF
                        </MenuItem>
                        }
                        { !_.isNil(projection.emdFileId) &&
                        <MenuItem
                          value="emd"
                          onClick={this.handleClose}
                        >
                          EMD
                        </MenuItem>
                        }
                      </Menu>
                    </TableCell>
                  </TableRow>
                  }
                  { ( !_.isNil(reconstruction) &&
                     (!_.isNil(reconstruction.tiffFileId) ||
                      !_.isNil(reconstruction.emdFileId))
                    ) &&
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      3D reconstruction file
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      <IconButton
                        aria-label="More"
                        aria-owns={this.state.reconstructionMenu.anchor ? 'reconstruction-menu' : null}
                        aria-haspopup="true"
                        onClick={(e) => {this.handleClick('reconstructionMenu', e.currentTarget)}}
                      >
                        <DownloadIcon />
                      </IconButton>
                      <Menu
                        id="reconstruction-menu"
                        anchorEl={this.state.reconstructionMenu.anchor}
                        open={Boolean(this.state.reconstructionMenu.anchor)}
                        onClose={this.handleClose}
                      >
                        { !_.isNil(reconstruction.tiffFileId) &&
                        <MenuItem
                          value="tiff"
                          onClick={this.handleClose}
                        >
                          TIFF
                        </MenuItem>
                        }
                        { !_.isNil(reconstruction.emdFileId) &&
                        <MenuItem
                          value="emd"
                          onClick={this.handleClose}
                        >
                          EMD
                        </MenuItem>
                        }
                      </Menu>
                    </TableCell>
                  </TableRow>
                  }
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      3D atomic structure file
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                      <IconButton
                        aria-label="More"
                        aria-owns={this.state.structureMenu.anchor ? 'structure-menu' : null}
                        aria-haspopup="true"
                        onClick={(e) => {this.handleClick('structureMenu', e.currentTarget)}}
                      >
                        <DownloadIcon />
                      </IconButton>
                      <Menu
                        id="structure-menu"
                        anchorEl={this.state.structureMenu.anchor}
                        open={Boolean(this.state.structureMenu.anchor)}
                        onClose={this.handleClose}
                      >
                        <MenuItem
                          value="xyz"
                          onClick={this.handleClose}
                        >
                          <a href={`${structureUrl}/xyz`}>XYZ
                        </MenuItem>
                        <MenuItem
                          value="cjson"
                          onClick={this.handleClose}
                        >
                          <a href={`${structureUrl}/cjson`}>CJSON
                        </MenuItem>
                        <MenuItem
                          value="cml"
                          onClick={this.handleClose}
                        >
                          <a href={`${structureUrl}/cml`}>CML
                        </MenuItem>
                      </Menu>
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      Full report (MatData)
                    </TableCell>
                    <TableCell style={{...tableStyle}}>
                    <a href={`data:' + ${jsonReportData}`} download={`${mdbId}.json`}>
                      <IconButton>
                        <DownloadIcon />
                      </IconButton>

                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell style={{...tableLabelStyle}}>
                      License
                    </TableCell>
                    <TableCell style={{...tableStyle}}>

                        CC BY 4

                    </TableCell>
                  </TableRow>
                </TableBody>

                <StructureContainer _id={_id}/>

              { !isPublic &&
              <Typography color="textSecondary" style={{flexGrow: 1}}>* This dataset is awaiting approval.</Typography>
              }
            </CardContent>
            { (isCurator || isOwner) &&
            <CardActions style={{display: 'flex'}}>
              <Button
                style={{marginLeft: 'auto'}}
                variant="contained"
                color="primary"
                disabled={!editable && !isCurator}
                onClick={() => this.edit()}
              >
                <EditIcon/>
                Edit
              </Button>
            </CardActions>
            }
          </Card>
          { isCurator &&

            <Card>
              <CardContent>
                <ValidateTable _id={_id} />
                <EditToggle _id={_id} />
              </CardContent>
              <CardActions style={{display: 'flex'}}>
                { !isPublic &&
                <Button
                  style={{marginLeft: 'auto'}}
                  variant="contained"
                  color="primary"
                  disabled={this.state.approving}
                  onClick={() => this.approve()}
                >
                  <DoneIcon/>
                  Approve
                </Button>
                }
              </CardActions>
            </Card>

          }
        </PageBody>

    );
  }
}

Dataset.propTypes = {
  _id: PropTypes.string,
  userId: PropTypes.string,
  title: PropTypes.string,
  authors: PropTypes.array,
  imageFileId:  PropTypes.string,
  doi:  PropTypes.string,
  isCurator: PropTypes.bool,
  public: PropTypes.bool,
  reconstruction:PropTypes.object,
  projection:PropTypes.object,
  isOwner: PropTypes.bool
}

Dataset.defaultProps = {
  title: '',
  userId: null,
  authors: [],
  imageFileId:  null,
  atomicSpecies: [],
  doi: null,
  isCurator: false,
  public: false,
  reconstruction: {},
  projection: {},
  isOwner: false
}

function mapStateToProps(state, ownProps) {
  let props = {};

  if (!_.isNull(ownProps._id)) {
    let structures = selectors.structures.getStructuresById(state);
    if (_.has(structures, ownProps._id)) {
      // For now we only have a single structure, so just pick the first.
      const structure = structures[ownProps._id][0];
      props = {
        structure,
        public: structure.public
      }
    }

    let reconstructions = selectors.reconstructions.getReconstructionsById(state);
    if (_.has(reconstructions, ownProps._id)) {
      // For now we only have a single reconstruction, so just pick the first.
      const reconstruction = reconstructions[ownProps._id][0];
      props = {...props,
        reconstruction
      }

      if (_.has(reconstruction, 'emdFileId')) {
        props['emdFileId'] = reconstruction.emdFileId
      }

      if (_.has(reconstruction, 'tiffFileId')) {
        props['tiffFileId'] = reconstruction.tiffFileId
      }
    }

    let projections = selectors.projections.getProjectionsById(state);
    if (_.has(projections, ownProps._id)) {
      // For now we only have a single projection, so just pick the first.
      const projection = projections[ownProps._id][0];
      props = {...props,
        projection
      }

      if (_.has(projection, 'emdFileId')) {
        props['emdFileId'] = projection.emdFileId
      }

      if (_.has(projection, 'tiffFileId')) {
        props['tiffFileId'] = projection.tiffFileId
      }
    }
  }

  const me = selectors.girder.getMe(state);

  const curatorGroup = selectors.girder.getCuratorGroup(state);
  if (!_.isNil(curatorGroup)) {
    if (!_.isNil(me)) {
      props['isCurator'] = _.includes(me.groups, curatorGroup['_id'])
    }
  }

  if (!_.isNil(me)) {
    if (me._id === ownProps.userId) {
      props['isOwner'] = true;
    }
  }

  return props;
}

export default connect(mapStateToProps)(Dataset)
<|endoftext|>


<commit_before>(function(define) {
'use strict';
define(function(require) {

var panthrMath;

panthrMath = require('panthr-math');

return function(loader) {
   /**
    * create and populate the math module. FIXME later
    * @module math
    * @author Haris Skiadas <skiadas@hanover.edu>
    * Barb Wahl <wahl@hanover.edu>
    */
   loader.addModule('math', {});
   loader.addModuleMethod('math', 'bd0', panthrMath.bd0);
   loader.addModuleMethod('math', 'bratio', panthrMath.bratio);
   loader.addModuleMethod('math', 'dbinomLog', panthrMath.dbinomLog);
   loader.addModuleMethod('math', 'erf', panthrMath.erf);
   loader.addModuleMethod('math', 'erfc', panthrMath.erfc);
   loader.addModuleMethod('math', 'gam1', panthrMath.gam1);
   loader.addModuleMethod('math', 'gratio', panthrMath.gratio);
   loader.addModuleMethod('math', 'gratioc', panthrMath.gratioc);
   loader.addModuleMethod('math', 'gaminv', panthrMath.gaminv);
   loader.addModuleMethod('math', 'gratR', panthrMath.gratR);
   loader.addModuleMethod('math', 'expm1', panthrMath.expm1);
   loader.addModuleMethod('math', 'lbeta', panthrMath.lbeta);
   loader.addModuleMethod('math', 'beta', panthrMath.beta);
   loader.addModuleMethod('math', 'lgamma', panthrMath.lgamma);
   loader.addModuleMethod('math', 'gamma', panthrMath.gamma);
   loader.addModuleMethod('math', 'log1p', panthrMath.log1p);
   loader.addModuleMethod('math', 'log10', panthrMath.log10);
   loader.addModuleMethod('math', 'log2', panthrMath.log2);
   loader.addModuleMethod('math', 'lpoisson', panthrMath.lpoisson);
   loader.addModuleMethod('math', 'phi', panthrMath.phi);
   loader.addModuleMethod('math', 'stirlerr', panthrMath.stirlerr);
};

});

}(typeof define === 'function' && define.amd ? define : function(factory) {
   'use strict';
   module.exports = factory(require);
}));
<commit_msg>Export lchoose and choose<commit_after>(function(define) {
'use strict';
define(function(require) {

var panthrMath;

panthrMath = require('panthr-math');

return function(loader) {
   /**
    * create and populate the math module. FIXME later
    * @module math
    * @author Haris Skiadas <skiadas@hanover.edu>
    * Barb Wahl <wahl@hanover.edu>
    */
   loader.addModule('math', {});
   loader.addModuleMethod('math', 'bd0', panthrMath.bd0);
   loader.addModuleMethod('math', 'bratio', panthrMath.bratio);
   loader.addModuleMethod('math', 'dbinomLog', panthrMath.dbinomLog);
   loader.addModuleMethod('math', 'erf', panthrMath.erf);
   loader.addModuleMethod('math', 'erfc', panthrMath.erfc);
   loader.addModuleMethod('math', 'gam1', panthrMath.gam1);
   loader.addModuleMethod('math', 'gratio', panthrMath.gratio);
   loader.addModuleMethod('math', 'gratioc', panthrMath.gratioc);
   loader.addModuleMethod('math', 'gaminv', panthrMath.gaminv);
   loader.addModuleMethod('math', 'gratR', panthrMath.gratR);
   loader.addModuleMethod('math', 'expm1', panthrMath.expm1);
   loader.addModuleMethod('math', 'lbeta', panthrMath.lbeta);
   loader.addModuleMethod('math', 'beta', panthrMath.beta);
   loader.addModuleMethod('math', 'lgamma', panthrMath.lgamma);
   loader.addModuleMethod('math', 'gamma', panthrMath.gamma);
   loader.addModuleMethod('math', 'lchoose', panthrMath.lchoose);
   loader.addModuleMethod('math', 'choose', panthrMath.choose);
   loader.addModuleMethod('math', 'log1p', panthrMath.log1p);
   loader.addModuleMethod('math', 'log10', panthrMath.log10);
   loader.addModuleMethod('math', 'log2', panthrMath.log2);
   loader.addModuleMethod('math', 'lpoisson', panthrMath.lpoisson);
   loader.addModuleMethod('math', 'phi', panthrMath.phi);
   loader.addModuleMethod('math', 'stirlerr', panthrMath.stirlerr);
};

});

}(typeof define === 'function' && define.amd ? define : function(factory) {
   'use strict';
   module.exports = factory(require);
}));
<|endoftext|>


<commit_before>import API, { Settings } from "api"
import AppContext from "components/AppContext"
import Autocomplete from "components/Autocomplete"
import * as FieldHelper from "components/FieldHelper"
import Fieldset from "components/Fieldset"
import LinkTo from "components/LinkTo"
import Messages from "components/Messages"
import MultiSelector from "components/MultiSelector"
import NavigationWarning from "components/NavigationWarning"
import { jumpToTop } from "components/Page"
import TaskTable from "components/TaskTable"
import { Field, FieldArray, Form, Formik } from "formik"
import { Organization, Person, Position, Task } from "models"
import PropTypes from "prop-types"
import React, { Component } from "react"
import { Button, Modal, Table } from "react-bootstrap"
import { withRouter } from "react-router-dom"
import REMOVE_ICON from "resources/delete.png"
import ORGANIZATIONS_ICON from "resources/organizations.png"
import POSITIONS_ICON from "resources/positions.png"
import TASKS_ICON from "resources/tasks.png"
import utils from "utils"
import DictionaryField from "../../HOC/DictionaryField"

const ApproverTable = props => (

        Name
        Position

      {props.approvers.map((approver, approverIndex) => (

            <LinkTo person={approver.person} target="_blank" />

            <LinkTo position={approver} target="_blank" />

           props.onDelete(approver)}>

      ))}

)

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

  static defaultProps = {
    initialValues: new Organization(),
    title: "",
    edit: false
  }

  statusButtons = [
    {
      id: "statusActiveButton",
      value: Organization.STATUS.ACTIVE,
      label: "Active"
    },
    {
      id: "statusInactiveButton",
      value: Organization.STATUS.INACTIVE,
      label: "Inactive"
    }
  ]
  typeButtons = [
    {
      id: "typeAdvisorButton",
      value: Organization.TYPE.ADVISOR_ORG,
      label: Settings.fields.advisor.org.name
    },
    {
      id: "typePrincipalButton",
      value: Organization.TYPE.PRINCIPAL_ORG,
      label: Settings.fields.principal.org.name
    }
  ]
  IdentificationCodeFieldWithLabel = DictionaryField(Field)
  LongNameWithLabel = DictionaryField(Field)
  state = {
    error: null,
    showAddApprovalStepAlert: false,
    showRemoveApprovalStepAlert: false
  }

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

    return (
      <Formik
        enableReinitialize
        onSubmit={this.onSubmit}
        validationSchema={Organization.yupSchema}
        isInitialValid
        {...myFormProps}
      >
        {({
          handleSubmit,
          isSubmitting,
          isValid,
          dirty,
          errors,
          setFieldValue,
          values,
          submitForm
        }) => {
          const isAdmin = currentUser && currentUser.isAdmin()
          const isAdvisorOrg = values.type === Organization.TYPE.ADVISOR_ORG
          const isPrincipalOrg = values.type === Organization.TYPE.PRINCIPAL_ORG
          const orgSettings = isPrincipalOrg
            ? Settings.fields.principal.org
            : Settings.fields.advisor.org
          const orgSearchQuery = {
            status: Organization.STATUS.ACTIVE,
            type: values.type
          }
          // Reset the parentOrg property when changing the organization type
          if (
            values.parentOrg &&
            values.parentOrg.type &&
            values.parentOrg.type !== values.type
          ) {
            values.parentOrg = {}
          }
          const action = (isAdmin || !isPrincipalOrg) && (

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

          )
          return (

              <NavigationWarning isBlocking={dirty} />
              <Messages error={this.state.error} />
              <Form className="form-horizontal" method="post">
                <Fieldset title={title} action={action} />
                <Fieldset>
                  {!isAdmin ? (
                    <Field
                      name="type"
                      component={FieldHelper.renderReadonlyField}
                      humanValue={Organization.humanNameOfType}
                    />
                  ) : (
                    <Field
                      name="type"
                      component={FieldHelper.renderButtonToggleGroup}
                      buttons={this.typeButtons}
                    />
                  )}

                  {!isAdmin && isPrincipalOrg ? (
                    <React.Fragment>
                      <Field
                        name="parentOrg"
                        component={FieldHelper.renderReadonlyField}
                        label={Settings.fields.organization.parentOrg}
                        humanValue={
                          values.parentOrg && (
                            <LinkTo organization={values.parentOrg}>
                              {values.parentOrg.shortName}{" "}
                              {values.parentOrg.longName}{" "}
                              {values.parentOrg.identificationCode}
                            </LinkTo>
                          )
                        }
                      />
                      <Field
                        name="shortName"
                        component={FieldHelper.renderReadonlyField}
                        label={Settings.fields.organization.shortName}
                      />
                      <this.LongNameWithLabel
                        dictProps={orgSettings.longName}
                        name="longName"
                        component={FieldHelper.renderReadonlyField}
                      />
                      <Field
                        name="status"
                        component={FieldHelper.renderReadonlyField}
                        humanValue={Organization.humanNameOfStatus}
                      />
                    </React.Fragment>
                  ) : (
                    <React.Fragment>
                      <Field
                        name="parentOrg"
                        component={FieldHelper.renderSpecialField}
                        label={Settings.fields.organization.parentOrg}
                        onChange={value => setFieldValue("parentOrg", value)}
                        addon={ORGANIZATIONS_ICON}
                        widget={
                          <Autocomplete
                            objectType={Organization}
                            valueKey="shortName"
                            fields={Organization.autocompleteQuery}
                            placeholder="Start typing to search for a higher level organization..."
                            queryParams={orgSearchQuery}
                            template={Organization.autocompleteTemplate}
                          />
                        }
                      />
                      <Field
                        name="shortName"
                        component={FieldHelper.renderInputField}
                        label={Settings.fields.organization.shortName}
                        placeholder="e.g. EF1.1"
                      />
                      <this.LongNameWithLabel
                        dictProps={orgSettings.longName}
                        name="longName"
                        component={FieldHelper.renderInputField}
                      />
                      <Field
                        name="status"
                        component={FieldHelper.renderButtonToggleGroup}
                        buttons={this.statusButtons}
                      />
                    </React.Fragment>
                  )}

                  {!isAdmin ? (
                    <this.IdentificationCodeFieldWithLabel
                      dictProps={orgSettings.identificationCode}
                      name="identificationCode"
                      component={FieldHelper.renderReadonlyField}
                    />
                  ) : (
                    <this.IdentificationCodeFieldWithLabel
                      dictProps={orgSettings.identificationCode}
                      name="identificationCode"
                      component={FieldHelper.renderInputField}
                    />
                  )}
                </Fieldset>

                {isAdvisorOrg && (

                    <Fieldset title="Approval process">
                      <FieldArray
                        name="approvalSteps"
                        render={arrayHelpers => (

                            <Button
                              className="pull-right"
                              onClick={() =>
                                this.addApprovalStep(arrayHelpers, values)
                              }
                              bsStyle="primary"
                              id="addApprovalStepButton"
                            >
                              Add an Approval Step
                            </Button>
                            <Modal
                              show={this.state.showAddApprovalStepAlert}
                              onHide={this.hideAddApprovalStepAlert}
                            >
                              <Modal.Header closeButton>
                                <Modal.Title>Step not added</Modal.Title>
                              </Modal.Header>
                              <Modal.Body>
                                Please complete all approval steps; there
                                already is an approval step that is not
                                completely filled in.
                              </Modal.Body>
                              <Modal.Footer>
                                <Button
                                  className="pull-right"
                                  onClick={this.hideAddApprovalStepAlert}
                                  bsStyle="primary"
                                >
                                  OK
                                </Button>
                              </Modal.Footer>
                            </Modal>
                            <Modal
                              show={this.state.showRemoveApprovalStepAlert}
                              onHide={this.hideRemoveApprovalStepAlert}
                            >
                              <Modal.Header closeButton>
                                <Modal.Title>Step not removed</Modal.Title>
                              </Modal.Header>
                              <Modal.Body>
                                You cannot remove this step; it is being used in
                                a report.
                              </Modal.Body>
                              <Modal.Footer>
                                <Button
                                  className="pull-right"
                                  onClick={this.hideRemoveApprovalStepAlert}
                                  bsStyle="primary"
                                >
                                  OK
                                </Button>
                              </Modal.Footer>
                            </Modal>

                            {values.approvalSteps.map((step, index) =>
                              this.renderApprovalStep(
                                arrayHelpers,
                                setFieldValue,
                                step,
                                index
                              )
                            )}

                        )}
                      />
                    </Fieldset>

                    {Organization.isTaskEnabled(values.shortName) && (
                      <Fieldset
                        title={Settings.fields.task.longLabel}
                        className="tasks-selector"
                      >
                        <MultiSelector
                          items={values.tasks}
                          objectType={Task}
                          queryParams={{ status: Task.STATUS.ACTIVE }}
                          placeholder={`Start typing to search for ${
                            Settings.fields.task.shortLabel
                          }...`}
                          fields={Task.autocompleteQuery}
                          template={Task.autocompleteTemplate}
                          addFieldName="tasks"
                          addFieldLabel={Settings.fields.task.shortLabel}
                          addon={TASKS_ICON}
                          renderSelected={
                            <TaskTable tasks={values.tasks} showDelete />
                          }
                          onChange={value => setFieldValue("tasks", value)}
                        />
                      </Fieldset>
                    )}

                )}

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

                  {(isAdmin || !isPrincipalOrg) && (

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

                  )}

              </Form>

          )
        }}
      </Formik>
    )
  }

  renderApprovalStep = (arrayHelpers, setFieldValue, step, index) => {
    const approvers = step.approvers

    return (
      <Fieldset title={`Step ${index + 1}`} key={index}>
        <Button
          className="pull-right"
          title="Remove this step"
          onClick={() => this.removeApprovalStep(arrayHelpers, index, step)}
        >

        </Button>

        <Field
          name={`approvalSteps.${index}.name`}
          component={FieldHelper.renderInputField}
          label="Step name"
        />

        <MultiSelector
          items={approvers}
          objectType={Position}
          queryParams={{
            status: Position.STATUS.ACTIVE,
            type: [
              Position.TYPE.ADVISOR,
              Position.TYPE.SUPER_USER,
              Position.TYPE.ADMINISTRATOR
            ],
            matchPersonName: true
          }}
          placeholder="Search for the approver's position"
          fields="uuid, name, code, type, person { uuid, name, rank, role }"
          template={position => (

              {" "}
              {position.person && (

                  {" "}
                  <LinkTo person={position.person} isLink={false} /> -{" "}

              )}{" "}
              <LinkTo position={position} isLink={false} />{" "}
              {position.code &&  - {position.code} }{" "}

          )}
          addFieldName={`approvalSteps.${index}.approvers`}
          addFieldLabel="Add an approver"
          addon={POSITIONS_ICON}
          renderSelected={<ApproverTable approvers={approvers} />}
          onChange={value =>
            setFieldValue(`approvalSteps.${index}.approvers`, value)
          }
        />
      </Fieldset>
    )
  }

  hideAddApprovalStepAlert = () => {
    this.setState({ showAddApprovalStepAlert: false })
  }

  hideRemoveApprovalStepAlert = () => {
    this.setState({ showRemoveApprovalStepAlert: false })
  }

  addApprovalStep = (arrayHelpers, values) => {
    const approvalSteps = values.approvalSteps || []

    for (let i = 0; i < approvalSteps.length; i++) {
      const step = approvalSteps[i]
      if (!step.name || !step.approvers || step.approvers.length === 0) {
        this.setState({ showAddApprovalStepAlert: true })
        return
      }
    }

    arrayHelpers.push({ name: "", approvers: [] })
  }

  removeApprovalStep = (arrayHelpers, index, step) => {
    return API.query(
      /* GraphQL */ `
      approvalStepInUse(uuid:"${step.uuid}")
    `
    ).then(data => {
      if (data) {
        this.setState({ showRemoveApprovalStepAlert: true })
      } else {
        arrayHelpers.remove(index)
      }
    })
  }

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

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

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

  save = (values, form) => {
    const organization = Object.without(
      new Organization(values),
      "childrenOrgs",
      "positions"
    )
    organization.parentOrg = utils.getReference(organization.parentOrg)
    const { edit } = this.props
    const operation = edit ? "updateOrganization" : "createOrganization"
    let graphql = operation + "(organization: $organization)"
    graphql += edit ? "" : " { uuid }"
    const variables = { organization: organization }
    const variableDef = "($organization: OrganizationInput!)"
    return API.mutation(graphql, variables, variableDef)
  }
}

const OrganizationForm = props => (
  <AppContext.Consumer>
    {context => (
      <BaseOrganizationForm currentUser={context.currentUser} {...props} />
    )}
  </AppContext.Consumer>
)

export default withRouter(OrganizationForm)
<commit_msg>NCI-Agency/anet#1530: Correct check if approval step is used in report<commit_after>import API, { Settings } from "api"
import AppContext from "components/AppContext"
import Autocomplete from "components/Autocomplete"
import * as FieldHelper from "components/FieldHelper"
import Fieldset from "components/Fieldset"
import LinkTo from "components/LinkTo"
import Messages from "components/Messages"
import MultiSelector from "components/MultiSelector"
import NavigationWarning from "components/NavigationWarning"
import { jumpToTop } from "components/Page"
import TaskTable from "components/TaskTable"
import { Field, FieldArray, Form, Formik } from "formik"
import { Organization, Person, Position, Task } from "models"
import PropTypes from "prop-types"
import React, { Component } from "react"
import { Button, Modal, Table } from "react-bootstrap"
import { withRouter } from "react-router-dom"
import REMOVE_ICON from "resources/delete.png"
import ORGANIZATIONS_ICON from "resources/organizations.png"
import POSITIONS_ICON from "resources/positions.png"
import TASKS_ICON from "resources/tasks.png"
import utils from "utils"
import DictionaryField from "../../HOC/DictionaryField"

const ApproverTable = props => (

        Name
        Position

      {props.approvers.map((approver, approverIndex) => (

            <LinkTo person={approver.person} target="_blank" />

            <LinkTo position={approver} target="_blank" />

           props.onDelete(approver)}>

      ))}

)

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

  static defaultProps = {
    initialValues: new Organization(),
    title: "",
    edit: false
  }

  statusButtons = [
    {
      id: "statusActiveButton",
      value: Organization.STATUS.ACTIVE,
      label: "Active"
    },
    {
      id: "statusInactiveButton",
      value: Organization.STATUS.INACTIVE,
      label: "Inactive"
    }
  ]
  typeButtons = [
    {
      id: "typeAdvisorButton",
      value: Organization.TYPE.ADVISOR_ORG,
      label: Settings.fields.advisor.org.name
    },
    {
      id: "typePrincipalButton",
      value: Organization.TYPE.PRINCIPAL_ORG,
      label: Settings.fields.principal.org.name
    }
  ]
  IdentificationCodeFieldWithLabel = DictionaryField(Field)
  LongNameWithLabel = DictionaryField(Field)
  state = {
    error: null,
    showAddApprovalStepAlert: false,
    showRemoveApprovalStepAlert: false
  }

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

    return (
      <Formik
        enableReinitialize
        onSubmit={this.onSubmit}
        validationSchema={Organization.yupSchema}
        isInitialValid
        {...myFormProps}
      >
        {({
          handleSubmit,
          isSubmitting,
          isValid,
          dirty,
          errors,
          setFieldValue,
          values,
          submitForm
        }) => {
          const isAdmin = currentUser && currentUser.isAdmin()
          const isAdvisorOrg = values.type === Organization.TYPE.ADVISOR_ORG
          const isPrincipalOrg = values.type === Organization.TYPE.PRINCIPAL_ORG
          const orgSettings = isPrincipalOrg
            ? Settings.fields.principal.org
            : Settings.fields.advisor.org
          const orgSearchQuery = {
            status: Organization.STATUS.ACTIVE,
            type: values.type
          }
          // Reset the parentOrg property when changing the organization type
          if (
            values.parentOrg &&
            values.parentOrg.type &&
            values.parentOrg.type !== values.type
          ) {
            values.parentOrg = {}
          }
          const action = (isAdmin || !isPrincipalOrg) && (

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

          )
          return (

              <NavigationWarning isBlocking={dirty} />
              <Messages error={this.state.error} />
              <Form className="form-horizontal" method="post">
                <Fieldset title={title} action={action} />
                <Fieldset>
                  {!isAdmin ? (
                    <Field
                      name="type"
                      component={FieldHelper.renderReadonlyField}
                      humanValue={Organization.humanNameOfType}
                    />
                  ) : (
                    <Field
                      name="type"
                      component={FieldHelper.renderButtonToggleGroup}
                      buttons={this.typeButtons}
                    />
                  )}

                  {!isAdmin && isPrincipalOrg ? (
                    <React.Fragment>
                      <Field
                        name="parentOrg"
                        component={FieldHelper.renderReadonlyField}
                        label={Settings.fields.organization.parentOrg}
                        humanValue={
                          values.parentOrg && (
                            <LinkTo organization={values.parentOrg}>
                              {values.parentOrg.shortName}{" "}
                              {values.parentOrg.longName}{" "}
                              {values.parentOrg.identificationCode}
                            </LinkTo>
                          )
                        }
                      />
                      <Field
                        name="shortName"
                        component={FieldHelper.renderReadonlyField}
                        label={Settings.fields.organization.shortName}
                      />
                      <this.LongNameWithLabel
                        dictProps={orgSettings.longName}
                        name="longName"
                        component={FieldHelper.renderReadonlyField}
                      />
                      <Field
                        name="status"
                        component={FieldHelper.renderReadonlyField}
                        humanValue={Organization.humanNameOfStatus}
                      />
                    </React.Fragment>
                  ) : (
                    <React.Fragment>
                      <Field
                        name="parentOrg"
                        component={FieldHelper.renderSpecialField}
                        label={Settings.fields.organization.parentOrg}
                        onChange={value => setFieldValue("parentOrg", value)}
                        addon={ORGANIZATIONS_ICON}
                        widget={
                          <Autocomplete
                            objectType={Organization}
                            valueKey="shortName"
                            fields={Organization.autocompleteQuery}
                            placeholder="Start typing to search for a higher level organization..."
                            queryParams={orgSearchQuery}
                            template={Organization.autocompleteTemplate}
                          />
                        }
                      />
                      <Field
                        name="shortName"
                        component={FieldHelper.renderInputField}
                        label={Settings.fields.organization.shortName}
                        placeholder="e.g. EF1.1"
                      />
                      <this.LongNameWithLabel
                        dictProps={orgSettings.longName}
                        name="longName"
                        component={FieldHelper.renderInputField}
                      />
                      <Field
                        name="status"
                        component={FieldHelper.renderButtonToggleGroup}
                        buttons={this.statusButtons}
                      />
                    </React.Fragment>
                  )}

                  {!isAdmin ? (
                    <this.IdentificationCodeFieldWithLabel
                      dictProps={orgSettings.identificationCode}
                      name="identificationCode"
                      component={FieldHelper.renderReadonlyField}
                    />
                  ) : (
                    <this.IdentificationCodeFieldWithLabel
                      dictProps={orgSettings.identificationCode}
                      name="identificationCode"
                      component={FieldHelper.renderInputField}
                    />
                  )}
                </Fieldset>

                {isAdvisorOrg && (

                    <Fieldset title="Approval process">
                      <FieldArray
                        name="approvalSteps"
                        render={arrayHelpers => (

                            <Button
                              className="pull-right"
                              onClick={() =>
                                this.addApprovalStep(arrayHelpers, values)
                              }
                              bsStyle="primary"
                              id="addApprovalStepButton"
                            >
                              Add an Approval Step
                            </Button>
                            <Modal
                              show={this.state.showAddApprovalStepAlert}
                              onHide={this.hideAddApprovalStepAlert}
                            >
                              <Modal.Header closeButton>
                                <Modal.Title>Step not added</Modal.Title>
                              </Modal.Header>
                              <Modal.Body>
                                Please complete all approval steps; there
                                already is an approval step that is not
                                completely filled in.
                              </Modal.Body>
                              <Modal.Footer>
                                <Button
                                  className="pull-right"
                                  onClick={this.hideAddApprovalStepAlert}
                                  bsStyle="primary"
                                >
                                  OK
                                </Button>
                              </Modal.Footer>
                            </Modal>
                            <Modal
                              show={this.state.showRemoveApprovalStepAlert}
                              onHide={this.hideRemoveApprovalStepAlert}
                            >
                              <Modal.Header closeButton>
                                <Modal.Title>Step not removed</Modal.Title>
                              </Modal.Header>
                              <Modal.Body>
                                You cannot remove this step; it is being used in
                                a report.
                              </Modal.Body>
                              <Modal.Footer>
                                <Button
                                  className="pull-right"
                                  onClick={this.hideRemoveApprovalStepAlert}
                                  bsStyle="primary"
                                >
                                  OK
                                </Button>
                              </Modal.Footer>
                            </Modal>

                            {values.approvalSteps.map((step, index) =>
                              this.renderApprovalStep(
                                arrayHelpers,
                                setFieldValue,
                                step,
                                index
                              )
                            )}

                        )}
                      />
                    </Fieldset>

                    {Organization.isTaskEnabled(values.shortName) && (
                      <Fieldset
                        title={Settings.fields.task.longLabel}
                        className="tasks-selector"
                      >
                        <MultiSelector
                          items={values.tasks}
                          objectType={Task}
                          queryParams={{ status: Task.STATUS.ACTIVE }}
                          placeholder={`Start typing to search for ${
                            Settings.fields.task.shortLabel
                          }...`}
                          fields={Task.autocompleteQuery}
                          template={Task.autocompleteTemplate}
                          addFieldName="tasks"
                          addFieldLabel={Settings.fields.task.shortLabel}
                          addon={TASKS_ICON}
                          renderSelected={
                            <TaskTable tasks={values.tasks} showDelete />
                          }
                          onChange={value => setFieldValue("tasks", value)}
                        />
                      </Fieldset>
                    )}

                )}

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

                  {(isAdmin || !isPrincipalOrg) && (

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

                  )}

              </Form>

          )
        }}
      </Formik>
    )
  }

  renderApprovalStep = (arrayHelpers, setFieldValue, step, index) => {
    const approvers = step.approvers

    return (
      <Fieldset title={`Step ${index + 1}`} key={index}>
        <Button
          className="pull-right"
          title="Remove this step"
          onClick={() => this.removeApprovalStep(arrayHelpers, index, step)}
        >

        </Button>

        <Field
          name={`approvalSteps.${index}.name`}
          component={FieldHelper.renderInputField}
          label="Step name"
        />

        <MultiSelector
          items={approvers}
          objectType={Position}
          queryParams={{
            status: Position.STATUS.ACTIVE,
            type: [
              Position.TYPE.ADVISOR,
              Position.TYPE.SUPER_USER,
              Position.TYPE.ADMINISTRATOR
            ],
            matchPersonName: true
          }}
          placeholder="Search for the approver's position"
          fields="uuid, name, code, type, person { uuid, name, rank, role }"
          template={position => (

              {" "}
              {position.person && (

                  {" "}
                  <LinkTo person={position.person} isLink={false} /> -{" "}

              )}{" "}
              <LinkTo position={position} isLink={false} />{" "}
              {position.code &&  - {position.code} }{" "}

          )}
          addFieldName={`approvalSteps.${index}.approvers`}
          addFieldLabel="Add an approver"
          addon={POSITIONS_ICON}
          renderSelected={<ApproverTable approvers={approvers} />}
          onChange={value =>
            setFieldValue(`approvalSteps.${index}.approvers`, value)
          }
        />
      </Fieldset>
    )
  }

  hideAddApprovalStepAlert = () => {
    this.setState({ showAddApprovalStepAlert: false })
  }

  hideRemoveApprovalStepAlert = () => {
    this.setState({ showRemoveApprovalStepAlert: false })
  }

  addApprovalStep = (arrayHelpers, values) => {
    const approvalSteps = values.approvalSteps || []

    for (let i = 0; i < approvalSteps.length; i++) {
      const step = approvalSteps[i]
      if (!step.name || !step.approvers || step.approvers.length === 0) {
        this.setState({ showAddApprovalStepAlert: true })
        return
      }
    }

    arrayHelpers.push({ name: "", approvers: [] })
  }

  removeApprovalStep = (arrayHelpers, index, step) => {
    return API.query(
      /* GraphQL */ `
      approvalStepInUse(uuid:"${step.uuid}")
    `
    ).then(data => {
      if (data.approvalStepInUse) {
        this.setState({ showRemoveApprovalStepAlert: true })
      } else {
        arrayHelpers.remove(index)
      }
    })
  }

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

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

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

  save = (values, form) => {
    const organization = Object.without(
      new Organization(values),
      "childrenOrgs",
      "positions"
    )
    organization.parentOrg = utils.getReference(organization.parentOrg)
    const { edit } = this.props
    const operation = edit ? "updateOrganization" : "createOrganization"
    let graphql = operation + "(organization: $organization)"
    graphql += edit ? "" : " { uuid }"
    const variables = { organization: organization }
    const variableDef = "($organization: OrganizationInput!)"
    return API.mutation(graphql, variables, variableDef)
  }
}

const OrganizationForm = props => (
  <AppContext.Consumer>
    {context => (
      <BaseOrganizationForm currentUser={context.currentUser} {...props} />
    )}
  </AppContext.Consumer>
)

export default withRouter(OrganizationForm)
<|endoftext|>


<commit_before>Template.testscript.events({
	'dblclick .text': function(e) {
		if (Meteor.user()) {
			$(e.currentTarget).find('.invisible').show();
			$(e.currentTarget).find('.testscript-steps').hide()
		}
	},
	'click .btn-new-testscript.edit.update': function(e) {
		if (Meteor.user()) {
			$(e.currentTarget).find('.invisible').hide();
			$(e.currentTarget).find('.testscript-steps').show()
			var steps = $(e.currentTarget).siblings('textarea').val();
			var id = this._id;
			Testscripts.update(id, { $set: { steps: steps }});
		}
	},
	'click .btn-new-testscript.edit.delete': function(e) {
		if (Meteor.user()) {
			$(e.currentTarget).find('.invisible').hide();
			$(e.currentTarget).find('.testscript-steps').show();

			if (confirm("Delete this testscript?")) {
				var id = this._id;
				Testscripts.remove(id);
			}
		}
	},
	'click .btn-test': function(e) {
		e.preventDefault();
		var pass = $(e.currentTarget).filter(".pass").length > 0;
		var fail = $(e.currentTarget).filter(".fail").length > 0;
		if (fail === true) {
			$(e.currentTarget).parents('.btn-holder').hide();
			$(e.currentTarget).parents('.btn-holder').siblings('.failure-reason').show();
			return;
		}
		if (pass === false && fail === false) {
			pass = '';
		}
		Meteor.call('updateTestscriptResult', this._id, pass, function(error) {
			if (error) {
				throwError(error.reason);
			}
		});
	},
	'click .btn-test.fail.interior': function(e) {
		var failReason = $(e.currentTarget).siblings('input').val();
		Meteor.call('updateTestscriptResult', this._id, false, failReason, function(error) {
			if (error) {
				throwError(error.reason);
			}
		});
	},
	'click .testscript-results': function(e) {
		e.preventDefault();
		$(e.currentTarget).find('.results-inner').show();
		$(e.currentTarget).find('.results').hide();
	},
	'click .results-inner': function(e) {
		e.preventDefault();
		e.stopPropagation();
		$(e.currentTarget).hide();
		$(e.currentTarget).siblings('.results').show();
	}
})<commit_msg>fail reason works with enter key<commit_after>Template.testscript.events({
	'dblclick .text': function(e) {
		if (Meteor.user()) {
			$(e.currentTarget).find('.invisible').show();
			$(e.currentTarget).find('.testscript-steps').hide()
		}
	},
	'click .btn-new-testscript.edit.update': function(e) {
		if (Meteor.user()) {
			$(e.currentTarget).find('.invisible').hide();
			$(e.currentTarget).find('.testscript-steps').show()
			var steps = $(e.currentTarget).siblings('textarea').val();
			var id = this._id;
			Testscripts.update(id, { $set: { steps: steps }});
		}
	},
	'click .btn-new-testscript.edit.delete': function(e) {
		if (Meteor.user()) {
			$(e.currentTarget).find('.invisible').hide();
			$(e.currentTarget).find('.testscript-steps').show();

			if (confirm("Delete this testscript?")) {
				var id = this._id;
				Testscripts.remove(id);
			}
		}
	},
	'click .btn-test': function(e) {
		e.preventDefault();
		var pass = $(e.currentTarget).filter(".pass").length > 0;
		var fail = $(e.currentTarget).filter(".fail").length > 0;
		if (fail === true) {
			$(e.currentTarget).parents('.btn-holder').hide();
			$(e.currentTarget).parents('.btn-holder').siblings('.failure-reason').show();
			return;
		}
		if (pass === false && fail === false) {
			pass = '';
		}
		Meteor.call('updateTestscriptResult', this._id, pass, function(error) {
			if (error) {
				throwError(error.reason);
			}
		});
	},
	'keydown, click .btn-test.fail.interior': function(e) {
		if (e.type === 'keydown' && e.which !== 13) {
			return;
		}
		e.preventDefault();
		var failReason = $(e.currentTarget).parents().find('input').val();
		Meteor.call('updateTestscriptResult', this._id, false, failReason, function(error) {
			if (error) {
				throwError(error.reason);
			}
		});
	},
	'click .testscript-results': function(e) {
		e.preventDefault();
		$(e.currentTarget).find('.results-inner').show();
		$(e.currentTarget).find('.results').hide();
	},
	'click .results-inner': function(e) {
		e.preventDefault();
		e.stopPropagation();
		$(e.currentTarget).hide();
		$(e.currentTarget).siblings('.results').show();
	}
})<|endoftext|>


<commit_before>'use strict'
/**
 * Created by tungtouch on 2/9/15.
 */

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

var dgram = require('dgram');
var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe:");
var client = dgram.createSocket("udp4");
var async = require('async');

var max = 100;
var numCluster = 100;
var arr = [];

for (var i = 0; i < max; i++) {
    arr.push(i);
}
var a = 0;

//[2GB]128.199.126.250 [8GB]128.199.109.202

if (cluster.isMaster) {

    // Keep track of http requests
    var numReqs = 0;
    setInterval(function() {
        console.log("numReqs =", numReqs);
    }, 1000);

    // Count requestes
    function messageHandler(msg) {
        if (msg.cmd && msg.cmd == 'notifyRequest') {
            numReqs += 1;
        }
    }

    // Start workers and listen for messages containing notifyRequest

    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    Object.keys(cluster.workers).forEach(function(id) {
        cluster.workers[id].on('message', messageHandler);
    });

} else {
    var q = async.queue(function(index, cb){
        console.log("Index: ", index);
        setTimeout(function () {
            client.send(message, 0, message.length, 4444, "128.199.126.250", function (err) {
                console.log("Request : ", a++);
                process.send({ cmd: 'notifyRequest' });
                if(err){
                    console.log('ERROR :', err);
                }
                cb(err);
            });
        }, 10);
    });

    q.push(arr);

}<commit_msg>Update UDPefef<commit_after>'use strict'
/**
 * Created by tungtouch on 2/9/15.
 */

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

var dgram = require('dgram');
var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe:");
var client = dgram.createSocket("udp4");
var async = require('async');

var max = 100;
var numCluster = 100;
var arr = [];

for (var i = 0; i < max; i++) {
    arr.push(i);
}
var a = 0;

//[2GB]128.199.126.250 [8GB]128.199.109.202

// Count requestes
function messageHandler(msg) {
    if (msg.cmd && msg.cmd == 'notifyRequest') {
        numReqs += 1;
    }
}

if (cluster.isMaster) {

    // Keep track of http requests
    var numReqs = 0;

    setInterval(function() {
        console.log("numReqs =", numReqs);
    }, 1000);

    // Start workers and listen for messages containing notifyRequest

    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    Object.keys(cluster.workers).forEach(function(id) {
        cluster.workers[id].on('message', messageHandler);
    });

} else {
    var q = async.queue(function(index, cb){
        console.log("Index: ", index);
        setTimeout(function () {
            client.send(message, 0, message.length, 4444, "128.199.126.250", function (err) {
                console.log("Request : ", a++);
                process.send({ cmd: 'notifyRequest' });
                if(err){
                    console.log('ERROR :', err);
                }
                cb(err);
            });
        }, 10);
    });

    q.push(arr);

}<|endoftext|>


<commit_before>
var fs = require('fs');
var ls = require('./lib/lookup_service');

function randip() {
    return [
        Math.floor(Math.random() * 255),
        Math.floor(Math.random() * 255),
        Math.floor(Math.random() * 255),
        Math.floor(Math.random() * 255)
    ].join('.');
}

ls.init('./test/dbs/GeoIPCity.dat', { memoryCache: true });
var ips = fs.readFileSync('./test/dbs/ips.txt');
ips = ips.toString().split("\n").map(function(line) {
    return line.trim();
});

var n = ips.length;
var s = new Date().getTime();

for (var i = ips.length - 1; i >= 0; i--) {
    ls.getLocation(ips[i]);
};

console.log('n: ', n);
console.log('time:', (new Date().getTime() - s), "msec");
console.log('speed:', Math.round(n / (new Date().getTime() - s) * 1000), 'per sec');
<commit_msg>fixed path in benchmark.js<commit_after>
var fs = require('fs');
var ls = require('./lib/lookup_service');

function randip() {
    return [
        Math.floor(Math.random() * 255),
        Math.floor(Math.random() * 255),
        Math.floor(Math.random() * 255),
        Math.floor(Math.random() * 255)
    ].join('.');
}

ls.init('./test/dbs/GeoIPCity.dat', { memoryCache: true });
var ips = fs.readFileSync('./test/dbs/full/ips.txt');
ips = ips.toString().split("\n").map(function(line) {
    return line.trim();
});

var n = ips.length;
var s = new Date().getTime();

for (var i = ips.length - 1; i >= 0; i--) {
    ls.getLocation(ips[i]);
};

console.log('n: ', n);
console.log('time:', (new Date().getTime() - s), "msec");
console.log('speed:', Math.round(n / (new Date().getTime() - s) * 1000), 'per sec');
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
const isAsyncSupported = require('is-async-supported')

// Ours
const pkg = require('../package')

// Support for keywords "async" and "await"
if (!isAsyncSupported()) {
  const pathSep = process.platform === 'win32' ? '\\\\' : '/'

  asyncToGen({
    includes: new RegExp(`.*serve?${pathSep}(lib|bin).*`),
    excludes: null,
    sourceMaps: false
  })
}

// Throw an error if node version is too low
if (nodeVersion.major < 6) {
  console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
  process.exit(1)
}

// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW && pkg.dist) {
  updateNotifier({pkg}).notify()
}

// Load package core with async/await support
require('../lib')
<commit_msg>Make `async-to-gen` work on Now<commit_after>#!/usr/bin/env node

// Native
const path = require('path')

// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
const isAsyncSupported = require('is-async-supported')

// Ours
const pkg = require('../package')

// Support for keywords "async" and "await"
if (!isAsyncSupported()) {
  const pathSep = process.platform === 'win32' ? '\\\\' : '/'
  const directoryName = path.parse(path.join(__dirname, '..')).base

  asyncToGen({
    includes: new RegExp(`.*${directoryName}?${pathSep}(lib|bin).*`),
    excludes: null,
    sourceMaps: false
  })
}

// Throw an error if node version is too low
if (nodeVersion.major < 6) {
  console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
  process.exit(1)
}

// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW && pkg.dist) {
  updateNotifier({pkg}).notify()
}

// Load package core with async/await support
require('../lib')
<|endoftext|>


<commit_before>#!/usr/bin/env node

import bin from 'commander'
import { log } from '../lib/utils'
import { execFile } from 'child_process'

bin
  .option('-w, --watch', 'Rebuild site if files change')
  .option('-p, --port <port>', 'The port on which your site will be available', parseInt)
  .parse(process.argv)

execFile('node', ['index.js'], (error, stdout, stderr) => {
  if (error) log(error)
  console.log(stdout)
})
<commit_msg>Move over certain parts from server<commit_after>#!/usr/bin/env node

import bin from 'commander'
import { log, isSite } from '../lib/utils'
import { execFile, exec } from 'child_process'

bin
  .option('-w, --watch', 'Rebuild site if files change')
  .option('-p, --port <port>', 'The port on which your site will be available', parseInt)
  .parse(process.argv)

if (!isSite()) {
  log(chalk.red('No site in here!'))
  process.exit(1)
}

// Build before serving if "dist" directory doesn't exist
if (bin.watch || !exists(process.cwd() + '/dist')) {
  const builder = exec('muffin build -w')

  builder.stdout.on('data', data => process.stdout.write(chalk.green(data)))
  builder.stderr.on('data', data => console.error(data))

  builder.on('error', err => {
    throw err
  })
}

execFile('node', ['index.js'], (error, stdout, stderr) => {
  if (error) log(error)
  console.log(stdout)
})
<|endoftext|>


<commit_before>const config                    = use('config');
const Factories                 = use('core/factories');
const NotificationEmailsFactory = Factories('NotificationEmails');

class NotificationEmails {

    constructor() {
        this.provider = require(`./providers/${config.mailGate.providers[config.mailGate.active].name}`);
    }

    send(options, additionalOptions) {

        let saveData = {
            accounts_senders_id: additionalOptions.sendersId,
            subject: options.subject,
            body: options.html,
            recipient_email_to: options.to,
            recipient_email_cc: options.cc.join(','),
            recipient_email_bcc: options.bcc.join(','),
            accounts_recipients_id: additionalOptions.accountRecipientsId,
            type: additionalOptions.type
        };

        return NotificationEmailsFactory.new(saveData)
            .then((notificationEmail)=> {
                return notificationEmail.save();
            })
            .then((notificationEmail)=> {
                return this.provider.send(options)
                    .then(response => {
                        notificationEmail.message_id = response.messageId;
                        notificationEmail.status = response.status;
                        return notificationEmail.save();
                    });
            });
    }

}

module.exports = NotificationEmails;<commit_msg>arguments of send method has been changed<commit_after>const config                    = use('config');
const Factories                 = use('core/factories');
const NotificationEmailsFactory = Factories('NotificationEmails');

class NotificationEmails {

    constructor() {
        this.provider = require(`./providers/${config.mailGate.providers[config.mailGate.active].name}`);
    }

    send({
        from='',
        to='',
        cc=[],
        bcc=[],
        subject='',
        body='',
        sendersId=null,
        accountRecipientsId=null,
        type='AUTOMATIC'
    }) {

        let saveData = {
            accounts_senders_id: sendersId,
            subject: subject,
            body: body,
            recipient_email_to: to,
            recipient_email_cc: cc.join(','),
            recipient_email_bcc: bcc.join(','),
            accounts_recipients_id: accountRecipientsId,
            type: type
        };

        let emailInfo = {
            from: from,
            to:to,
            cc:cc,
            bcc:bcc,
            subject:subject,
            body:body
        };

        return NotificationEmailsFactory.new(saveData)
            .then((notificationEmail)=> {
                return notificationEmail.save();
            })
            .then((notificationEmail)=> {
                return this.provider.send(emailInfo)
                    .then(response => {
                        notificationEmail.message_id = response.messageId;
                        notificationEmail.status = response.status;
                        return notificationEmail.save();
                    });
            });
    }

}

module.exports = NotificationEmails;<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'

import LoadingComp from '@/widget/loading'
import ErrorComp from '@/widget/error'
import Hello from '@/demo/get-started'
import TemplateInterpolation from '@/demo/template-interpolation'
import Computed from '@/demo/computed'
import Key from '@/demo/key'
import VModel from '@/demo/v-model'
import ComponentProps from '@/demo/component-props'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    },
    {
      path: '/template-interpolation',
      name: 'TemplateInterpolation',
      component: TemplateInterpolation
    },
    {
      path: '/computed',
      name: 'computed',
      component: Computed
    },
    {
      path: '/key',
      name: 'key',
      component: Key
    },
    {
      path: '/v-model',
      name: 'v-model',
      component: VModel
    },
    {
      path: '/component-props',
      name: 'component-props',
      component: ComponentProps
    },
    {
      path: '/component-event',
      name: 'component-event',
      component: import('@/demo/component-event')
    },
    {
      path: '/async-component',
      name: 'async-component',
      component: resolve => import('@/demo/async-component'),
      // component: import('@/demo/async-component').then(a => a()),
      // loading 时应当渲染的组件
      loading: LoadingComp,
      // 出错时渲染的组件
      error: ErrorComp,
      // 渲染 loading 组件前的等待时间。默认：200ms.
      // delay: 200,
      // 最长等待时间。超出此时间则渲染 error 组件。默认：Infinity
      timeout: 3000
    }
  ]
})
<commit_msg> API 组件篇 - 我怀疑是框架问题<commit_after>import Vue from 'vue'
import Router from 'vue-router'

import LoadingComp from '@/widget/loading'
import ErrorComp from '@/widget/error'
import Hello from '@/demo/get-started'
import TemplateInterpolation from '@/demo/template-interpolation'
import Computed from '@/demo/computed'
import Key from '@/demo/key'
import VModel from '@/demo/v-model'
import ComponentProps from '@/demo/component-props'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    },
    {
      path: '/template-interpolation',
      name: 'TemplateInterpolation',
      component: TemplateInterpolation
    },
    {
      path: '/computed',
      name: 'computed',
      component: Computed
    },
    {
      path: '/key',
      name: 'key',
      component: Key
    },
    {
      path: '/v-model',
      name: 'v-model',
      component: VModel
    },
    {
      path: '/component-props',
      name: 'component-props',
      component: ComponentProps
    },
    {
      path: '/component-event',
      name: 'component-event',
      component: import('@/demo/component-event')
    },
    {
      path: '/async-component',
      name: 'async-component',
      component: resolve => import('@/demo/async-component'),

      // 下面的配置项不生效，在源码搜了一下没找到相关实现
      // loading 时应当渲染的组件
      loading: LoadingComp,
      // 出错时渲染的组件
      error: ErrorComp,
      // 渲染 loading 组件前的等待时间。默认：200ms.
      // delay: 200,
      // 最长等待时间。超出此时间则渲染 error 组件。默认：Infinity
      timeout: 3000
    }
  ]
})
<|endoftext|>