<commit_before>const React = require('react');
const ReactDOM = require('react-dom');
const Radium = require('radium');

const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

const isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i).test(navigator.userAgent);

const Select = React.createClass({
  propTypes: {
    color: React.PropTypes.string,
    dropdownStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    onChange: React.PropTypes.func,
    options: React.PropTypes.array,
    optionsStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    optionStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    placeholderText: React.PropTypes.string,
    scrimStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    selected: React.PropTypes.object,
    selectedStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    valid: React.PropTypes.bool
  },

  getDefaultProps () {
    return {
      color: StyleConstants.Colors.PRIMARY,
      onChange () {},
      options: [],
      placeholderText: 'Select One',
      valid: true
    };
  },

  getInitialState () {
    return {
      highlightedValue: null,
      isOpen: false
    };
  },

  componentDidMount () {
    styles.option[':hover'].backgroundColor = this.props.color;
    styles.activeItem.backgroundColor = this.props.color;
  },

  _handleScrimClick () {
    this.setState({
      isOpen: false,
      highlightedValue: null
    });
  },

  _handleClick () {
    if (!isMobile) {
      this.setState({
        isOpen: !this.state.isOpen
      });
    }
  },

  _handleOptionClick (option) {
    this.setState({
      selected: option,
      isOpen: false,
      highlightedValue: null
    });

    this.props.onChange(option);
  },

  _handleSelectChange (e) {
    const selectedOption = this.props.options.filter(option => {
      return option.value + '' === e.target.value;
    })[0];

    this._handleOptionClick(selectedOption);
  },

  _handleInputKeyDown (e) {
    const highlightedValue = this.state.highlightedValue;

    if (e.keyCode === 13 && highlightedValue) {
      this._handleOptionClick(highlightedValue);
    }

    if (e.keyCode === 40) {
      e.preventDefault();

      const nextIndex = this.props.options.indexOf(highlightedValue) + 1;

      if (nextIndex < this.props.options.length) {
        this.setState({
          highlightedValue: this.props.options[nextIndex]
        });

        this._scrollListDown(nextIndex);
      }
    }

    if (e.keyCode === 38) {
      e.preventDefault();

      const previousIndex = this.props.options.indexOf(highlightedValue) - 1;

      if (previousIndex > -1) {
        this.setState({
          highlightedValue: this.props.options[previousIndex]
        });

        this._scrollListUp(previousIndex);
      }
    }
  },

  _scrollListDown (nextIndex) {
    const ul = ReactDOM.findDOMNode(this.refs.optionList);
    const activeLi = ul.children[nextIndex];
    const heightFromTop = nextIndex * activeLi.clientHeight;

    if (heightFromTop > ul.clientHeight) {
      ul.scrollTop = activeLi.offsetTop - activeLi.clientHeight;
    }
  },

  _scrollListUp (prevIndex) {
    const ul = ReactDOM.findDOMNode(this.refs.optionList);
    const activeLi = ul.children[prevIndex];
    const heightFromBottom = (this.props.options.length - prevIndex) * activeLi.clientHeight;

    if (heightFromBottom > ul.clientHeight) {
      ul.scrollTop = activeLi.offsetTop - activeLi.clientHeight;
    }
  },

  _renderScrim () {
    if (this.state.isOpen) {
      return (

      );
    } else {
      return null;
    }
  },

  _renderOptions () {
    if (this.state.isOpen) {
      if (this.props.children) {
        return (

            {this.props.children}

        );
      } else {
        return (

            {this.props.options.map(option => {
              return (

                {option.displayValue}

              );
            })}

        );
      }
    } else {
      return null;
    }
  },

  render () {
    const selected = this.state.selected || this.props.selected || { displayValue: this.props.placeholderText, value: '' };

    return (

          {this._renderScrim()}

            {selected.displayValue}
            <Icon
              size='20'
              style={styles.caret}
              type={this.state.isOpen ? 'caret-up' : 'caret-down'}
            />

          {this.props.options.length || this.props.children ? this._renderOptions() : null}

        {isMobile ? (
          <select className='mx-select-default' onChange={this._handleSelectChange} ref='defaultSelect' style={styles.select} value={selected.value}>
            {this.props.options.map(option => {
              return (<option key={option.displayValue + option.value} value={option.value}>{option.displayValue}</option>);
            })}
          </select>
        ) : null }

    );
  }
});

const styles = {
  caret: {
    color: '#CCCCCC',
    cursor: 'pointer',
    position: 'absolute',
    right: '-5px',
    top: '50%',
    transform: 'translateY(-50%)'
  },
  component: {
    backgroundColor: '#FFFFFF',
    borderRadius: '3px',
    border: '1px solid #E5E5E5',
    cursor: 'pointer',
    fontFamily: StyleConstants.FontFamily,
    fontSize: StyleConstants.FontSizes.MEDIUM,
    padding: '11px 10px 12px',
    position: 'relative',
    appearance: 'none',
    WebkitAppearance: 'none',
    boxSizing: 'border-box',
    outline: 'none'
  },
  select: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    width: '100%',
    WebkitAppearance: 'none',
    opacity: 0
  },
  selected: {
    position: 'relative'
  },
  activeItem: {
    color: StyleConstants.Colors.WHITE
  },
  invalid: {
    borderColor: StyleConstants.Colors.STRAWBERRY
  },
  options: {
    backgroundColor: '#FFFFFF',
    border: '1px solid #E5E5E5',
    borderRadius: '0 0 3px 3px',
    left: '-1px',
    right: '-1px',
    margin: '10px 0 0 0',
    padding: '0',
    minWidth: '100%',
    position: 'absolute',
    zIndex: 10,
    fontSize: '12px',
    boxShadow: '0 30px 30px 10px rgba(0,0,0,0.1)',
    boxSizing: 'border-box',
    maxHeight: '260px',
    overflow: 'auto'
  },
  option: {
    cursor: 'pointer',
    backgroundColor: '#FFFFFF',
    padding: '10px',
    whiteSpace: 'nowrap',

    ':hover': {
      color: StyleConstants.Colors.WHITE
    }
  },
  scrim: {
    position: 'fixed',
    zIndex: 9,
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  }
};

module.exports = Radium(Select);
<commit_msg>styles method added<commit_after>const React = require('react');
const ReactDOM = require('react-dom');
const Radium = require('radium');

const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

const isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i).test(navigator.userAgent);

const Select = React.createClass({
  propTypes: {
    color: React.PropTypes.string,
    dropdownStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    onChange: React.PropTypes.func,
    options: React.PropTypes.array,
    optionsStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    optionStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    placeholderText: React.PropTypes.string,
    scrimStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    selected: React.PropTypes.object,
    selectedStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    valid: React.PropTypes.bool
  },

  getDefaultProps () {
    return {
      color: StyleConstants.Colors.PRIMARY,
      onChange () {},
      options: [],
      placeholderText: 'Select One',
      valid: true
    };
  },

  getInitialState () {
    return {
      highlightedValue: null,
      isOpen: false
    };
  },

  _handleScrimClick () {
    this.setState({
      isOpen: false,
      highlightedValue: null
    });
  },

  _handleClick () {
    if (!isMobile) {
      this.setState({
        isOpen: !this.state.isOpen
      });
    }
  },

  _handleOptionClick (option) {
    this.setState({
      selected: option,
      isOpen: false,
      highlightedValue: null
    });

    this.props.onChange(option);
  },

  _handleSelectChange (e) {
    const selectedOption = this.props.options.filter(option => {
      return option.value + '' === e.target.value;
    })[0];

    this._handleOptionClick(selectedOption);
  },

  _handleInputKeyDown (e) {
    const highlightedValue = this.state.highlightedValue;

    if (e.keyCode === 13 && highlightedValue) {
      this._handleOptionClick(highlightedValue);
    }

    if (e.keyCode === 40) {
      e.preventDefault();

      const nextIndex = this.props.options.indexOf(highlightedValue) + 1;

      if (nextIndex < this.props.options.length) {
        this.setState({
          highlightedValue: this.props.options[nextIndex]
        });

        this._scrollListDown(nextIndex);
      }
    }

    if (e.keyCode === 38) {
      e.preventDefault();

      const previousIndex = this.props.options.indexOf(highlightedValue) - 1;

      if (previousIndex > -1) {
        this.setState({
          highlightedValue: this.props.options[previousIndex]
        });

        this._scrollListUp(previousIndex);
      }
    }
  },

  _scrollListDown (nextIndex) {
    const ul = ReactDOM.findDOMNode(this.refs.optionList);
    const activeLi = ul.children[nextIndex];
    const heightFromTop = nextIndex * activeLi.clientHeight;

    if (heightFromTop > ul.clientHeight) {
      ul.scrollTop = activeLi.offsetTop - activeLi.clientHeight;
    }
  },

  _scrollListUp (prevIndex) {
    const ul = ReactDOM.findDOMNode(this.refs.optionList);
    const activeLi = ul.children[prevIndex];
    const heightFromBottom = (this.props.options.length - prevIndex) * activeLi.clientHeight;

    if (heightFromBottom > ul.clientHeight) {
      ul.scrollTop = activeLi.offsetTop - activeLi.clientHeight;
    }
  },

  _renderScrim () {
    if (this.state.isOpen) {
      const styles = this.styles();

      return (

      );
    } else {
      return null;
    }
  },

  _renderOptions () {
    if (this.state.isOpen) {
      const styles = this.styles();

      if (this.props.children) {
        return (

            {this.props.children}

        );
      } else {
        return (

            {this.props.options.map(option => {
              return (

                {option.displayValue}

              );
            })}

        );
      }
    } else {
      return null;
    }
  },

  render () {
    const styles = this.styles();
    const selected = this.state.selected || this.props.selected || { displayValue: this.props.placeholderText, value: '' };

    return (

          {this._renderScrim()}

            {selected.displayValue}
            <Icon
              size='20'
              style={styles.caret}
              type={this.state.isOpen ? 'caret-up' : 'caret-down'}
            />

          {this.props.options.length || this.props.children ? this._renderOptions() : null}

        {isMobile ? (
          <select className='mx-select-default' onChange={this._handleSelectChange} ref='defaultSelect' style={styles.select} value={selected.value}>
            {this.props.options.map(option => {
              return (<option key={option.displayValue + option.value} value={option.value}>{option.displayValue}</option>);
            })}
          </select>
        ) : null }

    );
  },

  styles () {
    return {
      caret: {
        color: '#CCCCCC',
        cursor: 'pointer',
        position: 'absolute',
        right: '-5px',
        top: '50%',
        transform: 'translateY(-50%)'
      },
      component: {
        backgroundColor: '#FFFFFF',
        borderRadius: '3px',
        border: '1px solid #E5E5E5',
        cursor: 'pointer',
        fontFamily: StyleConstants.FontFamily,
        fontSize: StyleConstants.FontSizes.MEDIUM,
        padding: '11px 10px 12px',
        position: 'relative',
        appearance: 'none',
        WebkitAppearance: 'none',
        boxSizing: 'border-box',
        outline: 'none'
      },
      select: {
        position: 'absolute',
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
        width: '100%',
        WebkitAppearance: 'none',
        opacity: 0
      },
      selected: {
        position: 'relative'
      },
      activeItem: {
        backgroundColor: this.props.color,
        color: StyleConstants.Colors.WHITE
      },
      invalid: {
        borderColor: StyleConstants.Colors.STRAWBERRY
      },
      options: {
        backgroundColor: '#FFFFFF',
        border: '1px solid #E5E5E5',
        borderRadius: '0 0 3px 3px',
        left: '-1px',
        right: '-1px',
        margin: '10px 0 0 0',
        padding: '0',
        minWidth: '100%',
        position: 'absolute',
        zIndex: 10,
        fontSize: '12px',
        boxShadow: '0 30px 30px 10px rgba(0,0,0,0.1)',
        boxSizing: 'border-box',
        maxHeight: '260px',
        overflow: 'auto'
      },
      option: {
        cursor: 'pointer',
        backgroundColor: '#FFFFFF',
        padding: '10px',
        whiteSpace: 'nowrap',

        ':hover': {
          backgroundColor: this.props.color,
          color: StyleConstants.Colors.WHITE
        }
      },
      scrim: {
        position: 'fixed',
        zIndex: 9,
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      }
    };
  }
});

module.exports = Radium(Select);
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var util = require('util');
var Transform = require('stream').Transform;

// Matches: 00:00:17,810 --> 00:00:20,330
var timeMatch = new RegExp(/\d+\:\d+\:\d+\,\d+\s\-\-\>\s\d+\:\d+\:\d+\,\d+/);
// Matches: "0:00:00.180,0:00:02.230"
var altTimeMatch = new RegExp(/\d+\:\d+\:\d+\.\d+\,\d+\:\d+\:\d+\.\d+/);

function Parser(opts) {
  // if no instance, call new
  if (!(this instanceof Parser)) {
    return new Parser(opts);
  }
  this.fileName = opts.fileName;
  Transform.call(this);
}

util.inherits(Parser, Transform);

Parser.prototype._transform = function _transform(data, enc, cb) {
  var buf = new Buffer(data);
  var str = buf.toString('utf-8');
  var begin = ['\n\n', this.fileName.split('.')[0], '\n'];
  var parsed = begin.concat(str.split('\r\n')).filter(function(line) {
    return !timeMatch.test(line) &&
      !altTimeMatch.test(line) &&
      line != (line.match(/\d+/) && line.match(/\d+/)[0]);
  }).join(' ').replace(/\>\>/, '\n\n');
  this.push(parsed);
  cb();
};

var writeEnabled = false;

function frListener(fr) {
  fr.on('end', function() {
    writeEnabled = true;
  });
}

function write(pipe, fw) {
  frListener(pipe.fr);
  return pipe.fr
    .pipe(pipe.parser)
    .pipe(fw, { end: false });
}

function writing(filePipes, fileWriter) {
  if (filePipes.length == 1 ) {
    var pipe = filePipes.shift();
    return pipe.fr
      .pipe(pipe.parser)
      .pipe(fileWriter, { end: true });
  }

  // Setup recursion
  if (writeEnabled) {
    writeEnabled = false;
    write(filePipes.shift(), fileWriter);
    writing(filePipes, fileWriter);
  } else {
    setImmediate(function() {
      writing(filePipes, fileWriter);
    });
  }
}

module.exports = function(dirName, fileName) {
  var dir = process.argv[2] || dirName;
  if (!dir) throw new Error('Directory required');

  var file = process.argv[3] || fileName || path.join(dir, 'parsed-srt.txt');

  var fileWriter = fs.createWriteStream(file);
  fileWriter.setMaxListeners(0);

  fs.readdir(dir, function(err, files) {
    var srtFiles = files.filter(function(file) {
      return /\.srt/.test(file);
    });
    var len = srtFiles.length;

    var pipes = srtFiles.map(function(srtFile) {
      var filePath = path.join(dir, srtFile);
      var fileReader = fs.createReadStream(filePath);
      var parseSrtFile = new Parser({ fileName: srtFile });

      return {
        fr: fileReader,
        parser: parseSrtFile
      };
    });
    writeEnabled = true;
    writing(pipes, fileWriter);
  });
};

<commit_msg>converts to markdown files<commit_after>var fs = require('fs');
var path = require('path');
var util = require('util');
var Transform = require('stream').Transform;

// Matches: 00:00:17,810 --> 00:00:20,330
var timeMatch = new RegExp(/\d+\:\d+\:\d+\,\d+\s\-\-\>\s\d+\:\d+\:\d+\,\d+/);
// Matches: "0:00:00.180,0:00:02.230"
var altTimeMatch = new RegExp(/\d+\:\d+\:\d+\.\d+\,\d+\:\d+\:\d+\.\d+/);

function Parser(opts) {
  // if no instance, call new
  if (!(this instanceof Parser)) {
    return new Parser(opts);
  }
  this.fileName = opts.fileName;
  Transform.call(this);
}

util.inherits(Parser, Transform);

Parser.prototype._transform = function _transform(data, enc, cb) {
  var buf = new Buffer(data);
  var str = buf.toString('utf-8');
  var begin = ['\n\n###', this.fileName.split('.')[0], '\n'];
  var parsed = begin.concat(str.split('\r\n')).filter(function(line) {
    return !timeMatch.test(line) &&
      !altTimeMatch.test(line) &&
      line != (line.match(/\d+/) && line.match(/\d+/)[0]);
  }).join(' ').replace(/\>\>/, '\n\n');
  this.push(parsed);
  cb();
};

var writeEnabled = false;

function frListener(fr) {
  fr.on('end', function() {
    writeEnabled = true;
  });
}

function write(pipe, fw) {
  frListener(pipe.fr);
  return pipe.fr
    .pipe(pipe.parser)
    .pipe(fw, { end: false });
}

function writing(filePipes, fileWriter) {
  if (filePipes.length == 1 ) {
    var pipe = filePipes.shift();
    return pipe.fr
      .pipe(pipe.parser)
      .pipe(fileWriter, { end: true });
  }

  // Setup recursion
  if (writeEnabled) {
    writeEnabled = false;
    write(filePipes.shift(), fileWriter);
    writing(filePipes, fileWriter);
  } else {
    setImmediate(function() {
      writing(filePipes, fileWriter);
    });
  }
}

module.exports = function(dirName, fileName) {
  var dir = process.argv[2] || dirName;
  if (!dir) throw new Error('Directory required');

  var file = process.argv[3] || fileName || path.join(dir, 'parsed-srt.txt');

  var title = '# ' + dir.split('/').pop() + '\n\n';

  var fileWriter = fs.createWriteStream(file);
  fileWriter.setMaxListeners(0);
  fileWriter.write(title);

  fs.readdir(dir, function(err, files) {
    var srtFiles = files.filter(function(file) {
      return /\.srt/.test(file);
    });
    var len = srtFiles.length;

    var pipes = srtFiles.map(function(srtFile) {
      var filePath = path.join(dir, srtFile);
      var fileReader = fs.createReadStream(filePath);
      var parseSrtFile = new Parser({ fileName: srtFile });

      return {
        fr: fileReader,
        parser: parseSrtFile
      };
    });
    writeEnabled = true;
    writing(pipes, fileWriter);
  });
};

<|endoftext|>


<commit_before>import React          from 'react'
import ChannelToolbar from './channel-toolbar'

import Paper
  from 'material-ui/lib/paper'
import Avatar
  from 'material-ui/lib/avatar'
import Slider
  from 'material-ui/lib/slider'
import FlatButton
  from 'material-ui/lib/flat-button'
import Divider
  from 'material-ui/lib/divider'
import IconVolumeUp
  from 'material-ui/lib/svg-icons/av/volume-up'
import IconButton
  from 'material-ui/lib/icon-button'

import { green400 }
  from 'material-ui/lib/styles/colors'

class Channel extends React.Component {
  constructor(props) {
    super(props)
  }
  updateVolume(e, value) {
    const { id, sendMessage } = this.props
    sendMessage('channelVolume', {
      [id]: value
    })
  }
  setMode(newMode) {
    const { id, mode, sendMessage } = this.props
    if ('free' != mode) {
      sendMessage('channelMode', {
        [id]: newMode
      })
    }
  }
  renderControls() {
    const {
      id,
      level,
      mode,
      muted,
      sendMessage,
    } = this.props
    switch (mode) {
      case 'defunct':
        return (

        )
      case 'free':
      default:
        return (

              <Avatar icon={remove} />

            <IconButton>
              <IconVolumeUp />
            </IconButton>

              <Slider
                onChange      = {::this.updateVolume}
                disabled      = {muted}
                min           = {1}
                max           = {100}
                value         = {level}
                defaultValue  = {level} />

        )
    }
  }
  renderActions() {
    const { mode } = this.props
    switch (mode) {
      case 'free':
      case 'defunct':
        return (

        )
      default:
        return (

            <Divider />

              <FlatButton
                style      = {styles.button}
                primary    = {true}
                label      = 'Master'
                icon       = {speaker}
                onClick    = {() => this.setMode('master')}
              />
              <FlatButton
                style      = {styles.button}
                primary    = {true}
                label      = 'On hold'
                icon       = {pause}
                onClick    = {() => this.setMode('on_hold')}
              />
              <FlatButton
                style      = {styles.button}
                secondary  = {true}
                label      = 'Reject'
                icon       = {cancel}
                onClick    = {() => this.setMode('free')}
              />

        )
    }
  }
  render() {
    const { mode } = this.props
    const colors = {
      defunct : '#dedede',
    }
    return (

        <Paper style={{
            ...styles.paper,
            borderLeft : `12px solid ${colors[mode] || green400}`,
          }}>
          <ChannelToolbar {...this.props} />
          {this.renderControls()}
          {this.renderActions()}
        </Paper>

    )
  }
}

const styles = {
  component: {
    padding         : '1em 1em 0 1em',
  },
  paper: {
    width           : '100%',
  },
  controls: {
    display         : 'flex',
    flexDirection   : 'row',
    alignItems      : 'center',
    height          : '60px',
    marginBottom    : '10px',
    padding         : '10px 0',
  },
  avatar: {
    padding         : '0 0 0 20px',
  },
  slider: {
    margin          : '22px 20px 0 20px',
    width           : '100%',
  },
}

export default Channel
<commit_msg>remove redundant constructor<commit_after>import React          from 'react'
import ChannelToolbar from './channel-toolbar'

import Paper
  from 'material-ui/lib/paper'
import Avatar
  from 'material-ui/lib/avatar'
import Slider
  from 'material-ui/lib/slider'
import FlatButton
  from 'material-ui/lib/flat-button'
import Divider
  from 'material-ui/lib/divider'
import IconVolumeUp
  from 'material-ui/lib/svg-icons/av/volume-up'
import IconButton
  from 'material-ui/lib/icon-button'

import { green400 }
  from 'material-ui/lib/styles/colors'

class Channel extends React.Component {
  updateVolume(e, value) {
    const { id, sendMessage } = this.props
    sendMessage('channelVolume', {
      [id]: value
    })
  }
  setMode(newMode) {
    const { id, mode, sendMessage } = this.props
    if ('free' != mode) {
      sendMessage('channelMode', {
        [id]: newMode
      })
    }
  }
  renderControls() {
    const {
      id,
      level,
      mode,
      muted,
      sendMessage,
    } = this.props
    switch (mode) {
      case 'defunct':
        return (

        )
      case 'free':
      default:
        return (

              <Avatar icon={remove} />

            <IconButton>
              <IconVolumeUp />
            </IconButton>

              <Slider
                onChange      = {::this.updateVolume}
                disabled      = {muted}
                min           = {1}
                max           = {100}
                value         = {level}
                defaultValue  = {level} />

        )
    }
  }
  renderActions() {
    const { mode } = this.props
    switch (mode) {
      case 'free':
      case 'defunct':
        return (

        )
      default:
        return (

            <Divider />

              <FlatButton
                style      = {styles.button}
                primary    = {true}
                label      = 'Master'
                icon       = {speaker}
                onClick    = {() => this.setMode('master')}
              />
              <FlatButton
                style      = {styles.button}
                primary    = {true}
                label      = 'On hold'
                icon       = {pause}
                onClick    = {() => this.setMode('on_hold')}
              />
              <FlatButton
                style      = {styles.button}
                secondary  = {true}
                label      = 'Reject'
                icon       = {cancel}
                onClick    = {() => this.setMode('free')}
              />

        )
    }
  }
  render() {
    const { mode } = this.props
    const colors = {
      defunct : '#dedede',
    }
    return (

        <Paper style={{
            ...styles.paper,
            borderLeft : `12px solid ${colors[mode] || green400}`,
          }}>
          <ChannelToolbar {...this.props} />
          {this.renderControls()}
          {this.renderActions()}
        </Paper>

    )
  }
}

const styles = {
  component: {
    padding         : '1em 1em 0 1em',
  },
  paper: {
    width           : '100%',
  },
  controls: {
    display         : 'flex',
    flexDirection   : 'row',
    alignItems      : 'center',
    height          : '60px',
    marginBottom    : '10px',
    padding         : '10px 0',
  },
  avatar: {
    padding         : '0 0 0 20px',
  },
  slider: {
    margin          : '22px 20px 0 20px',
    width           : '100%',
  },
}

export default Channel
<|endoftext|>


<commit_before>import { CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping } from '../../constants.js';
import { WebGLCubeRenderTarget } from '../WebGLCubeRenderTarget.js';

function WebGLCubeMaps( renderer ) {

	let cubemaps = new WeakMap();

	function mapTextureMapping( texture, mapping ) {

		if ( mapping === EquirectangularReflectionMapping ) {

			texture.mapping = CubeReflectionMapping;

		} else if ( mapping === EquirectangularRefractionMapping ) {

			texture.mapping = CubeRefractionMapping;

		}

		return texture;

	}

	function get( texture ) {

		if ( texture && texture.isTexture ) {

			const mapping = texture.mapping;

			if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {

				if ( cubemaps.has( texture ) ) {

					const cubemap = cubemaps.get( texture ).texture;
					return mapTextureMapping( cubemap, texture.mapping );

				} else {

					const image = texture.image;

					if ( image && image.height > 0 ) {

						const currentRenderList = renderer.getRenderList();
						const currentRenderTarget = renderer.getRenderTarget();
						const currentRenderState = renderer.getRenderState();

						const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
						renderTarget.fromEquirectangularTexture( renderer, texture );
						cubemaps.set( texture, renderTarget );

						renderer.setRenderTarget( currentRenderTarget );
						renderer.setRenderList( currentRenderList );
						renderer.setRenderState( currentRenderState );

						return mapTextureMapping( renderTarget.texture, texture.mapping );

					} else {

						// image not yet ready. try the conversion next frame

						return null;

					}

				}

			}

		}

		return texture;

	}

	function dispose() {

		cubemaps = new WeakMap();

	}

	return {
		get: get,
		dispose: dispose
	};

}

export { WebGLCubeMaps };
<commit_msg>WebGLCubeMaps: Support Texture.dispose().<commit_after>import { CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping } from '../../constants.js';
import { WebGLCubeRenderTarget } from '../WebGLCubeRenderTarget.js';

function WebGLCubeMaps( renderer ) {

	let cubemaps = new WeakMap();

	function mapTextureMapping( texture, mapping ) {

		if ( mapping === EquirectangularReflectionMapping ) {

			texture.mapping = CubeReflectionMapping;

		} else if ( mapping === EquirectangularRefractionMapping ) {

			texture.mapping = CubeRefractionMapping;

		}

		return texture;

	}

	function get( texture ) {

		if ( texture && texture.isTexture ) {

			const mapping = texture.mapping;

			if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {

				if ( cubemaps.has( texture ) ) {

					const cubemap = cubemaps.get( texture ).texture;
					return mapTextureMapping( cubemap, texture.mapping );

				} else {

					const image = texture.image;

					if ( image && image.height > 0 ) {

						const currentRenderList = renderer.getRenderList();
						const currentRenderTarget = renderer.getRenderTarget();
						const currentRenderState = renderer.getRenderState();

						const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
						renderTarget.fromEquirectangularTexture( renderer, texture );
						cubemaps.set( texture, renderTarget );

						renderer.setRenderTarget( currentRenderTarget );
						renderer.setRenderList( currentRenderList );
						renderer.setRenderState( currentRenderState );

						texture.addEventListener( 'dispose', onTextureDispose );

						return mapTextureMapping( renderTarget.texture, texture.mapping );

					} else {

						// image not yet ready. try the conversion next frame

						return null;

					}

				}

			}

		}

		return texture;

	}

	function onTextureDispose( event ) {

		const texture = event.target;

		texture.removeEventListener( 'dispose', onTextureDispose );

		const cubemap = cubemaps.get( texture );

		if ( cubemap !== undefined ) {

			cubemaps.delete( texture );
			cubemap.dispose();

		}

	}

	function dispose() {

		cubemaps = new WeakMap();

	}

	return {
		get: get,
		dispose: dispose
	};

}

export { WebGLCubeMaps };
<|endoftext|>


<commit_before>import { documentHelpers, Command } from 'substance'
import { findParentByType } from './nodeHelpers'
import CustomMetadataField from '../models/CustomMetadataField'

class BasicCustomMetadataFieldCommand extends Command {
  get contextType () {
    return 'custom-metadata-field'
  }

  getCommandState (params, context) {
    return {
      disabled: this.isDisabled(params, context)
    }
  }

  isDisabled (params) {
    const xpath = params.selectionState.xpath
    return !xpath.find(n => n.type === this.contextType)
  }

  _getCollectionPath (params, context) {
    const doc = params.editorSession.getDocument()
    const nodeId = params.selection.getNodeId()
    const node = doc.get(nodeId)
    let figurePanelId = node.id
    if (node.type !== 'figure-panel') {
      const parentFigurePanel = findParentByType(node, 'figure-panel')
      figurePanelId = parentFigurePanel.id
    }
    return [figurePanelId, 'metadata']
  }
}

export class AddCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  get contextType () {
    return 'figure-panel'
  }

  execute (params, context) {
    const collectionPath = this._getCollectionPath(params, context)
    context.editorSession.transaction(tx => {
      let node = documentHelpers.createNodeFromJson(tx, CustomMetadataField.getTemplate())
      documentHelpers.append(tx, collectionPath, node.id)
      const path = [node.id, 'name']
      const viewName = context.appState.viewName
      const surfaceId = context.api._getSurfaceId(node, path, viewName)
      tx.setSelection({
        type: 'property',
        path,
        surfaceId,
        startOffset: 0
      })
    })
  }
}

export class RemoveCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  execute (params, context) {
    const collectionPath = this._getCollectionPath(params, context)
    context.editorSession.transaction(tx => {
      const nodeId = tx.selection.getNodeId()
      documentHelpers.remove(tx, collectionPath, nodeId)
      tx.selection = null
    })
  }
}

export class MoveCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  execute (params, context) {
    const direction = this.config.direction
    const collectionPath = this._getCollectionPath(params, context)
    const nodeId = params.selection.getNodeId()
    const doc = context.editorSession.getDocument()
    const customField = doc.get(nodeId)
    const shift = direction === 'up' ? -1 : 1
    context.api._moveChild(collectionPath, customField, shift)
  }

  isDisabled (params, context) {
    const matchSelection = !super.isDisabled(params)
    if (matchSelection) {
      const direction = this.config.direction
      const collectionPath = this._getCollectionPath(params, context)
      const nodeId = params.selection.getNodeId()
      const doc = context.editorSession.getDocument()
      const customFieldsIndex = doc.get(collectionPath)
      const currentIndex = customFieldsIndex.indexOf(nodeId)
      if (customFieldsIndex.length > 0) {
        if ((direction === 'up' && currentIndex > 0) || (direction === 'down' && currentIndex < customFieldsIndex.length - 1)) {
          return false
        }
      }
    }
    return true
  }
}
<commit_msg>Add custom field for figure selection.<commit_after>import { documentHelpers, Command } from 'substance'
import { findParentByType } from './nodeHelpers'
import CustomMetadataField from '../models/CustomMetadataField'

class BasicCustomMetadataFieldCommand extends Command {
  get contextType () {
    return 'custom-metadata-field'
  }

  getCommandState (params, context) {
    return {
      disabled: this.isDisabled(params, context)
    }
  }

  isDisabled (params) {
    const xpath = params.selectionState.xpath
    return !xpath.find(n => n.type === this.contextType)
  }

  _getCollectionPath (params, context) {
    const doc = params.editorSession.getDocument()
    const nodeId = params.selection.getNodeId()
    const node = doc.get(nodeId)
    let figurePanelId = node.id
    if (params.selection.type === 'node' && this.contextType === 'figure') {
      const currentIndex = node.getCurrentPanelIndex()
      figurePanelId = node.panels[currentIndex]
    } else if (node.type !== 'figure-panel') {
      const parentFigurePanel = findParentByType(node, 'figure-panel')
      figurePanelId = parentFigurePanel.id
    }
    return [figurePanelId, 'metadata']
  }
}

export class AddCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  get contextType () {
    return 'figure'
  }

  execute (params, context) {
    const collectionPath = this._getCollectionPath(params, context)
    context.editorSession.transaction(tx => {
      let node = documentHelpers.createNodeFromJson(tx, CustomMetadataField.getTemplate())
      documentHelpers.append(tx, collectionPath, node.id)
      const path = [node.id, 'name']
      const viewName = context.appState.viewName
      const surfaceId = context.api._getSurfaceId(node, path, viewName)
      tx.setSelection({
        type: 'property',
        path,
        surfaceId,
        startOffset: 0
      })
    })
  }
}

export class RemoveCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  execute (params, context) {
    const collectionPath = this._getCollectionPath(params, context)
    context.editorSession.transaction(tx => {
      const nodeId = tx.selection.getNodeId()
      documentHelpers.remove(tx, collectionPath, nodeId)
      tx.selection = null
    })
  }
}

export class MoveCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  execute (params, context) {
    const direction = this.config.direction
    const collectionPath = this._getCollectionPath(params, context)
    const nodeId = params.selection.getNodeId()
    const doc = context.editorSession.getDocument()
    const customField = doc.get(nodeId)
    const shift = direction === 'up' ? -1 : 1
    context.api._moveChild(collectionPath, customField, shift)
  }

  isDisabled (params, context) {
    const matchSelection = !super.isDisabled(params)
    if (matchSelection) {
      const direction = this.config.direction
      const collectionPath = this._getCollectionPath(params, context)
      const nodeId = params.selection.getNodeId()
      const doc = context.editorSession.getDocument()
      const customFieldsIndex = doc.get(collectionPath)
      const currentIndex = customFieldsIndex.indexOf(nodeId)
      if (customFieldsIndex.length > 0) {
        if ((direction === 'up' && currentIndex > 0) || (direction === 'down' && currentIndex < customFieldsIndex.length - 1)) {
          return false
        }
      }
    }
    return true
  }
}
<|endoftext|>


<commit_before>
export default class Eventhandler {

	constructor(config = {}) {
		this._init(config);
	}

	/**
	 * Passed config object
	 * @type {Object}
	 */
	config = {
		events: {},
		element: null,
		bind: null,
	};

	/**
	 * Main event callback wrapper
	 * @type {Object}
	 */
	mainEventCallackContainer = {};

	/**
	 * Initialize Eventhandler
	 * @return {undefined}
	 */
	_init(config){

		/**
		 * Throw error if no events passed
		 */
		if(!config.events) {
			throw new Error('Please pass events. See documentation!');
		}

		/**
		 * Throw error if no element passed
		 */
		if(!config.element){
			throw new Error('Please pass an element. See documentation!');
		}

		// bind bindObject
		if(config.bind){
			Eventhandler.bindObjectToEventList(config.events, config.bind);
		}
		// group events
		let groupedEvents = Eventhandler.groupEvents(config.events);
		// Merge passed config
		Object.assign(this.config.events, groupedEvents);
		// Assign element
		this.config.element = config.element;

		// add events eventListener
		this._addEventCollection(groupedEvents);

	}

	/**
	 * Create and return an instace of Eventhandler
	 * @param  {Object} ...args
	 * @return {Object}
	 */
	static create(...args){
		return new Eventhandler(...args);
	}

	/**
	 * Convert eventDomain into seperate item
	 * @param  {String} eventDomain
	 * @return {Array} [ type, delegateSelector ]
	 */
	static prepareEventdomain(eventDomain) {

		if(Object.classof(eventDomain) !== 'String'){
			throw new Error('Passed argument must be a string');
		}

		let splitedEventDomain = eventDomain.split(' ');
		let type = splitedEventDomain[0];
		let delegateSelector = null;
		if(splitedEventDomain[1]){
			delegateSelector = splitedEventDomain.splice(1).join(' ');
		}

		return [ type, delegateSelector ];

	}

	/**
	 * Group events
	 * @param  {Object} config
	 * @return {Object}
	 */
	static groupEvents(events = {}){

		let tmpConfig = {};

		for(let eventDomain in events){
			if(!events.hasOwnProperty(eventDomain)){
				continue;
			}

			let [ type, delegateSelector ] = Eventhandler.prepareEventdomain(eventDomain);
			if(!tmpConfig[type]){
				tmpConfig[type] = [];
			}

			tmpConfig[type].push({
				[ delegateSelector ]: events[eventDomain],
			});
		}

		return tmpConfig;

	}

	/**
	 * Bind object to event value
	 * @param  {Object} events
	 * @param  {Object} bindObject
	 * @return {undefined}
	 */
	static bindObjectToEventList(events = {}, bindObject){

		for(let eventDomain in events){
			if(!events.hasOwnProperty(eventDomain)){
				continue;
			}
			// bind and assign bindObject
			events[eventDomain] = bindObject::events[eventDomain];
		}

	}

	/**
	 * Return event callbacks
	 * @param  {String} eventType
	 * @return {Array|null}
	 */
	getHandlers(eventType){
		return this.config.events[eventType] || null;
	}

	/**
	 * Add collection of events
	 * Example: see above constructor config.events
	 * @param {Objbect} events
	 */
	_addEventCollection(events){

		// add events eventlistener
		for(let type in events){
			if(!events.hasOwnProperty(type)){
				continue;
			}
			this._addEvent(this.config.element, type, events[type]);
		}

	}

	/**
	 * Add single event
	 * @param {HTMLElement} element
	 * @param {String} eventDomain
	 * @param {Function} callback
	 */
	_addEvent(element, type, delegateSelectors) {

		this.mainEventCallackContainer[type] = function( event ){

			for(let delegateObject of delegateSelectors){

				// received key (delegateSelector) is always a key
				// therefore (see below) delegateSelector === "null"
				let delegateSelector = Object.keys(delegateObject)[0];
				let callback = delegateObject[delegateSelector];
				let matchedSelector = false;

				if(delegateSelector){
					matchedSelector = event.target.matches(delegateSelector);
				}

				if(delegateSelector === "null" || matchedSelector){
					callback(event);
				}

			}
		};

		element.addEventListener(type, this.mainEventCallackContainer[type]);

	}

	/**
	 * Remove event from listener by given eventdomain
	 * @param  {String} eventDomain
	 * @return {undefined}
	 */
	removeEvent(eventDomain) {

		let [ type, delegateSelector ] = Eventhandler.prepareEventdomain(eventDomain);

		if(!this.config.events[type]) {
			throw new Error(`Event: ${type} not exists!`);
		}

		let index = 0;
		for(let delegateObject of this.config.events[type]){
			// remove delegate callback if passed e.g. "click .foo"
			if(delegateSelector && delegateObject[delegateSelector]){
				this.config.events[type].splice(index, 1);
			}
			// remove all callbacks if passed type e.g. "click" or e.g. "click" is empty
			if((type && delegateSelector === null) || this.config.events[type].length === 0){
				delete this.config.events[type];
			}
			index++;
		}

		// remove listener if eventsList empty or not exists
		if(!this.config.events[type]){
			this.config.element.removeEventListener(type, this.mainEventCallackContainer[type]);
			delete this.config.events[type];
		}

	}

	/**
	 * Removes all eventhandler
	 * @return {undefined}
	 */
	reset() {

		if(!Object.keys(this.config.events).length){
			return;
		}

		// add events eventlistener
		for(let type in this.config.events){
			if(!events.hasOwnProperty(type)){
				continue;
			}
			this.removeEvent(type);
		}

	}

}
<commit_msg>Eventhandler: refactored for new api method "on".<commit_after>
export default class Eventhandler {

	constructor(config = {}) {
		this._init(config);
	}

	/**
	 * Passed config object
	 * @type {Object}
	 */
	config = {
		events: {},
		element: null,
		bind: null,
	};

	/**
	 * Main event callback wrapper
	 * @type {Object}
	 */
	mainEventCallackContainer = {};

	/**
	 * Initialize Eventhandler
	 * @return {undefined}
	 */
	_init(config){

		/**
		* Throw error if no element passed
		*/
		if(!config.element){
			throw new Error('Please pass an element. See documentation!');
		}
		// Assign element
		this.config.element = config.element;

		/**
		 * Throw error if no events passed
		 */
		if(!config.events) {
			return;
		}

		// bind bindObject
		if(config.bind){
			Eventhandler.bindObjectToEventList(config.events, config.bind);
		}
		// group events
		this.config.events = Eventhandler.groupEvents(config.events);

		// add events eventListener
		this._addEventCollection(this.config.events);

	}

	/**
	 * Create and return an instace of Eventhandler
	 * @param  {Object} ...args
	 * @return {Object}
	 */
	static create(...args){
		return new Eventhandler(...args);
	}

	/**
	 * Convert eventDomain into seperate item
	 * @param  {String} eventDomain
	 * @return {Array} [ type, delegateSelector ]
	 */
	static prepareEventdomain(eventDomain) {

		if(Object.classof(eventDomain) !== 'String'){
			throw new Error('Passed argument must be a string');
		}

		let splitedEventDomain = eventDomain.split(' ');
		let type = splitedEventDomain[0];
		let delegateSelector = null;
		if(splitedEventDomain[1]){
			delegateSelector = splitedEventDomain.splice(1).join(' ');
		}

		return [ type, delegateSelector ];

	}

	/**
	 * Group events
	 * @param  {Object} config
	 * @return {Object}
	 */
	static groupEvents(events = {}){

		let tmpConfig = {};

		for(let eventDomain in events){
			if(!events.hasOwnProperty(eventDomain)){
				continue;
			}

			let [ type, delegateSelector ] = Eventhandler.prepareEventdomain(eventDomain);
			if(!tmpConfig[type]){
				tmpConfig[type] = [];
			}

			tmpConfig[type].push({
				[ delegateSelector ]: events[eventDomain],
			});
		}

		return tmpConfig;

	}

	/**
	 * Bind object to event value
	 * @param  {Object} events
	 * @param  {Object} bindObject
	 * @return {undefined}
	 */
	static bindObjectToEventList(events = {}, bindObject){

		for(let eventDomain in events){
			if(!events.hasOwnProperty(eventDomain)){
				continue;
			}
			// bind and assign bindObject
			events[eventDomain] = bindObject::events[eventDomain];
		}

	}

	/**
	 * on
	 * @param  {String} eventDomain
	 * @param  {Function} handler
	 * @return {Undefined}
	 */
	on(eventDomain, handler){

		this._addConfigEvents(eventDomain, handler);
		this._addEvent(this.config.element, type, this.config.events[type]);

	}

	/**
	 * trigger
	 * @param  {String} event
	 * @param  {Any} value
	 * @return {Undefined}
	 */
	trigger(event, value = null){

		this.config.element.dispatchEvent(
			new Event(event, { detail: value })
		);

	}

	/**
	 * Return event callbacks
	 * @param  {String} eventType
	 * @return {Array|null}
	 */
	getHandlers(eventType){
		return this.config.events[eventType] || null;
	}

	/**
	 * Add collection of events
	 * Example: see above constructor config.events
	 * @param {Objbect} events
	 */
	_addEventCollection(events){

		// add events eventlistener
		for(let type in events){
			if(!events.hasOwnProperty(type)){
				continue;
			}
			this._addEvent(this.config.element, type, events[type]);
		}

	}

	/**
	 * _addConfigEvents
	 * @param {String} eventDomain
	 * @param {Function} handler
	 */
	_addConfigEvents(eventDomain, handler){

		let [ type, delegateSelector ] = Eventhandler.prepareEventdomain(eventDomain);
		if(!this.config.events[type]){
			this.config.events[type] = [];
		}

		this.config.events[type].push({
			[ delegateSelector ]: handler,
		});

	}

	/**
	 * Add single event
	 * @param {HTMLElement} element
	 * @param {String} type
	 * @param {Function} callback
	 */
	_addEvent(element, type, delegateSelectors) {

		this.mainEventCallackContainer[type] = function( event ){

			for(let delegateObject of delegateSelectors){

				// received key (delegateSelector) is always a key
				// therefore (see below) delegateSelector === "null"
				let delegateSelector = Object.keys(delegateObject)[0];
				let callback = delegateObject[delegateSelector];
				let matchedSelector = false;

				if(delegateSelector){
					matchedSelector = event.target.matches(delegateSelector);
				}

				if(delegateSelector === "null" || matchedSelector){
					callback(event);
				}

			}
		};

		element.addEventListener(type, this.mainEventCallackContainer[type]);

	}

	/**
	 * Remove event from listener by given eventdomain
	 * @param  {String} eventDomain
	 * @return {undefined}
	 */
	removeEvent(eventDomain) {

		let [ type, delegateSelector ] = Eventhandler.prepareEventdomain(eventDomain);

		if(!this.config.events[type]) {
			throw new Error(`Event: ${type} not exists!`);
		}

		let index = 0;
		for(let delegateObject of this.config.events[type]){
			// remove delegate callback if passed e.g. "click .foo"
			if(delegateSelector && delegateObject[delegateSelector]){
				this.config.events[type].splice(index, 1);
			}
			// remove all callbacks if passed type e.g. "click" or e.g. "click" is empty
			if((type && delegateSelector === null) || this.config.events[type].length === 0){
				delete this.config.events[type];
			}
			index++;
		}

		// remove listener if eventsList empty or not exists
		if(!this.config.events[type]){
			this.config.element.removeEventListener(type, this.mainEventCallackContainer[type]);
			delete this.config.events[type];
		}

	}

	/**
	 * Removes all eventhandler
	 * @return {undefined}
	 */
	reset() {

		if(!Object.keys(this.config.events).length){
			return;
		}

		// add events eventlistener
		for(let type in this.config.events){
			if(!events.hasOwnProperty(type)){
				continue;
			}
			this.removeEvent(type);
		}

	}

}
<|endoftext|>


<commit_before>// Jaksot-taulukko ja koodit-taulukko ladataan tiedostosta lukkariTaulukot.js

// Linkki jos lukkari ladataan
var linkki = "";

// Rakentaa linkin josta lukkari löytyy
function haeJakso(){
    x = nykyinenJakso();
    if (x != 4 && x != 5)
    {
        alkupvm = jaksot[x][0].replace(/\./gi, "");
        loppupvm = jaksot[x][1].replace(/\./gi, "");
        linkki = "http://www.rpkk.fi/lukkarit/lukkari_show.php?toiminto=luokka&jalku="+alkupvm+"&jloppu="+loppupvm+"&jjakso="+x+"&luokka=D3";
        //var linkki = "jakso2.html";

        $("#lukkarinimet").load(linkki + " .lukkari_table2", function(){
            korvaa();
        });
        $("#lukkarikoodit").load(linkki + " .lukkari_table2");
    }
    else{
        linkki = "img/toissa.jpg";
        $("#lukkarinimet").html("");
        $("#lukkarikoodit").html("");
    }
    if (x == 5)
	$("#jaksoNumero").text("Jakso " + x + "a");
	else if ( x == 6)
	$("#jaksoNumero").text("Jakso " + x + "b");
	else
	$("#jaksoNumero").text("Jakso " + x);
}

// Hakee nykyisen jakson päivämäärän perusteella
function nykyinenJakso(){
	var nyt = Date.today();
	//var nyt = Date.parse(prompt("Anna testipäivämäärä")); //debug

	for (var i = 1; i <= 7; i++){
		loppupvm_seuraava = Date.parse(jaksot[i+1][1]);
		alkupvm = Date.parse(jaksot[i][0]);
		loppupvm = Date.parse(jaksot[i][1]);

		// Tarkistaa onko nykyinen päivämäärä jonkun jakson sisällä ja palauttaa jakson
		if(nyt >= alkupvm && nyt <= loppupvm){
			return i;
		}
		// Tarkista onko jakso mennyt ohi mutta uusi ei ole vielä alkanut(viikonloput jaksojen välissä)
		// Ja palautaa uuden jakson
		else if(nyt < loppupvm_seuraava && nyt >= loppupvm)
			return i+1;
	}
	// Palauttaa viimeisen jakson jos koulu loppunut
	if(nyt > jaksot[7][1])
	return 6;
}

// Korvaa talukosta koodit nimillä
function korvaa(){
	$("#lukkarinimet td").each(function(){
		var text = $(this).html(), i;
		for(i in koodit){
			text = text.replace(i, koodit[i]);
		}
		$(this).html(text);
	});
}

$(document).ready(function(){

	// Hae oikea jakso ja muuta jaksolistan vakioarvo samaksi
	haeJakso();

	$("#ruokalista").load("ruokalistaa.php");

	$(".jakso").click(function(){
		haeJakso($(this).attr("id"));
	});

	// Vaihtaa nimet koodeiksi ja toisinpäin
	$("#toggle").click(function(){
		$(".lukkari").toggle();
	});
});
<commit_msg>Fixed a derp<commit_after>// Jaksot-taulukko ja koodit-taulukko ladataan tiedostosta lukkariTaulukot.js

// Rakentaa linkin josta lukkari löytyy
function haeJakso(){
	var linkki = "";
    x = nykyinenJakso();
    if (x != 4 && x != 5)
    {
        alkupvm = jaksot[x][0].replace(/\./gi, "");
        loppupvm = jaksot[x][1].replace(/\./gi, "");
        linkki = "http://www.rpkk.fi/lukkarit/lukkari_show.php?toiminto=luokka&jalku="+alkupvm+"&jloppu="+loppupvm+"&jjakso="+x+"&luokka=D3";
        //var linkki = "jakso2.html";

        $("#lukkarinimet").load(linkki + " .lukkari_table2", function(){
            korvaa();
        });
        $("#lukkarikoodit").load(linkki + " .lukkari_table2");
    }
    else{
        linkki = "img/toissa.jpg";
        $("#lukkarinimet").html("");
        $("#lukkarikoodit").html("");
    }
    if (x == 5)
	$("#jaksoNumero").text("Jakso " + x + "a");
	else if ( x == 6)
	$("#jaksoNumero").text("Jakso " + x + "b");
	else
	$("#jaksoNumero").text("Jakso " + x);
}

// Hakee nykyisen jakson päivämäärän perusteella
function nykyinenJakso(){
	var nyt = Date.today();
	//var nyt = Date.parse(prompt("Anna testipäivämäärä")); //debug

	for (var i = 1; i <= 7; i++){
		loppupvm_seuraava = Date.parse(jaksot[i+1][1]);
		alkupvm = Date.parse(jaksot[i][0]);
		loppupvm = Date.parse(jaksot[i][1]);

		// Tarkistaa onko nykyinen päivämäärä jonkun jakson sisällä ja palauttaa jakson
		if(nyt >= alkupvm && nyt <= loppupvm){
			return i;
		}
		// Tarkista onko jakso mennyt ohi mutta uusi ei ole vielä alkanut(viikonloput jaksojen välissä)
		// Ja palautaa uuden jakson
		else if(nyt < loppupvm_seuraava && nyt >= loppupvm)
			return i+1;
	}
	// Palauttaa viimeisen jakson jos koulu loppunut
	if(nyt > jaksot[7][1])
	return 6;
}

// Korvaa talukosta koodit nimillä
function korvaa(){
	$("#lukkarinimet td").each(function(){
		var text = $(this).html(), i;
		for(i in koodit){
			text = text.replace(i, koodit[i]);
		}
		$(this).html(text);
	});
}

$(document).ready(function(){

	// Hae oikea jakso ja muuta jaksolistan vakioarvo samaksi
	haeJakso();

	$("#ruokalista").load("ruokalistaa.php");

	$(".jakso").click(function(){
		haeJakso($(this).attr("id"));
	});

	// Vaihtaa nimet koodeiksi ja toisinpäin
	$("#toggle").click(function(){
		$(".lukkari").toggle();
	});
});
<|endoftext|>


<commit_before>var stickyHeader = function(){
	var tables = $('table');
	var i, navbarHeight, scroll;

	function calculateNavbar(){
		if( window.innerWidth >= 840){
			navbarHeight = $('.navbar').height();
		}else{
			navbarHeight = 0;
		}
	}
	calculateNavbar();

	function calculateHeaderCutoffs(table){
		table.querySelector('thead').style.webkitTransform = 'translate(0px,0px)';
		table.querySelector('thead').style.MozTransform = 'translate(0px,0px)';
		table.dataset.top = parseInt( $(table).children('thead').offset().top, 10 );
		table.dataset.bottom = parseInt( $(table).height() - $(tables[i]).children('thead').height() - $(tables[i]).children('tbody tr:last').height(), 10 );
	}

	function positionHeaders(table){
		var difference_top = scroll + navbarHeight - table.dataset.top;
		var thead = table.querySelector('thead');
		if(difference_top <= 0){
			thead.style.webkitTransform = 'translate(0px,0px)';
			thead.style.MozTransform = 'translate(0px,0px)';
		}
		if(difference_top > 0){
			if(table.getAttribute('id') == 'schedule'){
				thead.style.webkitTransform = 'translate(0px,'+ (difference_top -1) +'px)';
				thead.style.MozTransform = 'translate(0px,'+ (difference_top -1)  +'px)';
			}else{
				thead.style.webkitTransform = 'translate(0px,'+ (difference_top - 10) +'px)';
				thead.style.MozTransform = 'translate(0px,'+ (difference_top -10) +'px)';
			}
		}
		if(difference_top > table.dataset.bottom){
			thead.style.webkitTransform = 'translate(0px,'+ table.dataset.bottom +'px)';
			thead.style.MozTransform = 'translate(0px,'+ table.dataset.bottom +'px)';
		}
	}

	for (i = 0; i < tables.length; i++) {
		calculateHeaderCutoffs(tables[i]);
		positionHeaders(tables[i]);
	}

	window.onscroll = function(){
		for (i = 0; i < tables.length; i++) {
			scroll = document.documentElement.scrollTop || document.body.scrollTop;
			positionHeaders(tables[i]);
		}
	};
	window.onresize = function(){
		calculateNavbar();
		for (i = 0; i < tables.length; i++) {
			calculateHeaderCutoffs(tables[i]);
			positionHeaders(tables[i]);
		}
	};
};

stickyHeader();
<commit_msg>modified id selector for speed<commit_after>var stickyHeader = function(){
	var tables = $('table');
	var i, navbarHeight, scroll;

	function calculateNavbar(){
		if( window.innerWidth >= 840){
			navbarHeight = $('.navbar').height();
		}else{
			navbarHeight = 0;
		}
	}
	calculateNavbar();

	function calculateHeaderCutoffs(table){
		table.querySelector('thead').style.webkitTransform = 'translate(0px,0px)';
		table.querySelector('thead').style.MozTransform = 'translate(0px,0px)';
		table.dataset.top = parseInt( $(table).children('thead').offset().top, 10 );
		table.dataset.bottom = parseInt( $(table).height() - $(tables[i]).children('thead').height() - $(tables[i]).children('tbody tr:last').height(), 10 );
	}

	function positionHeaders(table){
		var difference_top = scroll + navbarHeight - table.dataset.top;
		var thead = table.querySelector('thead');
		if(difference_top <= 0){
			thead.style.webkitTransform = 'translate(0px,0px)';
			thead.style.MozTransform = 'translate(0px,0px)';
		}
		if(difference_top > 0){
			if(table.id == 'schedule'){
				thead.style.webkitTransform = 'translate(0px,'+ (difference_top -1) +'px)';
				thead.style.MozTransform = 'translate(0px,'+ (difference_top -1)  +'px)';
			}else{
				thead.style.webkitTransform = 'translate(0px,'+ (difference_top - 10) +'px)';
				thead.style.MozTransform = 'translate(0px,'+ (difference_top -10) +'px)';
			}
		}
		if(difference_top > table.dataset.bottom){
			thead.style.webkitTransform = 'translate(0px,'+ table.dataset.bottom +'px)';
			thead.style.MozTransform = 'translate(0px,'+ table.dataset.bottom +'px)';
		}
	}

	for (i = 0; i < tables.length; i++) {
		calculateHeaderCutoffs(tables[i]);
		positionHeaders(tables[i]);
	}

	window.onscroll = function(){
		for (i = 0; i < tables.length; i++) {
			scroll = document.documentElement.scrollTop || document.body.scrollTop;
			positionHeaders(tables[i]);
		}
	};
	window.onresize = function(){
		calculateNavbar();
		for (i = 0; i < tables.length; i++) {
			calculateHeaderCutoffs(tables[i]);
			positionHeaders(tables[i]);
		}
	};
};

stickyHeader();
<|endoftext|>


<commit_before>const assert = require('assert');

describe('Array', () => {
  it('should return -1 when the value is not present', () => {
    assert.equal(false, [1, 2, 3].indexOf(4));
  });
});
<commit_msg>indexOf instead of includes<commit_after>const assert = require('assert');

describe('Array', () => {
  it('should return -1 when the value is not present', () => {
    assert.equal(-1, [1, 2, 3].indexOf(4));
  });
});
<|endoftext|>


<commit_before>'use strict'

const ActiveRules = require('../src/ActiveRules.js')
const sinon = require('sinon')

describe('Rule', () => {
  const AR = new ActiveRules()
  let rule = new AR.Rule()
  let conditionBase = factories.condition({
    fact: 'age',
    value: 50
  })

  describe('constructor()', () => {
    it('can be initialized with priority, conditions, and event', () => {
      let condition = {
        all: [ Object.assign({}, conditionBase) ]
      }
      condition.operator = 'all'
      condition.priority = 25
      let opts = {
        priority: 50,
        conditions: condition,
        event: {
          type: 'awesome'
        }
      }
      let rule = new AR.Rule(opts)
      expect(rule.priority).to.eql(opts.priority)
      expect(rule.conditions).to.eql(opts.conditions)
      expect(rule.event).to.eql(opts.event)
    })

    it('it can be initialized with a json string', () => {
      let condition = {
        all: [ Object.assign({}, conditionBase) ]
      }
      condition.operator = 'all'
      condition.priority = 25
      let opts = {
        priority: 50,
        conditions: condition,
        event: {
          type: 'awesome'
        }
      }
      let json = JSON.stringify(opts)
      let rule = new AR.Rule(json)
      expect(rule.priority).to.eql(opts.priority)
      expect(rule.conditions).to.eql(opts.conditions)
      expect(rule.event).to.eql(opts.event)
    })
  })

  describe('event emissions', () => {
    it('can emit', () => {
      let rule = new AR.Rule()
      let successSpy = sinon.spy()
      rule.on('test', successSpy)
      rule.emit('test')
      expect(successSpy.callCount).to.equal(1)
    })

    it('can be initialized with an onSuccess option', (done) => {
      let event = { type: 'test' }
      let onSuccess = function (e) {
        expect(e).to.equal(event)
        done()
      }
      let rule = new AR.Rule({ onSuccess })
      rule.emit('success', event)
    })

    it('can be initialized with an onFailure option', (done) => {
      let event = { type: 'test' }
      let onFailure = function (e) {
        expect(e).to.equal(event)
        done()
      }
      let rule = new AR.Rule({ onFailure })
      rule.emit('failure', event)
    })
  })

  describe('setEvent()', () => {
    it('throws if no argument provided', () => {
      expect(() => rule.setEvent()).to.throw(/Rule: setEvent\(\) requires event object/)
    })

    it('throws if argument is missing "type" property', () => {
      expect(() => rule.setEvent({})).to.throw(/Rule: setEvent\(\) requires event object with "type" property/)
    })
  })

  describe('setConditions()', () => {
    describe('validations', () => {
      it('throws an exception for invalid root conditions', () => {
        expect(rule.setConditions.bind(rule, { foo: true })).to.throw(/"conditions" root must contain a single instance of "all" or "any"/)
      })
    })
  })

  describe('setPriority', () => {
    it('defaults to a priority of 1', () => {
      expect(rule.priority).to.equal(1)
    })

    it('allows a priority to be set', () => {
      rule.setPriority(10)
      expect(rule.priority).to.equal(10)
    })

    it('errors if priority is less than 0', () => {
      expect(rule.setPriority.bind(null, 0)).to.throw(/greater than zero/)
    })
  })

  describe('priotizeConditions()', () => {
    let conditions = [{
      fact: 'age',
      operator: 'greaterThanInclusive',
      value: 18
    }, {
      fact: 'segment',
      operator: 'equal',
      value: 'human'
    }, {
      fact: 'accountType',
      operator: 'equal',
      value: 'admin'
    }, {
      fact: 'state',
      operator: 'equal',
      value: 'admin'
    }]

    it('orders based on priority', async () => {
      let engine = new AR.Engine()
      engine.addFact('state', async () => {}, { priority: 500 })
      engine.addFact('segment', async () => {}, { priority: 50 })
      engine.addFact('accountType', async () => {}, { priority: 25 })
      engine.addFact('age', async () => {}, { priority: 100 })
      let rule = new AR.Rule()
      rule.setEngine(engine)

      let prioritizedConditions = rule.prioritizeConditions(conditions)
      expect(prioritizedConditions.length).to.equal(4)
      expect(prioritizedConditions[0][0].fact).to.equal('state')
      expect(prioritizedConditions[1][0].fact).to.equal('age')
      expect(prioritizedConditions[2][0].fact).to.equal('segment')
      expect(prioritizedConditions[3][0].fact).to.equal('accountType')
    })
  })

  describe('evaluate()', () => {
    it('evalutes truthy when there are no conditions', async () => {
      let eventSpy = sinon.spy()
      let engine = new AR.Engine()
      let rule = new AR.Rule()
      rule.setConditions({
        all: []
      })
      engine.addRule(rule)
      engine.on('success', eventSpy)
      await engine.run()
      expect(eventSpy).to.have.been.calledOnce()
    })
  })

  describe('toJSON() and fromJSON()', () => {
    let priority = 50
    let event = {
      type: 'to-json!',
      params: { id: 1 }
    }
    let conditions = {
      priority: 1,
      all: [{
        value: 10,
        operator: 'equals',
        fact: 'user',
        params: {
          foo: true
        },
        path: '.id'
      }]
    }
    let rule
    beforeEach(() => {
      rule = new AR.Rule()
      rule.setConditions(conditions)
      rule.setPriority(priority)
      rule.setEvent(event)
    })

    it('serializes itself', () => {
      let json = rule.toJSON(false)
      expect(Object.keys(json).length).to.equal(3)
      expect(json.conditions).to.eql(conditions)
      expect(json.priority).to.eql(priority)
      expect(json.event).to.eql(event)
    })

    it('serializes itself as json', () => {
      let jsonString = rule.toJSON()
      expect(jsonString).to.be.a('string')
      let json = JSON.parse(jsonString)
      expect(Object.keys(json).length).to.equal(3)
      expect(json.conditions).to.eql(conditions)
      expect(json.priority).to.eql(priority)
      expect(json.event).to.eql(event)
    })

    it('rehydrates itself using a JSON string', () => {
      let jsonString = rule.toJSON()
      expect(jsonString).to.be.a('string')
      let hydratedRule = new AR.Rule(jsonString)
      expect(hydratedRule.conditions).to.eql(rule.conditions)
      expect(hydratedRule.priority).to.eql(rule.priority)
      expect(hydratedRule.event).to.eql(rule.event)
    })

    it('rehydrates itself using an object from JSON.parse()', () => {
      let jsonString = rule.toJSON()
      expect(jsonString).to.be.a('string')
      let json = JSON.parse(jsonString)
      let hydratedRule = new AR.Rule(json)
      expect(hydratedRule.conditions).to.eql(rule.conditions)
      expect(hydratedRule.priority).to.eql(rule.priority)
      expect(hydratedRule.event).to.eql(rule.event)
    })
  })
})
<commit_msg>use names from other project for test of those elements<commit_after><|endoftext|>


<commit_before>'use strict';

if (window.Quill === null) {
  window.alert("You must download quilljs! It needs to be in the same directory as y-richtext!");
}

var colors = ['rgb(0, 0, 0)', 'rgb(230, 0, 0)', 'rgb(255, 153, 0)',
  'rgb(255, 255, 0)', 'rgb(0, 138, 0)', 'rgb(0, 102, 204)',
  'rgb(153, 51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
  'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
  'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
  'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
  'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
  'rgb(136, 136, 136)', 'rgb(161, 0, 0)', 'rgb(178, 107, 0)',
  'rgb(178, 178, 0)', 'rgb(0, 97, 0)', 'rgb(0, 71, 178)',
  'rgb(107, 36, 178)', 'rgb(68, 68, 68)', 'rgb(92, 0, 0)',
  'rgb(102, 61, 0)', 'rgb(102, 102, 0)', 'rgb(0, 55, 0)',
  'rgb(0, 41, 102)', 'rgb(61, 20, 102)'];

// Fill the palette
$('.ql-color, .ql-background').each(function () {
  var i, generate;
  generate = function (what) {
    return '<option value="' + what + '" label="' + what + '"></option>';
  };
  for (i = 0; i < colors.length; i++) {
    $(this).append(generate(colors[i]));
  }
});
$('.ql-color option[label="rgb(255,255,255)"]').select();

var quill = new Quill('#editor', {
  modules: {
    'link-tooltip': true,
    'image-tooltip': true
  },
  theme: 'snow'
});
quill.addModule('toolbar', { container: '#toolbar' });
quill.addModule('multi-cursor', { timeout: 2500});
window.connector = new Y.WebRTC('thisIsMyRoom2');
//{url: 'http://localhost:8888'});

// connector.debug = true;
window.y = new Y(window.connector);

var checkConsistency = function () {
  var deltas = window.editor.getDelta(),
    quill_deltas = quill.getContents().ops,
    d,
    delta, name, quill_value, value, n;
  for (d in deltas) {
    delta = deltas[d];
    for (name in delta) {
      value = delta[name];
      quill_value = quill_deltas[d][name];
      if (value.constructor === Object) {
        for (n in value) {
          if (value[n] !== quill_value[n]) {
            return false;
          }
        }
      } else if (value !== quill_value) {
        return false;
      }
    }
  }
  return true;
};

var checkCursor = function () {
  var cursor, quill_cursor;
  cursor = window.editor.selfCursor.getPosition();
  quill_cursor = quill.getSelection().start;
  return cursor === quill_cursor;
};

quill.on("text-change", function () {
  window.setTimeout(function () {
    if (window.editor !== null && window.editor.getDelta !== null) {
      console.log("Quill & y-richtext are equal: " + checkConsistency());
    }
  }, 0);
});
quill.on("selection-change", function () {
  window.setTimeout(function () {
    if (window.editor !== null && window.editor.selfCursor !== null) {
      console.log("Quill & y-richtext are equal: " + checkCursor());
    }
  }, 0);
});

function fuzzy_cursor(n) {
  var i, m;
  for (i = 0; i < n; i++) {
    m = Math.floor(Math.random() * quill.getLength());
    quill.setSelection(m, m);
  }
}
function fuzzy_insert(n) {
  var N = 5, i, m, j, delta={}, some;
  for (var i = 0; i < n; i++) {
    m = Math.floor(Math.random() * quill.getLength());
    j = Math.floor(Math.random() * 2);
    delta = {};
    delta.ops = [{retain: m}];
    some = Math.min(
      Math.floor(Math.random() * (quill.getLength() - m)) +
      quill.getLength() - m,
      N);
    var randLetter = (Math.random().toString(36) + '00000000000000000')
      .slice(2, 2 + some);
    delta.ops.push({insert: randLetter});
    quill.setContents(delta);
  }
}

function fuzzy_all(n) {
  for (var i = 0; i < n; i++) {
    var which = Math.floor(Math.random() * 2);
    (which === 0) && fuzzy_cursor(1) || fuzzy_insert(1);
  }
}

// TODO: only for debugging
// y._model.HB.stopGarbageCollection();
// y._model.HB.setGarbageCollectTimeout(1500);

y.observe (function (events) {
  for (i in events) {
    if (events[i].name === 'editor') {
      y.val('editor').bind('QuillJs', quill);
      window.editor = y.val('editor');
    }
  }
});

connector.whenSynced(function(){
  if (y.val('editor') == null) {
    y.val('editor', new Y.RichText('QuillJs', quill));
  }
  y.val('editor').setAuthor($('#name').val());
});

$('#name')
  .click(function() {
    $(this).select();
  })
  .change(function() {
    window.editor.setAuthor({name: $(this).val()});
    // Change the background of the indicator
  });
$('#toolbar .author-color')
  .change(function(ev) {
    window.editor.setAuthor({color: ev.target.value});
    $('#name').css('color', ev.target.value);
    $(this).css('background', $(this).val());
  });
var cp = new ColorPicker($('#toolbar .author-color')[0]);

// Some CSS
$('#name-wrapper')
  .focusin(function() {
    $(this).css('border-bottom', '1px solid black');
  })
  .focusout(function() {
    $(this).css('border-bottom', '1px solid rgba(0,0,0,0)');
  });
// $('#name')
//     .focus(function() {
//         rgba = $(this).val();
//         $(this).parent().css(
//             {'border-bottom': '5px black'
//             });
//         $(this).siblings().find('.ql-picker-label').css(
//             {'background': rgba});
//     })
//     .blur(function() {
//         $(this).parent().css(
//             {'border-bottom' : '0'});
//     });
<commit_msg>Prevent nasty bugs from sneaking in :)<commit_after>'use strict';

if (window.Quill === null) {
  window.alert("You must download quilljs! It needs to be in the same directory as y-richtext!");
}

var colors = ['rgb(0, 0, 0)', 'rgb(230, 0, 0)', 'rgb(255, 153, 0)',
  'rgb(255, 255, 0)', 'rgb(0, 138, 0)', 'rgb(0, 102, 204)',
  'rgb(153, 51, 255)', 'rgb(255, 255, 255)', 'rgb(250, 204, 204)',
  'rgb(255, 235, 204)', 'rgb(255, 255, 204)', 'rgb(204, 232, 204)',
  'rgb(204, 224, 245)', 'rgb(235, 214, 255)', 'rgb(187, 187, 187)',
  'rgb(240, 102, 102)', 'rgb(255, 194, 102)', 'rgb(255, 255, 102)',
  'rgb(102, 185, 102)', 'rgb(102, 163, 224)', 'rgb(194, 133, 255)',
  'rgb(136, 136, 136)', 'rgb(161, 0, 0)', 'rgb(178, 107, 0)',
  'rgb(178, 178, 0)', 'rgb(0, 97, 0)', 'rgb(0, 71, 178)',
  'rgb(107, 36, 178)', 'rgb(68, 68, 68)', 'rgb(92, 0, 0)',
  'rgb(102, 61, 0)', 'rgb(102, 102, 0)', 'rgb(0, 55, 0)',
  'rgb(0, 41, 102)', 'rgb(61, 20, 102)'];

// Fill the palette
$('.ql-color, .ql-background').each(function () {
  var i, generate;
  generate = function (what) {
    return '<option value="' + what + '" label="' + what + '"></option>';
  };
  for (i = 0; i < colors.length; i++) {
    $(this).append(generate(colors[i]));
  }
});
$('.ql-color option[label="rgb(255,255,255)"]').select();

var quill = new Quill('#editor', {
  modules: {
    'link-tooltip': true,
    'image-tooltip': true
  },
  theme: 'snow'
});
quill.addModule('toolbar', { container: '#toolbar' });
quill.addModule('multi-cursor', { timeout: 2500});
window.connector = new Y.WebRTC('thisIsMyRoom2');
//{url: 'http://localhost:8888'});

// connector.debug = true;
window.y = new Y(window.connector);

var checkConsistency = function () {
  var deltas = window.editor.getDelta(),
    quill_deltas = quill.getContents().ops,
    d,
    delta, name, quill_value, value, n;
  for (d in deltas) {
    delta = deltas[d];
    for (name in delta) {
      value = delta[name];
      quill_value = quill_deltas[d][name];
      if (value.constructor === Object) {
        for (n in value) {
          if (value[n] !== quill_value[n]) {
            return false;
          }
        }
      } else if (value !== quill_value) {
        return false;
      }
    }
  }
  return true;
};

var checkCursor = function () {
  var cursor, quill_cursor, sel;
  cursor = window.editor.selfCursor.getPosition();
  sel = quill.getSelection();
  if (sel !== null && sel.start !== undefined) {
    quill_cursor = sel.start;
    return cursor === quill_cursor;
  }
  else {
    return true;
  }
};

quill.on("text-change", function () {
  window.setTimeout(function () {
    if (window.editor !== null && window.editor.getDelta !== null) {
      console.log("Quill & y-richtext are equal: " + checkConsistency());
    }
  }, 0);
});
quill.on("selection-change", function () {
  window.setTimeout(function () {
    if (window.editor !== null && window.editor.selfCursor !== null) {
      console.log("Quill & y-richtext are equal: " + checkCursor());
    }
  }, 0);
});

function fuzzy_cursor(n) {
  var i, m;
  for (i = 0; i < n; i++) {
    m = Math.floor(Math.random() * quill.getLength());
    quill.setSelection(m, m);
  }
}
function fuzzy_insert(n) {
  var N = 5, i, m, j, delta={}, some;
  for (var i = 0; i < n; i++) {
    m = Math.floor(Math.random() * quill.getLength());
    j = Math.floor(Math.random() * 2);
    delta = {};
    delta.ops = [{retain: m}];
    some = Math.min(
      Math.floor(Math.random() * (quill.getLength() - m)) +
      quill.getLength() - m,
      N);
    var randLetter = (Math.random().toString(36) + '00000000000000000')
      .slice(2, 2 + some);
    delta.ops.push({insert: randLetter});
    quill.setContents(delta);
  }
}

function fuzzy_all(n) {
  for (var i = 0; i < n; i++) {
    var which = Math.floor(Math.random() * 2);
    (which === 0) && fuzzy_cursor(1) || fuzzy_insert(1);
  }
}

// TODO: only for debugging
// y._model.HB.stopGarbageCollection();
// y._model.HB.setGarbageCollectTimeout(1500);

y.observe (function (events) {
  var i;
  for (i in events) {
    if (events[i].name === 'editor') {
      y.val('editor').bind('QuillJs', quill);
      window.editor = y.val('editor');
    }
  }
});

connector.whenSynced(function(){
  if (y.val('editor') == null) {
    y.val('editor', new Y.RichText('QuillJs', quill));
  }
  y.val('editor').setAuthor($('#name').val());
});

$('#name')
  .click(function() {
    $(this).select();
  })
  .change(function() {
    window.editor.setAuthor({name: $(this).val()});
    // Change the background of the indicator
  });
$('#toolbar .author-color')
  .change(function(ev) {
    window.editor.setAuthor({color: ev.target.value});
    $('#name').css('color', ev.target.value);
    $(this).css('background', $(this).val());
  });
var cp = new ColorPicker($('#toolbar .author-color')[0]);

// Some CSS
$('#name-wrapper')
  .focusin(function() {
    $(this).css('border-bottom', '1px solid black');
  })
  .focusout(function() {
    $(this).css('border-bottom', '1px solid rgba(0,0,0,0)');
  });
// $('#name')
//     .focus(function() {
//         rgba = $(this).val();
//         $(this).parent().css(
//             {'border-bottom': '5px black'
//             });
//         $(this).siblings().find('.ql-picker-label').css(
//             {'background': rgba});
//     })
//     .blur(function() {
//         $(this).parent().css(
//             {'border-bottom' : '0'});
//     });
<|endoftext|>


<commit_before>const events = require('events');
const http = require('http');
const stream = require('stream');
const util = require('util');
const ws = require('ws');

const debug = util.debuglog('rdbg');

function Client() {
  events.EventEmitter.call(this);

  this._socket = null;

  this._callbacks = {};
  this._commands = {};
  this._counter = 0;

  this._console = new stream.Readable({ objectMode: true });
  this._console._read = function() { };
}

util.inherits(Client, events.EventEmitter);

Object.defineProperty(Client.prototype, 'socket', {
  get: function() {
    return this._socket;
  },
});

Object.defineProperty(Client.prototype, 'console', {
  get: function() {
    return this._console;
  },
});

Client.prototype.request = function(method, params, id, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = undefined;
  } else if (typeof id === 'function') {
    callback = id;
    id = undefined;
  }

  if (params === undefined) {
    params = {};
  }

  if (id === undefined) {
    id = this._counter++;
  }

  var request = {
    id: id,
    method: method,
    params: params
  };

  debug('request %s', util.inspect(request));
  this.emit('request', request);
  this._socket.send(JSON.stringify(request));

  this._callbacks[id] = callback;
  this._commands[id] = request;
};

Client.prototype.connect = function(target, callback) {
  if (typeof target === 'object') {
    target = target.webSocketDebuggerUrl;
  }

  if (callback) {
    this.on('connect', callback);
  }

  var socket = ws.connect(target);
  socket.on('open', function() {
    debug('connect');
    this.emit('connect');
  }.bind(this));

  socket.on('close', function() {
    debug('close');
    self.emit('close');
  }.bind(this));

  socket.on('error', function(error) {
    debug('error %s', util.inspect(error));
    self.emit('error', error);
  }.bind(this));

  socket.on('message', function(data) {
    try {
      var message = JSON.parse(data);

      if (message.id) {
        var command = this._commands[message.id];
        var callback = this._callbacks[message.id];

        debug('response %s, %s', util.inspect(command), util.inspect(message));
        this.emit('response', command, message);

        if (callback) {
          if (message.error) {
            callback(message.error);
          } else if (message.result) {
            callback(null, message.result);
          }

          delete this._callbacks[message.id];
        }

        delete this._commands[message.id];

        if (Object.keys(this._commands).length === 0) {
          this.emit('ready');
        }
      } else {
        this.emit('message', message);
        if (message.method === 'Console.messageAdded') {
          this._console.push(message.params.message);
        }

        if (message.method === 'Debugger.scriptParsed') {
          this._scripts = this._scripts.filter(function(script) {
            return message.params.url !== script.url;
          });

          this._scripts.push(message.params);
          this.emit('scriptParse', message.params);
        }
      }
    } catch (error) {
      this.emit('error', error);
    }
  }.bind(this));

  this._socket = socket;

  debug('socket');
  this.emit('socket');
};

Client.prototype.close = function() {
  if (this._socket) {
    this._socket.close();
  }
};

module.exports.Client = Client;

function createClient() {
  var client = new Client();
  return client;
}

module.exports.createClient = createClient;

function connect(target, callback) {
  var client = createClient();
  client.connect(target, callback);

  return client;
}

module.exports.connect = connect;

function get(port, host, callback) {
  if (typeof host === 'function') {
    callback = host;
    host = 'localhost';
  }

  var request = http.get({
    port: port,
    host: host,
    path: '/json'
  });

  request.on('response', function(response) {
    var body = '';

    response.on('data', function(chunk) {
      body += chunk;
    });

    response.on('end', function() {
      try {
        var targets = JSON.parse(body);
        return callback(null, targets);
      } catch (error) {
        return callback(error);
      }
    });
  });

  request.on('error', function(error) {
    return callback(error);
  });
};

module.exports.get = get;
<commit_msg>Reset socket to null on connection close<commit_after>const events = require('events');
const http = require('http');
const stream = require('stream');
const util = require('util');
const ws = require('ws');

const debug = util.debuglog('rdbg');

function Client() {
  events.EventEmitter.call(this);

  this._socket = null;

  this._callbacks = {};
  this._commands = {};
  this._counter = 0;

  this._console = new stream.Readable({ objectMode: true });
  this._console._read = function() { };
}

util.inherits(Client, events.EventEmitter);

Object.defineProperty(Client.prototype, 'socket', {
  get: function() {
    return this._socket;
  },
});

Object.defineProperty(Client.prototype, 'console', {
  get: function() {
    return this._console;
  },
});

Client.prototype.request = function(method, params, id, callback) {
  if (typeof params === 'function') {
    callback = params;
    params = undefined;
  } else if (typeof id === 'function') {
    callback = id;
    id = undefined;
  }

  if (params === undefined) {
    params = {};
  }

  if (id === undefined) {
    id = this._counter++;
  }

  var request = {
    id: id,
    method: method,
    params: params
  };

  debug('request %s', util.inspect(request));
  this.emit('request', request);
  this._socket.send(JSON.stringify(request));

  this._callbacks[id] = callback;
  this._commands[id] = request;
};

Client.prototype.connect = function(target, callback) {
  if (typeof target === 'object') {
    target = target.webSocketDebuggerUrl;
  }

  if (callback) {
    this.on('connect', callback);
  }

  var socket = ws.connect(target);
  socket.on('open', function() {
    debug('connect');
    this.emit('connect');
  }.bind(this));

  socket.on('close', function() {
    debug('close');
    self.emit('close');
    self._socket = null;
  }.bind(this));

  socket.on('error', function(error) {
    debug('error %s', util.inspect(error));
    self.emit('error', error);
  }.bind(this));

  socket.on('message', function(data) {
    try {
      var message = JSON.parse(data);

      if (message.id) {
        var command = this._commands[message.id];
        var callback = this._callbacks[message.id];

        debug('response %s, %s', util.inspect(command), util.inspect(message));
        this.emit('response', command, message);

        if (callback) {
          if (message.error) {
            callback(message.error);
          } else if (message.result) {
            callback(null, message.result);
          }

          delete this._callbacks[message.id];
        }

        delete this._commands[message.id];

        if (Object.keys(this._commands).length === 0) {
          this.emit('ready');
        }
      } else {
        this.emit('message', message);
        if (message.method === 'Console.messageAdded') {
          this._console.push(message.params.message);
        }

        if (message.method === 'Debugger.scriptParsed') {
          this._scripts = this._scripts.filter(function(script) {
            return message.params.url !== script.url;
          });

          this._scripts.push(message.params);
          this.emit('scriptParse', message.params);
        }
      }
    } catch (error) {
      this.emit('error', error);
    }
  }.bind(this));

  this._socket = socket;

  debug('socket');
  this.emit('socket');
};

Client.prototype.close = function() {
  if (this._socket) {
    this._socket.close();
  }
};

module.exports.Client = Client;

function createClient() {
  var client = new Client();
  return client;
}

module.exports.createClient = createClient;

function connect(target, callback) {
  var client = createClient();
  client.connect(target, callback);

  return client;
}

module.exports.connect = connect;

function get(port, host, callback) {
  if (typeof host === 'function') {
    callback = host;
    host = 'localhost';
  }

  var request = http.get({
    port: port,
    host: host,
    path: '/json'
  });

  request.on('response', function(response) {
    var body = '';

    response.on('data', function(chunk) {
      body += chunk;
    });

    response.on('end', function() {
      try {
        var targets = JSON.parse(body);
        return callback(null, targets);
      } catch (error) {
        return callback(error);
      }
    });
  });

  request.on('error', function(error) {
    return callback(error);
  });
};

module.exports.get = get;
<|endoftext|>


<commit_before>'use strict';

// Declare app level module with routes
var app = angular.module('fabLab', [], function($routeProvider) {
    $routeProvider.when('/',
        {
            templateUrl: 'partials/main.html',
            controller: MainCtrl
        });
        $routeProvider.when('/about',
            {
                templateUrl: 'partials/about.html'
            });
        $routeProvider.when('/:machine',
            {
                templateUrl: 'partials/details.html',
                controller: MachineCtrl
            });
        $routeProvider.otherwise({
            redirectTo: '/'
        });
});<commit_msg>Added a "draggable" and "droppable" directive makeing use of jQueryUI and its draggable and droppable feature for the machine specific pages<commit_after>'use strict';

// Declare app level module with routes
var app = angular.module('fabLab', [], function($routeProvider) {
    $routeProvider.when('/',
        {
            templateUrl: 'partials/main.html',
            controller: MainCtrl
        });
        $routeProvider.when('/about',
            {
                templateUrl: 'partials/about.html'
            });
        $routeProvider.when('/:machine',
            {
                templateUrl: 'partials/details.html',
                controller: MachineCtrl
            });
        $routeProvider.otherwise({
            redirectTo: '/'
        });
}).directive('draggable', function() {
    return {
        restrict: 'A',
        link: function(scope, elm, attrs) {
            var vars = scope.$eval(attrs.draggable),
                options = {
                    addClass: false,
                    cursorAt: { left: 17, top: 17 },
                    revert: true,
                    zIndex: 900,
                    scope: vars.scope,
                    helper: function(event) {
                        return $('
'+ vars.helper.letter + '
');
                    },
                    start: function(event, ui) {
                        var self = $(this);
                        if (self.hasClass('ui-state-disabled')) {
                            self.draggable({ disabled: true });
                        } else {
                            self.addClass('ui-state-disabled');
                        }
                    },
                    stop: function(evenr, ui) {
                        var self = $(this);
                        if (self.hasClass('ui-state-disabled')) {
                            self.draggable({ disabled: false });
                            self.removeClass('ui-state-disabled');
                        }
                    }
                };

            elm.draggable(options);
            console.log('draggable:', options);
        }
    };
}).directive('droppable', function() {
    return {
        restrict: 'A',
        link: function(scope, elm, attrs) {
            var vars = scope.$eval(attrs.droppable),
                options = {
                    hoverClass: 'ui-state-hover',
                    scope: vars.scope
                };

            elm.droppable(options);
            console.log('droppable:', options);
        }
    };
});<|endoftext|>


<commit_before>/*
    倒计时 v1.0
    BY:le

	输出格式说明：月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
*/
	(function($) {
		$.fn.countdown = function (parameter,getApi) {
			if(typeof parameter == 'function'){ //重载
	            getApi = parameter;
	            parameter = {};
	        }else{
	            parameter = parameter || {};
	            getApi = getApi||function(){};
	        }
			return this.each(function (i) {
				var $this = $(this);
				var defaults = {
					'format': 'hh:mm:ss',					//格式
					'starttime': $this.text(),				//开始时间
					'endtime': '',							//结束时间
					'duration': 1000,							//多久倒计时一次 单位：ms
					'disableBtnCls':'disable',
					'auto':true,							//是否默认自动计数
					'countEach': function (time) {			//每单位时间出发事件
						$this.text(time);
					},
					'countEnd':function (time) {			//倒计时结束回调事件
						$this.text(time);
					}
				};
				var options = $.extend({}, defaults, parameter);
				var _api = {};              //对外的函数接口
				var _hander = null;
				var _start=0,_end=0;
				var isTimestamp = isNaN(options.starttime);//是否为秒计数模式
				var count = function(){
					if(_hander){
						clearInterval(_hander);
					}
					options.countEach(isTimestamp?timeFormat(options.format,_start):_start/1e3);
					$this.addClass(options.disableBtnCls);
					_hander = setInterval(function(){
						_start -= options.duration;
						if(_start<=_end){
							clearInterval(_hander);
							options.countEnd(isTimestamp?timeFormat(options.format,_end):_end/1e3);
							$this.removeClass(options.disableBtnCls);
						}else{
							options.countEach(isTimestamp?timeFormat(options.format,_start):_start/1e3);
						}
					},options.duration);
				};
				_api.reset = function(){
					if(isTimestamp){
						_start = getTimestamp(options.starttime);
						_end = getTimestamp(options.endtime);
					}else{
						_start = options.starttime*1e3;
						_end = options.endtime*1e3;
					}
					count();
				};
				_api.setStarttime = function(start){
					isTimestamp = isNaN(start);
					if(isTimestamp){
						_start = getTimestamp(start);
					}else{
						_start = start*1e3;
					}
					count();
				};
				_api.setEndtime = function(end){
					isTimestamp = isNaN(end);
					if(isTimestamp){
						_end = getTimestamp(end);
					}else{
						_end = end*1e3;
					}
					count();
				};
				//初始化
				if(options.auto){
					_api.reset();
				}
	            getApi(_api);
			});
			function getTimestamp(str){
				return +new Date(str)||+new Date('1970/1/1 '+str);
			}
			function timeFormat(fmt,timestamp){
				var date = new Date(timestamp);
				var o = {
					"M+" : date.getMonth()+1,                 //月份
					"d+" : date.getDate(),                    //日
					"h+" : date.getHours(),                   //小时
					"m+" : date.getMinutes(),                 //分
					"s+" : date.getSeconds(),                 //秒
					"q+" : Math.floor((date.getMonth()+3)/3), //季度
					"S"  : date.getMilliseconds()             //毫秒
				};
				if(/(y+)/.test(fmt)){
					fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
				}
				for(var k in o){
					if(new RegExp("("+ k +")").test(fmt)){
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
					}
				}
				return fmt;
			}
		}
	})(jQuery);<commit_msg>变量规范化<commit_after>/*
    倒计时 v1.0
    BY:le

	输出格式说明：月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
*/
	(function($) {
		$.fn.countdown = function (parameter,getApi) {
			if(typeof parameter == 'function'){ //重载
	            getApi = parameter;
	            parameter = {};
	        }else{
	            parameter = parameter || {};
	            getApi = getApi||function(){};
	        }
			return this.each(function (i) {
				var $this = $(this);
				var defaults = {
					'format': 'hh:mm:ss',					//格式
					'starttime': $this.text(),				//开始时间
					'endtime': '',							//结束时间
					'interval': 1000,							//多久倒计时一次 单位：ms
					'disableBtnCls':'disable',
					'auto':true,							//是否默认自动计数
					'countEach': function (time) {			//每单位时间出发事件
						$this.text(time);
					},
					'countEnd':function (time) {			//倒计时结束回调事件
						$this.text(time);
					}
				};
				var options = $.extend({}, defaults, parameter);
				var _api = {};              //对外的函数接口
				var _hander = null;
				var _start=0,_end=0;
				var isTimestamp = isNaN(options.starttime);//是否为秒计数模式
				var count = function(){
					if(_hander){
						clearInterval(_hander);
					}
					options.countEach(isTimestamp?timeFormat(options.format,_start):_start/1e3);
					$this.addClass(options.disableBtnCls);
					_hander = setInterval(function(){
						_start -= options.duration;
						if(_start<=_end){
							clearInterval(_hander);
							options.countEnd(isTimestamp?timeFormat(options.format,_end):_end/1e3);
							$this.removeClass(options.disableBtnCls);
						}else{
							options.countEach(isTimestamp?timeFormat(options.format,_start):_start/1e3);
						}
					},options.interval);
				};
				_api.reset = function(){
					if(isTimestamp){
						_start = getTimestamp(options.starttime);
						_end = getTimestamp(options.endtime);
					}else{
						_start = options.starttime*1e3;
						_end = options.endtime*1e3;
					}
					count();
				};
				_api.setStarttime = function(start){
					isTimestamp = isNaN(start);
					if(isTimestamp){
						_start = getTimestamp(start);
					}else{
						_start = start*1e3;
					}
					count();
				};
				_api.setEndtime = function(end){
					isTimestamp = isNaN(end);
					if(isTimestamp){
						_end = getTimestamp(end);
					}else{
						_end = end*1e3;
					}
					count();
				};
				//初始化
				if(options.auto){
					_api.reset();
				}
	            getApi(_api);
			});
			function getTimestamp(str){
				return +new Date(str)||+new Date('1970/1/1 '+str);
			}
			function timeFormat(fmt,timestamp){
				var date = new Date(timestamp);
				var o = {
					"M+" : date.getMonth()+1,                 //月份
					"d+" : date.getDate(),                    //日
					"h+" : date.getHours(),                   //小时
					"m+" : date.getMinutes(),                 //分
					"s+" : date.getSeconds(),                 //秒
					"q+" : Math.floor((date.getMonth()+3)/3), //季度
					"S"  : date.getMilliseconds()             //毫秒
				};
				if(/(y+)/.test(fmt)){
					fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
				}
				for(var k in o){
					if(new RegExp("("+ k +")").test(fmt)){
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
					}
				}
				return fmt;
			}
		}
	})(jQuery);<|endoftext|>


<commit_before>'use strict'

const nock = require('nock')
const HOST = 'http://osapi.dmm.com'
const SECURITY_TOKEN_PATTERN = /^[a-zA-Z0-9/=+]{220}$/
const DONT_BE_EVIL = 'throw 1; < don\'t be evil\' >'

nock(HOST)
.post('/gadgets/makeRequest', {
  url: 'http://www.example.com',
  st: SECURITY_TOKEN_PATTERN,
  authz: 'signed',
  signOwner: 'true'
})
.reply(200, DONT_BE_EVIL + `{"http:\/\/www.example.com":{"rc":200,"body":"<!doctype html>\n\n\n    <title>Example Domain<\/title>\n\n    <meta charset=\"utf-8\" \/>\n    <meta http-equiv=\"Content-type\" content=\"text\/html; charset=utf-8\" \/>\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" \/>\n