<commit_before>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import { FormattedDate } from 'react-intl';
import Intl from '../utils/Intl';
import Box from './Box';
import Animate from './Animate';
import Meter from './Meter';
import Button from './Button';
import StatusIcon from './icons/Status';
import CloseIcon from './icons/base/Close';
import Props from '../utils/Props';
import CSSClassnames from '../utils/CSSClassnames';

const CLASS_ROOT = CSSClassnames.NOTIFICATION;
const BACKGROUND_COLOR_INDEX = CSSClassnames.BACKGROUND_COLOR_INDEX;

export default class Notification extends Component {

  render () {
    let classes = classnames(
      CLASS_ROOT,
      `${CLASS_ROOT}--status-${this.props.status.toLowerCase()}`,
      `${BACKGROUND_COLOR_INDEX}-${this.props.status.toLowerCase()}`,
      this.props.className,
      {
        [`${CLASS_ROOT}--${this.props.size}`]: this.props.size,
        [`${CLASS_ROOT}--disabled`]: !this.props.onClick
      }
    );

    let status;
    if (this.props.status) {
      status = (
        <StatusIcon className={`${CLASS_ROOT}__status`}
          value={this.props.status} size={this.props.size} />
      );
    }

    let state;
    if (this.props.state) {
      state = (
        <div className={`${CLASS_ROOT}__state`}>{this.props.state}

      );
    }

    let progress;
    if (this.props.percentComplete || 0 === this.props.percentComplete) {
      progress = (
        <Meter units="%"
          series={[{
            value: this.props.percentComplete,
            label: '',
            colorIndex: 'light-1'
          }]} />
      );
    }

    let timestamp;
    if (this.props.timestamp) {
      let timestampFormatted = this.props.timestamp.toString();
      if (this.context.intl) {
        timestampFormatted = (
          <FormattedDate value={this.props.timestamp}
            weekday="long"
            day="numeric"
            month="long"
            year="numeric"
            hour="numeric"
            minute="numeric"
            second="numeric" />
        );
      }

      timestamp = (
        <div className={`${CLASS_ROOT}__timestamp`}>
          {timestampFormatted}

      );
    }

    let closer;
    if (typeof this.props.closer === 'object') {
      closer = this.props.closer;
    } else if (this.props.onClose && this.props.closer) {
      closer = (
        <Button plain={true} onClick={this.props.onClose}
          icon={<CloseIcon className={`${CLASS_ROOT}__close`} />}
          a11yTitle={
            Intl.getMessage(this.context.intl, 'Close Notification')
          } />
      );
    }

    let boxProps = Props.pick(this.props, Object.keys(Box.propTypes));
    let fullBox =
      boxProps.hasOwnProperty('full') ? boxProps.full : 'horizontal';

    return (
      <Animate
        enter={{ animation: 'fade', duration: 1000 }}
        leave={{ animation: 'fade', duration: 1000 }}>
        <Box {...boxProps} className={classes} pad='small'
          direction="row" align="start" responsive={false}>
          <Box pad='small'>
            {status}
          </Box>
          <Box full={fullBox} pad='small'>
            <span className={`${CLASS_ROOT}__message`}>
              {this.props.message}

            {this.props.context}
            {timestamp}
            {state}
            {progress}
            {this.props.children}
          </Box>
          {closer}
        </Box>
      </Animate>
    );
  }
};

Notification.propTypes = {
  closer: PropTypes.oneOfType([
    PropTypes.node,
    PropTypes.bool
  ]),
  context: PropTypes.node,
  message: PropTypes.string.isRequired,
  onClose: PropTypes.func,
  percentComplete: PropTypes.number,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  state: PropTypes.string,
  status: PropTypes.string,
  timestamp: PropTypes.object, // Date
  ...Box.propTypes
};

Notification.contextTypes = {
  intl: PropTypes.object
};

Notification.defaultProps = {
  closer: false,
  flush: true,
  status: 'unknown',
  pad: 'medium'
};
<commit_msg>Notification: fixed problem with floating footer.<commit_after>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import { FormattedDate } from 'react-intl';
import Intl from '../utils/Intl';
import Box from './Box';
import Animate from './Animate';
import Meter from './Meter';
import Button from './Button';
import StatusIcon from './icons/Status';
import CloseIcon from './icons/base/Close';
import Props from '../utils/Props';
import CSSClassnames from '../utils/CSSClassnames';

const CLASS_ROOT = CSSClassnames.NOTIFICATION;
const BACKGROUND_COLOR_INDEX = CSSClassnames.BACKGROUND_COLOR_INDEX;

export default class Notification extends Component {

  render () {
    let classes = classnames(
      CLASS_ROOT,
      `${CLASS_ROOT}--status-${this.props.status.toLowerCase()}`,
      `${BACKGROUND_COLOR_INDEX}-${this.props.status.toLowerCase()}`,
      this.props.className,
      {
        [`${CLASS_ROOT}--${this.props.size}`]: this.props.size,
        [`${CLASS_ROOT}--disabled`]: !this.props.onClick
      }
    );

    let status;
    if (this.props.status) {
      status = (
        <StatusIcon className={`${CLASS_ROOT}__status`}
          value={this.props.status} size={this.props.size} />
      );
    }

    let state;
    if (this.props.state) {
      state = (
        <div className={`${CLASS_ROOT}__state`}>{this.props.state}

      );
    }

    let progress;
    if (this.props.percentComplete || 0 === this.props.percentComplete) {
      progress = (
        <Meter units="%"
          series={[{
            value: this.props.percentComplete,
            label: '',
            colorIndex: 'light-1'
          }]} />
      );
    }

    let timestamp;
    if (this.props.timestamp) {
      let timestampFormatted = this.props.timestamp.toString();
      if (this.context.intl) {
        timestampFormatted = (
          <FormattedDate value={this.props.timestamp}
            weekday="long"
            day="numeric"
            month="long"
            year="numeric"
            hour="numeric"
            minute="numeric"
            second="numeric" />
        );
      }

      timestamp = (
        <div className={`${CLASS_ROOT}__timestamp`}>
          {timestampFormatted}

      );
    }

    let closer;
    if (typeof this.props.closer === 'object') {
      closer = this.props.closer;
    } else if (this.props.onClose && this.props.closer) {
      closer = (
        <Button plain={true} onClick={this.props.onClose}
          icon={<CloseIcon className={`${CLASS_ROOT}__close`} />}
          a11yTitle={
            Intl.getMessage(this.context.intl, 'Close Notification')
          } />
      );
    }

    let boxProps = Props.pick(this.props, Object.keys(Box.propTypes));
    let fullBox =
      boxProps.hasOwnProperty('full') ? boxProps.full : 'horizontal';

    return (
      <Animate
        enter={{ animation: 'fade', duration: 1000 }}
        leave={{ animation: 'fade', duration: 1000 }}>
        <Box {...boxProps} className={classes} pad='small'
          direction="row" align="start" responsive={false}
          full={fullBox}>
          <Box pad='small'>
            {status}
          </Box>
          <Box flex={true} pad='small'>
            <span className={`${CLASS_ROOT}__message`}>
              {this.props.message}

            {this.props.context}
            {timestamp}
            {state}
            {progress}
            {this.props.children}
          </Box>
          {closer}
        </Box>
      </Animate>
    );
  }
};

Notification.propTypes = {
  closer: PropTypes.oneOfType([
    PropTypes.node,
    PropTypes.bool
  ]),
  context: PropTypes.node,
  message: PropTypes.string.isRequired,
  onClose: PropTypes.func,
  percentComplete: PropTypes.number,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  state: PropTypes.string,
  status: PropTypes.string,
  timestamp: PropTypes.object, // Date
  ...Box.propTypes
};

Notification.contextTypes = {
  intl: PropTypes.object
};

Notification.defaultProps = {
  closer: false,
  flush: true,
  status: 'unknown',
  pad: 'medium'
};
<|endoftext|>


<commit_before>/**
 * Created by huangling on 19/01/2017.
 */
import React, {Component} from 'react';
import Text from '../components/singleItem/Text';
import Image from '../components/singleItem/Image';
import BoardSquare from '../components/BoardSquare';
import {Button, Modal} from 'antd';
import * as ReactDOM from 'react-dom';

const Widgets = {
  Image,
  Text
};

let previewHtml = '';

export default class Page extends Component {
  componentWillMount() {
    this.state = {
      boxes: [{top: 20, left: 80, title: 'Drag me around'},
        {top: 180, left: 20, title: 'Drag me too'}
      ],
      newBox: null
    };
    this.onAddItem = this.onAddItem.bind(this);
    this.onPreview = this.onPreview.bind(this);
  }

  onAddItem(type) {
    const Comp = Widgets[type];
    this.setState({newBox: {top: 20, left: 80, title: <Comp />}});
  }

  onSave() {
    const board = ReactDOM.findDOMNode(this.board);
    previewHtml = board.innerHTML;
  }

  onPreview() {
    this.setState({preview: true});
  }

  renderPreview() {
    return (

        <Modal
          visible
          title="Preview"
          onOk={() => this.setState({preview: false})}
          footer={[
            <Button key="back" type="ghost" size="large" onClick={() => this.setState({preview: false})}>Return</Button>
          ]}>

        </Modal>

    );
  }

  render() {
    const headerItem = [
      {title: 'Text'}, {title: 'Image'}
    ];

    return (

          {
            headerItem.map((item, index) => (
              <Button className="item"
                      onClick={() => this.onAddItem(item.title)}>
                {item.title}
              </Button>)
            )
          }

            <BoardSquare ref={node => this.board = node} boxes={this.state.boxes} newBox={this.state.newBox}/>

            <Button onClick={() => this.onSave()}>Save</Button>
            <Button onClick={() => this.onPreview()}>Preview</Button>

          {this.state.preview && this.renderPreview()}

    );
  }
}

<commit_msg>[Save and Preview]  // TODO: open a new tab to preview<commit_after>/**
 * Created by huangling on 19/01/2017.
 */
import React, {Component} from 'react';
import Text from '../components/singleItem/Text';
import Image from '../components/singleItem/Image';
import BoardSquare from '../components/BoardSquare';
import {Button, Modal} from 'antd';
import * as ReactDOM from 'react-dom';

const Widgets = {
  Image,
  Text
};

let previewHtml = '';

export default class Page extends Component {
  componentWillMount() {
    this.state = {
      boxes: [{top: 20, left: 80, title: 'Drag me around'},
        {top: 180, left: 20, title: 'Drag me too'}
      ],
      newBox: null
    };
    this.onAddItem = this.onAddItem.bind(this);
    this.onPreview = this.onPreview.bind(this);
  }

  onAddItem(type) {
    const Comp = Widgets[type];
    this.setState({newBox: {top: 20, left: 80, title: <Comp />}});
  }

  onSave() {
    const board = ReactDOM.findDOMNode(this.board);
    previewHtml = board.innerHTML;
  }

  onPreview() {
    if (!previewHtml) {
      this.onSave();
    }

    this.setState({preview: true});
  }

  renderPreview() {
    return (

        <Modal
          visible
          title="Preview"
          onOk={() => this.setState({preview: false})}
          footer={[
            <Button key="back" type="ghost" size="large" onClick={() => this.setState({preview: false})}>Return</Button>
          ]}>

        </Modal>

    );
  }

  render() {
    const headerItem = [
      {title: 'Text'}, {title: 'Image'}
    ];

    return (

          {
            headerItem.map((item, index) => (
              <Button className="item"
                      onClick={() => this.onAddItem(item.title)}>
                {item.title}
              </Button>)
            )
          }

            <BoardSquare ref={node => this.board = node} boxes={this.state.boxes} newBox={this.state.newBox}/>

            <Button onClick={() => this.onSave()}>Save</Button>
            <Button onClick={() => this.onPreview()}>Preview</Button>

          {this.state.preview && this.renderPreview()}

    );
  }
}

<|endoftext|>


<commit_before>define('draw/click-bind', ['core/core', 'draw/core'], function(NIRS, draw) {
    $(function() {
        var DEFAULT_DRAW_TYPE = 'Rect',
            _drawType = DEFAULT_DRAW_TYPE, // type of Object for drawing
            tools__item = $('.tools__item'),
            canvas = new fabric.Canvas('canvas');

        NIRS.on('set-draw-type', function(drawType) {

            if (drawType === 'Move') {
                canvas.selection = true;
            } else {
                canvas.selection = false;
            }

            _drawType = drawType;
        });

        NIRS.getDrawType = function() {
            return _drawType;
        };

        tools__item.on('click', function(e) {
            var type = _.last(e.target.className.split('_')),

                // convert from css class names to fabric objects
                fabricType = {
                    'rectangle': 'Rect',
                    'ellipse': 'Ellipse',
                    'line': 'Line', // x1, x2, y1, y2
                    'triangle': 'Triangle',
                    'move': 'Move'
                }[type] || DEFAULT_DRAW_TYPE;

            tools__item.removeClass('active');
            $(e.target).addClass('active');

            // set draw type from class name
            NIRS.trigger('set-draw-type', fabricType);
        });

        bindDraw(canvas);

        // precent objects selection
        canvas.selection = false;

        setInterval(function() {
            canvas.renderAll();
        }, 15);
    });

    /**
     * Bind handlers to canvas events
     *
     * @param {fabric.Canvas} canvas
     */
    function bindDraw(canvas) {
        // params of canvas object
        var canvasOffset = $(canvas.upperCanvasEl).offset(),
            startCoord = {},
            // not needed draw if drawType === 'Move'
            drawType,
            drawingObj;

        canvas.on('mouse:down', function(options) {
            drawType = NIRS.getDrawType();

            if (drawType === 'Move') return;

            startCoord = {
                left: options.e.clientX - canvasOffset.left,
                top: options.e.clientY - canvasOffset.top,
            };

            drawingObj = draw.createDrawingObj(canvas, {
                type: drawType,
                left: startCoord.left,
                top: startCoord.top
            });
        });

        // TODO: _.throttle
        canvas.on('mouse:move', function(options) {
            if (drawType === 'Move') return;

            drawingObj && drawingObj.update({
                left: options.e.clientX - canvasOffset.left - startCoord.left,
                top: options.e.clientY - canvasOffset.top - startCoord.top
            });
        });

        canvas.on('mouse:up', function(options) {
            drawingObj = undefined;
        });
    }
});
<commit_msg>disable drawing for Cursor<commit_after>define('draw/click-bind', ['core/core', 'draw/core'], function(NIRS, draw) {
    $(function() {
        var DEFAULT_DRAW_TYPE = 'Rect',
            _drawType = DEFAULT_DRAW_TYPE, // type of Object for drawing
            tools__item = $('.tools__item'),
            canvas = new fabric.Canvas('canvas');

        NIRS.on('set-draw-type', function(drawType) {

            if (drawType === 'Move') {
                canvas.selection = true;
            } else {
                canvas.selection = false;
            }

            _drawType = drawType;
        });

        NIRS.getDrawType = function() {
            return _drawType;
        };

        tools__item.on('click', function(e) {
            var type = _.last(e.target.className.split('_')),

                // convert from css class names to fabric objects
                fabricType = {
                    'rectangle': 'Rect',
                    'ellipse': 'Ellipse',
                    'line': 'Line', // x1, x2, y1, y2
                    'triangle': 'Triangle',
                    'cursor': 'Cursor',
                    'move': 'Move'
                }[type] || DEFAULT_DRAW_TYPE;

            tools__item.removeClass('active');
            $(e.target).addClass('active');

            // set draw type from class name
            NIRS.trigger('set-draw-type', fabricType);
        });

        bindDraw(canvas);

        // precent objects selection
        canvas.selection = false;

        setInterval(function() {
            canvas.renderAll();
        }, 15);
    });

    /**
     * Bind handlers to canvas events
     *
     * @param {fabric.Canvas} canvas
     */
    function bindDraw(canvas) {
        // params of canvas object
        var canvasOffset = $(canvas.upperCanvasEl).offset(),
            startCoord = {},
            // not needed draw if drawType === 'Move'
            drawType,
            drawingObj;

        canvas.on('mouse:down', function(options) {
            drawType = NIRS.getDrawType();

            if (notNeedDrawing(drawType)) return;

            startCoord = {
                left: options.e.clientX - canvasOffset.left,
                top: options.e.clientY - canvasOffset.top,
            };

            drawingObj = draw.createDrawingObj(canvas, {
                type: drawType,
                left: startCoord.left,
                top: startCoord.top
            });
        });

        // TODO: _.throttle
        canvas.on('mouse:move', function(options) {
            if (notNeedDrawing(drawType)) return;

            drawingObj && drawingObj.update({
                left: options.e.clientX - canvasOffset.left - startCoord.left,
                top: options.e.clientY - canvasOffset.top - startCoord.top
            });
        });

        canvas.on('mouse:up', function(options) {
            drawingObj = undefined;
        });
    }

    /**
     * @param {String} drawType
     *
     * @return {Boolean} true if not needing drawing
     */
    function notNeedDrawing(drawType) {
        return ~['Move', 'Cursor'].indexOf(drawType);
    }
});
<|endoftext|>


<commit_before>import parse from 'try-json-parse'
import handleAuth from './auth'
import KiteError from './error'
import { Event } from '../constants'

export default function handleIncomingMessage(proto, message) {
  this.emit(Event.debug, `Receiving: ${message}`)

  if (typeof message === 'string') {
    message = parse(message)
  }

  const req = message

  if (req == null) {
    this.emit(Event.warning, new KiteError(`Invalid payload! (${message})`))
    return
  }

  if (!isKiteReq(req)) {
    this.emit(Event.debug, 'Handling a normal dnode message')
    return proto.handle(req)
  }

  const { links, method, callbacks } = req
  const { authentication: auth, responseCallback } = parseKiteReq(req)

  this.emit(Event.debug, 'Authenticating request')

  return handleAuth(this, method, auth, this.key)
    .then(token => {
      this.emit(Event.debug, 'Authentication passed')

      // set this as the current token for the duration of the synchronous
      // method call.
      // NOTE: this mechanism may be changed at some point in the future.
      this.currentToken = token

      try {
        proto.handle(req)
      } catch (err) {
        this.emit(Event.debug, 'Error processing request', err)
        proto.handle(
          getTraceReq({
            kite: this.getKiteInfo(),
            err,
            responseCallback,
            links,
            callbacks,
          })
        )
      }

      this.currentToken = null
      return null
    })
    .catch(err => {
      this.emit(Event.debug, 'Authentication failed', err)

      proto.handle(
        getTraceReq({
          kite: this.getKiteInfo(),
          err,
          responseCallback,
          links,
          callbacks,
        })
      )
    })
}

const isKiteReq = req =>
  req.arguments.length &&
  req.arguments[0] &&
  req.arguments[0].responseCallback &&
  req.arguments[0].withArgs

const getTraceReq = o => {
  return {
    method: 'kite.echo',
    arguments: [
      {
        withArgs: [{ error: o.err }],
        responseCallback: o.responseCallback,
        kite: o.kite,
      },
    ],
    links: o.links,
    callbacks: o.callbacks,
  }
}

const parseKiteReq = req => req.arguments[0]

const isResponseCallback = callback =>
  Array.isArray(callback) && callback.join('.') === '0.responseCallback'

const mungeCallbacks = (callbacks, n) => {
  // FIXME: this is an ugly hack; there must be a better way to implement it:

  for (let key of Object.keys(callbacks || {})) {
    const callback = callbacks[key]
    if (isResponseCallback(callback)) {
      callbacks[key] = [n]
    }
    if (callback[1] === 'withArgs') {
      // since we're rewriting the protocol for the withArgs case,
      // we need to remove everything up to withArgs
      callbacks[key] = callback.slice(2)
    }
  }

  return callbacks
}

const toProtoReq = ({
  method,
  withArgs,
  responseCallback,
  links,
  callbacks,
}) => {
  if (!Array.isArray(withArgs)) {
    withArgs = [withArgs]
  }

  mungeCallbacks(callbacks, withArgs.length)

  return {
    method,
    arguments: [...Array.from(withArgs), responseCallback],
    links,
    callbacks,
  }
}
<commit_msg>kite/handle: remove dirty hacks to rewrite protocol<commit_after>import parse from 'try-json-parse'
import handleAuth from './auth'
import KiteError from './error'
import { Event } from '../constants'

export default function handleIncomingMessage(proto, message) {
  this.emit(Event.debug, `Receiving: ${message}`)

  if (typeof message === 'string') {
    message = parse(message)
  }

  const req = message

  if (req == null) {
    this.emit(Event.warning, new KiteError(`Invalid payload! (${message})`))
    return
  }

  if (!isKiteReq(req)) {
    this.emit(Event.debug, 'Handling a normal dnode message')
    return proto.handle(req)
  }

  const { links, method, callbacks } = req
  const { authentication: auth, responseCallback } = parseKiteReq(req)

  this.emit(Event.debug, 'Authenticating request')

  return handleAuth(this, method, auth, this.key)
    .then(token => {
      this.emit(Event.debug, 'Authentication passed')

      // set this as the current token for the duration of the synchronous
      // method call.
      // NOTE: this mechanism may be changed at some point in the future.
      this.currentToken = token

      try {
        proto.handle(req)
      } catch (err) {
        this.emit(Event.debug, 'Error processing request', err)
        proto.handle(
          getTraceReq({
            kite: this.getKiteInfo(),
            err,
            responseCallback,
            links,
            callbacks,
          })
        )
      }

      this.currentToken = null
      return null
    })
    .catch(err => {
      this.emit(Event.debug, 'Authentication failed', err)

      proto.handle(
        getTraceReq({
          kite: this.getKiteInfo(),
          err,
          responseCallback,
          links,
          callbacks,
        })
      )
    })
}

const isKiteReq = req =>
  req.arguments.length &&
  req.arguments[0] &&
  req.arguments[0].responseCallback &&
  req.arguments[0].withArgs

const getTraceReq = o => {
  return {
    method: 'kite.echo',
    arguments: [
      {
        withArgs: [{ error: o.err }],
        responseCallback: o.responseCallback,
        kite: o.kite,
      },
    ],
    links: o.links,
    callbacks: o.callbacks,
  }
}

const parseKiteReq = req => req.arguments[0]
<|endoftext|>


<commit_before>if(!window.fhq) window.fhq = {};
if(!window.fhq.ws) window.fhq.ws = {};

fhq.ws.protocol = window.location.protocol == "https:" ? "wss:" : "ws:";
fhq.ws.port = window.location.protocol == "https:" ? "4613" : "1234";
fhq.ws.hostname = window.location.hostname;
<commit_msg>Changed defaults port<commit_after>if(!window.fhq) window.fhq = {};
if(!window.fhq.ws) window.fhq.ws = {};

fhq.ws.protocol = window.location.protocol == "https:" ? "wss:" : "ws:";
// fhq.ws.port = window.location.protocol == "https:" ? "4613" : "1234";
fhq.ws.port = window.location.protocol == "https:" ? "355" : "350";
fhq.ws.hostname = window.location.hostname;
<|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const path = require('path')
const marked = require('marked')
const highlight = require('highlight.js')
const colors = require('colors/safe')

/** marked settings */
const renderer = new marked.Renderer()
renderer.heading = (text, level) => {
  if (level === 1) {
    return `<h${level}>${text}</h${level}>`
  }
  const id = text.replace(/\s+/g, '_')
  return `<h${level} id="${id}">${text}</h${level}>`
}
renderer.image = (href, title, text) => {
  if (title === null) {
    return `<img src="${href}" alt="${text}">`
  }
  const sizes = title.split('x')
  const sizeAttr = sizes.map((size, index) => {
    if (/^[0-9]+$/.test(size) === false) {
      return ''
    }
    return index === 0
      ? `width: ${size}px`
      : `height: ${size}px`
  }).join(' ')
  return `<img src="${href}" alt="${text}" style="${sizeAttr}">`
}

marked.setOptions({
  renderer: renderer,
  highlight (code) {
    return highlight.highlightAuto(code).value
  },
})

/** constants */
const ARGV = Object.freeze({
  TARGET: {
    NAME: 'target',
    COMMAND: '-t',
    CORRECT_VALUES: ['pages', 'slides', 'posts'],
  },
  FILE: {
    NAME: 'file',
    COMMAND: '-f',
  },
})

const PATH_INFO = Object.freeze({
  DIST: `${__dirname}/../static/contents`,
})

/** functions */
const extractArgv = (argv, command) => {
  let isExtract = false
  return argv.filter((value) => {
    if (/^-/.test(value) === true) {
      isExtract = value === command
      return false
    }
    return isExtract
  })
}

const verifyValues = (values, argObject) => {
  for (let value of values) {
    if (argObject.CORRECT_VALUES.includes(value) === false) {
      // eslint-disable-next-line
      console.error(colors.red(`Error: Invalid value '${value}' in ${argObject.NAME}[${argObject.COMMAND}].`))
      process.exit()
    }
  }
}

const createTargets = (argTargets) => {
  let targets = []
  if (argTargets.length === 0) {
    targets = Array.from(ARGV.TARGET.CORRECT_VALUES)
  } else {
    targets = Array.from(argTargets)
  }
  return targets
}

const getFolderFileNames = (folderName) => {
  try {
    return fs.readdirSync(folderName)
  } catch (err) {
    // eslint-disable-next-line
    console.error(colors.red(err))
    process.exit()
  }
}

const getTargetFileNames = (targets) => {
  const fileNames = {}
  for (let target of targets) {
    fileNames[target] = getFolderFileNames(path.join(__dirname, target))
  }
  return fileNames
}

const getConvertFilePaths = (targetFileNames, argFileNames) => {
  let convertFileNames = []
  const funcFilter = (() => {
    if (argFileNames.length === 0) {
      return () => {
        return true
      }
    }
    return (fileName) => {
      return argFileNames.includes(fileName)
    }
  })()

  Object.keys(targetFileNames).forEach((folderName) => {
    const fileNames = targetFileNames[folderName]
    const tmpFileNames = fileNames.filter(funcFilter)
      .map((fileName) => `${folderName}/${fileName}`)
    convertFileNames = convertFileNames.concat(tmpFileNames)
  })
  return convertFileNames
}

const verifyFilePaths = (fileNames) => {
  if (fileNames.length === 0) {
    // eslint-disable-next-line
    console.error(colors.red('Error: No file to convert.'))
    process.exit()
  }
}

const changeExtensionMdToJson = (fileName) => {
  return fileName.replace(/\.md$/, '.json')
}

const extractTitle = (html) => {
  return html.match(/
(.*?)<\/h1>/)
}

const extractDescription = (html) => {
  return html.match(/@@\n?(.*?)\n?@@/)
}

const extractDate = (html) => {
  return html.match(/==([0-9\\-]+),?([0-9\\-]+)?==/)
}

const appendCodeHljsClass = (html) => {
  return html.replace(/
/g, '
')
}

const removeEmptyPTag = (html) => {
  return html.replace(/
\s*<\/p>/, '')
}

const removeBeforeAndAfterNewLine = (html) => {
  return html.replace(/^\n*|\n*$/g, '')
}

const buildJson = (html) => {
  const [removeHtmlTitle, title] = extractTitle(html) || ['', '']
  const [removeHtmlDesciption, description] = extractDescription(html) || ['', '']
  const [removeHtmlDate, createdAt, updatedAt] = extractDate(html) || ['', '', '']
  html = html.replace(removeHtmlTitle, '')
          .replace(removeHtmlDesciption, '')
          .replace(removeHtmlDate, '')
  html = appendCodeHljsClass(html)
  html = removeEmptyPTag(html)
  html = removeBeforeAndAfterNewLine(html)

  return {
    title,
    description,
    body: html,
    createdAt,
    updatedAt,
  }
}

/** main process */
const argv = process.argv.filter((value, index) => index > 1)

// Targets
const argTargets = extractArgv(argv, ARGV.TARGET.COMMAND)
verifyValues(argTargets, ARGV.TARGET)
const targets = createTargets(argTargets)
// eslint-disable-next-line
console.info(colors.cyan(`Target Folders: ${targets.join(', ')}`))

// File Names
const targetFileNames = getTargetFileNames(targets)
const argFileNames = extractArgv(argv, ARGV.FILE.COMMAND)
const filePaths = getConvertFilePaths(targetFileNames, argFileNames)
verifyFilePaths(filePaths)
// eslint-disable-next-line
console.info(colors.cyan(`Files to convert: ${filePaths.join(', ')}`))

// Convert
for (let filePath of filePaths) {
  try {
    let fileData = fs.readFileSync(path.join(__dirname, filePath)).toString()
    let html = marked(fileData)
    let json = JSON.stringify(buildJson(html))
    let saveFilePath = changeExtensionMdToJson(filePath)
    fs.writeFileSync(path.join(PATH_INFO.DIST, saveFilePath), json)
  } catch (error) {
    // eslint-disable-next-line
    console.error(colors.red(error))
    process.exit()
  }
}

console.info(colors.green('Completed.'))
<commit_msg>imgタグにdraggable属性追加<commit_after>'use strict'

const fs = require('fs')
const path = require('path')
const marked = require('marked')
const highlight = require('highlight.js')
const colors = require('colors/safe')

/** marked settings */
const renderer = new marked.Renderer()
renderer.heading = (text, level) => {
  if (level === 1) {
    return `<h${level}>${text}</h${level}>`
  }
  const id = text.replace(/\s+/g, '_')
  return `<h${level} id="${id}">${text}</h${level}>`
}
renderer.image = (href, title, text) => {
  if (title === null) {
    return `<img src="${href}" alt="${text}" draggable="false">`
  }
  const sizes = title.split('x')
  const sizeAttr = sizes.map((size, index) => {
    if (/^[0-9]+$/.test(size) === false) {
      return ''
    }
    return index === 0
      ? `width: ${size}px`
      : `height: ${size}px`
  }).join(' ')
  return `<img src="${href}" alt="${text}" style="${sizeAttr}" draggable="false">`
}

marked.setOptions({
  renderer: renderer,
  highlight (code) {
    return highlight.highlightAuto(code).value
  },
})

/** constants */
const ARGV = Object.freeze({
  TARGET: {
    NAME: 'target',
    COMMAND: '-t',
    CORRECT_VALUES: ['pages', 'slides', 'posts'],
  },
  FILE: {
    NAME: 'file',
    COMMAND: '-f',
  },
})

const PATH_INFO = Object.freeze({
  DIST: `${__dirname}/../static/contents`,
})

/** functions */
const extractArgv = (argv, command) => {
  let isExtract = false
  return argv.filter((value) => {
    if (/^-/.test(value) === true) {
      isExtract = value === command
      return false
    }
    return isExtract
  })
}

const verifyValues = (values, argObject) => {
  for (let value of values) {
    if (argObject.CORRECT_VALUES.includes(value) === false) {
      // eslint-disable-next-line
      console.error(colors.red(`Error: Invalid value '${value}' in ${argObject.NAME}[${argObject.COMMAND}].`))
      process.exit()
    }
  }
}

const createTargets = (argTargets) => {
  let targets = []
  if (argTargets.length === 0) {
    targets = Array.from(ARGV.TARGET.CORRECT_VALUES)
  } else {
    targets = Array.from(argTargets)
  }
  return targets
}

const getFolderFileNames = (folderName) => {
  try {
    return fs.readdirSync(folderName)
  } catch (err) {
    // eslint-disable-next-line
    console.error(colors.red(err))
    process.exit()
  }
}

const getTargetFileNames = (targets) => {
  const fileNames = {}
  for (let target of targets) {
    fileNames[target] = getFolderFileNames(path.join(__dirname, target))
  }
  return fileNames
}

const getConvertFilePaths = (targetFileNames, argFileNames) => {
  let convertFileNames = []
  const funcFilter = (() => {
    if (argFileNames.length === 0) {
      return () => {
        return true
      }
    }
    return (fileName) => {
      return argFileNames.includes(fileName)
    }
  })()

  Object.keys(targetFileNames).forEach((folderName) => {
    const fileNames = targetFileNames[folderName]
    const tmpFileNames = fileNames.filter(funcFilter)
      .map((fileName) => `${folderName}/${fileName}`)
    convertFileNames = convertFileNames.concat(tmpFileNames)
  })
  return convertFileNames
}

const verifyFilePaths = (fileNames) => {
  if (fileNames.length === 0) {
    // eslint-disable-next-line
    console.error(colors.red('Error: No file to convert.'))
    process.exit()
  }
}

const changeExtensionMdToJson = (fileName) => {
  return fileName.replace(/\.md$/, '.json')
}

const extractTitle = (html) => {
  return html.match(/
(.*?)<\/h1>/)
}

const extractDescription = (html) => {
  return html.match(/@@\n?(.*?)\n?@@/)
}

const extractDate = (html) => {
  return html.match(/==([0-9\\-]+),?([0-9\\-]+)?==/)
}

const appendCodeHljsClass = (html) => {
  return html.replace(/
/g, '
')
}

const removeEmptyPTag = (html) => {
  return html.replace(/
\s*<\/p>/, '')
}

const removeBeforeAndAfterNewLine = (html) => {
  return html.replace(/^\n*|\n*$/g, '')
}

const buildJson = (html) => {
  const [removeHtmlTitle, title] = extractTitle(html) || ['', '']
  const [removeHtmlDesciption, description] = extractDescription(html) || ['', '']
  const [removeHtmlDate, createdAt, updatedAt] = extractDate(html) || ['', '', '']
  html = html.replace(removeHtmlTitle, '')
          .replace(removeHtmlDesciption, '')
          .replace(removeHtmlDate, '')
  html = appendCodeHljsClass(html)
  html = removeEmptyPTag(html)
  html = removeBeforeAndAfterNewLine(html)

  return {
    title,
    description,
    body: html,
    createdAt,
    updatedAt,
  }
}

/** main process */
const argv = process.argv.filter((value, index) => index > 1)

// Targets
const argTargets = extractArgv(argv, ARGV.TARGET.COMMAND)
verifyValues(argTargets, ARGV.TARGET)
const targets = createTargets(argTargets)
// eslint-disable-next-line
console.info(colors.cyan(`Target Folders: ${targets.join(', ')}`))

// File Names
const targetFileNames = getTargetFileNames(targets)
const argFileNames = extractArgv(argv, ARGV.FILE.COMMAND)
const filePaths = getConvertFilePaths(targetFileNames, argFileNames)
verifyFilePaths(filePaths)
// eslint-disable-next-line
console.info(colors.cyan(`Files to convert: ${filePaths.join(', ')}`))

// Convert
for (let filePath of filePaths) {
  try {
    let fileData = fs.readFileSync(path.join(__dirname, filePath)).toString()
    let html = marked(fileData)
    let json = JSON.stringify(buildJson(html))
    let saveFilePath = changeExtensionMdToJson(filePath)
    fs.writeFileSync(path.join(PATH_INFO.DIST, saveFilePath), json)
  } catch (error) {
    // eslint-disable-next-line
    console.error(colors.red(error))
    process.exit()
  }
}

console.info(colors.green('Completed.'))
<|endoftext|>


<commit_before>

import React from 'react';

class SearchForm extends React.Component{

    render(){
        return
SearchForm comp

    }
};

export {SearchForm};<commit_msg>write search form<commit_after>

import React from 'react';

class SearchForm extends React.Component{
    constructor(props){
        super(props);
        this.state = {searchString: ''};

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(e){
        this.setState({searchString: e.target.value});
    }

    handleSubmit(e){
        console.log(this.state.searchString);
        this.setState({searchString: ''});
        e.preventDefault();
    }

    render(){
        return (

                <form onSubmit={this.handleSubmit}>
                    <input
                        type="text"
                        name="searchInput"
                        placeholder="Input name here"
                        onChange={this.handleChange}
                    />
                    <input type="submit" name="submitBtn" value="Search"/>
                </form>

        );
    }
};

export {SearchForm};<|endoftext|>


<commit_before>import invariant from "@octetstream/invariant"
import isObject from "lodash/isObject"

import deprecate from "lib/helper/decorator/deprecate"

class ObjectIterator {
  constructor(iterable) {
    invariant(
      iterable && isObject(iterable) === false, TypeError,

      "Iterable must be an object."
    )

    this.__iterable = iterable

    // I'm using this method because of fucking semicolon -_-
    Array.from([Symbol.iterator, "keys", "values", "entries"])
      .forEach(name => this[name] = this[name].bind(this))
  }

  keys() {
    if (!this.__iterable) {
      return []
    }

    return Object.keys(this.__iterable)
  }

  * values() {
    for (const [, value] of this.entries()) {
      yield value
    }
  }

  * entries() {
    for (const key of this.keys()) {
      const value = this.__iterable[key]

      yield [key, value]
    }
  }

  [Symbol.iterator]() {
    return this.values()
  }
}

const objectIterator = (iterable, entries = false) => {
  if (entries) {
    console.warn(
      "The \"entries\" flag is deprecated. "
        + "Use objectIterator(iterable).entries() instead."
    )

    return new ObjectIterator(iterable).entries()
  }

  return new ObjectIterator(iterable)
}

const keys = iterable => new ObjectIterator(iterable).keys()

const values = iterable => new ObjectIterator(iterable).values()

const entries = iterable => new ObjectIterator(iterable).entries()

objectIterator.keys = keys |> deprecate(
  "Use objectIterator(iterable).keys() instead."
)

objectIterator.values = values |> deprecate(
  "Use objectIterator(iterable).values() instead."
)

objectIterator.entries = entries |> deprecate(
  "Use objectIterator(iterable).entries() instead"
)

export default objectIterator
export {keys, values, entries}
<commit_msg>Rewrite object iterator.<commit_after>import invariant from "@octetstream/invariant"
import isObject from "lodash/isObject"

import proxy from "lib/helper/decorator/proxy"
import apply from "lib/helper/proxy/selfInvokingClass"

@proxy({apply})
class ObjectIterator {
  static keys(iterable) {
    return new ObjectIterator(iterable).keys()
  }

  static values(iterable) {
    return new ObjectIterator(iterable).values()
  }

  static entries(iterable) {
    return new ObjectIterator(iterable).entries()
  }

  constructor(iterable) {
    if (iterable && !isObject(iterable)) {
      throw new TypeError("Iterable must be an object.")
    }

    this.__iterable = iterable
  }

  keys() {
    if (!this.__iterable) {
      return []
    }

    return Object.keys(this.__iterable)
  }

  * values() {
    for (const [, value] of this.entries()) {
      yield value
    }
  }

  * entries() {
    for (const key of this.keys()) {
      const value = this.__iterable[key]

      yield [key, value]
    }
  }

  [Symbol.iterator]() {
    return this.values()
  }
}

export default ObjectIterator
export const keys = ObjectIterator.keys
export const values = ObjectIterator.values
export const entries = ObjectIterator.entries
<|endoftext|>


<commit_before>var maintenanceCost = function maintenanceCost(room) {
  var hitsLostPerTick = 0.0;
  const structures = room.find(FIND_STRUCTURES);
  for (var i = structures.length - 1; i >= 0; i--) {
    const str = structures[i];
    switch(str.structureType) {
      case STRUCTURE_ROAD:
        if (str.hits > 5000) {
          // assume swampy
          hitsLostPerTick = hitsLostPerTick + 5; //(500 / 1000)
        } else {
          hitsLostPerTick = hitsLostPerTick + 1; //(100 / 1000)
        }
        break;
      case STRUCTURE_RAMPART :
        hitsLostPerTick = hitsLostPerTick + 30; //(300 / 100)
        break;
      case STRUCTURE_CONTAINER:
        hitsLostPerTick = hitsLostPerTick + 100; //(5000 / 500)
        break;
      // case STRUCTURE_WALL:
      // case STRUCTURE_TOWER:
      // case STRUCTURE_TERMINAL:
      // case STRUCTURE_POWER_SPAWN:
      // case STRUCTURE_POWER_BANK:
      // case STRUCTURE_OBSERVER:
      // case STRUCTURE_NUKER:
      // case STRUCTURE_LAB:
      // case STRUCTURE_STORAGE :
      // case STRUCTURE_LINK :
      // case STRUCTURE_EXTRACTOR:
      // case STRUCTURE_CONTROLLER :
      // case STRUCTURE_PORTAL :
      // case STRUCTURE_KEEPER_LAIR :
      // case STRUCTURE_SPAWN:
      // case STRUCTURE_EXTENSION:
      default:
        break;
    }
  }
  return hitsLostPerTick /  200; // 20 hits per unit energy * 10 to compensate for JS floating point ugly
};

var buildCosts = function buildCosts(room) {
  var hits = 0;
  var sites = room.find(FIND_CONSTRUCTION_SITES);
  for (var i = sites.length - 1; i >= 0; i--) {
    let site = sites[i];
    hits += site.progressTotal - site.progress;
  }
  if (hits > 10000) {
    return 50;
  } else {
    return hits / 200;
  }
};

var roleCosts = function roleCosts(room) {
  var roles = {};
  var energyPerTick = 0;
  room.find(FIND_MY_CREEPS, {filter:(creep) => {
    if (!roles[creep.memory.role]) {
      roles[creep.memory.role] = 0;
    }
    roles[creep.memory.role] += creep.getActiveBodyparts(WORK);
    }
  });
  for (var role in roles) {
    if (roles.hasOwnProperty(role)) {
      switch(role) {
        case 'builder':
          energyPerTick += 5 * roles[role];
          break;
        case 'upgrader':
          energyPerTick += roles[role];
          break;
        case 'containerUpgrader':
          energyPerTick += roles[role];
          break;
      }
    }
  }
  return energyPerTick;
};

var maxIncome = function maxIncome(room) {
  return room.find(FIND_SOURCES).length * 10;
};

var incomePerTick = function incomePerTick(room) {
    var minerParts = 0;
    var miners = room.find(FIND_MY_CREEPS, {filter:(creep) => {
        if(creep.memory.role == 'harvester' || creep.memory.role == 'containerHarvester') {
            minerParts += creep.getActiveBodyparts(WORK);
            return true;
        } else {
            return false;
        }
    }
    });
    if (minerParts >= 10) {
        minerParts = 10;
    }
    return minerParts * 2;
};

// var creepCost = function creepCost(body) {
//   var cost = 0;
//   var life = 1500;
//   for (var i = body.length - 1; i >= 0; i--) {
//     switch(body[i]) {
//       case WORK:
//         cost += 100;
//         break;
//       case MOVE:
//         cost += 50;
//         break;
//       case CARRY:
//         cost += 50;
//         break;
//       case ATTACK:
//         cost += 80;
//         break;
//       case RANGED_ATTACK:
//         cost += 150;
//         break;
//       case HEAL:
//         cost += 250;
//         break;
//       case CLAIM:
//         cost += 600;
//         life = 500;
//         break;
//       case TOUGH:
//         cost += 10;
//         break;
//       default:
//       break;
//     }
//   }
//   return cost / life;
// };

// var creepsCost = function creepsCost(stageController) {
//   var creepsCostPerTick = 0;
//   for (var role in stageController.creeps) {
//     if (stageController.hasOwnProperty(role)) {
//       const creep = stageController.creeps[role].body;
//       creepsCostPerTick = creepsCostPerTick + creepCost(creep);
//     }
//   }
//   return creepsCostPerTick;
// };

var simpleRoomMetric = function simpleRoomMetric(room) {
  const spawn = room.find(FIND_MY_SPAWNS)[0];
  const controller = room.controller;
  const furthestSource = room.find(FIND_SOURCES).sort((a, b) => {
    var bLen = room.findPath(b.pos, controller.pos).length;
    var aLen = room.findPath(a.pos, controller.pos).length;
    return bLen - aLen;
  })[0];
  const furthestDistance = [room.findPath(spawn.pos, furthestSource.pos).length, room.findPath(controller.pos, furthestSource.pos)].sort((a, b) => b - a)[0];
  return furthestDistance;
};
var simpleRoomCost = function simpleRoomCost(room) {
  // const metric = simpleRoomMetric(room);
  // console.log(room.name + ' has a simpleMetric of ' + metric);
//  const creeps = creepsCost(require('controller.stage').stageModule(room.stage));
  // console.log('cost of creeps ' + creeps);
  const buildings =  maintenanceCost(room);
  // console.log('cost of existing structures ' + buildings);
  // const construction = buildCosts(room);
  // console.log('cost of new structures ' + construction);
  const costsPerTick = buildings;
  // console.log(room.name + ' costs ' + costsPerTick + ' per tick.');
  return costsPerTick;
};

var simpleRoomEfficiency = function simpleRoomEfficiency(room) {};

var analyze = function analyze(room) {
  return {
    next: Game.time + 1500,
    costsPerTick: simpleRoomCost(room),
    productionPerTick: roleCosts(room),
    incomePerTick: incomePerTick(room),
    sourcesContained: containerCheck(room)
  };
};

var containerCheck = function(room) {
	// const containers = room.find(FIND_STRUCTURES, {filter: (str) => str.type == STRUCTURE_CONTAINER});
	const sources = room.find(FIND_SOURCES);
	const contained_sources = sources.filter((source) => source.pos.findInRange(FIND_STRUCTURES, 2, {filter: (str) => str.type == STRUCTURE_CONTAINER}));
	return sources.length == contained_sources.length;

}

module.exports = {
  'analyze': analyze,
  maintenanceCost: maintenanceCost,
//  creepsCost: creepsCost,
  buildCosts: buildCosts,
  // creepCost: creepCost,
  maxIncome: maxIncome,
  simpleRoomMetric: simpleRoomMetric,
  simpleRoomCost: simpleRoomCost
};<commit_msg>correct check for containers.<commit_after>var maintenanceCost = function maintenanceCost(room) {
  var hitsLostPerTick = 0.0;
  const structures = room.find(FIND_STRUCTURES);
  for (var i = structures.length - 1; i >= 0; i--) {
    const str = structures[i];
    switch(str.structureType) {
      case STRUCTURE_ROAD:
        if (str.hits > 5000) {
          // assume swampy
          hitsLostPerTick = hitsLostPerTick + 5; //(500 / 1000)
        } else {
          hitsLostPerTick = hitsLostPerTick + 1; //(100 / 1000)
        }
        break;
      case STRUCTURE_RAMPART :
        hitsLostPerTick = hitsLostPerTick + 30; //(300 / 100)
        break;
      case STRUCTURE_CONTAINER:
        hitsLostPerTick = hitsLostPerTick + 100; //(5000 / 500)
        break;
      // case STRUCTURE_WALL:
      // case STRUCTURE_TOWER:
      // case STRUCTURE_TERMINAL:
      // case STRUCTURE_POWER_SPAWN:
      // case STRUCTURE_POWER_BANK:
      // case STRUCTURE_OBSERVER:
      // case STRUCTURE_NUKER:
      // case STRUCTURE_LAB:
      // case STRUCTURE_STORAGE :
      // case STRUCTURE_LINK :
      // case STRUCTURE_EXTRACTOR:
      // case STRUCTURE_CONTROLLER :
      // case STRUCTURE_PORTAL :
      // case STRUCTURE_KEEPER_LAIR :
      // case STRUCTURE_SPAWN:
      // case STRUCTURE_EXTENSION:
      default:
        break;
    }
  }
  return hitsLostPerTick /  200; // 20 hits per unit energy * 10 to compensate for JS floating point ugly
};

var buildCosts = function buildCosts(room) {
  var hits = 0;
  var sites = room.find(FIND_CONSTRUCTION_SITES);
  for (var i = sites.length - 1; i >= 0; i--) {
    let site = sites[i];
    hits += site.progressTotal - site.progress;
  }
  if (hits > 10000) {
    return 50;
  } else {
    return hits / 200;
  }
};

var roleCosts = function roleCosts(room) {
  var roles = {};
  var energyPerTick = 0;
  room.find(FIND_MY_CREEPS, {filter:(creep) => {
    if (!roles[creep.memory.role]) {
      roles[creep.memory.role] = 0;
    }
    roles[creep.memory.role] += creep.getActiveBodyparts(WORK);
    }
  });
  for (var role in roles) {
    if (roles.hasOwnProperty(role)) {
      switch(role) {
        case 'builder':
          energyPerTick += 5 * roles[role];
          break;
        case 'upgrader':
          energyPerTick += roles[role];
          break;
        case 'containerUpgrader':
          energyPerTick += roles[role];
          break;
      }
    }
  }
  return energyPerTick;
};

var maxIncome = function maxIncome(room) {
  return room.find(FIND_SOURCES).length * 10;
};

var incomePerTick = function incomePerTick(room) {
    var minerParts = 0;
    var miners = room.find(FIND_MY_CREEPS, {filter:(creep) => {
        if(creep.memory.role == 'harvester' || creep.memory.role == 'containerHarvester') {
            minerParts += creep.getActiveBodyparts(WORK);
            return true;
        } else {
            return false;
        }
    }
    });
    if (minerParts >= 10) {
        minerParts = 10;
    }
    return minerParts * 2;
};

// var creepCost = function creepCost(body) {
//   var cost = 0;
//   var life = 1500;
//   for (var i = body.length - 1; i >= 0; i--) {
//     switch(body[i]) {
//       case WORK:
//         cost += 100;
//         break;
//       case MOVE:
//         cost += 50;
//         break;
//       case CARRY:
//         cost += 50;
//         break;
//       case ATTACK:
//         cost += 80;
//         break;
//       case RANGED_ATTACK:
//         cost += 150;
//         break;
//       case HEAL:
//         cost += 250;
//         break;
//       case CLAIM:
//         cost += 600;
//         life = 500;
//         break;
//       case TOUGH:
//         cost += 10;
//         break;
//       default:
//       break;
//     }
//   }
//   return cost / life;
// };

// var creepsCost = function creepsCost(stageController) {
//   var creepsCostPerTick = 0;
//   for (var role in stageController.creeps) {
//     if (stageController.hasOwnProperty(role)) {
//       const creep = stageController.creeps[role].body;
//       creepsCostPerTick = creepsCostPerTick + creepCost(creep);
//     }
//   }
//   return creepsCostPerTick;
// };

var simpleRoomMetric = function simpleRoomMetric(room) {
  const spawn = room.find(FIND_MY_SPAWNS)[0];
  const controller = room.controller;
  const furthestSource = room.find(FIND_SOURCES).sort((a, b) => {
    var bLen = room.findPath(b.pos, controller.pos).length;
    var aLen = room.findPath(a.pos, controller.pos).length;
    return bLen - aLen;
  })[0];
  const furthestDistance = [room.findPath(spawn.pos, furthestSource.pos).length, room.findPath(controller.pos, furthestSource.pos)].sort((a, b) => b - a)[0];
  return furthestDistance;
};
var simpleRoomCost = function simpleRoomCost(room) {
  // const metric = simpleRoomMetric(room);
  // console.log(room.name + ' has a simpleMetric of ' + metric);
//  const creeps = creepsCost(require('controller.stage').stageModule(room.stage));
  // console.log('cost of creeps ' + creeps);
  const buildings =  maintenanceCost(room);
  // console.log('cost of existing structures ' + buildings);
  // const construction = buildCosts(room);
  // console.log('cost of new structures ' + construction);
  const costsPerTick = buildings;
  // console.log(room.name + ' costs ' + costsPerTick + ' per tick.');
  return costsPerTick;
};

var simpleRoomEfficiency = function simpleRoomEfficiency(room) {};

var analyze = function analyze(room) {
  return {
    next: Game.time + 1500,
    costsPerTick: simpleRoomCost(room),
    productionPerTick: roleCosts(room),
    incomePerTick: incomePerTick(room),
    sourcesContained: containerCheck(room)
  };
};

var containerCheck = function(room) {
	// const containers = room.find(FIND_STRUCTURES, {filter: (str) => str.type == STRUCTURE_CONTAINER});
	const sources = room.find(FIND_SOURCES);
	const contained_sources = sources.filter((source) => source.pos.findInRange(FIND_STRUCTURES, 2, {filter: (str) => str.type == STRUCTURE_CONTAINER}).length != 0);
	return sources.length == contained_sources.length;

}

module.exports = {
  'analyze': analyze,
  maintenanceCost: maintenanceCost,
//  creepsCost: creepsCost,
  buildCosts: buildCosts,
  // creepCost: creepCost,
  maxIncome: maxIncome,
  simpleRoomMetric: simpleRoomMetric,
  simpleRoomCost: simpleRoomCost
};<|endoftext|>


<commit_before>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import React from 'react';
import * as d3Selection from 'd3-selection';

import AbstractSeries from './abstract-series';
import {getDOMNode} from '../../utils/react-utils';

class BarSeries extends AbstractSeries {

  static get propTypes() {
    return {
      ... AbstractSeries.propTypes,
      linePosAttr: React.PropTypes.string,
      valuePosAttr: React.PropTypes.string,
      lineSizeAttr: React.PropTypes.string,
      valueSizeAttr: React.PropTypes.string
    };
  }

  componentDidMount() {
    this._updateSeries();
  }

  componentDidUpdate() {
    this._updateSeries();
  }

  _updateSeries() {
    const container = getDOMNode(this.refs.container);
    const {
      _stackBy,
      data,
      lineSizeAttr,
      valuePosAttr,
      linePosAttr,
      valueSizeAttr} = this.props;

    let {
      sameTypeTotal = 1,
      sameTypeIndex = 0} = this.props;

    if (!data || !data.length) {
      return;
    }

    const distance = this._getScaleDistance(linePosAttr);
    const lineFunctor = this._getAttributeFunctor(linePosAttr);
    const valueFunctor = this._getAttributeFunctor(valuePosAttr);
    const value0Functor = this._getAttr0Functor(valuePosAttr);

    if (_stackBy === valuePosAttr) {
      sameTypeTotal = 1;
      sameTypeIndex = 0;
    }

    const rects = d3Selection.select(container).selectAll('rect')
      .data(data)
      .on('mouseover', this._mouseOverWithValue)
      .on('mouseout', this._mouseOutWithValue)
      .on('click', this._clickWithValue);

    const itemSize = (distance / 2) * 0.85;

    this._applyTransition(rects)
      .style('opacity', this._getAttributeFunctor('opacity'))
      .style('fill', this._getAttributeFunctor('fill') ||
        this._getAttributeFunctor('color'))
      .style('stroke', this._getAttributeFunctor('stroke') ||
        this._getAttributeFunctor('color'))
      .attr(linePosAttr, d => lineFunctor(d) - itemSize +
        (itemSize * 2 / sameTypeTotal * sameTypeIndex)
      )
      .attr(lineSizeAttr, itemSize * 2 / sameTypeTotal)
      .attr(valuePosAttr,
        d => Math.min(value0Functor(d), valueFunctor(d)))
      .attr(valueSizeAttr,
        d => Math.abs(-value0Functor(d) + valueFunctor(d)));
  }

  render() {
    const {data, marginLeft, marginTop} = this.props;
    if (!data) {
      return null;
    }
    return (
      <g
        className="rv-xy-plot__series rv-xy-plot__series--bar"
        ref="container"
        transform={`translate(${marginLeft},${marginTop})`}>
        {data.map((d, i) => <rect style={{opacity: 0}} key={i}/>)}
      </g>
    );
  }
}

BarSeries.displayName = 'BarSeries';

export default BarSeries;
<commit_msg>Add animation to bar series, eliminate the d3 rendering.<commit_after>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import React from 'react';
import AbstractSeries from './abstract-series';
import Animation from '../../animation';
import {ANIMATED_SERIES_PROPS} from '../../utils/series-utils';

class BarSeries extends AbstractSeries {

  static get propTypes() {
    return {
      ... AbstractSeries.propTypes,
      linePosAttr: React.PropTypes.string,
      valuePosAttr: React.PropTypes.string,
      lineSizeAttr: React.PropTypes.string,
      valueSizeAttr: React.PropTypes.string
    };
  }

  render() {
    const {data, marginLeft, marginTop, animation} = this.props;

    if (!data) {
      return null;
    }

    if (animation) {
      return (
        <Animation {...this.props} animatedProps={ANIMATED_SERIES_PROPS}>
          <BarSeries {...this.props} animation={null}/>
        </Animation>
      );
    }

    const {
      _stackBy,
      lineSizeAttr,
      valuePosAttr,
      linePosAttr,
      valueSizeAttr} = this.props;

    let {
      sameTypeTotal = 1,
      sameTypeIndex = 0} = this.props;

    if (!data || !data.length) {
      return;
    }

    const distance = this._getScaleDistance(linePosAttr);
    const lineFunctor = this._getAttributeFunctor(linePosAttr);
    const valueFunctor = this._getAttributeFunctor(valuePosAttr);
    const value0Functor = this._getAttr0Functor(valuePosAttr);
    const fillFunctor = this._getAttributeFunctor('fill') ||
      this._getAttributeFunctor('color');
    const strokeFunctor = this._getAttributeFunctor('stroke') ||
      this._getAttributeFunctor('color');
    const opacityFunctor = this._getAttributeFunctor('opacity');

    if (_stackBy === valuePosAttr) {
      sameTypeTotal = 1;
      sameTypeIndex = 0;
    }

    const itemSize = (distance / 2) * 0.85;

    return (
      <g
        className="rv-xy-plot__series rv-xy-plot__series--bar"
        ref="container"
        transform={`translate(${marginLeft},${marginTop})`}>
        {data.map((d, i) => {
          const attrs = {
            style: {
              opacity: opacityFunctor(d),
              stroke: strokeFunctor(d),
              fill: fillFunctor(d)
            },
            [linePosAttr]: lineFunctor(d) - itemSize +
              (itemSize * 2 / sameTypeTotal * sameTypeIndex),
            [lineSizeAttr]: itemSize * 2 / sameTypeTotal,
            [valuePosAttr]: Math.min(value0Functor(d), valueFunctor(d)),
            [valueSizeAttr]: Math.abs(-value0Functor(d) + valueFunctor(d)),
            key: i
          };
          return (<rect {...attrs} />);
        })}
      </g>
    );
  }
}

BarSeries.displayName = 'BarSeries';

export default BarSeries;
<|endoftext|>


<commit_before>const Cron = require('../util/Cron');
const { isObject } = require('../util/util');

/**
 * The structure for future tasks to be run
 */
class ScheduledTask {

	/**
	 * @typedef  {(Date|number|Cron|string)} TimeResolvable
	 */

	/**
	 * @typedef  {Object} ScheduledTaskOptions
	 * @property {string} [id] The ID for the task. By default, it generates one in base36
	 * @property {boolean} [catchUp=true] If the task should try to catch up if the bot is down
	 * @property {*} [data] The data to pass to the Task piece when the ScheduledTask is ready for execution
	 */

	/**
	 * @typedef  {Object} ScheduledTaskUpdateOptions
	 * @property {TimeResolvable} [time] The time or {@link Cron} pattern
	 * @property {boolean} [catchUp] If the task should try to catch up if the bot is down
	 * @property {*} [data] The data to pass to the Task piece when the ScheduledTask is ready for execution
	 */

	/**
	 * @typedef  {Object} ScheduledTaskJSON
	 * @property {string} id The task's ID
	 * @property {string} taskName The name of the Task piece this will execute
	 * @property {number} time The UNIX timestamp for when this task ends at
	 * @property {boolean} catchUp If the task should try to catch up if the bot is down
	 * @property {string} [repeat] The {@link Cron} pattern
	 * @property {Object<string,*>} data The data to pass to the Task piece when the ScheduledTask is ready for execution
	 */

	/**
	 * Initializes a new ScheduledTask
	 * @since 0.5.0
	 * @param {KlasaClient} client The client that initialized this instance
	 * @param {string} taskName The name of the task this ScheduledTask is for
	 * @param {TimeResolvable} time The time or {@link Cron} pattern
	 * @param {ScheduledTaskOptions} [options={}] The options for this ScheduledTask instance
	 */
	constructor(client, taskName, time, options = {}) {
		const [_time, _recurring] = this.constructor._resolveTime(time);

		/**
		 * The Client instance that initialized this instance
		 * @since 0.5.0
		 * @name ScheduledTask#client
		 * @type {KlasaClient}
		 * @readonly
		 */
		Object.defineProperty(this, 'client', { value: client });

		/**
		 * The name of the Task this scheduled task will run
		 * @since 0.5.0
		 * @type {string}
		 */
		this.taskName = taskName;

		/**
		 * Whether this scheduled task is scheduled with the {@link Cron} pattern
		 * @since 0.5.0
		 * @type {?Cron}
		 */
		this.recurring = _recurring;

		/**
		 * The Date when this scheduled task ends
		 * @since 0.5.0
		 * @type {Date}
		 */
		this.time = 'time' in options ? new Date(options.time) : _time;

		/**
		 * The id for this scheduled task
		 * @since 0.5.0
		 * @type {string}
		 */
		this.id = options.id || this.constructor._generateID(this.client);

		/**
		 * If the task should catch up in the event the bot is down
		 * @since 0.5.0
		 * @type {string}
		 */
		this.catchUp = 'catchUp' in options ? options.catchUp : true;

		/**
		 * The stored metadata to send to the Task
		 * @since 0.5.0
		 * @type {*}
		 */
		this.data = 'data' in options && isObject(options.data) ? options.data : {};

		/**
		 * If the ScheduledTask is being run currently
		 * @since 0.5.0
		 * @type {boolean}
		 * @private
		 */
		this.running = false;

		this.constructor._validate(this);
	}

	/**
	 * The Schedule class that manages all scheduled tasks
	 * @since 0.5.0
	 * @name ScheduledTask#store
	 * @type {Schedule}
	 * @readonly
	 */
	get store() {
		return this.client.schedule;
	}

	/**
	 * The Task instance this scheduled task will run
	 * @since 0.5.0
	 * @type {?Task}
	 * @readonly
	 */
	get task() {
		return this.client.tasks.get(this.taskName) || null;
	}

	/**
	 * Run the current task and bump it if needed
	 * @since 0.5.0
	 * @returns {this}
	 */
	async run() {
		const { task } = this;
		if (!task || !task.enabled || this.running) return this;

		this.running = true;
		try {
			await task.run({ id: this.id, ...this.data });
		} catch (err) {
			this.client.emit('taskError', this, task, err);
		}
		this.running = false;

		if (!this.recurring) return this.delete();
		return this.update({ time: this.recurring });
	}

	/**
	 * Update the task
	 * @since 0.5.0
	 * @param {ScheduledTaskUpdateOptions} options The options to update
	 * @returns {this}
	 * @example
	 * // Update the data from the current scheduled task. Let's say I want to change the reminder content to remind me
	 * // another thing
	 * ScheduledTask.update({ data: { content: 'Woo! I edited this reminder\'s content!' } });
	 *
	 * // But you can also update the time this will end at, for example, to change it so it ends in 1 hour:
	 * ScheduledTask.update({ time: Date.now() + 60000 * 60 });
	 */
	async update({ time, data, catchUp } = {}) {
		if (time) {
			const [_time, _cron] = this.constructor._resolveTime(time);
			this.time = _time;
			this.store.tasks.splice(this.store.tasks.indexOf(this), 1);
			this.store._insert(this);
			this.recurring = _cron;
		}
		if (data) this.data = data;
		if (typeof catchUp !== 'undefined') this.catchUp = catchUp;

		// Sync the database if some of the properties changed or the time changed manually
		// (recurring tasks bump the time automatically)
		const _index = this.store._tasks.findIndex(entry => entry.id === this.id);
		if (_index !== -1) await this.client.settings.update('schedules', this.toJSON(), { arrayPosition: _index });

		return this;
	}

	/**
	 * Delete the task
	 * @since 0.5.0
	 * @returns {Promise<Schedule>}
	 * @example
	 * ScheduledTask.delete()
	 *     .then(() => console.log('Successfully deleted the task'))
	 *     .catch(console.error);
	 */
	delete() {
		return this.store.delete(this.id);
	}

	/**
	 * Override for JSON.stringify
	 * @since 0.5.0
	 * @returns {ScheduledTaskJSON}
	 */
	toJSON() {
		return {
			id: this.id,
			taskName: this.taskName,
			time: this.time.getTime(),
			catchUp: this.catchUp,
			data: this.data,
			repeat: this.recurring ? this.recurring.cron : null
		};
	}

	/**
	 * Resolve the time and cron
	 * @since 0.5.0
	 * @param {TimeResolvable} time The time or {@link Cron} pattern
	 * @returns {any[]}
	 * @private
	 */
	static _resolveTime(time) {
		if (time instanceof Date) return [time, null];
		if (time instanceof Cron) return [time.next(), time];
		if (typeof time === 'number') return [new Date(time), null];
		if (typeof time === 'string') {
			const cron = new Cron(time);
			return [cron.next(), cron];
		}
		throw new Error('invalid time passed');
	}

	/**
	 * Generate a new ID based on timestamp and shard
	 * @since 0.5.0
	 * @param {KlasaClient} client The Discord client
	 * @returns {string}
	 * @private
	 */
	static _generateID(client) {
		const id = client.shard ? (Array.isArray(client.shard.id) ? client.shard.id[0] : client.shard.id).toString(36) : null;
		return Date.now().toString(36) + id;
	}

	/**
	 * Validate a task
	 * @since 0.5.0
	 * @param {ScheduledTask} st The task to validate
	 * @private
	 */
	static _validate(st) {
		if (!st.task) throw new Error('invalid task');
		if (!st.time) throw new Error('time or repeat option required');
		if (Number.isNaN(st.time.getTime())) throw new Error('invalid time passed');
	}

}

module.exports = ScheduledTask;
<commit_msg>Pass empty string to task ID if not sharded (#481)<commit_after>const Cron = require('../util/Cron');
const { isObject } = require('../util/util');

/**
 * The structure for future tasks to be run
 */
class ScheduledTask {

	/**
	 * @typedef  {(Date|number|Cron|string)} TimeResolvable
	 */

	/**
	 * @typedef  {Object} ScheduledTaskOptions
	 * @property {string} [id] The ID for the task. By default, it generates one in base36
	 * @property {boolean} [catchUp=true] If the task should try to catch up if the bot is down
	 * @property {*} [data] The data to pass to the Task piece when the ScheduledTask is ready for execution
	 */

	/**
	 * @typedef  {Object} ScheduledTaskUpdateOptions
	 * @property {TimeResolvable} [time] The time or {@link Cron} pattern
	 * @property {boolean} [catchUp] If the task should try to catch up if the bot is down
	 * @property {*} [data] The data to pass to the Task piece when the ScheduledTask is ready for execution
	 */

	/**
	 * @typedef  {Object} ScheduledTaskJSON
	 * @property {string} id The task's ID
	 * @property {string} taskName The name of the Task piece this will execute
	 * @property {number} time The UNIX timestamp for when this task ends at
	 * @property {boolean} catchUp If the task should try to catch up if the bot is down
	 * @property {string} [repeat] The {@link Cron} pattern
	 * @property {Object<string,*>} data The data to pass to the Task piece when the ScheduledTask is ready for execution
	 */

	/**
	 * Initializes a new ScheduledTask
	 * @since 0.5.0
	 * @param {KlasaClient} client The client that initialized this instance
	 * @param {string} taskName The name of the task this ScheduledTask is for
	 * @param {TimeResolvable} time The time or {@link Cron} pattern
	 * @param {ScheduledTaskOptions} [options={}] The options for this ScheduledTask instance
	 */
	constructor(client, taskName, time, options = {}) {
		const [_time, _recurring] = this.constructor._resolveTime(time);

		/**
		 * The Client instance that initialized this instance
		 * @since 0.5.0
		 * @name ScheduledTask#client
		 * @type {KlasaClient}
		 * @readonly
		 */
		Object.defineProperty(this, 'client', { value: client });

		/**
		 * The name of the Task this scheduled task will run
		 * @since 0.5.0
		 * @type {string}
		 */
		this.taskName = taskName;

		/**
		 * Whether this scheduled task is scheduled with the {@link Cron} pattern
		 * @since 0.5.0
		 * @type {?Cron}
		 */
		this.recurring = _recurring;

		/**
		 * The Date when this scheduled task ends
		 * @since 0.5.0
		 * @type {Date}
		 */
		this.time = 'time' in options ? new Date(options.time) : _time;

		/**
		 * The id for this scheduled task
		 * @since 0.5.0
		 * @type {string}
		 */
		this.id = options.id || this.constructor._generateID(this.client);

		/**
		 * If the task should catch up in the event the bot is down
		 * @since 0.5.0
		 * @type {string}
		 */
		this.catchUp = 'catchUp' in options ? options.catchUp : true;

		/**
		 * The stored metadata to send to the Task
		 * @since 0.5.0
		 * @type {*}
		 */
		this.data = 'data' in options && isObject(options.data) ? options.data : {};

		/**
		 * If the ScheduledTask is being run currently
		 * @since 0.5.0
		 * @type {boolean}
		 * @private
		 */
		this.running = false;

		this.constructor._validate(this);
	}

	/**
	 * The Schedule class that manages all scheduled tasks
	 * @since 0.5.0
	 * @name ScheduledTask#store
	 * @type {Schedule}
	 * @readonly
	 */
	get store() {
		return this.client.schedule;
	}

	/**
	 * The Task instance this scheduled task will run
	 * @since 0.5.0
	 * @type {?Task}
	 * @readonly
	 */
	get task() {
		return this.client.tasks.get(this.taskName) || null;
	}

	/**
	 * Run the current task and bump it if needed
	 * @since 0.5.0
	 * @returns {this}
	 */
	async run() {
		const { task } = this;
		if (!task || !task.enabled || this.running) return this;

		this.running = true;
		try {
			await task.run({ id: this.id, ...this.data });
		} catch (err) {
			this.client.emit('taskError', this, task, err);
		}
		this.running = false;

		if (!this.recurring) return this.delete();
		return this.update({ time: this.recurring });
	}

	/**
	 * Update the task
	 * @since 0.5.0
	 * @param {ScheduledTaskUpdateOptions} options The options to update
	 * @returns {this}
	 * @example
	 * // Update the data from the current scheduled task. Let's say I want to change the reminder content to remind me
	 * // another thing
	 * ScheduledTask.update({ data: { content: 'Woo! I edited this reminder\'s content!' } });
	 *
	 * // But you can also update the time this will end at, for example, to change it so it ends in 1 hour:
	 * ScheduledTask.update({ time: Date.now() + 60000 * 60 });
	 */
	async update({ time, data, catchUp } = {}) {
		if (time) {
			const [_time, _cron] = this.constructor._resolveTime(time);
			this.time = _time;
			this.store.tasks.splice(this.store.tasks.indexOf(this), 1);
			this.store._insert(this);
			this.recurring = _cron;
		}
		if (data) this.data = data;
		if (typeof catchUp !== 'undefined') this.catchUp = catchUp;

		// Sync the database if some of the properties changed or the time changed manually
		// (recurring tasks bump the time automatically)
		const _index = this.store._tasks.findIndex(entry => entry.id === this.id);
		if (_index !== -1) await this.client.settings.update('schedules', this.toJSON(), { arrayPosition: _index });

		return this;
	}

	/**
	 * Delete the task
	 * @since 0.5.0
	 * @returns {Promise<Schedule>}
	 * @example
	 * ScheduledTask.delete()
	 *     .then(() => console.log('Successfully deleted the task'))
	 *     .catch(console.error);
	 */
	delete() {
		return this.store.delete(this.id);
	}

	/**
	 * Override for JSON.stringify
	 * @since 0.5.0
	 * @returns {ScheduledTaskJSON}
	 */
	toJSON() {
		return {
			id: this.id,
			taskName: this.taskName,
			time: this.time.getTime(),
			catchUp: this.catchUp,
			data: this.data,
			repeat: this.recurring ? this.recurring.cron : null
		};
	}

	/**
	 * Resolve the time and cron
	 * @since 0.5.0
	 * @param {TimeResolvable} time The time or {@link Cron} pattern
	 * @returns {any[]}
	 * @private
	 */
	static _resolveTime(time) {
		if (time instanceof Date) return [time, null];
		if (time instanceof Cron) return [time.next(), time];
		if (typeof time === 'number') return [new Date(time), null];
		if (typeof time === 'string') {
			const cron = new Cron(time);
			return [cron.next(), cron];
		}
		throw new Error('invalid time passed');
	}

	/**
	 * Generate a new ID based on timestamp and shard
	 * @since 0.5.0
	 * @param {KlasaClient} client The Discord client
	 * @returns {string}
	 * @private
	 */
	static _generateID(client) {
		const id = client.shard ? (Array.isArray(client.shard.id) ? client.shard.id[0] : client.shard.id).toString(36) : '';
		return Date.now().toString(36) + id;
	}

	/**
	 * Validate a task
	 * @since 0.5.0
	 * @param {ScheduledTask} st The task to validate
	 * @private
	 */
	static _validate(st) {
		if (!st.task) throw new Error('invalid task');
		if (!st.time) throw new Error('time or repeat option required');
		if (Number.isNaN(st.time.getTime())) throw new Error('invalid time passed');
	}

}

module.exports = ScheduledTask;
<|endoftext|>


<commit_before>import {
  AlreadyConstructedMarker,
  CustomElementDefinition,
} from './CustomElementDefinition';
import * as Utilities from './Utilities';
import * as CustomElementInternalSymbols from './CustomElementInternalSymbols';
const CustomElementState = CustomElementInternalSymbols.CustomElementState;

export class CustomElementInternals {
  constructor() {
    /** @type {!Map<string, !CustomElementDefinition>} */
    this._localNameToDefinition = new Map();

    /** @type {!Map<!Function, !CustomElementDefinition>} */
    this._constructorToDefinition = new Map();
  }

  /**
   * @param {string} localName
   * @param {!CustomElementDefinition} definition
   */
  setDefinition(localName, definition) {
    this._localNameToDefinition.set(localName, definition);
    this._constructorToDefinition.set(definition.constructor, definition);
  }

  /**
   * @param {string} localName
   * @return {!CustomElementDefinition|undefined}
   */
  localNameToDefinition(localName) {
    return this._localNameToDefinition.get(localName);
  }

  /**
   * @param {!Function} constructor
   * @return {!CustomElementDefinition|undefined}
   */
  constructorToDefinition(constructor) {
    return this._constructorToDefinition.get(constructor);
  }

  /**
   * @param {!Node} root
   */
  upgradeTree(root) {
    Utilities.walkDeepDescendantElements(root, element => this.upgradeElement(element));
  }

  /**
   * @param {!Element} element
   */
  upgradeElement(element) {
    if (
      element[CustomElementInternalSymbols.state] === CustomElementState.custom ||
      element[CustomElementInternalSymbols.state] === CustomElementState.failed
    ) return;

    const definition = this.localNameToDefinition(element.localName);
    if (!definition) return;

    definition.constructionStack.push(element);

    const constructor = definition.constructor;
    try {
      try {
        let result = new (constructor)();
        if (result !== element) {
          throw new Error('The custom element constructor did not produce the element being upgraded.');
        }
      } finally {
        definition.constructionStack.pop();
      }
    } catch (e) {
      element[CustomElementInternalSymbols.state] = CustomElementState.failed;
      throw e;
    }

    element[CustomElementInternalSymbols.state] = CustomElementState.custom;
    element[CustomElementInternalSymbols.definition] = definition;

    if (Utilities.isConnected(element)) {
      this.connectedCallback(element);
    }

    if (definition.attributeChangedCallback) {
      for (const name of definition.observedAttributes) {
        const value = element.getAttribute(name);
        if (value !== null) {
          this.attributeChangedCallback(element, name, null, value, null);
        }
      }
    }
  }

  /**
   * @param {!Element} element
   */
  connectedCallback(element) {
    if (element[CustomElementInternalSymbols.state] === CustomElementState.custom) {
      const definition = element[CustomElementInternalSymbols.definition];
      if (definition && definition.connectedCallback) {
        definition.connectedCallback.call(element);
      }
    }
  }

  /**
   * @param {!Element} element
   */
  disconnectedCallback(element) {
    if (element[CustomElementInternalSymbols.state] === CustomElementState.custom) {
      const definition = element[CustomElementInternalSymbols.definition];
      if (definition && definition.disconnectedCallback) {
        definition.disconnectedCallback.call(element);
      }
    }
  }

  /**
   * @param {!Element} element
   * @param {string} name
   * @param {?string} oldValue
   * @param {?string} newValue
   * @param {?string} namespace
   */
  attributeChangedCallback(element, name, oldValue, newValue, namespace) {
    if (element[CustomElementInternalSymbols.state] === CustomElementState.custom) {
      const definition = element[CustomElementInternalSymbols.definition];
      if (
        definition &&
        definition.attributeChangedCallback &&
        definition.observedAttributes.indexOf(name) > -1
      ) {
        definition.attributeChangedCallback.call(element, name, oldValue, newValue, namespace);
      }
    }
  }
}
<commit_msg>Fix incorrect `attributeChangedCallback` and `connectedCallback` ordering during upgrades.<commit_after>import {
  AlreadyConstructedMarker,
  CustomElementDefinition,
} from './CustomElementDefinition';
import * as Utilities from './Utilities';
import * as CustomElementInternalSymbols from './CustomElementInternalSymbols';
const CustomElementState = CustomElementInternalSymbols.CustomElementState;

export class CustomElementInternals {
  constructor() {
    /** @type {!Map<string, !CustomElementDefinition>} */
    this._localNameToDefinition = new Map();

    /** @type {!Map<!Function, !CustomElementDefinition>} */
    this._constructorToDefinition = new Map();
  }

  /**
   * @param {string} localName
   * @param {!CustomElementDefinition} definition
   */
  setDefinition(localName, definition) {
    this._localNameToDefinition.set(localName, definition);
    this._constructorToDefinition.set(definition.constructor, definition);
  }

  /**
   * @param {string} localName
   * @return {!CustomElementDefinition|undefined}
   */
  localNameToDefinition(localName) {
    return this._localNameToDefinition.get(localName);
  }

  /**
   * @param {!Function} constructor
   * @return {!CustomElementDefinition|undefined}
   */
  constructorToDefinition(constructor) {
    return this._constructorToDefinition.get(constructor);
  }

  /**
   * @param {!Node} root
   */
  upgradeTree(root) {
    Utilities.walkDeepDescendantElements(root, element => this.upgradeElement(element));
  }

  /**
   * @param {!Element} element
   */
  upgradeElement(element) {
    if (
      element[CustomElementInternalSymbols.state] === CustomElementState.custom ||
      element[CustomElementInternalSymbols.state] === CustomElementState.failed
    ) return;

    const definition = this.localNameToDefinition(element.localName);
    if (!definition) return;

    definition.constructionStack.push(element);

    const constructor = definition.constructor;
    try {
      try {
        let result = new (constructor)();
        if (result !== element) {
          throw new Error('The custom element constructor did not produce the element being upgraded.');
        }
      } finally {
        definition.constructionStack.pop();
      }
    } catch (e) {
      element[CustomElementInternalSymbols.state] = CustomElementState.failed;
      throw e;
    }

    element[CustomElementInternalSymbols.state] = CustomElementState.custom;
    element[CustomElementInternalSymbols.definition] = definition;

    if (definition.attributeChangedCallback) {
      for (const name of definition.observedAttributes) {
        const value = element.getAttribute(name);
        if (value !== null) {
          this.attributeChangedCallback(element, name, null, value, null);
        }
      }
    }

    if (Utilities.isConnected(element)) {
      this.connectedCallback(element);
    }
  }

  /**
   * @param {!Element} element
   */
  connectedCallback(element) {
    if (element[CustomElementInternalSymbols.state] === CustomElementState.custom) {
      const definition = element[CustomElementInternalSymbols.definition];
      if (definition && definition.connectedCallback) {
        definition.connectedCallback.call(element);
      }
    }
  }

  /**
   * @param {!Element} element
   */
  disconnectedCallback(element) {
    if (element[CustomElementInternalSymbols.state] === CustomElementState.custom) {
      const definition = element[CustomElementInternalSymbols.definition];
      if (definition && definition.disconnectedCallback) {
        definition.disconnectedCallback.call(element);
      }
    }
  }

  /**
   * @param {!Element} element
   * @param {string} name
   * @param {?string} oldValue
   * @param {?string} newValue
   * @param {?string} namespace
   */
  attributeChangedCallback(element, name, oldValue, newValue, namespace) {
    if (element[CustomElementInternalSymbols.state] === CustomElementState.custom) {
      const definition = element[CustomElementInternalSymbols.definition];
      if (
        definition &&
        definition.attributeChangedCallback &&
        definition.observedAttributes.indexOf(name) > -1
      ) {
        definition.attributeChangedCallback.call(element, name, oldValue, newValue, namespace);
      }
    }
  }
}
<|endoftext|>


<commit_before>var models  = require('../models');

module.exports = function(req, res) {

	// Create obj for rendering
	var hbsObject = {
		username: req.user.username,
		recentGroups: [],
		userGroups: []
	};

	// Find most recently created groups
	models.Group.findAll({
		limit: 5,
		order: 'created_at DESC'
		// Create a loop through function that is called recursively
	}).then(function loopThrough(recentGroups, counter) {
			// Set counter
			if (counter === undefined) counter = 0;
			if (counter >= recentGroups.length) return;
			// Get groupname and totalusers
			var obj = {
				groupname: recentGroups[counter].dataValues.groupname,
				totalusers: recentGroups[counter].dataValues.totalusers
			}
			// Check if total users is reached
			if (obj.totalusers === 4) {
	  		obj.joined = true; // Even though not actually joined, it does not display ability to join
	  		// Push obj to recent groups
	    	hbsObject.recentGroups.push(obj);
	    	// Recursion
	    	counter++;
	    	loopThrough(recentGroups, counter)
	  	} else {
	  		// Check if user is in group
	    	recentGroups[counter].getUsers({where : {username: req.user.username}}).then(function(results) {
	    		// If no result, not used yet
		    	if (results.length === 0)
		    		obj.joined = false;
		    	else
		    		obj.joined = true;
		    	// Push obj to recent groups
		    	hbsObject.recentGroups.push(obj);
		    	// Recursion
		    	counter++;
		    	loopThrough(recentGroups, counter)
	    	})
	  	}

	}).then(function() {
		// Get sequelize user object
		models.User.findOne({
			where: {username: req.user.username}
		}).then(function(user) {

			// Retrieve all groups from user
			user.getGroups().then(function(groups) {
				// Add user's groups
				for (var i in groups) {
					var obj = {
						groupname: groups[i].dataValues.groupname,
						totalusers: groups[i].dataValues.totalusers
					}
					hbsObject.userGroups.push(obj);
				}
				// Render group page with groups
	  		res.render('groups', hbsObject);
			}).error(function(err) {
		    console.log(err);
		  })

		}).error(function(err) {
	    console.log(err);
	  })
	})

}<commit_msg>Fixed recent group callback error<commit_after>var models  = require('../models');

module.exports = function(req, res) {

	// Create obj for rendering
	var hbsObject = {
		username: req.user.username,
		recentGroups: [],
		userGroups: []
	};

	// Find most recently created groups
	models.Group.findAll({
		limit: 5,
		order: 'id DESC'
		// Create a loop through function that is called recursively
	}).then(function loopThrough(recentGroups, counter) {
		// Set counter
		if (counter === undefined) counter = 0;
		if (counter >= recentGroups.length) {
			cb()
			return
		}
		// Get groupname and totalusers
		var obj = {
			groupname: recentGroups[counter].dataValues.groupname,
			totalusers: recentGroups[counter].dataValues.totalusers
		}
		// Check if total users is reached
		if (obj.totalusers === 4) {
  		obj.joined = true; // Even though not actually joined, it does not display ability to join
  		// Push obj to recent groups
    	hbsObject.recentGroups.push(obj);
    	// Recursion
    	counter++;
    	loopThrough(recentGroups, counter)
  	} else {
  		// Check if user is in group
    	recentGroups[counter].getUsers({where : {username: req.user.username}}).then(function(results) {
    		// If no result, not used yet
	    	if (results.length === 0)
	    		obj.joined = false;
	    	else
	    		obj.joined = true;
	    	// Push obj to recent groups
	    	hbsObject.recentGroups.push(obj);
	    	// Recursion
	    	counter++;
	    	loopThrough(recentGroups, counter)
    	})
  	}

	})

	// Used a callback function instead of then (then was causing problems)
	function cb() {
		// Get sequelize user object
		models.User.findOne({
			where: {username: req.user.username}
		}).then(function(user) {

			// Retrieve all groups from user
			user.getGroups().then(function(groups) {
				// Add user's groups
				for (var i in groups) {
					var obj = {
						groupname: groups[i].dataValues.groupname,
						totalusers: groups[i].dataValues.totalusers
					}
					hbsObject.userGroups.push(obj);
				}
				// Render group page with groups
	  		res.render('groups', hbsObject);
			}).error(function(err) {
		    console.log(err);
		  })

		}).error(function(err) {
	    console.log(err);
	  })
	}

}<|endoftext|>


<commit_before>'use strict'

/**
 * Native Dependencies
 */
var path = require('path')

/**
 * External Dependencies
 */
var glob = require('glob')

/**
 * Local Dependencies
 */
var Plugin = require('./plugin')
var Injector = require('./injector')

/**
 * Symbols
 */
const plugins = Symbol()
const injector = Symbol()

/**
 * Sunstone
 */
class Sunstone {

  /**
   * Constructor
   */
  constructor () {
    this[injector] = new Injector()
    this[plugins] = {}
  }

  /**
   * Plugin
   */
  plugin (name, manifest) {
    if (manifest) {
      let plugin = new Plugin(name, manifest, this[injector])
      this[plugins][name] = plugin
      return plugin
    } else {
      return this[plugins][name]
    }
  }

  /**
   * Require
   */
  require () {
    let segments = Array.prototype.slice.call(arguments, this.require.length)
    let directory = path.join.apply(null, segments)
    let pattern = path.join(directory, '**/index.js')
    let plugins = glob.sync(path.resolve(pattern))

    plugins.forEach((plugin) => {
      require(plugin)(this)
    })
  }

  /**
   * Bootstrap
   */
  bootstrap () {
    let cwd = process.cwd()

    // load plugins from source code
    this.require(__dirname, 'plugins')

    // load plugins from node_modules
    // ???

    // load plugins from project
    if (cwd !== __dirname) {
      this.require(cwd, 'plugins')
    }

    // assemble the server and create a reference
    this.server = this[injector].get('server')
    this.settings = this[injector].get('settings')

    // register routes
    this[injector].find({
      type: 'router'
    }).forEach((router) => {
      router.mount()
    })
  }

  /**
   * Start
   */
  static start () {
    let sunstone = new Sunstone()
    sunstone.bootstrap()

    let host = sunstone.settings.host
    let port = sunstone.settings.port

    sunstone.server.listen(port, function () {
      console.log(`Listening on ${port}`)
    })
  }

}

/**
 * Exports
 */
module.exports = Sunstone

<commit_msg>feat(plugin): added plugin dependency validation<commit_after>'use strict'

/**
 * Native Dependencies
 */
var path = require('path')

/**
 * External Dependencies
 */
var glob = require('glob')
var _ = require('lodash')
var semver = require('semver')

/**
 * Local Dependencies
 */
var Plugin = require('./plugin')
var Injector = require('./injector')

/**
 * Symbols
 */
const plugins = Symbol()
const injector = Symbol()

/**
 * Sunstone
 */
class Sunstone {

  /**
   * Constructor
   */
  constructor () {
    this[injector] = new Injector()
    this[plugins] = {}
  }

  /**
   * Plugin
   */
  plugin (name, manifest) {
    if (manifest) {
      let plugin = new Plugin(name, manifest, this[injector])
      this[plugins][name] = plugin
      return plugin
    } else {
      return this[plugins][name]
    }
  }

  /**
   * Require
   */
  require () {
    let segments = Array.prototype.slice.call(arguments, this.require.length)
    let directory = path.join.apply(null, segments)
    let pattern = path.join(directory, '**/index.js')
    let plugins = glob.sync(path.resolve(pattern))

    plugins.forEach((plugin) => {
      require(plugin)(this)
    })
  }

  /**
   * Bootstrap
   */
  bootstrap () {
    let cwd = process.cwd()

    // load plugins from source code
    this.require(__dirname, 'plugins')

    // load plugins from node_modules
    // ???

    // load plugins from project
    if (cwd !== __dirname) {
      this.require(cwd, 'plugins')
    }

    // assemble the server and create a reference
    this.server = this[injector].get('server')
    this.settings = this[injector].get('settings')

    // register routes
    this[injector].find({
      type: 'router'
    }).forEach((router) => {
      router.mount()
    })

    // validate plugin dependencies
    this.validate()
  }

  /**
   * Validate Plugins
   */
  validate () {
    Object.keys(this[plugins]).forEach((pluginName) => {
      let plugin = this[plugins][pluginName]
      let dependencies = plugin.manifest.dependencies || {}
      Object.keys(dependencies).forEach((dependencyName) => {
        let dependency = this[plugins][dependencyName]
        if (!dependency) {
          throw new Error(
            `Plugin ${pluginName} has a missing dependency ${dependencyName}`
          )
        }
        if (!semver.satisfies(dependency.manifest.version, dependencies[dependencyName])) {
          throw new Error(
            `Plugin ${pluginName} requires ${dependencyName} version ${dependencies[dependencyName]}`
          )
        }
      })
    })
  }

  /**
   * Start
   */
  static start () {
    let sunstone = new Sunstone()
    sunstone.bootstrap()

    let host = sunstone.settings.host
    let port = sunstone.settings.port

    sunstone.server.listen(port, function () {
      console.log(`Listening on ${port}`)
    })
  }

}

/**
 * Exports
 */
module.exports = Sunstone

<|endoftext|>