<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import d3 from 'd3';
import _ from 'lodash';

import Axis from './axis';

export default class XYAxis extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    const xSettings = {
      translate: `translate(0, ${this.props.height - this.props.padding})`,
      scale: this.props.xScale,
      orient: 'bottom',
    };
    // const ySettings = {
    //   translate: `translate(${this.props.padding}, 0)`,
    //   scale: this.props.yScale,
    //   orient: 'left',
    // };
    const line = d3.svg.line()
      .x((d) => d.x)
      .y((d) => d.y)
      .interpolate('linear');

    // const margin = {top: 5, right: 50, bottom: 20, left: 50};
    // const transform ='translate(' + margin.left + ',' + margin.top + ')';
    const reactionEnergy = this.props.selectedReaction.reactionEnergy;
    let activationEnergy = this.props.selectedReaction.activationEnergy;
    if (_.isEmpty(activationEnergy)) {
      activationEnergy = reactionEnergy / 2.0;
    }

    const data = [
      { x: 0, y: 200 },
      { x: 180, y: 200 },
      { x: 200, y: 200 - (20 * activationEnergy) },
      { x: 220, y: 200 - (20 * reactionEnergy) },
      { x: 400, y: 200 - (20 * reactionEnergy) },
    ];

    return (<g className="xy-axis">
      <Axis {...xSettings} />
      <path stroke="black" fill="none" strokeWidth={8} className="line shadow" d={line(data)} />
      <line x1={0} x2={500} y1={200} y2={400} />
      <text x={120} y={340} fontFamily="sans-serif" fontSize="14px" fill="red">Reaction Energy {reactionEnergy.toFixed(2)} eV</text>
      {activationEnergy === reactionEnergy / 2.0 ? null :
          null
      }
    </g>);
  }
}

XYAxis.propTypes = {
  height: PropTypes.number,
  padding: PropTypes.number,
  selectedReaction: PropTypes.object,
  xScale: PropTypes.object,
};

XYAxis.defaultProps = {
};
<commit_msg>trying to plot activation energy<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import d3 from 'd3';
import _ from 'lodash';

import Axis from './axis';

export default class XYAxis extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    const xSettings = {
      translate: `translate(0, ${this.props.height - this.props.padding})`,
      scale: this.props.xScale,
      orient: 'bottom',
    };
    // const ySettings = {
    //   translate: `translate(${this.props.padding}, 0)`,
    //   scale: this.props.yScale,
    //   orient: 'left',
    // };
    const line = d3.svg.line()
      .x((d) => d.x)
      .y((d) => d.y)
      .interpolate('linear');

    // const margin = {top: 5, right: 50, bottom: 20, left: 50};
    // const transform ='translate(' + margin.left + ',' + margin.top + ')';
    const reactionEnergy = this.props.selectedReaction.reactionEnergy;
    const activationEnergy = this.props.selectedReaction.activationEnergy;
      console.log(this.props.selectedReaction.activationEnergy)
      console.log(activationEnergy)
      console.log(_.isEmpty(activationEnergy))

    /*if (_.isEmpty(activationEnergy)) {
      activationEnergy = reactionEnergy / 2.0;
    }*/

    const data = [
      { x: 0, y: 200 },
      { x: 120, y: 200 },
      { x: 200, y: 200 - (100 * activationEnergy) },
      { x: 280, y: 200 - (100 * reactionEnergy) },
      { x: 400, y: 200 - (100 * reactionEnergy) },
    ];

    return (<g className="xy-axis">
      <Axis {...xSettings} />
      <path stroke="black" fill="none" strokeWidth={8} className="line shadow" d={line(data)} />
      <line x1={0} x2={500} y1={200} y2={400} />
      <text x={120} y={340} fontFamily="sans-serif" fontSize="14px" fill="red">Reaction Energy {reactionEnergy.toFixed(2)} eV</text>
      {activationEnergy === activationEnergy / 2.0 ? null :
          null
      }
    </g>);
  }
}

XYAxis.propTypes = {
  height: PropTypes.number,
  padding: PropTypes.number,
  selectedReaction: PropTypes.object,
  xScale: PropTypes.object,
};

XYAxis.defaultProps = {
};
<|endoftext|>


<commit_before>/**
*
* BitcoinStream
*
*/

import React from 'react';

import request from 'utils/request';
import { call } from 'redux-saga/effects';

import styles from './styles.css';

import WebSocket from 'ws';

import Block from 'components/Block';

class BitcoinStream extends React.Component {

  static defaultProps = {
    blocksUrl: "https://bitcoin.toshi.io/api/v0/blocks/latest",
    interval: 5000
  }

  constructor() {
    super();
    this.blockList = []
    this.blocks = []
    this.ws = new WebSocket('wss://bitcoin.toshi.io');
    this.state = { blocks: this.blocks}
  }

  componentDidMount() {
    setInterval(() => {
      this.loadLatestBlock();
    }, this.props.interval);
    this.loadLatestBlock();

    this.ws.on('transactions', function (data, flags) {
        console.log(data, flags);
    });
  }

  loadLatestBlock() {
    request(this.props.blocksUrl)
      .then(blocks => {
        if(!this.blockList[blocks.data.hash]) {
          this.blocks.unshift(blocks.data);
          this.blockList[blocks.data.hash] = blocks.data;
          this.setState({blocks: this.blocks})
        }
      })
  }

  render() {
    return (

Bitcoin Blockchain

          { this.state.blocks.map(this.renderBlock) }

    );
  }

  renderBlock(block) {
    return <Block data={block} key={block.hash}/>;
  }
}

export default BitcoinStream;
<commit_msg>-Working stream of transactions from WebSockets<commit_after>/**
*
* BitcoinStream
*
*/

import React from 'react';

import request from 'utils/request';
import { call } from 'redux-saga/effects';

import styles from './styles.css';

import Block from 'components/Block';

class BitcoinStream extends React.Component {

  static defaultProps = {
    blocksUrl: "https://bitcoin.toshi.io/api/v0/blocks/latest",
    interval: 5000
  }

  constructor() {
    super();
    this.blockList = []
    this.blocks = []
    this.state = { blocks: this.blocks}
  }

  componentDidMount() {
    setInterval(() => {
      this.loadLatestBlock();
    }, this.props.interval);
    this.loadLatestBlock();

    this.ws = new WebSocket('wss://bitcoin.toshi.io');
    this.ws.onopen = () => {
        this.ws.send('{"subscribe":"transactions"}');
    }
    this.ws.onmessage = (evt) => {
      console.log("message recieved", evt);
    };
  }

  loadLatestBlock() {
    request(this.props.blocksUrl)
      .then(blocks => {
        if(!this.blockList[blocks.data.hash]) {
          this.blocks.unshift(blocks.data);
          this.blockList[blocks.data.hash] = blocks.data;
          this.setState({blocks: this.blocks})
        }
      })
  }

  render() {
    return (

Bitcoin Blockchain

          { this.state.blocks.map(this.renderBlock) }

    );
  }

  renderBlock(block) {
    return <Block data={block} key={block.hash}/>;
  }
}

export default BitcoinStream;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import Dropzone from 'react-dropzone'
import { Glyphicon } from 'react-bootstrap'
import { shell } from 'electron'
import { observer, inject } from 'mobx-react'
import compose from 'recompose/compose'
import withHandlers from 'recompose/withHandlers'
import styled from 'styled-components'

import regularStyles from './areaLinks.css'
import pdfStyles from './areaLinksPdf.css'

const StyledDropzone = styled(Dropzone)`
  width: 100%;
  height: 100%;
  border-color: transparent;
`
const DropzoneInnerDiv = styled.div`
  width: 100%;
  height: 100%;
  border-width: 2px;
  border-color: #666;
  border-style: dashed;
  border-radius: 5px;
  padding: 5px;
`
const Container = styled.div`
  grid-area: areaLinks;
  background-color: ${props =>
    props['data-isPdf'] ? 'rgb(227, 232, 255)' : '#e3fff0'};
  display: grid;
  grid-template-columns: ${props =>
    props['data-isPdf'] ? '100%' : 'calc(100% - 308px) 300px'};
  grid-template-areas: ${props =>
    props['data-isPdf']
      ? `'title' 'links'`
      : `'title dropzone' 'links dropzone'`};
  grid-column-gap: 8px;
  grid-row-gap: ${props => (props['data-isPdf'] ? '1px' : '8px')};
  padding: 8px;
  /*pdf*/
  border: ${props => (props['data-isPdf'] ? '1px solid #ccc' : 'none')};
  border-bottom: none;
  font-size: ${props => (props['data-isPdf'] ? '10px' : 'inherit')};
`

const enhance = compose(
  inject('store'),
  withHandlers({
    onDrop: props => files => {
      const { store } = props
      const { linkNewCreate } = store
      const { activeId } = store.geschaefte
      linkNewCreate(activeId, files[0].path)
    },
  }),
  observer
)

const AreaLinks = ({ store, onDrop }) => {
  const { linkRemove } = store
  const { activeId, links } = store.geschaefte
  const myLinks = links.filter(l => l.idGeschaeft === activeId)
  const path = store.history.location.pathname
  const isPdf = path === '/geschaeftPdf'
  const styles = isPdf ? pdfStyles : regularStyles

  return (
    <Container data-isPdf={isPdf}>

Links

        {myLinks.map(link => (
          <div key={`${link.idGeschaeft}${link.url}`} className={styles.fields}>

               {
                  event.preventDefault()
                  shell.openItem(link.url)
                }}
              >
                {link.url}

              <Glyphicon
                glyph="remove-circle"
                onClick={() => linkRemove(activeId, link.url)}
                className={styles.removeGlyphicon}
                title="Link entfernen"
              />

        ))}

    </Container>
  )
}

AreaLinks.displayName = 'AreaLinks'

AreaLinks.propTypes = {
  store: PropTypes.object.isRequired,
  onDrop: PropTypes.func.isRequired,
}

export default enhance(AreaLinks)
<commit_msg>use styled<commit_after>import React, { PropTypes } from 'react'
import Dropzone from 'react-dropzone'
import { Glyphicon } from 'react-bootstrap'
import { shell } from 'electron'
import { observer, inject } from 'mobx-react'
import compose from 'recompose/compose'
import withHandlers from 'recompose/withHandlers'
import styled from 'styled-components'

import regularStyles from './areaLinks.css'
import pdfStyles from './areaLinksPdf.css'

const StyledDropzone = styled(Dropzone)`
  width: 100%;
  height: 100%;
  border-color: transparent;
`
const DropzoneInnerDiv = styled.div`
  width: 100%;
  height: 100%;
  border-width: 2px;
  border-color: #666;
  border-style: dashed;
  border-radius: 5px;
  padding: 5px;
`
const Container = styled.div`
  grid-area: areaLinks;
  background-color: ${props =>
    props['data-isPdf'] ? 'rgb(227, 232, 255)' : '#e3fff0'};
  display: grid;
  grid-template-columns: ${props =>
    props['data-isPdf'] ? '100%' : 'calc(100% - 308px) 300px'};
  grid-template-areas: ${props =>
    props['data-isPdf']
      ? `'title' 'links'`
      : `'title dropzone' 'links dropzone'`};
  grid-column-gap: 8px;
  grid-row-gap: ${props => (props['data-isPdf'] ? '1px' : '8px')};
  padding: 8px;
  border: ${props => (props['data-isPdf'] ? '1px solid #ccc' : 'none')};
  border-bottom: none;
  font-size: ${props => (props['data-isPdf'] ? '10px' : 'inherit')};
`
const Title = styled.div`
  font-weight: 900;
  font-size: 16px;
  grid-area: title;
`
const Links = styled.div`
  grid-area: links;
  /*pdf*/
  display: ${props => (props['data-isPdf'] ? 'grid' : 'block')};
  display: ${props => (props['data-isPdf'] ? '100%' : 'none')};
`
const Field = styled.div`
  grid-column: 1;
  display: grid;
  grid-template-columns: calc(100% - 20px) 20px;
  grid-gap: 0;
  border-bottom: thin solid #cecbcb;
  padding: 3px;
  align-items: center;
  &:first-of-type {
    border-top: thin solid #cecbcb;
  }
  &:hover {
    background-color: #ceffe5;
  }
`

const enhance = compose(
  inject('store'),
  withHandlers({
    onDrop: props => files => {
      const { store } = props
      const { linkNewCreate } = store
      const { activeId } = store.geschaefte
      console.log('AreaLinks: activeId:', activeId)
      console.log('AreaLinks: path:', files[0].path)
      linkNewCreate(activeId, files[0].path)
    },
  }),
  observer
)

const AreaLinks = ({ store, onDrop }) => {
  const { linkRemove } = store
  const { activeId, links } = store.geschaefte
  const myLinks = links.filter(l => l.idGeschaeft === activeId)
  const path = store.history.location.pathname
  const isPdf = path === '/geschaeftPdf'
  const styles = isPdf ? pdfStyles : regularStyles

  return (
    <Container data-isPdf={isPdf}>
      <Title>Links</Title>
      <Links data-isPdf={isPdf}>
        {myLinks.map(link => (
          <Field key={`${link.idGeschaeft}${link.url}`}>

               {
                  event.preventDefault()
                  shell.openItem(link.url)
                }}
              >
                {link.url}

              <Glyphicon
                glyph="remove-circle"
                onClick={() => linkRemove(activeId, link.url)}
                className={styles.removeGlyphicon}
                title="Link entfernen"
              />

          </Field>
        ))}
      </Links>

    </Container>
  )
}

AreaLinks.displayName = 'AreaLinks'

AreaLinks.propTypes = {
  store: PropTypes.object.isRequired,
  onDrop: PropTypes.func.isRequired,
}

export default enhance(AreaLinks)
<|endoftext|>


<commit_before>import React, { useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import isEqual from 'lodash/isEqual';
import get from 'lodash/get';
import map from 'lodash/map';
import noop from 'lodash/noop';
import { Flex, Box } from 'rebass/styled-components';
import { Label, Switch } from '@rebass/forms/styled-components';
import moment from 'moment-timezone';

import Accordion from './elements/Accordion';
import Button from './elements/Button';
import DateRangePicker from './elements/DateRangePicker';
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
} from './elements/Dialog';
import { MediumTitle, Caption, Body1 } from './elements/FontStyles';

export const PrintDateRangeModal = (props) => {
  const {
    mostRecentDatumDates,
    onClose,
    onClickPrint,
    onDatesChange,
    open,
    timePrefs: { timezoneName },
  } = props;

  const initialErrorState = {
    basics: false,
    bgLog: false,
    daily: false,
  };

  const [errors, setErrors] = useState(initialErrorState);
  const [submitted, setSubmitted] = useState(false);

  const endOfToday = useMemo(() => moment().tz(timezoneName).endOf('day').subtract(1, 'ms'), [open]);

  // We want the set dates to start at the floor of the start date and the ceiling of the end date
  // to ensure we are selecting full days of data.
  const setDateRangeToExtents = ({ startDate, endDate }) => ({
    startDate: startDate ? moment(startDate).tz(timezoneName).startOf('day') : null,
    endDate: endDate ? moment(endDate).tz(timezoneName).endOf('day').subtract(1, 'ms') : null,
  });

  const getLastNDays = (days, chartType) => {
    const endDate = get(mostRecentDatumDates, chartType)
      ? moment.utc(mostRecentDatumDates[chartType])
      : endOfToday;

    return setDateRangeToExtents({
      startDate: moment(endDate).tz(timezoneName).subtract(days - 1, 'days'),
      endDate: endDate,
    });
  };

  const basicsDaysOptions = [7,14,21];
  const [basicsEnabled, setBasicsEnabled] = useState(true);
  const [basicsDays, setBasicsDays] = useState(basicsDaysOptions[2]);

  const bgLogDaysOptions = [7,14,21,30];
  const [bgLogEnabled, setBgLogEnabled] = useState(true);
  const [bgLogDays, setBgLogDays] = useState(bgLogDaysOptions[3]);

  const dailyDaysOptions = [7,14,21];
  const [dailyEnabled, setDailyEnabled] = useState(true);
  const [dailyDays, setDailyDays] = useState(dailyDaysOptions[0]);

  const [settingsEnabled, setSettingsEnabled] = useState(true);

  const presetDateRanges = {
    basics: useMemo(() => map(basicsDaysOptions, days => getLastNDays(days, 'basics')), [open]),
    bgLog: useMemo(() => map(bgLogDaysOptions, days => getLastNDays(days, 'bgLog')), [open]),
    daily: useMemo(() => map(dailyDaysOptions, days => getLastNDays(days, 'daily')), [open]),
  };

  const [dates, setDates] = useState({
    basics: getLastNDays(basicsDays, 'basics'),
    bgLog: getLastNDays(bgLogDays, 'bgLog'),
    daily: getLastNDays(dailyDays, 'daily'),
  });

  const [datePickerOpen, setDatePickerOpen] = useState(false);

  const datesMatchPreset = (dates, presetDates) => {
    return moment(dates.startDate).isSame(presetDates.startDate) && moment(dates.endDate).isSame(presetDates.endDate);
  };

  const validateDates = ({ basics, bgLog, daily }) => {
    const validationErrors = {
      basics: !moment.isMoment(basics.startDate) || !moment.isMoment(basics.endDate),
      bgLog: !moment.isMoment(bgLog.startDate) || !moment.isMoment(bgLog.endDate),
      daily: !moment.isMoment(daily.startDate) || !moment.isMoment(daily.endDate),
    };

    setErrors(validationErrors);
    return validationErrors;
  };

  useEffect(() => {
    if (submitted) validateDates(dates);
    onDatesChange(dates);
  }, [dates]);

  const handleSubmit = () => {
    setSubmitted(true);
    const validationErrors = validateDates(dates);
    if (!isEqual(validationErrors, initialErrorState)) return;

    onClickPrint({
      basics: { ...dates.basics, enabled: basicsEnabled },
      bgLog: { ...dates.bgLog, enabled: bgLogEnabled },
      daily: { ...dates.daily, enabled: dailyEnabled },
      settings: { enabled: settingsEnabled },
    });
  };

  const handleClose = () => {
    setSubmitted(false);
    setErrors(initialErrorState);
    onClose();
  };

  // Accordion Panels
  const [expandedPanel, setExpandedPanel] = React.useState('basics');

  const handleAccordionChange = key => (event, isExpanded) => {
    setExpandedPanel(key);
  };

  const accordionProps = (chartType, header) => ({
    label: chartType,
    key: chartType,
    expanded: expandedPanel === chartType,
    onChange: handleAccordionChange(chartType),
    themeProps: {
      wrapper: {
        width: '100%',
      },
      panel: {
        width: '100%',
        px: 5,
        pt: 1,
        pb: 3,
      },
      header: {
        width: '100%',
        color: errors[chartType] ? 'feedback.danger' : undefined,
      },
    },
    header,
  });

  const panels = [
    {
      days: basicsDays,
      daysOptions: basicsDaysOptions,
      enabled: basicsEnabled,
      error: errors.basics,
      header: 'Basics Chart',
      key: 'basics',
      setDays: setBasicsDays,
      setEnabled: setBasicsEnabled,
    },
    {
      days: dailyDays,
      daysOptions: dailyDaysOptions,
      enabled: dailyEnabled,
      error: errors.daily,
      header: 'Daily Charts',
      key: 'daily',
      setDays: setDailyDays,
      setEnabled: setDailyEnabled,
    },
    {
      days: bgLogDays,
      daysOptions: bgLogDaysOptions,
      enabled: bgLogEnabled,
      error: errors.bgLog,
      header: 'BG Log Chart',
      key: 'bgLog',
      setDays: setBgLogDays,
      setEnabled: setBgLogEnabled,
    },
    {
      enabled: settingsEnabled,
      header: 'Device Settings',
      key: 'settings',
      setEnabled: setSettingsEnabled,
    },
  ];

  return (
    <Dialog id="printDateRangePicker" maxWidth="md" open={open} onClose={onClose}>
      <DialogTitle divider={false} onClose={onClose}>
        <MediumTitle>Print Report</MediumTitle>
      </DialogTitle>
      <DialogContent divider={false} minWidth="400px" p={0}>
        {map(panels, panel => (
          <Accordion {...accordionProps(panel.key, panel.header)}>
            <Box width="100%">
              <Flex mb={4}>
                <Label htmlFor={`enabled-${panel.key}`}>
                  <Body1 alignSelf="center">Include {panel.header}</Body1>
                  <Switch
                    name={`enabled-${panel.key}`}
                    ml={4}
                    checked={panel.enabled}
                    onClick={() => panel.setEnabled(enabled => !enabled)}
                  />
                </Label>
              </Flex>

              {panel.enabled && panel.days && (
                <Box>
                  <Box mb={5}>
                    <Body1 mb={2}>Number of days (most recent)</Body1>
                    <Flex>
                      {map(panel.daysOptions, (days, i) => (
                        <Button
                          mr={2}
                          variant="chip"
                          id={`days-${panel.key}`}
                          name={`days-${panel.key}`}
                          key={`days-${panel.key}-${i}`}
                          value={days}
                          selected={datesMatchPreset(dates[panel.key], presetDateRanges[panel.key][i])}
                          onClick={() => setDates({ ...dates, [panel.key]: getLastNDays(days, panel.key) })}
                        >
                          {days} days
                        </Button>
                      ))}
                    </Flex>
                  </Box>
                  <Box mb={3}>
                    <Body1 mb={2}>Or select a custom date range</Body1>
                    <DateRangePicker
                      startDate={dates[panel.key].startDate}
                      startDateId={`${[panel.key]}-start-date`}
                      endDate={dates[panel.key].endDate}
                      endDateId={`${[panel.key]}-end-date`}
                      onDatesChange={newDates => setDates({ ...dates, [panel.key]: setDateRangeToExtents(newDates) })}
                      isOutsideRange={day => (endOfToday.diff(day) < 0)}
                      onFocusChange={input => setDatePickerOpen(!!input)}
                      themeProps={{
                        minWidth: '580px',
                        minHeight: datePickerOpen ? '300px' : undefined,
                      }}
                    />
                  </Box>
                </Box>
              )}
            </Box>
            {panel.error && (
              <Caption mt={2} color="feedback.danger">
                Please select a date range
              </Caption>
            )}
          </Accordion>
        ))}
      </DialogContent>
      <DialogActions justifyContent="space-between" py={2}>
        <Button variant="textSecondary" onClick={handleClose}>
          Cancel
        </Button>
        <Button variant="textPrimary" onClick={handleSubmit}>
          Print
        </Button>
      </DialogActions>
    </Dialog>
  );
};

PrintDateRangeModal.propTypes = {
  mostRecentDatumDates: PropTypes.shape({
    basics: PropTypes.number.isRequired,
    bgLog: PropTypes.number.isRequired,
    daily: PropTypes.number.isRequired,
  }),
  onClickPrint: PropTypes.func,
  onClose: PropTypes.func,
  onDatesChange: PropTypes.func,
  open: PropTypes.bool,
  timePrefs: PropTypes.shape({
    timezoneAware: PropTypes.bool,
    timezoneName: PropTypes.string.isRequired,
  }).isRequired,
};

PrintDateRangeModal.defaultProps = {
  onClickPrint: noop,
  onClose: noop,
  onDatesChange: noop,
};

export default PrintDateRangeModal;
<commit_msg>[WEB-981] Manage default print dialog states in a cleaner fashion<commit_after>import React, { useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import isEqual from 'lodash/isEqual';
import get from 'lodash/get';
import map from 'lodash/map';
import noop from 'lodash/noop';
import { Flex, Box } from 'rebass/styled-components';
import { Label, Switch } from '@rebass/forms/styled-components';
import moment from 'moment-timezone';

import Accordion from './elements/Accordion';
import Button from './elements/Button';
import DateRangePicker from './elements/DateRangePicker';
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
} from './elements/Dialog';
import { MediumTitle, Caption, Body1 } from './elements/FontStyles';

export const PrintDateRangeModal = (props) => {
  const {
    mostRecentDatumDates,
    onClose,
    onClickPrint,
    onDatesChange,
    open,
    timePrefs: { timezoneName = 'UTC' },
  } = props;

  const endOfToday = useMemo(() => moment().tz(timezoneName).endOf('day').subtract(1, 'ms'), [open]);

  // We want the set dates to start at the floor of the start date and the ceiling of the end date
  // to ensure we are selecting full days of data.
  const setDateRangeToExtents = ({ startDate, endDate }) => ({
    startDate: startDate ? moment(startDate).tz(timezoneName).startOf('day') : null,
    endDate: endDate ? moment(endDate).tz(timezoneName).endOf('day').subtract(1, 'ms') : null,
  });

  const getLastNDays = (days, chartType) => {
    const endDate = get(mostRecentDatumDates, chartType)
      ? moment.utc(mostRecentDatumDates[chartType])
      : endOfToday;

    return setDateRangeToExtents({
      startDate: moment(endDate).tz(timezoneName).subtract(days - 1, 'days'),
      endDate,
    });
  };

  const basicsDaysOptions = [14, 21, 30];
  const bgLogDaysOptions = [14, 21,30];
  const dailyDaysOptions = [14, 21, 30];

  const defaultDates = () => ({
    basics: getLastNDays(basicsDaysOptions[0], 'basics'),
    bgLog: getLastNDays(bgLogDaysOptions[2], 'bgLog'),
    daily: getLastNDays(dailyDaysOptions[0], 'daily'),
  });

  const defaults = useMemo(() => ({
    datePickerOpen: false,
    dates: defaultDates(),
    enabled: {
      basics: true,
      bgLog: true,
      daily: true,
      settings: true,
    },
    errors: {
      basics: false,
      bgLog: false,
      daily: false,
    },
    expandedPanel: 'basics',
    submitted: false,
  }), [mostRecentDatumDates]);

  const [dates, setDates] = useState(defaults.dates);
  const [enabled, setEnabled] = useState(defaults.enabled);
  const [errors, setErrors] = useState(defaults.errors);
  const [expandedPanel, setExpandedPanel] = React.useState(defaults.expandedPanel);
  const [submitted, setSubmitted] = useState(defaults.submitted);
  const [datePickerOpen, setDatePickerOpen] = useState(defaults.datePickerOpen);

  const presetDateRanges = {
    basics: useMemo(() => map(basicsDaysOptions, days => getLastNDays(days, 'basics')), [open]),
    bgLog: useMemo(() => map(bgLogDaysOptions, days => getLastNDays(days, 'bgLog')), [open]),
    daily: useMemo(() => map(dailyDaysOptions, days => getLastNDays(days, 'daily')), [open]),
  };

  const datesMatchPreset = (dates, presetDates) => {
    return moment(dates.startDate).isSame(presetDates.startDate) && moment(dates.endDate).isSame(presetDates.endDate);
  };

  const validateDates = ({ basics, bgLog, daily }) => {
    const validationErrors = {
      basics: !moment.isMoment(basics.startDate) || !moment.isMoment(basics.endDate),
      bgLog: !moment.isMoment(bgLog.startDate) || !moment.isMoment(bgLog.endDate),
      daily: !moment.isMoment(daily.startDate) || !moment.isMoment(daily.endDate),
    };

    setErrors(validationErrors);
    return validationErrors;
  };

  // Accordion Panels
  const handleAccordionChange = key => (event, isExpanded) => {
    setExpandedPanel(key);
  };

  const accordionProps = (chartType, header) => ({
    label: chartType,
    key: chartType,
    expanded: expandedPanel === chartType,
    onChange: handleAccordionChange(chartType),
    themeProps: {
      wrapper: {
        width: '100%',
      },
      panel: {
        width: '100%',
        px: 5,
        pt: 1,
        pb: 3,
      },
      header: {
        width: '100%',
        color: errors[chartType] ? 'feedback.danger' : undefined,
      },
    },
    header,
  });

  const panels = [
    {
      daysOptions: basicsDaysOptions,
      header: 'Basics Chart',
      key: 'basics',
    },
    {
      daysOptions: dailyDaysOptions,
      header: 'Daily Charts',
      key: 'daily',
    },
    {
      daysOptions: bgLogDaysOptions,
      header: 'BG Log Chart',
      key: 'bgLog',
    },
    {
      header: 'Device Settings',
      key: 'settings',
    },
  ];

  // Handlers
  const handleSubmit = () => {
    setSubmitted(true);
    const validationErrors = validateDates(dates);
    if (!isEqual(validationErrors, defaults.errors)) return;

    onClickPrint({
      basics: { ...dates.basics, enabled: enabled.basics },
      bgLog: { ...dates.bgLog, enabled: enabled.bgLog },
      daily: { ...dates.daily, enabled: enabled.daily },
      settings: { enabled: enabled.settings },
    });
  };

  const handleClose = () => {
    onClose();
  };

  // Set to default state when dialog is newly opened
  useEffect(() => {
    if (open) {
      setDatePickerOpen(defaults.datePickerOpen);
      setDates(defaults.dates);
      setEnabled(defaults.enabled);
      setErrors(defaults.errors);
      setExpandedPanel(defaults.expandedPanel);
      setSubmitted(defaults.submitted);
    }
  }, [open]);

  // Validate dates if submitted and call `onDatesChange` prop method when dates change
  useEffect(() => {
    if (submitted) validateDates(dates);
    onDatesChange(dates);
  }, [dates]);

  return (
    <Dialog id="printDateRangePicker" maxWidth="md" open={open} onClose={handleClose}>
      <DialogTitle divider={false} onClose={handleClose}>
        <MediumTitle>Print Report</MediumTitle>
      </DialogTitle>
      <DialogContent divider={false} minWidth="400px" p={0}>
        {map(panels, panel => (
          <Accordion {...accordionProps(panel.key, panel.header)}>
            <Box width="100%">
              <Flex mb={4}>
                <Label htmlFor={`enabled-${panel.key}`}>
                  <Body1 alignSelf="center">Include {panel.header}</Body1>
                  <Switch
                    name={`enabled-${panel.key}`}
                    ml={4}
                    checked={enabled[panel.key]}
                    onClick={() => setEnabled({ ...enabled, [panel.key]: !enabled[panel.key] })}
                  />
                </Label>
              </Flex>

              {enabled[panel.key] && panel.daysOptions && (
                <Box>
                  <Box mb={5}>
                    <Body1 mb={2}>Number of days (most recent)</Body1>
                    <Flex>
                      {map(panel.daysOptions, (days, i) => (
                        <Button
                          mr={2}
                          variant="chip"
                          id={`days-${panel.key}`}
                          name={`days-${panel.key}`}
                          key={`days-${panel.key}-${i}`}
                          value={days}
                          selected={datesMatchPreset(dates[panel.key], presetDateRanges[panel.key][i])}
                          onClick={() => setDates({ ...dates, [panel.key]: getLastNDays(days, panel.key) })}
                        >
                          {days} days
                        </Button>
                      ))}
                    </Flex>
                  </Box>
                  <Box mb={3}>
                    <Body1 mb={2}>Or select a custom date range</Body1>
                    <DateRangePicker
                      startDate={dates[panel.key].startDate}
                      startDateId={`${[panel.key]}-start-date`}
                      endDate={dates[panel.key].endDate}
                      endDateId={`${[panel.key]}-end-date`}
                      onDatesChange={newDates => setDates({ ...dates, [panel.key]: setDateRangeToExtents(newDates) })}
                      isOutsideRange={day => (endOfToday.diff(day) < 0)}
                      onFocusChange={input => setDatePickerOpen(!!input)}
                      themeProps={{
                        minWidth: '580px',
                        minHeight: datePickerOpen ? '300px' : undefined,
                      }}
                    />
                  </Box>
                </Box>
              )}
            </Box>
            {errors[panel.key] && (
              <Caption mt={2} color="feedback.danger">
                Please select a date range
              </Caption>
            )}
          </Accordion>
        ))}
      </DialogContent>
      <DialogActions justifyContent="space-between" py={2}>
        <Button variant="textSecondary" onClick={handleClose}>
          Cancel
        </Button>
        <Button variant="textPrimary" onClick={handleSubmit}>
          Print
        </Button>
      </DialogActions>
    </Dialog>
  );
};

PrintDateRangeModal.propTypes = {
  mostRecentDatumDates: PropTypes.shape({
    basics: PropTypes.number.isRequired,
    bgLog: PropTypes.number.isRequired,
    daily: PropTypes.number.isRequired,
  }),
  onClickPrint: PropTypes.func,
  onClose: PropTypes.func,
  onDatesChange: PropTypes.func,
  open: PropTypes.bool,
  timePrefs: PropTypes.shape({
    timezoneAware: PropTypes.bool,
    timezoneName: PropTypes.string.isRequired,
  }).isRequired,
};

PrintDateRangeModal.defaultProps = {
  onClickPrint: noop,
  onClose: noop,
  onDatesChange: noop,
};

export default PrintDateRangeModal;
<|endoftext|>


<commit_before>"use strict";
Seed({
		name : "Mold.Lib.DomPointer",
		dna : "class",
		compiler : {
			preparsePublics : true
		}
	},
	function(config){

		var _name = config.name,
			_type = config.type,
			_node = config.node,
			_nodeValue = _node.nodeValue,
			_oldValue = _nodeValue,
			_subnodes = config.subnodes,
			_subnodeValues = [],
			_lastShadowNode = config.lastShadowNode,
			_lastNode = config.lastNode,
			_parentElement = config.parentElement || _node.parentElement,
			_shadowDom = config.shadowDom || false,
			_isVisible = false,
			_valueStore = false,
			_filter = config.filter,
			_childIndex = false;

			_node.nodeValue = ""

		var _cleanSubnodes = function(){
			var i = 0, len = _subnodes.length;
			for(; i < len; i++){
				_subnodes[i].nodeValue = "";
			}
		}

		var _remove = function(pointer, dontremove){
			Mold.each(pointer, function(element){
				if(Mold.isArray(element)){
					_remove(element, dontremove);
				}else{
					if(element.parentNode && element !== dontremove){
						element.parentNode.removeChild(element);
					}
				}
			});
		}

		var _hideList = function(pointer, dontremove){
			Mold.each(pointer, function(element){
				if(Mold.isArray(element)){
					_hideList(element, dontremove);
				}else{
					if(element.parentNode && element !== dontremove){
						if(!_valueStore){
							_valueStore = document.createElement("div");
						}
						_valueStore.appendChild(element);
					}
				}
			});
		}

		var _hide = function(from, to, dontremove){
			var node = from, nextNode;
			while(node != null){

				nextNode = node.nextSibling;
				if(node.parentNode && node !== dontremove){
					if(!_valueStore){
						_valueStore = document.createElement("div");
					}
					_valueStore.appendChild(node);
				}
				if(node === to){
					node = null;
					break;
				}else{
					node = nextNode;
				}
			}
		}

		var _show = function(value){

			if(value.hasChildNodes && value.hasChildNodes()){
				_subnodes = [];
				var  subnode = value.firstChild;

				while(subnode != null){

					var nextNode = subnode.nextSibling;
					if(subnode.hasChildNodes()){
						_show(subnode.childNodes)
					}
					if(subnode){
						var lastNode = _getLastShadowNode(_subnodes);
						_parentElement.insertBefore(subnode, _lastShadowNode);

						_subnodes.push(subnode);
					}

					subnode = nextNode;
				}
			}
		}

		var _getFragment = function(shadowDom, fragment){
			if(shadowDom){

				Mold.each(shadowDom, function(element){

					if(Mold.isArray(element)){
						_getFragment(element, fragment);
					}else{
						// referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);

						fragment.appendChild(element)
						//_parentElement.insertBefore(element, _lastNode);
					}
				});
			}
			return fragment;
		}

		var _add = function(shadowDom){
			if(shadowDom){
				//var frament = document.createDocumentFragment();
				Mold.each(shadowDom, function(element){

					if(Mold.isArray(element)){
						_add(element);
					}else{
						// referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
						_parentElement.insertBefore(element, _lastNode);
					}
				});

				//_parentElement.insertBefore(_getFragment(shadowDom, document.createDocumentFragment()), _lastNode);
			}
		}

		var _copy = function(nodes, doNotCopy){
			var newBlock = [];
			Mold.each(nodes, function(element){
				if(Mold.isArray(element)){
					newBlock.push(_copy(element, doNotCopy));
				}else{
					if(!doNotCopy || element !== doNotCopy){
						newBlock.push(element.cloneNode(true));
					}
				}
			});

			return newBlock;
		}

		var _clone = function(node, subnodes, shadowDom){

			var shadowCopy = shadowDom || (_shadowDom) ? _copy(_shadowDom) : false;
			var subnodeCopy = subnodes || (_subnodes) ? _copy(shadowCopy)  : false;
			var lastShadowNode = (subnodeCopy) ? _getLastShadowNode(subnodeCopy) : _lastNode;

			var pointer = new Mold.Lib.DomPointer({
				name : _name,
				type : _type,
				node : node || _node.cloneNode(true),
				parentElement : _parentElement,
				shadowDom : shadowCopy,
				lastShadowNode : lastShadowNode,
				lastNode : _lastNode,
				subnodes : subnodeCopy
			});

			return pointer;
		}

		var _getLastShadowNode = function(element){
			if(Mold.isArray(element)){
				return _getLastShadowNode(element[element.length -1])
			}else{
				return element;
			}
		}

		if(!_lastShadowNode){
			_lastShadowNode = _getLastShadowNode(_subnodes)
		}

		this.publics = {
			node : _node,
			subnodes : _subnodes,
			shadowDom : _shadowDom,
			name : _name,
			filter : _filter,
			getNode : function(){
				return _node;
			},
			setChildIndex : function(index){
				_childIndex = index;
			},
			getChildIndex : function(){
				return _childIndex;
			},
			getType : function(){
				return _type;
			},
			getSubnodes : function(){
				return _subnodes;
			},
			getLastNode : function(){
				return _lastNode;
			},
			getFirsNode : function(){
				if(_shadowDom){

				}else{
					return false;
				}
			},
			remove : function(){
				_remove(_subnodes);
				_remove(_shadowDom);
			},
			clone : function(node, subnodes, shadowDom){
				return _clone(node, subnodes, shadowDom);
			},
			add : function(){
				_add(_subnodes);
			},
			show : function(value){
				_isVisible = true;
				if(_type === "value"){
					if(value !== false && value !== "" && value !== undefined){
						_nodeValue = _node.nodeValue;
						_node.nodeValue = value;
					}else{
						_node.nodeValue = _nodeValue;
					}

				}else{
					_show(_valueStore)
				}
			},
			hide : function(){
				_isVisible = false;
				if(_type === "value"){
					_nodeValue = _node.nodeValue;
					_node.nodeValue = "";
				}else{
					if(_subnodes){
						_hideList(_subnodes, _lastShadowNode)

					}
				}

			},
			isVisible : function(){
				return _isVisible;
			},
			test : function(){
				return "twst"
			}
		}

	}
)<commit_msg>comments removed<commit_after>"use strict";
Seed({
		name : "Mold.Lib.DomPointer",
		dna : "class",
		compiler : {
			//preparsePublics : true
		}
	},
	function(config){

		var _name = config.name,
			_type = config.type,
			_node = config.node,
			_nodeValue = _node.nodeValue,
			_oldValue = _nodeValue,
			_subnodes = config.subnodes,
			_subnodeValues = [],
			_lastShadowNode = config.lastShadowNode,
			_lastNode = config.lastNode,
			_parentElement = config.parentElement || _node.parentNode,
			_shadowDom = config.shadowDom || false,
			_isVisible = false,
			_valueStore = false,
			_filter = config.filter,
			_childIndex = false;

			_node.nodeValue = "";

		var _cleanSubnodes = function(){
			var i = 0, len = _subnodes.length;
			for(; i < len; i++){
				_subnodes[i].nodeValue = "";
			}
		}

		var _remove = function(pointer, dontremove){
			Mold.each(pointer, function(element){
				if(Mold.isArray(element)){
					_remove(element, dontremove);
				}else{
					if(element.parentNode && element !== dontremove){
						element.parentNode.removeChild(element);
					}
				}
			});
		}

		var _hideList = function(pointer, dontremove){
			Mold.each(pointer, function(element){
				if(Mold.isArray(element)){
					_hideList(element, dontremove);
				}else{
					if(element.parentNode && element !== dontremove){
						if(!_valueStore){
							_valueStore = document.createElement("div");
						}
						_valueStore.appendChild(element);
					}
				}
			});
		}

		var _hide = function(from, to, dontremove){
			var node = from, nextNode;
			while(node != null){

				nextNode = node.nextSibling;
				if(node.parentNode && node !== dontremove){
					if(!_valueStore){
						_valueStore = document.createElement("div");
					}
					_valueStore.appendChild(node);
				}
				if(node === to){
					node = null;
					break;
				}else{
					node = nextNode;
				}
			}
		}

		var _show = function(value){

			if(value.hasChildNodes && value.hasChildNodes()){
				_subnodes = [];
				var  subnode = value.firstChild;

				while(subnode != null){

					var nextNode = subnode.nextSibling;
					if(subnode.hasChildNodes()){
						_show(subnode.childNodes)
					}
					if(subnode){
						var lastNode = _getLastShadowNode(_subnodes);
						if(_parentElement){
							_parentElement.insertBefore(subnode, _lastShadowNode);
						}
						_subnodes.push(subnode);
					}

					subnode = nextNode;
				}
			}
		}

		var _getFragment = function(shadowDom, fragment){
			if(shadowDom){

				Mold.each(shadowDom, function(element){

					if(Mold.isArray(element)){
						_getFragment(element, fragment);
					}else{
						fragment.appendChild(element)
					}
				});
			}
			return fragment;
		}

		var _add = function(shadowDom){
			if(shadowDom){
				Mold.each(shadowDom, function(element){

					if(Mold.isArray(element)){
						_add(element);
					}else{
						_parentElement.insertBefore(element, _lastNode);
					}
				});
			}
		}

		var _copy = function(nodes, doNotCopy){
			var newBlock = [];
			Mold.each(nodes, function(element){
				if(Mold.isArray(element)){
					newBlock.push(_copy(element, doNotCopy));
				}else{
					if(!doNotCopy || element !== doNotCopy){
						newBlock.push(element.cloneNode(true));
					}
				}
			});

			return newBlock;
		}

		var _clone = function(node, subnodes, shadowDom){

			var shadowCopy = shadowDom || (_shadowDom) ? _copy(_shadowDom) : false;
			var subnodeCopy = subnodes || (_subnodes) ? _copy(shadowCopy)  : false;
			var lastShadowNode = (subnodeCopy) ? _getLastShadowNode(subnodeCopy) : _lastNode;

			var pointer = new Mold.Lib.DomPointer({
				name : _name,
				type : _type,
				node : node || _node.cloneNode(true),
				parentElement : _parentElement,
				shadowDom : shadowCopy,
				lastShadowNode : lastShadowNode,
				lastNode : _lastNode,
				subnodes : subnodeCopy
			});

			return pointer;
		}

		var _getLastShadowNode = function(element){
			if(Mold.isArray(element)){
				return _getLastShadowNode(element[element.length -1])
			}else{
				return element;
			}
		}

		if(!_lastShadowNode){
			_lastShadowNode = _getLastShadowNode(_subnodes)
		}

		this.publics = {
			node : _node,
			subnodes : _subnodes,
			shadowDom : _shadowDom,
			name : _name,
			filter : _filter,
			getNode : function(){
				return _node;
			},
			setChildIndex : function(index){
				_childIndex = index;
			},
			getChildIndex : function(){
				return _childIndex;
			},
			getType : function(){
				return _type;
			},
			getSubnodes : function(){
				return _subnodes;
			},
			getLastNode : function(){
				return _lastNode;
			},
			getFirsNode : function(){
				if(_shadowDom){

				}else{
					return false;
				}
			},
			remove : function(){
				_remove(_subnodes);
				_remove(_shadowDom);
			},
			clone : function(node, subnodes, shadowDom){
				return _clone(node, subnodes, shadowDom);
			},
			add : function(){
				_add(_subnodes);
			},
			show : function(value){
				_isVisible = true;
				if(_type === "value"){
					if(value !== false && value !== "" && value !== undefined){
						_nodeValue = _node.nodeValue;
						_node.nodeValue = value;
					}else{
						_node.nodeValue = _nodeValue;
					}

				}else{
					_show(_valueStore)
				}
			},
			hide : function(){
				_isVisible = false;
				if(_type === "value"){
					_nodeValue = _node.nodeValue;
					_node.nodeValue = "";
				}else{
					if(_subnodes){
						_hideList(_subnodes, _lastShadowNode)

					}
				}

			},
			isVisible : function(){
				return _isVisible;
			},
			test : function(){
				return "test"
			}
		}

	}
)<|endoftext|>


<commit_before>/**
 *
 * StructureView2
 *
 */

import React from 'react';
import { Tabs, Tab } from 'material-ui/Tabs';
import GeometryCanvas from 'components/GeometryCanvas';

const cifdata = `data_global
_cell_length_a 24
_cell_length_b 5.91
_cell_length_c 5.85
_cell_angle_alpha 90
_cell_angle_beta 90
_cell_angle_gamma 90
_symmetry_space_group_name_H-M 'P1'
loop_
_symmetry_equiv_pos_as_xyz
x,y,z
loop_
_atom_site_label
_atom_site_type_symbol
_atom_site_fract_x
_atom_site_fract_y
_atom_site_fract_z
O1 O 0.425 0.262 0.009
O2 O -0.425 0.262 0.009
H3 H 0.444 0.258 0.154
H4 H -0.444 0.258 0.154
H5 H 0.396 0.124 0.012
H6 H -0.396 0.124 0.012
O7 O 0.425 0.236 0.510
O8 O -0.425 0.236 0.510
H9 H 0.444 0.239 0.656
H10 H -0.444 0.239 0.656
H11 H 0.396 0.374 0.512
H12 H -0.396 0.374 0.512
Sr13 Sr 0.342 0.964 0.467
Sr14 Sr -0.342 0.964 0.467
Sr15 Sr 0.342 0.535 0.967
Sr16 Sr -0.342 0.535 0.967
O17 O 0.348 0.971 0.019
O18 O -0.348 0.971 0.019
O19 O 0.348 0.528 0.519
O20 O -0.348 0.528 0.519
O21 O 0.263 0.803 0.701
O22 O -0.263 0.803 0.701
O23 O 0.264 0.695 0.200
O24 O -0.264 0.695 0.200
Zr25 Zr 0.261 0.000 0.998
Zr26 Zr -0.261 0.000 0.998
Zr27 Zr 0.261 0.499 0.498
Zr28 Zr -0.261 0.499 0.498
O29 O 0.257 0.304 0.806
O30 O -0.257 0.304 0.806
O31 O 0.257 0.195 0.306
O32 O -0.257 0.195 0.306
Sr33 Sr 0.173 0.993 0.524
Sr34 Sr -0.173 0.993 0.524
Sr35 Sr 0.173 0.506 0.024
Sr36 Sr -0.173 0.506 0.024
O37 O 0.173 0.947 0.986
O38 O -0.173 0.947 0.986
O39 O 0.173 0.551 0.486
O40 O -0.173 0.551 0.486
O41 O 0.098 0.204 0.295
O42 O -0.098 0.204 0.295
O43 O 0.098 0.295 0.795
O44 O -0.098 0.295 0.795
Zr45 Zr 0.086 0.004 0.998
Zr46 Zr -0.086 0.004 0.998
Zr47 Zr 0.086 0.495 0.498
Zr48 Zr -0.086 0.495 0.498
O49 O 0.074 0.709 0.211
O50 O -0.074 0.709 0.211
O51 O 0.074 0.790 0.711
O52 O -0.074 0.790 0.711
Sr53 Sr 0 0.991 0.467
Sr54 Sr 0 0.508 0.967
O55 O 0 0.076 0.020
O56 O 0 0.423 0.520`;

window.parent.cifdata = cifdata;

class StructureView2 extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    return (

Detailed Structure View

        <Tabs
          tabItemContainerStyle={{ width: '900px' }}
        >
          <Tab label="Structure One">

Structure 1

            <GeometryCanvas id="structure1" cifdata={cifdata} />
          </Tab>
          <Tab label="Structure Two">

Structure 2

            <GeometryCanvas id="structure2" cifdata={cifdata} />
          </Tab>
          <Tab label="Structure Three">

Structure 3

            <GeometryCanvas id="structure3" cifdata={cifdata} />
          </Tab>
          <Tab label="Structure Four">

Structure 4

            <GeometryCanvas id="structure4" cifdata={cifdata} />
          </Tab>
        </Tabs>

    );
  }
}

StructureView2.propTypes = {

};

export default StructureView2;
<commit_msg>Show four different structures in structure_view<commit_after>/**
 *
 * StructureView2
 *
 */

import React from 'react';
import { Tabs, Tab } from 'material-ui/Tabs';
import GeometryCanvas from 'components/GeometryCanvas';

import { backendRoot } from 'utils/constants';

class StructureView2 extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    const cifurl1 = `${backendRoot}get_cif/?path=6f_doping/Ce_6f_doping/addOempty/final_geo_for_db_Ce_6f_doping_addOempty.traj`;
    const cifurl2 = `${backendRoot}get_cif/?path=6f_doping/Ce_6f_doping/addOaddOH/final_geo_for_db_Ce_6f_doping_addOaddOH.traj`;
    const cifurl3 = `${backendRoot}get_cif/?path=6f_doping/Ce_6f_doping/addOaddO/final_geo_for_db_Ce_6f_doping_addOaddO.traj`;
    const cifurl4 = `${backendRoot}get_cif/?path=6f_doping/Ce_6f_doping/addOaddOOH/final_geo_for_db_Ce_6f_doping_addOaddOOH.traj`;

    return (

Detailed Structure View

        <Tabs
          tabItemContainerStyle={{ width: '900px' }}
        >
          <Tab label="Structure One">

Structure 1

            <GeometryCanvas id="structure1" cifurl={cifurl1} />
          </Tab>
          <Tab label="Structure Two">

Structure 2

            <GeometryCanvas id="structure2" cifurl={cifurl2} />
          </Tab>
          <Tab label="Structure Three">

Structure 3

            <GeometryCanvas id="structure3" cifurl={cifurl3} />
          </Tab>
          <Tab label="Structure Four">

Structure 4

            <GeometryCanvas id="structure4" cifurl={cifurl4} />
          </Tab>
        </Tabs>

    );
  }
}

StructureView2.propTypes = {

};

export default StructureView2;
<|endoftext|>


<commit_before>/**
*
* StructureView
*
*/

import React from 'react';

/* import { FormattedMessage } from 'react-intl'; */
/* import messages from './messages'; */

import { Tabs, Tab } from 'material-ui/Tabs';

function StructureView() {
  return (

Detailed Structure View

      <Tabs
        tabItemContainerStyle={{ width: '900px' }}
      >
        <Tab label="Structure One">

... More on Structure 1

        </Tab>
        <Tab label="Structure Two">

... More on Structure 2

        </Tab>
        <Tab label="Structure Three">

... More on Structure 3

        </Tab>
        <Tab label="Structure Four">

... More on Structure 4

        </Tab>
      </Tabs>

  );
}

StructureView.propTypes = {

};

export default StructureView;
<commit_msg>Fixed mock-up content for structure view<commit_after>/**
*
* StructureView
*
*/

import React from 'react';

/* import { FormattedMessage } from 'react-intl'; */
/* import messages from './messages'; */

import { Tabs, Tab } from 'material-ui/Tabs';

function StructureView() {
  return (

Detailed Structure View

      <Tabs
        tabItemContainerStyle={{ width: '900px' }}
      >
        <Tab label="Structure One">

... More to follow on Structure 1

        </Tab>
        <Tab label="Structure Two">

... More to follow on Structure 2

        </Tab>
        <Tab label="Structure Three">

... More to follow on Structure 3

        </Tab>
        <Tab label="Structure Four">

... More to follow on Structure 4

        </Tab>
      </Tabs>

  );
}

StructureView.propTypes = {

};

export default StructureView;
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['create-comment-form'],
  tagName: 'form',

  session: Ember.inject.service(),

  actions: {
    saveComment() {
      let comment = this.get('comment');
      this.sendAction('saveComment', comment);
    },
  }
});
<commit_msg>add create-comment-form documentation (#349)<commit_after>import Ember from 'ember';

const {
  Component,
  get,
  inject,
} = Ember;

const { service } = inject;

/**
  `create-comment-form` composes the comment form. The comment form allows for
  editing and previewing the contents of a comment.

  ## default usage

  ```handlebars
  {{create-comment-form comment=comment saveComment='saveCommentAction'}}
  ```

  @class create-comment-form
  @module Component
  @extends Ember.Component
 */
export default Component.extend({
  classNames: ['create-comment-form'],
  tagName: 'form',

  /**
    @property session
    @type Ember.Service
   */
  session: service(),

  actions: {

    /**
      Action that sends the given `saveComment` action with the comment.

      @method saveComment
     */
    saveComment() {
      let comment = get(this, 'comment');

      this.sendAction('saveComment', comment);
    },
  },
});
<|endoftext|>


<commit_before>WatchMe = {
  initial: {
    diameter: 300
  }
};

WatchMe.padLeft = function (x, padCharacter, length) {
  var s = '' + x,
      parts = [];
  for (var i = s.length; i < length; ++i) {
    parts.push(padCharacter);
  }
  parts.push(s);
  return parts.join('');
};

WatchMe.cachedTextMeasurements = {};

WatchMe.measureText = function (text, font, fontSize) {
  var cache = WatchMe.cachedTextMeasurements;
  if (cache[font] !== undefined && cache[font][text] !== undefined) {
    return cache[font][text];
  }
  var canvas = WatchMe.canvas.measure,
      context = WatchMe.context.measure;
  if (context.font != font) {
    context.font = font;
  }
  var width = Math.ceil(context.measureText(text).width);
  if (canvas.width < width) {
    canvas.width = width;
    context.font = font;
  }
  if (canvas.height < 2 * fontSize) {
    canvas.height = 2 * fontSize;
    context.font = font;
  }
  context.clearRect(0, 0, canvas.width, canvas.height);
  var height = canvas.height,
      xFill = 0,
      yFill = height / 2;
  context.fillText(text, xFill, yFill);
  var data = context.getImageData(0, 0, width, height).data,
      xMin, xMax, yMin, yMax;
  for (var x = 0; x < width; ++x) {
    for (var y = 0; y < height; ++y) {
      var i = 4 * (y * width + x);
      if (data[i + 3] == 0) {
        continue;
      }
      if (xMin === undefined) {
        xMin = xMax = x;
        yMin = yMax = y;
      } else {
        xMin = Math.min(xMin, x);
        xMax = Math.max(xMax, x);
        yMin = Math.min(yMin, y);
        yMax = Math.max(yMax, y);
      }
    }
  }
  var x0 = (xMin + xMax) / 2,
      y0 = (yMin + yMax) / 2,
      radiusSquared = 0;
  for (var x = xMin; x <= xMax; ++x) {
    for (var y = yMin; y <= yMax; ++y) {
      var i = 4 * (y * width + x);
      if (data[i + 3] == 0) {
        continue;
      }
      var dx = Math.abs(x - x0) + 1,
          dy = Math.abs(y - y0) + 1;
      radiusSquared = Math.max(radiusSquared, dx * dx + dy * dy);
    }
  }
  var radius = Math.ceil(Math.sqrt(radiusSquared));
  context.fillStyle = '#ccc';
  context.beginPath();
  context.arc(x0, y0, radius, 0, 2 * Math.PI);
  context.fill();
  context.fillStyle = '#000';
  context.fillText(text, 0, height / 2);
  if (cache[font] === undefined) {
    cache[font] = {};
  }
  var measurement = cache[font][text] = {
    xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax,
    radius: radius,
    centerFromFill: {
      x: x0 - xFill,
      y: y0 - yFill
    }
  };
  console.log(measurement);
  return measurement;
};

WatchMe.update = function () {
  var date = new Date(),
      hour = date.getHours() % 12,
      minute = date.getMinutes(),
      second = date.getSeconds(),
      millisecond = date.getMilliseconds();

  // Textual time check.
  var hourText = (hour == 0 ? 12: hour) + '',
      minuteText = WatchMe.padLeft(minute, '0', 2),
      secondText = WatchMe.padLeft(second, '0', 2);
  WatchMe.display.timeCheck.innerHTML =
      [ hourText, minuteText, secondText ].join(':');

  // Draw background graphics.
  var context = WatchMe.context.watch,
      radius = WatchMe.radius,
      center = { x: radius, y: radius };
      thickness = 1;
  context.clearRect(0, 0, 2 * radius, 2 * radius);
  context.lineWidth = thickness;

  var hourRadius = 0.20 * radius,
      hourDistance = radius - hourRadius,
      minuteRadius = 0.16 * radius,
      minuteDistance = hourDistance - hourRadius - minuteRadius,
      secondRadius = 0.12 * radius,
      secondDistance = minuteDistance - minuteRadius - secondRadius;

  var paintArc = function (value, valueText, hertz, handDistance, handRadius,
        edgeProportion, circleColor, arcColor) {
    var angle = -Math.PI / 2 + value * 2 * Math.PI / hertz;
    thickness = edgeProportion * 2 * handRadius;
    // Background circle.
    context.lineWidth = thickness;
    context.beginPath();
    context.strokeStyle = circleColor;
    context.arc(center.x, center.y, handDistance + handRadius - thickness / 2,
        0, 2 * Math.PI);
    context.stroke();
    // Foreground arc.
    context.beginPath();
    context.strokeStyle = arcColor;
    context.arc(center.x, center.y, handDistance + handRadius - thickness / 2,
        angle - Math.PI / hertz, angle + Math.PI / hertz);
    context.stroke();
    // Value position.
    context.beginPath();
    context.lineWidth = 1;
    context.fillStyle = '#e8e8e8';
    var x = center.x + Math.cos(angle) * (handDistance - thickness / 2),
        y = center.y + Math.sin(angle) * (handDistance - thickness / 2);
    context.arc(x, y, handRadius - thickness / 2, 0, 2 * Math.PI);
    context.lineWidth = 1;
    context.fill();
    // Value text.
    context.fillStyle = '#444';
    var fontSize = Math.round(2 * handRadius - thickness),
        font = fontSize + 'px sans-serif';
    context.font = font;
    var width = context.measureText(valueText).width;
    WatchMe.measureText(valueText, font, fontSize);
    context.fillText(valueText, x - width / 2, y + handRadius - thickness / 2);
  };
  paintArc(hour, hourText, 12, hourDistance, hourRadius,
      0.105, '#f4f4f4', '#888');
  paintArc(minute, minuteText, 60, minuteDistance, minuteRadius,
      0.135, '#f4f4f4', '#666');
  paintArc(second, secondText, 60, secondDistance, secondRadius,
      0.165, '#f4f4f4', '#444');

  if (WatchMe.stopped) {
    return;
  }
  window.requestAnimationFrame(WatchMe.update);
};

WatchMe.load = function () {
  WatchMe.display = {
    timeCheck: document.getElementById('timeCheck')
  };
  WatchMe.canvas = {
    watch: document.createElement('canvas'),
    measure: document.createElement('canvas')
  };
  var canvas = WatchMe.canvas.watch,
      diameter = WatchMe.diameter = WatchMe.initial.diameter,
      radius = WatchMe.radius = diameter / 2;
  document.getElementById('watchContainer').appendChild(canvas);
  canvas.width = diameter;
  canvas.height = diameter;
  WatchMe.context = {
    watch: canvas.getContext('2d'),
    measure: WatchMe.canvas.measure.getContext('2d')
  };
  var measureCanvas = WatchMe.canvas.measure;
  measureCanvas.width = measureCanvas.height = 10;
  measureCanvas.style.border = '1px dotted #ccc';
  document.getElementById('wrapper').appendChild(measureCanvas);
  document.getElementById('stopButton').onmousedown = function () {
    WatchMe.stopped = true;
  };
  window.requestAnimationFrame(WatchMe.update);
};

window.onload = WatchMe.load;
<commit_msg>Paint correct disc behind text<commit_after>WatchMe = {
  initial: {
    diameter: 300
  }
};

WatchMe.padLeft = function (x, padCharacter, length) {
  var s = '' + x,
      parts = [];
  for (var i = s.length; i < length; ++i) {
    parts.push(padCharacter);
  }
  parts.push(s);
  return parts.join('');
};

WatchMe.cachedTextMeasurements = {};

WatchMe.measureText = function (text, font, fontSize) {
  var cache = WatchMe.cachedTextMeasurements;
  if (cache[font] !== undefined && cache[font][text] !== undefined) {
    return cache[font][text];
  }
  var canvas = WatchMe.canvas.measure,
      context = WatchMe.context.measure;
  if (context.font != font) {
    context.font = font;
  }
  var width = Math.ceil(context.measureText(text).width);
  if (canvas.width < width) {
    canvas.width = width;
    context.font = font;
  }
  if (canvas.height < 2 * fontSize) {
    canvas.height = 2 * fontSize;
    context.font = font;
  }
  context.clearRect(0, 0, canvas.width, canvas.height);
  var height = canvas.height,
      xFill = 0,
      yFill = height / 2;
  context.fillText(text, xFill, yFill);
  var data = context.getImageData(0, 0, width, height).data,
      xMin, xMax, yMin, yMax;
  for (var x = 0; x < width; ++x) {
    for (var y = 0; y < height; ++y) {
      var i = 4 * (y * width + x);
      if (data[i + 3] == 0) {
        continue;
      }
      if (xMin === undefined) {
        xMin = xMax = x;
        yMin = yMax = y;
      } else {
        xMin = Math.min(xMin, x);
        xMax = Math.max(xMax, x);
        yMin = Math.min(yMin, y);
        yMax = Math.max(yMax, y);
      }
    }
  }
  var x0 = (xMin + xMax) / 2,
      y0 = (yMin + yMax) / 2,
      radiusSquared = 0;
  for (var x = xMin; x <= xMax; ++x) {
    for (var y = yMin; y <= yMax; ++y) {
      var i = 4 * (y * width + x);
      if (data[i + 3] == 0) {
        continue;
      }
      var dx = Math.abs(x - x0) + 1,
          dy = Math.abs(y - y0) + 1;
      radiusSquared = Math.max(radiusSquared, dx * dx + dy * dy);
    }
  }
  var radius = Math.ceil(Math.sqrt(radiusSquared));
  context.fillStyle = '#ccc';
  context.beginPath();
  context.arc(x0, y0, radius, 0, 2 * Math.PI);
  context.fill();
  context.fillStyle = '#000';
  context.fillText(text, 0, height / 2);
  if (cache[font] === undefined) {
    cache[font] = {};
  }
  var measurement = cache[font][text] = {
    xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax,
    radius: radius,
    fillCenter: {
      x: x0 - xFill,
      y: y0 - yFill
    }
  };
  return measurement;
};

WatchMe.update = function () {
  var date = new Date(),
      hour = date.getHours() % 12,
      minute = date.getMinutes(),
      second = date.getSeconds(),
      millisecond = date.getMilliseconds();

  // Textual time check.
  var hourText = (hour == 0 ? 12: hour) + '',
      minuteText = WatchMe.padLeft(minute, '0', 2),
      secondText = WatchMe.padLeft(second, '0', 2);
  WatchMe.display.timeCheck.innerHTML =
      [ hourText, minuteText, secondText ].join(':');

  // Draw background graphics.
  var context = WatchMe.context.watch,
      radius = WatchMe.radius,
      center = { x: radius, y: radius };
      thickness = 1;
  context.clearRect(0, 0, 2 * radius, 2 * radius);
  context.lineWidth = thickness;

  var hourRadius = 0.20 * radius,
      hourDistance = radius - hourRadius,
      minuteRadius = 0.16 * radius,
      minuteDistance = hourDistance - hourRadius - minuteRadius,
      secondRadius = 0.12 * radius,
      secondDistance = minuteDistance - minuteRadius - secondRadius;

  var paintArc = function (value, valueText, hertz, handDistance, handRadius,
        edgeProportion, circleColor, arcColor) {
    var angle = -Math.PI / 2 + value * 2 * Math.PI / hertz;
    thickness = edgeProportion * 2 * handRadius;
    // Background circle.
    context.lineWidth = thickness;
    context.beginPath();
    context.strokeStyle = circleColor;
    context.arc(center.x, center.y, handDistance + handRadius - thickness / 2,
        0, 2 * Math.PI);
    context.stroke();
    // Foreground arc.
    context.beginPath();
    context.strokeStyle = arcColor;
    context.arc(center.x, center.y, handDistance + handRadius - thickness / 2,
        angle - Math.PI / hertz, angle + Math.PI / hertz);
    context.stroke();
    // Value position.
    var x = center.x + Math.cos(angle) * (handDistance - thickness / 2),
        y = center.y + Math.sin(angle) * (handDistance - thickness / 2);
    // Value text.
    var fontSize = Math.round(2 * handRadius - thickness),
        font = fontSize + 'px sans-serif';
    context.font = font;
    var m = WatchMe.measureText(valueText, font, fontSize);
    context.beginPath();
    context.fillStyle = '#e8e8e8';
    context.arc(x, y, m.radius, 0, 2 * Math.PI);
    context.fill();
    context.fillStyle = '#444';
    context.fillText(valueText,
        x - m.fillCenter.x,
        y - m.fillCenter.y);
  };
  paintArc(hour, hourText, 12, hourDistance, hourRadius,
      0.105, '#f4f4f4', '#888');
  paintArc(minute, minuteText, 60, minuteDistance, minuteRadius,
      0.135, '#f4f4f4', '#666');
  paintArc(second, secondText, 60, secondDistance, secondRadius,
      0.165, '#f4f4f4', '#444');

  if (WatchMe.stopped) {
    return;
  }
  window.requestAnimationFrame(WatchMe.update);
};

WatchMe.load = function () {
  WatchMe.display = {
    timeCheck: document.getElementById('timeCheck')
  };
  WatchMe.canvas = {
    watch: document.createElement('canvas'),
    measure: document.createElement('canvas')
  };
  var canvas = WatchMe.canvas.watch,
      diameter = WatchMe.diameter = WatchMe.initial.diameter,
      radius = WatchMe.radius = diameter / 2;
  document.getElementById('watchContainer').appendChild(canvas);
  canvas.width = diameter;
  canvas.height = diameter;
  WatchMe.context = {
    watch: canvas.getContext('2d'),
    measure: WatchMe.canvas.measure.getContext('2d')
  };
  document.getElementById('stopButton').onmousedown = function () {
    WatchMe.stopped = true;
  };
  window.requestAnimationFrame(WatchMe.update);
};

window.onload = WatchMe.load;
<|endoftext|>


<commit_before><commit_msg>handle ??? in math_number block<commit_after><|endoftext|>


<commit_before>// @flow

import React from 'react';
import Relay from 'react-relay/classic';

import Link from './link';
import Icon from 'app/components/shared/Icon';

type Props = {
  viewer?: {
    unreadChangelogs?: {
      count: number
    }
  },
  relay: Object
};

class Footer extends React.PureComponent<Props> {
  componentDidMount() {
    this.props.relay.setVariables({ isMounted: true });
  }

  render() {
    let changelogBadge;
    // Viewer is not supplied when rendered for an anonymous user
    if (this.props.viewer && this.props.viewer.unreadChangelogs && this.props.viewer.unreadChangelogs.count > 0) {
      changelogBadge = (
        <span className={`inline-block bg-dark-gray hover-lime-child white rounded ml1 small p1 line-height-1`}>{this.props.viewer.unreadChangelogs.count}
      );
    }

    return (

            <Link href="/home">Home</Link>
            <Link href="/changelog">
              Changelog{changelogBadge}
            </Link>
            <Link href="/blog">Blog</Link>
            <Link href="/docs">Docs</Link>
            <Link href="https://github.com/buildkite/feedback/issues">Feedback</Link>
            <Link href="/privacy-policy">Privacy</Link>
            <Link href="/terms-of-service">Terms</Link>
            <Link href="https://forum.buildkite.community/">Community Forum</Link>
            <Link href="https://buildkitestatus.com/">System Status</Link>

            <a href="http://twitter.com/buildkite" className={`btn hover-lime px1`}><Icon icon="twitter" />
            <a href="https://github.com/buildkite" className={`btn hover-lime px1`}><Icon icon="github" />

    );
  }
}

export default Relay.createContainer(Footer, {
  initialVariables: {
    isMounted: false
  },

  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        unreadChangelogs: changelogs(read: false) @include(if: $isMounted) {
          count
        }
      }
    `
  }
});
<commit_msg>Update index.js<commit_after>// @flow

import React from 'react';
import Relay from 'react-relay/classic';

import Link from './link';
import Icon from 'app/components/shared/Icon';

type Props = {
  viewer?: {
    unreadChangelogs?: {
      count: number
    }
  },
  relay: Object
};

class Footer extends React.PureComponent<Props> {
  componentDidMount() {
    this.props.relay.setVariables({ isMounted: true });
  }

  render() {
    let changelogBadge;
    // Viewer is not supplied when rendered for an anonymous user
    if (this.props.viewer && this.props.viewer.unreadChangelogs && this.props.viewer.unreadChangelogs.count > 0) {
      changelogBadge = (
        <span className={`inline-block bg-dark-gray hover-lime-child white rounded ml1 small p1 line-height-1`}>{this.props.viewer.unreadChangelogs.count}
      );
    }

    return (

            <Link href="/home">Home</Link>
            <Link href="/changelog">
              Changelog{changelogBadge}
            </Link>
            <Link href="/blog">Blog</Link>
            <Link href="/docs">Docs</Link>
            <Link href="https://github.com/buildkite/feedback/issues">Feedback</Link>
            <Link href="/privacy-policy">Privacy</Link>
            <Link href="/terms-of-service">Terms</Link>
            <Link href="https://forum.buildkite.community/">Forum</Link>
            <Link href="https://buildkitestatus.com/">System Status</Link>

            <a href="http://twitter.com/buildkite" className={`btn hover-lime px1`}><Icon icon="twitter" />
            <a href="https://github.com/buildkite" className={`btn hover-lime px1`}><Icon icon="github" />

    );
  }
}

export default Relay.createContainer(Footer, {
  initialVariables: {
    isMounted: false
  },

  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        unreadChangelogs: changelogs(read: false) @include(if: $isMounted) {
          count
        }
      }
    `
  }
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';

import {
  getAvailableTime,
  getCaption,
  getMainImage,
  getName,
  getOpeningHours,
} from 'utils/DataUtils';

class SearchResult extends Component {
  renderImage(image) {
    if (image && image.url) {
      const src = `${image.url}?dim=80x80`;
      return ;
    }
    return null;
  }

  render() {
    const { date, result, unit } = this.props;

    return (

          {this.renderImage(getMainImage(result.images))}

          <Link to={`/resources/${result.id}`}>
            {getName(result)}
          </Link>

{getName(unit)}

          <Link
            to={`/resources/${result.id}/reservation`}
            query={{ date: date.split('T')[0] }}
          >
            {getAvailableTime(getOpeningHours(result), result.reservations)}
          </Link>

    );
  }
}

SearchResult.propTypes = {
  date: PropTypes.string.isRequired,
  result: PropTypes.object.isRequired,
  unit: PropTypes.object.isRequired,
};

export default SearchResult;
<commit_msg>Make search results more clickable<commit_after>import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';

import {
  getAvailableTime,
  getCaption,
  getMainImage,
  getName,
  getOpeningHours,
} from 'utils/DataUtils';

class SearchResult extends Component {
  renderImage(image) {
    if (image && image.url) {
      const src = `${image.url}?dim=80x80`;
      return ;
    }
    return null;
  }

  render() {
    const { date, result, unit } = this.props;

    return (

          <Link to={`/resources/${result.id}`}>
            {this.renderImage(getMainImage(result.images))}
          </Link>

          <Link to={`/resources/${result.id}`}>

{getName(result)}

{getName(unit)}

          </Link>

          <Link
            to={`/resources/${result.id}/reservation`}
            query={{ date: date.split('T')[0] }}
          >
            {getAvailableTime(getOpeningHours(result), result.reservations)}
          </Link>

    );
  }
}

SearchResult.propTypes = {
  date: PropTypes.string.isRequired,
  result: PropTypes.object.isRequired,
  unit: PropTypes.object.isRequired,
};

export default SearchResult;
<|endoftext|>


<commit_before>var TMT = TMT || {};
//title screen
TMT.LeaderBoard = function () {};

var arr = [];

TMT.LeaderBoard.prototype = {
    preload: function () {
    },
    create: function () {
        // Set background and give background speed in x
        this.background = this.game.add.tileSprite(0, 0, this.game.width, this.game.height, 'peaks');

        // Read leadere board data and put it in array arr
        this.readBoardData();

        // Add back button
        this.backButton = this.game.add.button(this.game.width / 2, 500, 'backUp', this.backClickEvent, this);
		this.backButton.events.onInputDown.add(this.touchDown, this);
        this.backButton.anchor.setTo(0.5, 0.8);
        this.backButton.scale.set(0.5, 0.5);
    },
    update: function () {
        /*
            If arr array has data, then we draw text into the page.
        */
        if (arr.length > 0){
            // Add text title: player and score
            this.game.add.text(this.game.width / 2 - 25, 64 + i * 32, 'Top 10',
            { font: "25px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 5 });
            this.game.add.text(this.game.width / 2 - 200, 64 + i * 32, 'Player',
            { font: "25px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 5 });
            this.game.add.text(this.game.width / 2 + 130, 64 + i * 32, 'Score',
            { font: "25px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 4 });

            // add all data
            for (var i = 0; i < arr.length; i++)
            {
                this.game.add.text(this.game.width / 2 - 200, 64 + i * 32, arr[i][0],
                { font: "20px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 4 });
                this.game.add.text(this.game.width / 2 + 130, 64 + i * 32, arr[i][1],
                { font: "20px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 4 });
            }
            arr = [];
        }
    },

	touchDown: function() {
		if(this.game.input.pointer1.isDown) {
			this.backButton.loadTexture('backDown');
		}
		this.backButton.loadTexture('backDown');
	},
    /*
        This ajax method will set a GET request to server and receive back a JSON data.
        Then it convert JSON data into JavaScript array.
    */
    readBoardData: function() {
        $.ajax({
            type: "GET",
            url: "test.php",
            data: "",
            dataType:'json',
            success: function(data) {
                for (i = 0; i < data.length; i++){
                    arr[i] = $.map(data[i], function(el) { return el; });
                }
                // console.log(data);
                // console.log(arr);
            },
            error: function(xhr, status, error) {
                // check status && error
                alert(xhr + "\n" +status + "\n" + error );
            },
        });
    },
    // Generate a random color code
    generateHexColor: function () {
        return '#' + ((0.5 + 0.5 * Math.random()) * 0xFFFFFF << 0).toString(16);
    },
    // Event for Back Button
    backClickEvent: function(){
        this.game.state.start('MainMenu');
    }
};                  <commit_msg>Fixed leaderboard bug.<commit_after>var TMT = TMT || {};
//title screen
TMT.LeaderBoard = function () {};

var arr = [];

TMT.LeaderBoard.prototype = {
    preload: function () {
    },
    create: function () {
        // Set background and give background speed in x
        this.background = this.game.add.tileSprite(0, 0, this.game.width, this.game.height, 'peaks');

        // Read leadere board data and put it in array arr
        this.readBoardData();

        // Add back button
        this.backButton = this.game.add.button(this.game.width / 2, 500, 'backUp', this.backClickEvent, this);
		this.backButton.events.onInputDown.add(this.touchDown, this);
        this.backButton.anchor.setTo(0.5, 0.8);
        this.backButton.scale.set(0.5, 0.5);
    },
    update: function () {
        /*
            If arr array has data, then we draw text into the page.
        */
        if (arr.length > 0){
            // Add text title: player and score
            this.game.add.text(this.game.width / 2 - 25, 10, 'Top 10',
            { font: "25px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 5 });
            this.game.add.text(this.game.width / 2 - 200, 10, 'Player',
            { font: "25px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 5 });
            this.game.add.text(this.game.width / 2 + 130, 10, 'Score',
            { font: "25px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 4 });

            // add all data
            for (var i = 0; i < arr.length; i++)
            {
                this.game.add.text(this.game.width / 2 - 200, 64 + i * 32, arr[i][0],
                { font: "20px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 4 });
                this.game.add.text(this.game.width / 2 + 130, 64 + i * 32, arr[i][1],
                { font: "20px Arial", fill: this.generateHexColor(), stroke: '#000000', strokeThickness: 4 });
            }
            arr = [];
        }
    },

	touchDown: function() {
		if(this.game.input.pointer1.isDown) {
			this.backButton.loadTexture('backDown');
		}
		this.backButton.loadTexture('backDown');
	},
    /*
        This ajax method will set a GET request to server and receive back a JSON data.
        Then it convert JSON data into JavaScript array.
    */
    readBoardData: function() {
        $.ajax({
            type: "GET",
            url: "test.php",
            data: "",
            dataType:'json',
            success: function(data) {
                for (i = 0; i < data.length; i++){
                    arr[i] = $.map(data[i], function(el) { return el; });
                }
                // console.log(data);
                // console.log(arr);
            },
            error: function(xhr, status, error) {
                // check status && error
                alert(xhr + "\n" +status + "\n" + error );
            },
        });
    },
    // Generate a random color code
    generateHexColor: function () {
        return '#' + ((0.5 + 0.5 * Math.random()) * 0xFFFFFF << 0).toString(16);
    },
    // Event for Back Button
    backClickEvent: function(){
        this.game.state.start('MainMenu');
    }
};                  <|endoftext|>


<commit_before>import FilterControls from './FilterControls';
import FilterContainer from './FilterContainer';
import Positions from './Positions';
import {
  debounce,
  intersection,
  isEqual,
  reverse,
  shuffle,
  sortBy,
} from './vendor/lodash.custom';
import {
  merge,
  stringInArray
} from './utils';

class Filterizr {
  constructor(selector = ".filtr-container", options) {
    // make the options a property of the Filterizr instance
    // so that we can later easily modify them
    this.options = options;

    // setup FilterControls and FilterContainer
    const filterControls  = new FilterControls(this);
    const filterContainer = new FilterContainer(selector, options);
    // define props
    this.props = {
      searchTerm: '',
      sort: 'index',
      sortOrder: 'asc',
      FilterContainer: filterContainer,
      FilterItems: filterContainer.props.FilterItems,
      FilteredItems: [],
    }

    // set up events needed by Filterizr
    this.setupEvents();
    // Init Filterizr
    this.filter(this.options.filter);
  }

  // Public API of Filterizr
  filter(category) {
    const {
      searchTerm,
      FilterContainer,
      FilterItems,
    } = this.props;

    // trigger filtering start event
    FilterContainer.trigger('filteringStart');

    // cast category to string or array of strings
    category = Array.isArray(category) ?
      category.map(c => c.toString()) :
      category.toString();

    // filter items and optionally apply search if a search term exists
    const FilteredItems = this.searchFilterItems(this.filterFilterItems(FilterItems, category), searchTerm);
    this.props.FilteredItems = FilteredItems;

    // set up events needed by Filterizr
    // render the items
    this.render(FilteredItems);
  }

  sort(sortAttr = 'index', sortOrder = 'asc') {
    const {
      FilterItems,
    } = this.props;

    // sort main array
    this.props.FilterItems = this.sortFilterItems(FilterItems, sortAttr, sortOrder);
    // apply filters
    const FilteredItems = this.filterFilterItems(this.props.FilterItems, this.options.filter);
    this.props.FilteredItems = FilteredItems;

    // Update and render the sorted items
    this.render(FilteredItems);
  }

  search(searchTerm = this.props.searchTerm) {
    const {
      FilterItems
    } = this.props;

    // filter items and optionally apply search if a search term exists
    const FilteredItems = this.searchFilterItems(this.filterFilterItems(FilterItems, this.options.filter), searchTerm);
    this.props.FilteredItems = FilteredItems;

    // render the items
    this.render(FilteredItems);
  }

  shuffle() {
    const {
      FilteredItems
    } = this.props;

    const ShuffledItems = this.shuffleFilterItems(FilteredItems);
    this.props.FilteredItems = ShuffledItems;

    this.render(ShuffledItems);
  }

  setOptions(newOptions) {
    this.options = merge(newOptions, this.options);
  }

  toggleFilter(toggledFilter) {
    let activeFilters = this.options.filter;

    if (activeFilters === 'all') {
      // if set to all then just set to new category
      activeFilters = toggledFilter;
    }
    else {
      if (Array.isArray(activeFilters)) {
        // if the toggledFilter is already included in the array
        if (stringInArray(activeFilters, toggledFilter)) {
          // then remove it
          activeFilters = activeFilters.filter(f => f !== toggledFilter);
          // and check if there is now only 1 item left in the array
          if (activeFilters.length === 1)
            // in that case flatten it
            activeFilters = activeFilters[0];
        }
        else {
          // if the item is not in the array then simply push it
          activeFilters.push(toggledFilter);
        }
      }
      else {
        // in case the filter is NOT set to "all"
        // check if the toggledFilter is the active one
        if (activeFilters === toggledFilter)
          // in this case revert to all
          activeFilters = "all";
        else
          // otherwise form an array with the two values
          activeFilters = [activeFilters, toggledFilter]
      }
    }

    // update active filter in Filterizr's options
    this.setOptions({
      filter: activeFilters,
    });

    this.filter(this.options.filter);
  }

  // Helper methods
  filterFilterItems(FilterItems, filters) {
    // Get filtered items
    const FilteredItems = (filters === "all") ?
      // in this case return all items
      FilterItems :
      // otherwise return filtered array
      FilterItems.filter(FilterItem => {
        const categories = FilterItem.getCategories();
        return Array.isArray(filters) ?
          intersection(categories, filters).length :
          stringInArray(categories, filters)
      });

    return FilteredItems;
  }

  sortFilterItems(FilterItems ,sortAttr = 'index', sortOrder = 'asc') {
    // Sort the FilterItems and reverse the array if order is descending
    let SortedItems = sortBy(FilterItems, (FilterItem) => {
      return (sortAttr !== 'index' && sortAttr !== 'sortData') ?
        // if the user has not used one of the two default sort attributes
        // then search for custom data attributes on the filter items to sort
        FilterItem.props.data[sortAttr] :
        // otherwise use the defaults
        FilterItem.props[sortAttr];
    });
    SortedItems = sortOrder === 'asc' ? SortedItems : reverse(SortedItems);

    return SortedItems;
  }

  searchFilterItems(FilterItems, searchTerm = this.props.searchTerm) {
    if (!searchTerm) return FilterItems; // exit case when no search is applied

    const SoughtItems =  FilterItems.filter(FilterItem => {
      const contents = FilterItem.getContentsLowercase();
      return ~contents.lastIndexOf(searchTerm);
    });

    return SoughtItems;
  }

  shuffleFilterItems(FilterItems) {
    let ShuffledItems = shuffle(FilterItems)
    // shuffle items until they are different from the initial FilteredItems
    while (FilterItems.length > 1 && isEqual(FilterItems, ShuffledItems)) {
      ShuffledItems = shuffle(FilterItems)
    }

    return ShuffledItems;
  }

  render(FilterItems) {
    // get items to be filtered out
    const FilteredOutItems = this.props.FilterItems.filter(FilterItem => {
      const categories = FilterItem.getCategories();
      const filters = this.options.filter;
      return Array.isArray(filters) ?
        !intersection(categories, filters).length :
        !stringInArray(categories, filters)
    })
    // filter out old items
    FilteredOutItems.forEach(FilterItem => {
      FilterItem.filterOut(this.options.filterOutCss);
    });

    // Determine target positions for items to be filtered in
    const PositionsArray = Positions(this.options.layout, this);

    // filter in new items
    FilterItems.forEach((FilterItem, index) => {
      FilterItem.filterIn(PositionsArray[index], this.options.filterInCss);
    });
  }

  setupEvents() {
    // set up a window resize event to fire refiltering
    $(window).on('resize', debounce((evt) => {
      // update dimensions of items based on new window size
      this.props.FilterContainer.updateWidth();
      this.props.FilterContainer.updateFilterItemsDimensions();
      // refilter the grid to assume new positions
      this.filter(this.options.filter);
    }, 250));
  }
}

export default Filterizr;
<commit_msg>increase readability<commit_after>import FilterControls from './FilterControls';
import FilterContainer from './FilterContainer';
import Positions from './Positions';
import {
  debounce,
  intersection,
  isEqual,
  reverse,
  shuffle,
  sortBy,
} from './vendor/lodash.custom';
import {
  merge,
  stringInArray
} from './utils';

class Filterizr {
  constructor(selector = ".filtr-container", options) {
    // make the options a property of the Filterizr instance
    // so that we can later easily modify them
    this.options = options;

    // setup FilterControls and FilterContainer
    const filterControls  = new FilterControls(this);
    const filterContainer = new FilterContainer(selector, options);
    // define props
    this.props = {
      searchTerm: '',
      sort: 'index',
      sortOrder: 'asc',
      FilterContainer: filterContainer,
      FilterItems: filterContainer.props.FilterItems,
      FilteredItems: [],
    }

    // set up events needed by Filterizr
    this.setupEvents();
    // Init Filterizr
    this.filter(this.options.filter);
  }

  // Public API of Filterizr
  filter(category) {
    const {
      searchTerm,
      FilterContainer,
      FilterItems,
    } = this.props;

    // trigger filtering start event
    FilterContainer.trigger('filteringStart');

    // cast category to string or array of strings
    category = Array.isArray(category) ?
      category.map(c => c.toString()) :
      category.toString();

    // filter items and optionally apply search if a search term exists
    const FilteredItems = this.searchFilterItems(
      this.filterFilterItems(FilterItems, category), searchTerm
    );
    this.props.FilteredItems = FilteredItems;

    // set up events needed by Filterizr
    // render the items
    this.render(FilteredItems);
  }

  sort(sortAttr = 'index', sortOrder = 'asc') {
    const {
      FilterItems,
    } = this.props;

    // sort main array
    this.props.FilterItems = this.sortFilterItems(FilterItems, sortAttr, sortOrder);
    // apply filters
    const FilteredItems = this.filterFilterItems(this.props.FilterItems, this.options.filter);
    this.props.FilteredItems = FilteredItems;

    // Update and render the sorted items
    this.render(FilteredItems);
  }

  search(searchTerm = this.props.searchTerm) {
    const {
      FilterItems
    } = this.props;

    // filter items and optionally apply search if a search term exists
    const FilteredItems = this.searchFilterItems(this.filterFilterItems(FilterItems, this.options.filter), searchTerm);
    this.props.FilteredItems = FilteredItems;

    // render the items
    this.render(FilteredItems);
  }

  shuffle() {
    const {
      FilteredItems
    } = this.props;

    const ShuffledItems = this.shuffleFilterItems(FilteredItems);
    this.props.FilteredItems = ShuffledItems;

    this.render(ShuffledItems);
  }

  setOptions(newOptions) {
    this.options = merge(newOptions, this.options);
  }

  toggleFilter(toggledFilter) {
    let activeFilters = this.options.filter;

    if (activeFilters === 'all') {
      // if set to all then just set to new category
      activeFilters = toggledFilter;
    }
    else {
      if (Array.isArray(activeFilters)) {
        // if the toggledFilter is already included in the array
        if (stringInArray(activeFilters, toggledFilter)) {
          // then remove it
          activeFilters = activeFilters.filter(f => f !== toggledFilter);
          // and check if there is now only 1 item left in the array
          if (activeFilters.length === 1)
            // in that case flatten it
            activeFilters = activeFilters[0];
        }
        else {
          // if the item is not in the array then simply push it
          activeFilters.push(toggledFilter);
        }
      }
      else {
        // in case the filter is NOT set to "all"
        // check if the toggledFilter is the active one
        if (activeFilters === toggledFilter)
          // in this case revert to all
          activeFilters = "all";
        else
          // otherwise form an array with the two values
          activeFilters = [activeFilters, toggledFilter]
      }
    }

    // update active filter in Filterizr's options
    this.setOptions({
      filter: activeFilters,
    });

    this.filter(this.options.filter);
  }

  // Helper methods
  filterFilterItems(FilterItems, filters) {
    // Get filtered items
    const FilteredItems = (filters === "all") ?
      // in this case return all items
      FilterItems :
      // otherwise return filtered array
      FilterItems.filter(FilterItem => {
        const categories = FilterItem.getCategories();
        return Array.isArray(filters) ?
          intersection(categories, filters).length :
          stringInArray(categories, filters)
      });

    return FilteredItems;
  }

  sortFilterItems(FilterItems ,sortAttr = 'index', sortOrder = 'asc') {
    // Sort the FilterItems and reverse the array if order is descending
    let SortedItems = sortBy(FilterItems, (FilterItem) => {
      return (sortAttr !== 'index' && sortAttr !== 'sortData') ?
        // if the user has not used one of the two default sort attributes
        // then search for custom data attributes on the filter items to sort
        FilterItem.props.data[sortAttr] :
        // otherwise use the defaults
        FilterItem.props[sortAttr];
    });
    SortedItems = sortOrder === 'asc' ? SortedItems : reverse(SortedItems);

    return SortedItems;
  }

  searchFilterItems(FilterItems, searchTerm = this.props.searchTerm) {
    if (!searchTerm) return FilterItems; // exit case when no search is applied

    const SoughtItems =  FilterItems.filter(FilterItem => {
      const contents = FilterItem.getContentsLowercase();
      return ~contents.lastIndexOf(searchTerm);
    });

    return SoughtItems;
  }

  shuffleFilterItems(FilterItems) {
    let ShuffledItems = shuffle(FilterItems)
    // shuffle items until they are different from the initial FilteredItems
    while (FilterItems.length > 1 && isEqual(FilterItems, ShuffledItems)) {
      ShuffledItems = shuffle(FilterItems)
    }

    return ShuffledItems;
  }

  render(FilterItems) {
    // get items to be filtered out
    const FilteredOutItems = this.props.FilterItems.filter(FilterItem => {
      const categories = FilterItem.getCategories();
      const filters = this.options.filter;
      return Array.isArray(filters) ?
        !intersection(categories, filters).length :
        !stringInArray(categories, filters)
    })
    // filter out old items
    FilteredOutItems.forEach(FilterItem => {
      FilterItem.filterOut(this.options.filterOutCss);
    });

    // Determine target positions for items to be filtered in
    const PositionsArray = Positions(this.options.layout, this);

    // filter in new items
    FilterItems.forEach((FilterItem, index) => {
      FilterItem.filterIn(PositionsArray[index], this.options.filterInCss);
    });
  }

  setupEvents() {
    // set up a window resize event to fire refiltering
    $(window).on('resize', debounce((evt) => {
      // update dimensions of items based on new window size
      this.props.FilterContainer.updateWidth();
      this.props.FilterContainer.updateFilterItemsDimensions();
      // refilter the grid to assume new positions
      this.filter(this.options.filter);
    }, 250));
  }
}

export default Filterizr;
<|endoftext|>