<commit_before>// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */

import React from 'react';
import { shallow, mount } from 'enzyme';
import chai from 'chai';
import sinon from 'sinon';

import Form from '../Form';

const expect = chai.expect;

/* eslint-disable no-unused-vars */
const debug = (component) => {
    console.info('------------------------------------------------------------');
    console.info(component.debug());
    console.info('------------------------------------------------------------');
};
/* eslint-enable no-unused-vars */

/* *****************************************************************************
a Form component containing a RadioButtonGroup
    should include a <Form.RadioButtonGroup> as a child
    should include a label if the label prop is set
    should not include a label if the label prop is not set
    should include a div.radio for each option
    should include a label for each option
    should include a span containing the option name for each option
    should include an input[type="radio"] for each option
    should select the first item if the value prop is not set
    should select the first item if the value prop is invalid
    should select the appropriate item if the value prop is set to a valid value
    should have a label.col-xs-3 when form is horizontal and labelColumns=3
    should have a div.col-xs-9 when form is horizontal and labelColumns=3
    should include the disabled flag on input elements when disabled is set
    should not include the disabled flag on input elements when disabled is not set
*/
describe('a Form component containing a RadioButtonGroup', () => {

    const options = [
        { value: '1', name: 'One' },
        { value: '2', name: 'Two' },
        { value: '3', name: 'Three' },
    ];

    it('should include a <Form.RadioButtonGroup> as a child', () => {
        const component = shallow(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find(Form.RadioButtonGroup)).to.have.length(1);
    });

    it('should include a label if the label prop is set', () => {

        const label = 'fee fi fo fum';

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} />
            </Form>
        );

        expect(component.find('label.control-label')).to.have.length(1);
        expect(component.find('label.control-label').text()).to.equal(label);
    });

    it('should not include a label if the label prop is not set', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('label.control-label')).to.have.length(0);
    });

    it('should include a div.radio for each option', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('div.radio')).to.have.length(options.length);
    });

    it('should include a label for each option', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('div.radio label')).to.have.length(options.length);
    });

    it('should include a span containing the option name for each option', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('div.radio span')).to.have.length(options.length);
        expect(component.find('div.radio span').at(0).text()).to.equal(options[0].name);
        expect(component.find('div.radio span').at(1).text()).to.equal(options[1].name);
        expect(component.find('div.radio span').at(2).text()).to.equal(options[2].name);
    });

    it('should include an input[type="radio"] for each option', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().value)
            .to.equal(options[0].value);
        expect(component.find('div.radio input[type="radio"]').at(1).props().value)
            .to.equal(options[1].value);
        expect(component.find('div.radio input[type="radio"]').at(2).props().value)
            .to.equal(options[2].value);
    });

    it('should select the first item if the value prop is not set', () => {

        const label = 'peter piper';

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(true);
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(false);
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false);
    });

    it('should select the first item if the value prop is invalid', () => {

        const label = 'peter piper';

        const value = 'not valid';

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(true);
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(false);
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false);
    });

    it('should select the appropriate item if the value prop is set to a valid value', () => {

        const label = 'peter piper';

        const value = 2;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(false);
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(true);
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false);
    });

    it('should have a label.col-xs-3 when form is horizontal and labelColumns=3', () => {

        const label = 'peter piper';
        const columns = 3;

        const value = 2;

        const component = mount(
            <Form horizontal labelColumns={columns}>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.form-horizontal')).to.have.length(1, 'form-horizontal');
        expect(component.find('label.control-label').props().className)
            .to.contain('col-xs-3', 'col-xs-3');
    });

    it('should have a div.col-xs-9 when form is horizontal and labelColumns=3', () => {

        const label = 'peter piper';
        const columns = 3;

        const value = 2;

        const component = mount(
            <Form horizontal labelColumns={columns}>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.form-horizontal')).to.have.length(1, 'form-horizontal');
        expect(component.find('div.form-radiobuttongroup-input-columns').props().className)
            .to.contain('col-xs-9', 'col-xs-9');
    });

});

/* *****************************************************************************
when a radio button in the group is clicked
    the onChange handler should be called if a new value is clicked
    the onChange handler should not be called if the same value is clicked
    the new value should be selected and all others should not be selected
*/
describe('when a radio button in the group is clicked', () => {

    const options = [
        { value: '1', name: 'One' },
        { value: '2', name: 'Two' },
        { value: '3', name: 'Three' },
    ];

    it('the onChange handler should be called if a new value is clicked', () => {

        const onChange = sinon.spy();

        const label = 'little miss muffet';

        const value = '1';

        const clickedItem = 2;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup
                    label={label}
                    options={options}
                    value={value}
                    onChange={onChange}
                />
            </Form>
        );

        expect(onChange.callCount).to.equal(0);

        component.find('div.radio input[type="radio"]').at(1).simulate('change', {
            target: { value: options[clickedItem].value }
        });

        expect(onChange.callCount).to.equal(1);
        expect(onChange.calledWith(options[clickedItem].value)).to.equal(true);
    });

    it('the onChange handler should not be called if the same value is clicked', () => {

        const onChange = sinon.spy();

        const label = 'little miss muffet';

        const value = '1';

        const clickedItem = 0;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup
                    label={label}
                    options={options}
                    value={value}
                    onChange={onChange}
                />
            </Form>
        );

        expect(onChange.callCount).to.equal(0);

        component.find('div.radio input[type="radio"]').at(1).simulate('change', {
            target: { value: options[clickedItem].value }
        });

        expect(onChange.callCount).to.equal(0);
    });

    it('the new value should be selected and all others should not be selected', () => {

        const label = 'little miss muffet';

        const value = '1';

        const clickedItem = 1;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(true, 'before - 0');
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(false, 'before - 1');
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false, 'before - 2');

        component.find('div.radio input[type="radio"]').at(1).simulate('change', {
            target: { value: options[clickedItem].value }
        });

        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(false, 'after - 0');
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(true, 'after - 1');
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false, 'after - 2');
    });

});
<commit_msg>added specs for disabled flag<commit_after>// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */

import React from 'react';
import { shallow, mount } from 'enzyme';
import chai from 'chai';
import sinon from 'sinon';

import Form from '../Form';

const expect = chai.expect;

/* eslint-disable no-unused-vars */
const debug = (component) => {
    console.info('------------------------------------------------------------');
    console.info(component.debug());
    console.info('------------------------------------------------------------');
};
/* eslint-enable no-unused-vars */

/* *****************************************************************************
a Form component containing a RadioButtonGroup
    should include a <Form.RadioButtonGroup> as a child
    should include a label if the label prop is set
    should not include a label if the label prop is not set
    should include a div.radio for each option
    should include a label for each option
    should include a span containing the option name for each option
    should include an input[type="radio"] for each option
    should select the first item if the value prop is not set
    should select the first item if the value prop is invalid
    should select the appropriate item if the value prop is set to a valid value
    should have a label.col-xs-3 when form is horizontal and labelColumns=3
    should have a div.col-xs-9 when form is horizontal and labelColumns=3
    should include the disabled flag on input elements when disabled is set
    should not include the disabled flag on input elements when disabled is not set
*/
describe('a Form component containing a RadioButtonGroup', () => {

    const options = [
        { value: '1', name: 'One' },
        { value: '2', name: 'Two' },
        { value: '3', name: 'Three' },
    ];

    it('should include a <Form.RadioButtonGroup> as a child', () => {
        const component = shallow(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find(Form.RadioButtonGroup)).to.have.length(1);
    });

    it('should include a label if the label prop is set', () => {

        const label = 'fee fi fo fum';

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} />
            </Form>
        );

        expect(component.find('label.control-label')).to.have.length(1);
        expect(component.find('label.control-label').text()).to.equal(label);
    });

    it('should not include a label if the label prop is not set', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('label.control-label')).to.have.length(0);
    });

    it('should include a div.radio for each option', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('div.radio')).to.have.length(options.length);
    });

    it('should include a label for each option', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('div.radio label')).to.have.length(options.length);
    });

    it('should include a span containing the option name for each option', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('div.radio span')).to.have.length(options.length);
        expect(component.find('div.radio span').at(0).text()).to.equal(options[0].name);
        expect(component.find('div.radio span').at(1).text()).to.equal(options[1].name);
        expect(component.find('div.radio span').at(2).text()).to.equal(options[2].name);
    });

    it('should include an input[type="radio"] for each option', () => {

        const component = mount(
            <Form>
                <Form.RadioButtonGroup options={options} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().value)
            .to.equal(options[0].value);
        expect(component.find('div.radio input[type="radio"]').at(1).props().value)
            .to.equal(options[1].value);
        expect(component.find('div.radio input[type="radio"]').at(2).props().value)
            .to.equal(options[2].value);
    });

    it('should select the first item if the value prop is not set', () => {

        const label = 'peter piper';

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(true);
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(false);
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false);
    });

    it('should select the first item if the value prop is invalid', () => {

        const label = 'peter piper';

        const value = 'not valid';

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(true);
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(false);
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false);
    });

    it('should select the appropriate item if the value prop is set to a valid value', () => {

        const label = 'peter piper';

        const value = 2;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(false);
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(true);
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false);
    });

    it('should have a label.col-xs-3 when form is horizontal and labelColumns=3', () => {

        const label = 'peter piper';
        const columns = 3;

        const value = 2;

        const component = mount(
            <Form horizontal labelColumns={columns}>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.form-horizontal')).to.have.length(1, 'form-horizontal');
        expect(component.find('label.control-label').props().className)
            .to.contain('col-xs-3', 'col-xs-3');
    });

    it('should have a div.col-xs-9 when form is horizontal and labelColumns=3', () => {

        const label = 'peter piper';
        const columns = 3;

        const value = 2;

        const component = mount(
            <Form horizontal labelColumns={columns}>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.form-horizontal')).to.have.length(1, 'form-horizontal');
        expect(component.find('div.form-radiobuttongroup-input-columns').props().className)
            .to.contain('col-xs-9', 'col-xs-9');
    });

    it('should include the disabled flag on input elements when disabled is set', () => {

        const disabled = true;

        const label = 'peter piper';

        const value = 2;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup disabled={disabled} label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().disabled)
            .to.equal(disabled);
        expect(component.find('div.radio input[type="radio"]').at(1).props().disabled)
            .to.equal(disabled);
        expect(component.find('div.radio input[type="radio"]').at(2).props().disabled)
            .to.equal(disabled);
    });

    it('should not include the disabled flag on input elements when disabled is not set', () => {

        const disabled = false;

        const label = 'peter piper';

        const value = 2;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup disabled={disabled} label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().disabled)
            .to.equal(disabled);
        expect(component.find('div.radio input[type="radio"]').at(1).props().disabled)
            .to.equal(disabled);
        expect(component.find('div.radio input[type="radio"]').at(2).props().disabled)
            .to.equal(disabled);
    });

});

/* *****************************************************************************
when a radio button in the group is clicked
    the onChange handler should be called if a new value is clicked
    the onChange handler should not be called if the same value is clicked
    the new value should be selected and all others should not be selected
*/
describe('when a radio button in the group is clicked', () => {

    const options = [
        { value: '1', name: 'One' },
        { value: '2', name: 'Two' },
        { value: '3', name: 'Three' },
    ];

    it('the onChange handler should be called if a new value is clicked', () => {

        const onChange = sinon.spy();

        const label = 'little miss muffet';

        const value = '1';

        const clickedItem = 2;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup
                    label={label}
                    options={options}
                    value={value}
                    onChange={onChange}
                />
            </Form>
        );

        expect(onChange.callCount).to.equal(0);

        component.find('div.radio input[type="radio"]').at(1).simulate('change', {
            target: { value: options[clickedItem].value }
        });

        expect(onChange.callCount).to.equal(1);
        expect(onChange.calledWith(options[clickedItem].value)).to.equal(true);
    });

    it('the onChange handler should not be called if the same value is clicked', () => {

        const onChange = sinon.spy();

        const label = 'little miss muffet';

        const value = '1';

        const clickedItem = 0;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup
                    label={label}
                    options={options}
                    value={value}
                    onChange={onChange}
                />
            </Form>
        );

        expect(onChange.callCount).to.equal(0);

        component.find('div.radio input[type="radio"]').at(1).simulate('change', {
            target: { value: options[clickedItem].value }
        });

        expect(onChange.callCount).to.equal(0);
    });

    it('the new value should be selected and all others should not be selected', () => {

        const label = 'little miss muffet';

        const value = '1';

        const clickedItem = 1;

        const component = mount(
            <Form>
                <Form.RadioButtonGroup label={label} options={options} value={value} />
            </Form>
        );

        expect(component.find('div.radio input[type="radio"]')).to.have.length(options.length);
        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(true, 'before - 0');
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(false, 'before - 1');
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false, 'before - 2');

        component.find('div.radio input[type="radio"]').at(1).simulate('change', {
            target: { value: options[clickedItem].value }
        });

        expect(component.find('div.radio input[type="radio"]').at(0).props().checked)
            .to.equal(false, 'after - 0');
        expect(component.find('div.radio input[type="radio"]').at(1).props().checked)
            .to.equal(true, 'after - 1');
        expect(component.find('div.radio input[type="radio"]').at(2).props().checked)
            .to.equal(false, 'after - 2');
    });

});
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { contextTypes } from '../../utils/decorators/withContext.js';
import { connect } from 'react-redux';

import PlayerModel from '../../models/PlayerModel.js';

import AutoComplete from 'material-ui/lib/auto-complete';
import MenuItem from 'material-ui/lib/menus/menu-item';

@connect(state => {
  return {
    players: state.players,
  };
})
export default class PlayerAutoComplete extends Component {
  static contextTypes = contextTypes;
  static propTypes = {
    players: ImmutablePropTypes.listOf(PropTypes.instanceOf(PlayerModel).isRequired).isRequired,
    selectPlayer: PropTypes.func.isRequired,
  }

  _onPlayerSelected(text) {
    if (text) {
      var matchedPlayers = this.props.players.filter(ply => ply.alias.toUpperCase() === text.toUpperCase());
      if (matchedPlayers.size === 1) {
        this.props.selectPlayer(matchedPlayers.first().id);
      } else if (text === 'system') {
        this.props.selectPlayer('system');
      }
    }
  }

  render() {
    var players = this.props.players.map(ply => ({
      text: ply.alias,
      value: <MenuItem primaryText={ply.alias} />,
    }));

    return (
      <AutoComplete
        filter={AutoComplete.fuzzyFilter}
        triggerUpdateOnFocus={false}
        {...this.props}
        onNewRequest={::this._onPlayerSelected}
        onUpdateInput={::this._onPlayerSelected}
        dataSource={players.toArray()} />
    );
  }
}<commit_msg>easier login for system/systeem<commit_after>import React, { PropTypes, Component } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { contextTypes } from '../../utils/decorators/withContext.js';
import { connect } from 'react-redux';

import PlayerModel from '../../models/PlayerModel.js';

import AutoComplete from 'material-ui/lib/auto-complete';
import MenuItem from 'material-ui/lib/menus/menu-item';

@connect(state => {
  return {
    players: state.players,
  };
})
export default class PlayerAutoComplete extends Component {
  static contextTypes = contextTypes;
  static propTypes = {
    players: ImmutablePropTypes.listOf(PropTypes.instanceOf(PlayerModel).isRequired).isRequired,
    selectPlayer: PropTypes.func.isRequired,
  }

  _onPlayerSelected(text) {
    if (text) {
      var matchedPlayers = this.props.players.filter(ply => ply.alias.toUpperCase() === text.toUpperCase());
      if (matchedPlayers.size === 1) {
        this.props.selectPlayer(matchedPlayers.first().id);
      } else if (text.toLowerCase() === 'system' || text.toLowerCase() === 'systeem') {
        this.props.selectPlayer('system');
      }
    }
  }

  render() {
    var players = this.props.players.map(ply => ({
      text: ply.alias,
      value: <MenuItem primaryText={ply.alias} />,
    }));

    return (
      <AutoComplete
        filter={AutoComplete.fuzzyFilter}
        triggerUpdateOnFocus={false}
        {...this.props}
        onNewRequest={::this._onPlayerSelected}
        onUpdateInput={::this._onPlayerSelected}
        dataSource={players.toArray()} />
    );
  }
}<|endoftext|>


<commit_before>window.diamondash = function() {

  return {
  };
}.call(this);
<commit_msg>Revert "Test to see why diff isn't changing in PR"<commit_after>window.diamondash = function() {
  return {
  };
}.call(this);
<|endoftext|>


<commit_before>/**
 * Created with RubyMine.
 * User: i061485
 * Date: 2/23/14
 * Time: 11:03 AM
 */

define([
    'plugins/plugin'
], function definePanelController(PluginBase) {

    /**
     * Define panel controller
     * @class Controller
     * @mixin {BaseController}
     * @constructor
     */
    var Controller = function Controller() {
    };

    return Controller.extend({

        /**
         * Define modules
         * @param modules
         */
        defineModules: function defineModules(modules) {

            for (var i = 0, l = modules.length; i < l; i++) {
                this.model.defineModule(modules[i]);
            }
        },

        /**
         * Define packages
         * @param packages
         */
        definePackages: function definePackages(packages) {

            for (var i = 0, l = packages.length; i < l; i++) {
                this.model.definePackage(packages[i]);
            }
        },

        /**
         * Check if opened
         * @returns {boolean|*}
         */
        isOpened: function isOpened() {
            return this.scope.opened;
        },

        /**
         * Update opened
         * @param {Boolean} opened
         */
        setBehavior: function setBehavior(opened) {

            /**
             * Update opened instance
             */
            this.scope.opened = !!opened;
        },

        /**
         * Close panel
         */
        closePanel: function closePanel() {
            this.view.elements.$panel.toggle(false);
        },

        /**
         * Open panel
         */
        openPanel: function openPanel() {
            this.view.elements.$panel.toggle(true);
        },

        /**
         * Show content
         * @param {Boolean} opened
         * @param {Number} [index]
         */
        showContent: function showContent(opened, index) {

            // TODO change to dynamic
            index = index || 0;

            if (opened) {

                /**
                 * Define module instance
                 * @type {*}
                 */
                var module = this.controller.activateModule(opened, index);

                this.view.renderContent(module, true);

                module.view.render();
                module.controller.loadContent(opened);
            }
        },

        /**
         * Get render at
         * @returns {*}
         */
        getRenderAt: function getRenderAt() {
            return [
                this.scope.constructor.name.toLowerCase(),
                this.model.getConfig('renderAt')
            ].join('-');
        },

        /**
         * Activate module
         * @param {Boolean} opened
         * @param {Number} index
         * @returns {*}
         */
        activateModule: function activateModule(opened, index) {

            /**
             * Define module config
             * @type {{activated: Boolean, module}}
             */
            var data = this.model.getModule(index) || {};

            if (data && !data.activated) {

                /**
                 * Activate module
                 * @type {boolean}
                 */
                data.activated = true;
            }

            return data.module;
        },

        renderPackages: function renderPackages() {

            var packages = this.model.getPackage();

            for (var i = 0, l = packages.length; i < l; i++) {

                /**
                 * Define package local instance
                 * @type {*}
                 */
                var module = packages[i];

                this.scope.view.renderContent(module, false);
                module.view.render();
                module.controller.loadContent();
            }
        }

    }, PluginBase.prototype);
});<commit_msg>add comments<commit_after>/**
 * Created with RubyMine.
 * User: i061485
 * Date: 2/23/14
 * Time: 11:03 AM
 */

define([
    'plugins/plugin'
], function definePanelController(PluginBase) {

    /**
     * Define panel controller
     * @class Controller
     * @mixin {BaseController}
     * @constructor
     */
    var Controller = function Controller() {
    };

    return Controller.extend({

        /**
         * Define modules
         * @param modules
         */
        defineModules: function defineModules(modules) {

            for (var i = 0, l = modules.length; i < l; i++) {
                this.model.defineModule(modules[i]);
            }
        },

        /**
         * Define packages
         * @param packages
         */
        definePackages: function definePackages(packages) {

            for (var i = 0, l = packages.length; i < l; i++) {
                this.model.definePackage(packages[i]);
            }
        },

        /**
         * Check if opened
         * @returns {boolean|*}
         */
        isOpened: function isOpened() {
            return this.scope.opened;
        },

        /**
         * Update opened
         * @param {Boolean} opened
         */
        setBehavior: function setBehavior(opened) {

            /**
             * Update opened instance
             */
            this.scope.opened = !!opened;
        },

        /**
         * Close panel
         */
        closePanel: function closePanel() {
            this.view.elements.$panel.toggle(false);
        },

        /**
         * Open panel
         */
        openPanel: function openPanel() {
            this.view.elements.$panel.toggle(true);
        },

        /**
         * Show content
         * @param {Boolean} opened
         * @param {Number} [index]
         */
        showContent: function showContent(opened, index) {

            // TODO change to dynamic
            index = index || 0;

            if (opened) {

                /**
                 * Define module instance
                 * @type {*}
                 */
                var module = this.controller.activateModule(opened, index);

                this.view.renderContent(module, true);

                module.view.render();
                module.controller.loadContent(opened);
            }
        },

        /**
         * Get render at
         * @returns {*}
         */
        getRenderAt: function getRenderAt() {

            return [
                this.scope.constructor.name.toLowerCase(),
                this.model.getConfig('renderAt')
            ].join('-');
        },

        /**
         * Activate module
         * @param {Boolean} opened
         * @param {Number} index
         * @returns {*}
         */
        activateModule: function activateModule(opened, index) {

            /**
             * Define module config
             * @type {{activated: Boolean, module}}
             */
            var data = this.model.getModule(index) || {};

            if (data && !data.activated) {

                /**
                 * Activate module
                 * @type {boolean}
                 */
                data.activated = true;
            }

            return data.module;
        },

        /**
         * Render packages
         */
        renderPackages: function renderPackages() {

            /**
             * Init packages
             * @type {*}
             */
            var packages = this.model.getPackage();

            for (var i = 0, l = packages.length; i < l; i++) {

                /**
                 * Define package local instance
                 * @type {*}
                 */
                var module = packages[i];

                this.scope.view.renderContent(module, false);
                module.view.render();
                module.controller.loadContent();
            }
        }

    }, PluginBase.prototype);
});<|endoftext|>


<commit_before>'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;
var BaseManager = require("module-toolkit").BaseManager;
var moment = require("moment");

// internal deps
require("mongodb-toolkit");

var DailyOperationManager = require("../managers/production/finishing-printing/daily-operation-manager");

module.exports = class FactDailyOperationEtlManager extends BaseManager {
    constructor(db, user, sql) {
        super(db, user);
        this.sql = sql;
        this.dailyOperationManager = new DailyOperationManager(db, user);
        this.migrationLog = this.db.collection("migration-log");
    }

    run() {
        var startedDate = new Date()
        this.migrationLog.insert({
            description: "Fact Daily Operation from MongoDB to Azure DWH",
            start: startedDate,
        })
        return this.timestamp()
            .then((time) => this.extract(time))
            .then((data) => this.transform(data))
            .then((data) => this.load(data))
            .then((results) => {
                var finishedDate = new Date();
                var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
                var updateLog = {
                    description: "Fact Daily Operation from MongoDB to Azure DWH",
                    start: startedDate,
                    finish: finishedDate,
                    executionTime: spentTime + " minutes",
                    status: "Successful"
                };
                this.migrationLog.updateOne({ start: startedDate }, updateLog);
            })
            .catch((err) => {
                var finishedDate = new Date();
                var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
                var updateLog = {
                    description: "Fact Daily Operation from MongoDB to Azure DWH",
                    start: startedDate,
                    finish: finishedDate,
                    executionTime: spentTime + " minutes",
                    status: err
                };
                this.migrationLog.updateOne({ start: startedDate }, updateLog);
            });
    };

    timestamp() {
        return this.migrationLog.find({
            description: "Fact Daily Operation from MongoDB to Azure DWH",
            status: "Successful"
        }).sort({ finish: -1 }).limit(1).toArray()
    }

    extract(time) {
        var timestamp = new Date(time[0].start);
        return this.dailyOperationManager.collection.find({
            _updatedDate: {
                $gt: timestamp
            }
        }).toArray();
    }

    // orderQuantityConvertion(uom, quantity) {
    //     if (uom.toLowerCase() === "met" || uom.toLowerCase() === "mtr" || uom.toLowerCase() === "pcs") {
    //         return quantity;
    //     } else if (uom.toLowerCase() === "yard" || uom.toLowerCase() === "yds") {
    //         return quantity * 0.9144;
    //     }
    // }

    transform(data) {
        var result = data.map((item) => {
            var orderUom = item.kanban.selectedProductionOrderDetail.uom ? item.kanban.selectedProductionOrderDetail.uom.unit : null;
            //     var orderQuantity = item.orderQuantity ? item.orderQuantity : null;
            //     var material = item.material ? item.material.name.replace(/'/g, '"') : null;
            //     var materialConstruction = item.materialConstruction ? item.materialConstruction.name.replace(/'/g, '"') : null;
            //     var yarnMaterialNo = item.yarnMaterial ? item.yarnMaterial.name.replace(/'/g, '"') : null;
            //     var materialWidth = item.materialWidth ? item.materialWidth : null;

            return {
                _deleted: `'${item._deleted}'`,
                badOutput: item.badOutput ? `${item.badOutput}` : null,
                badOutputDescription: item.badOutputDescription ? `'${item.badOutputDescription}'` : null,
                code: item.code ? `'${item.code}'` : null,
                inputDate: item.dateInput ? `'${moment(item.dateInput).format("YYYY-MM-DD")}'` : null,
                outputDate: item.dateOutput ? `'${moment(item.dateOutput).format("YYYY-MM-DD")}'` : null,
                goodOutput: item.goodOutput ? `'${item.goodOutput}'` : null,
                input: item.input ? `${item.input}` : null,
                shift: item.shift ? `'${item.shift}'` : null,
                inputTime: item.timeInput ? `'${moment(item.timeInput).format("HH:mm:ss")}'` : null,
                outputTime: item.timeOutput ? `'${moment(item.timeOutput).format("HH:mm:ss")}'` : null,
                kanbanCode: item.kanban ? `'${item.kanban.code}'` : null,
                kanbanGrade: item.kanban ? `'${item.kanban.grade}'` : null,
                kanbanCartCartNumber: item.kanban.cart ? `'${item.kanban.cart.cartNumber}'` : null,
                kanbanCartCode: item.kanban.cart ? `'${item.kanban.cart.code}'` : null,
                kanbanCartPcs: item.kanban.cart ? `'${item.kanban.cart.pcs}'` : null,
                kanbanCartQty: item.kanban.cart ? `'${item.kanban.cart.qty}'` : null,
                kanbanInstructionCode: item.kanban.instruction ? `'${item.kanban.instruction.code}'` : null,
                kanbanInstructionName: item.kanban.instruction ? `'${item.kanban.instruction.name}'` : null,
                orderType: item.kanban.productionOrder && item.kanban.productionOrder.orderType ? `'${item.kanban.productionOrder.orderType.name}'` : null,
                selectedProductionOrderDetailCode: item.kanban.selectedProductionOrderDetail.code ? `'${item.kanban.selectedProductionOrderDetail.code.replace(/'/g, '"')}'` : null,
                selectedProductionOrderDetailColorRequest: item.kanban.selectedProductionOrderDetail.colorRequest ? `'${item.kanban.selectedProductionOrderDetail.colorRequest.replace(/'/g, '"')}'` : null,
                selectedProductionOrderDetailColorTemplate: item.kanban.selectedProductionOrderDetail.colorTemplate ? `'${item.kanban.selectedProductionOrderDetail.colorTemplate.replace(/'/g, '"')}'` : null,
                machineCode: item.machine && item.machine.code ? `'${item.machine.code}'` : null,
                machineCondition: item.machine && item.machine.condition ? `'${item.machine.condition}'` : null,
                machineManufacture: item.machine && item.machine.manufacture ? `'${item.machine.manufacture}'` : null,
                machineMonthlyCapacity: item.machine && item.machine.monthlyCapacity  ? `${item.machine.monthlyCapacity}` : null,
                machineName: item.machine && item.machine.name ? `'${item.machine.name}'` : null,
                machineProcess: item.machine && item.machine.process ? `'${item.machine.process}'` : null,
                machineYear: item.machine && item.machine.year ? `'${item.machine.year}'` : null,
                inputQuantityConvertion: item.kanban.selectedProductionOrderDetail.uom && item.input ? `${item.input}` : null,
                goodOutputQuantityConvertion: item.goodOutput && item.kanban.selectedProductionOrderDetail.uom ? `${item.goodOutput}` : null,
                badOutputQuantityConvertion: item.badOutput && item.kanban.selectedProductionOrderDetail.uom ? `${item.badOutput}` : null,
                failedOutputQuantityConvertion: item.failedOutput && item.kanban.selectedProductionOrderDetail.uom ? `${item.failedOutput}` : null
            }

        });
        return Promise.resolve([].concat.apply([], result));
    };

    insertQuery(sql, query) {
        return new Promise((resolve, reject) => {
            sql.query(query, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                };
            });
        });
    };

    load(data) {
        return new Promise((resolve, reject) => {
            this.sql.startConnection()
                .then(() => {

                    var transaction = this.sql.transaction();

                    transaction.begin((err) => {

                        var request = this.sql.transactionRequest(transaction);

                        var command = [];

                        var sqlQuery = '';

                        var count = 1;

                        for (var item of data) {
                            if (item) {
                                var queryString = `INSERT INTO [dbo].[DL_Fact_Daily_Operation_Temp]([_deleted], [badOutput], [badOutputDescription], [code], [inputDate], [outputDate], [goodOutput], [input], [shift], [inputTime], [outputTime], [kanbanCode], [kanbanGrade], [kanbanCartCartNumber], [kanbanCartCode], [kanbanCartPcs], [kanbanCartQty], [kanbanInstructionCode], [kanbanInstructionName], [orderType], [selectedProductionOrderDetailCode], [selectedProductionOrderDetailColorRequest], [selectedProductionOrderDetailColorTemplate], [machineCode], [machineCondition], [machineManufacture], [machineMonthlyCapacity], [machineName], [machineProcess], [machineYear], [inputQuantityConvertion], [goodOutputQuantityConvertion], [badOutputQuantityConvertion], [failedOutputQuantityConvertion]) VALUES(${item._deleted}, ${item.badOutput}, ${item.badOutputDescription}, ${item.code}, ${item.inputDate}, ${item.outputDate}, ${item.goodOutput}, ${item.input}, ${item.shift}, ${item.inputTime}, ${item.outputTime}, ${item.kanbanCode}, ${item.kanbanGrade}, ${item.kanbanCartCartNumber}, ${item.kanbanCartCode}, ${item.kanbanCartPcs}, ${item.kanbanCartQty}, ${item.kanbanInstructionCode}, ${item.kanbanInstructionName}, ${item.orderType}, ${item.selectedProductionOrderDetailCode}, ${item.selectedProductionOrderDetailColorRequest}, ${item.selectedProductionOrderDetailColorTemplate}, ${item.machineCode}, ${item.machineCondition}, ${item.machineManufacture}, ${item.machineMonthlyCapacity}, ${item.machineName}, ${item.machineProcess}, ${item.machineYear}, ${item.inputQuantityConvertion}, ${item.goodOutputQuantityConvertion}, ${item.badOutputQuantityConvertion}, ${item.failedOutputQuantityConvertion});\n`;
                                sqlQuery = sqlQuery.concat(queryString);
                                if (count % 10000 === 0) {
                                    command.push(this.insertQuery(request, sqlQuery));
                                    sqlQuery = "";
                                }
                                console.log(`add data to query  : ${count}`);
                                count++;
                            }
                        }

                        if (sqlQuery != "")
                            command.push(this.insertQuery(request, `${sqlQuery}`));

                        this.sql.multiple = true;

                        return Promise.all(command)
                            .then((results) => {
                                request.execute("DL_UPSERT_FACT_DAILY_OPERATION").then((execResult) => {
                                    request.execute("DL_INSERT_DIMTIME").then((execResult) => {
                                        transaction.commit((err) => {
                                            if (err)
                                                reject(err);
                                            else
                                                resolve(results);
                                        });
                                    }).catch((error) => {
                                        transaction.rollback((err) => {
                                            console.log("rollback")
                                            if (err)
                                                reject(err)
                                            else
                                                reject(error);
                                        });
                                    })
                                }).catch((error) => {
                                    transaction.rollback((err) => {
                                        console.log("rollback")
                                        if (err)
                                            reject(err)
                                        else
                                            reject(error);
                                    });
                                })
                            })
                            .catch((error) => {
                                transaction.rollback((err) => {
                                    console.log("rollback");
                                    if (err)
                                        reject(err)
                                    else
                                        reject(error);
                                });
                            });
                    })
                })
                .catch((err) => {
                    reject(err);
                })
        })
            .catch((err) => {
                reject(err);
            })
    }
}<commit_msg>update daily operation etl<commit_after>'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;
var BaseManager = require("module-toolkit").BaseManager;
var moment = require("moment");

// internal deps
require("mongodb-toolkit");

var DailyOperationManager = require("../managers/production/finishing-printing/daily-operation-manager");

module.exports = class FactDailyOperationEtlManager extends BaseManager {
    constructor(db, user, sql) {
        super(db, user);
        this.sql = sql;
        this.dailyOperationManager = new DailyOperationManager(db, user);
        this.migrationLog = this.db.collection("migration-log");
    }

    run() {
        var startedDate = new Date()
        this.migrationLog.insert({
            description: "Fact Daily Operation from MongoDB to Azure DWH",
            start: startedDate,
        })
        return this.timestamp()
            .then((time) => this.extract(time))
            .then((data) => this.transform(data))
            .then((data) => this.load(data))
            .then((results) => {
                var finishedDate = new Date();
                var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
                var updateLog = {
                    description: "Fact Daily Operation from MongoDB to Azure DWH",
                    start: startedDate,
                    finish: finishedDate,
                    executionTime: spentTime + " minutes",
                    status: "Successful"
                };
                this.migrationLog.updateOne({ start: startedDate }, updateLog);
            })
            .catch((err) => {
                var finishedDate = new Date();
                var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
                var updateLog = {
                    description: "Fact Daily Operation from MongoDB to Azure DWH",
                    start: startedDate,
                    finish: finishedDate,
                    executionTime: spentTime + " minutes",
                    status: err
                };
                this.migrationLog.updateOne({ start: startedDate }, updateLog);
            });
    };

    timestamp() {
        return this.migrationLog.find({
            description: "Fact Daily Operation from MongoDB to Azure DWH",
            status: "Successful"
        }).sort({ finish: -1 }).limit(1).toArray()
    }

    extract(time) {
        var timestamp = new Date(time[0].start);
        return this.dailyOperationManager.collection.find({
            _updatedDate: {
                $gt: timestamp
            }
        }).toArray();
    }

    // orderQuantityConvertion(uom, quantity) {
    //     if (uom.toLowerCase() === "met" || uom.toLowerCase() === "mtr" || uom.toLowerCase() === "pcs") {
    //         return quantity;
    //     } else if (uom.toLowerCase() === "yard" || uom.toLowerCase() === "yds") {
    //         return quantity * 0.9144;
    //     }
    // }

    transform(data) {
        var result = data.map((item) => {
            var orderUom = item.kanban.selectedProductionOrderDetail.uom ? item.kanban.selectedProductionOrderDetail.uom.unit : null;
            //     var orderQuantity = item.orderQuantity ? item.orderQuantity : null;
            //     var material = item.material ? item.material.name.replace(/'/g, '"') : null;
            //     var materialConstruction = item.materialConstruction ? item.materialConstruction.name.replace(/'/g, '"') : null;
            //     var yarnMaterialNo = item.yarnMaterial ? item.yarnMaterial.name.replace(/'/g, '"') : null;
            //     var materialWidth = item.materialWidth ? item.materialWidth : null;

            return {
                _deleted: `'${item._deleted}'`,
                badOutput: item.badOutput ? `${item.badOutput}` : null,
                badOutputDescription: item.badOutputDescription ? `'${item.badOutputDescription}'` : null,
                code: item.code ? `'${item.code}'` : null,
                inputDate: item.dateInput ? `'${moment(item.dateInput).format("YYYY-MM-DD")}'` : null,
                outputDate: item.dateOutput ? `'${moment(item.dateOutput).format("YYYY-MM-DD")}'` : null,
                goodOutput: item.goodOutput ? `'${item.goodOutput}'` : null,
                input: item.input ? `${item.input}` : null,
                shift: item.shift ? `'${item.shift}'` : null,
                inputTime: item.timeInput ? `'${moment(item.timeInput).format("HH:mm:ss")}'` : null,
                outputTime: item.timeOutput ? `'${moment(item.timeOutput).format("HH:mm:ss")}'` : null,
                kanbanCode: item.kanban ? `'${item.kanban.code}'` : null,
                kanbanGrade: item.kanban ? `'${item.kanban.grade}'` : null,
                kanbanCartCartNumber: item.kanban.cart ? `'${item.kanban.cart.cartNumber}'` : null,
                kanbanCartCode: item.kanban.cart ? `'${item.kanban.cart.code}'` : null,
                kanbanCartPcs: item.kanban.cart ? `${item.kanban.cart.pcs}` : null,
                kanbanCartQty: item.kanban.cart ? `${item.kanban.cart.qty}` : null,
                kanbanInstructionCode: item.kanban.instruction ? `'${item.kanban.instruction.code}'` : null,
                kanbanInstructionName: item.kanban.instruction ? `'${item.kanban.instruction.name}'` : null,
                orderType: item.kanban.productionOrder && item.kanban.productionOrder.orderType ? `'${item.kanban.productionOrder.orderType.name}'` : null,
                selectedProductionOrderDetailCode: item.kanban.selectedProductionOrderDetail.code ? `'${item.kanban.selectedProductionOrderDetail.code.replace(/'/g, '"')}'` : null,
                selectedProductionOrderDetailColorRequest: item.kanban.selectedProductionOrderDetail.colorRequest ? `'${item.kanban.selectedProductionOrderDetail.colorRequest.replace(/'/g, '"')}'` : null,
                selectedProductionOrderDetailColorTemplate: item.kanban.selectedProductionOrderDetail.colorTemplate ? `'${item.kanban.selectedProductionOrderDetail.colorTemplate.replace(/'/g, '"')}'` : null,
                machineCode: item.machine && item.machine.code ? `'${item.machine.code}'` : null,
                machineCondition: item.machine && item.machine.condition ? `'${item.machine.condition}'` : null,
                machineManufacture: item.machine && item.machine.manufacture ? `'${item.machine.manufacture}'` : null,
                machineMonthlyCapacity: item.machine && item.machine.monthlyCapacity ? `${item.machine.monthlyCapacity}` : null,
                machineName: item.machine && item.machine.name ? `'${item.machine.name}'` : null,
                machineProcess: item.machine && item.machine.process ? `'${item.machine.process}'` : null,
                machineYear: item.machine && item.machine.year ? `'${item.machine.year}'` : null,
                inputQuantityConvertion: item.kanban.selectedProductionOrderDetail.uom && item.input ? `${item.input}` : null,
                goodOutputQuantityConvertion: item.goodOutput && item.kanban.selectedProductionOrderDetail.uom ? `${item.goodOutput}` : null,
                badOutputQuantityConvertion: item.badOutput && item.kanban.selectedProductionOrderDetail.uom ? `${item.badOutput}` : null,
                failedOutputQuantityConvertion: item.failedOutput && item.kanban.selectedProductionOrderDetail.uom ? `${item.failedOutput}` : null
            }

        });
        return Promise.resolve([].concat.apply([], result));
    };

    insertQuery(sql, query) {
        return new Promise((resolve, reject) => {
            sql.query(query, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                };
            });
        });
    };

    load(data) {
        return new Promise((resolve, reject) => {
            this.sql.startConnection()
                .then(() => {

                    var transaction = this.sql.transaction();

                    transaction.begin((err) => {

                        var request = this.sql.transactionRequest(transaction);

                        var command = [];

                        var sqlQuery = '';

                        var count = 1;

                        for (var item of data) {
                            if (item) {
                                var queryString = `INSERT INTO [dbo].[DL_Fact_Daily_Operation_Temp]([_deleted], [badOutput], [badOutputDescription], [code], [inputDate], [outputDate], [goodOutput], [input], [shift], [inputTime], [outputTime], [kanbanCode], [kanbanGrade], [kanbanCartCartNumber], [kanbanCartCode], [kanbanCartPcs], [kanbanCartQty], [kanbanInstructionCode], [kanbanInstructionName], [orderType], [selectedProductionOrderDetailCode], [selectedProductionOrderDetailColorRequest], [selectedProductionOrderDetailColorTemplate], [machineCode], [machineCondition], [machineManufacture], [machineMonthlyCapacity], [machineName], [machineProcess], [machineYear], [inputQuantityConvertion], [goodOutputQuantityConvertion], [badOutputQuantityConvertion], [failedOutputQuantityConvertion]) VALUES(${item._deleted}, ${item.badOutput}, ${item.badOutputDescription}, ${item.code}, ${item.inputDate}, ${item.outputDate}, ${item.goodOutput}, ${item.input}, ${item.shift}, ${item.inputTime}, ${item.outputTime}, ${item.kanbanCode}, ${item.kanbanGrade}, ${item.kanbanCartCartNumber}, ${item.kanbanCartCode}, ${item.kanbanCartPcs}, ${item.kanbanCartQty}, ${item.kanbanInstructionCode}, ${item.kanbanInstructionName}, ${item.orderType}, ${item.selectedProductionOrderDetailCode}, ${item.selectedProductionOrderDetailColorRequest}, ${item.selectedProductionOrderDetailColorTemplate}, ${item.machineCode}, ${item.machineCondition}, ${item.machineManufacture}, ${item.machineMonthlyCapacity}, ${item.machineName}, ${item.machineProcess}, ${item.machineYear}, ${item.inputQuantityConvertion}, ${item.goodOutputQuantityConvertion}, ${item.badOutputQuantityConvertion}, ${item.failedOutputQuantityConvertion});\n`;
                                sqlQuery = sqlQuery.concat(queryString);
                                if (count % 10000 === 0) {
                                    command.push(this.insertQuery(request, sqlQuery));
                                    sqlQuery = "";
                                }
                                console.log(`add data to query  : ${count}`);
                                count++;
                            }
                        }

                        if (sqlQuery != "")
                            command.push(this.insertQuery(request, `${sqlQuery}`));

                        this.sql.multiple = true;

                        var fs = require("fs");
                        var path = "C:\\Users\\Itta And Leslie\\Desktop\\daily.txt";

                        fs.writeFile(path, sqlQuery, function (error) {
                            if (error) {
                                console.log("write error:  " + error.message);
                            } else {
                                console.log("Successful Write to " + path);
                            }
                        });

                        return Promise.all(command)
                            .then((results) => {
                                request.execute("DL_UPSERT_FACT_DAILY_OPERATION").then((execResult) => {
                                    request.execute("DL_INSERT_DIMTIME").then((execResult) => {
                                        transaction.commit((err) => {
                                            if (err)
                                                reject(err);
                                            else
                                                resolve(results);
                                        });
                                    }).catch((error) => {
                                        transaction.rollback((err) => {
                                            console.log("rollback")
                                            if (err)
                                                reject(err)
                                            else
                                                reject(error);
                                        });
                                    })
                                }).catch((error) => {
                                    transaction.rollback((err) => {
                                        console.log("rollback")
                                        if (err)
                                            reject(err)
                                        else
                                            reject(error);
                                    });
                                })
                            })
                            .catch((error) => {
                                transaction.rollback((err) => {
                                    console.log("rollback");
                                    if (err)
                                        reject(err)
                                    else
                                        reject(error);
                                });
                            });
                    })
                })
                .catch((err) => {
                    reject(err);
                })
        })
            .catch((err) => {
                reject(err);
            })
    }
}<|endoftext|>


<commit_before>var cheerio = require('cheerio'),
fs = require('fs'),
pg = require('pg');
<commit_msg>ugly spagetti for gettin title<commit_after>var cheerio = require('cheerio'),
fs = require('fs'),
pg = require('pg'),
opath = __dirname + '/output/';

fs.readdir(opath, function(e, files) {
	if (e) {
		throw e;
	}
	files.forEach(function(item, idx) {
		if (item.match(/html$/)) {
			fs.readFile(opath + item, {encoding: 'utf8'}, function(er, data) {
				if (er && ! data) {
					console.log(er);
				} else {
					var $ = cheerio.load(data),
					title = $('font').children()[0];
					if (title) {
						console.log("TITLE: ", title.children[0].data.replace(/\n/g, ''));
					}
				}
			});
		}
	});
});
<|endoftext|>


<commit_before>class PrimeFactors {
    of(n) {
        let result = [];

        while (1 < n) {
            for (let divisor = 2; n >= divisor; divisor++) {
                for (; 0 === n % divisor; n /= divisor) {
                    result.push(divisor);
                }
            }
        }

        return result;
    }
}

export default new PrimeFactors();<commit_msg>clean up, the outter while is redundent<commit_after>class PrimeFactors {
    of(n) {
        let result = [];

        for (let divisor = 2; n >= divisor; divisor++) {
            for (; 0 === n % divisor; n /= divisor) {
                result.push(divisor);
            }
        }

        return result;
    }
}

export default new PrimeFactors();<|endoftext|>


<commit_before>const fs = require('fs')
const YoutubeDL = require('youtube-dl')
const ytdl = require('ytdl-core')
const ficherConfig = JSON.parse(fs.readFileSync('./module/config.json', 'utf8'))
const prefixConfig = ficherConfig.prefix

/**
 * Takes a discord.js client and turns it into a music bot.
 * Thanks to 'derekmartinez18' for helping.
 *
 * @param {Client} client - The discord.js client.
 * @param {object} options - (Optional) Options to configure the music bot. Acceptable options are:
 * 							prefix: The prefix to use for the commands (default '!').
 * 							global: Whether to use a global queue instead of a server-specific queue (default false).
 * 							maxQueueSize: The maximum queue size (default 20).
 * 							anyoneCanSkip: Allow anybody to skip the song.
 * 							clearInvoker: Clear the command message.
 * 							volume: The default volume of the player.
 */
module.exports = function (client, options) {
  // Get all options.
  let PREFIX = (options && options.prefix) || prefixConfig
  let GLOBAL = (options && options.global) || true
  let MAX_QUEUE_SIZE = (options && options.maxQueueSize) || 10
  let DEFAULT_VOLUME = (options && options.volume) || 50
  let ALLOW_ALL_SKIP = (options && options.anyoneCanSkip) || true
  let CLEAR_INVOKER = (options && options.clearInvoker) || true

  // Create an object of queues.
  let queues = {}

  // Catch message events.
  client.on('message', msg => {
    const message = msg.content.trim()

    // Check if the message is a command.
    if (message.toLowerCase().startsWith(PREFIX.toLowerCase())) {
      // Get the command and suffix.
      const command = message.substring(PREFIX.length).split(/[ \n]/)[0].toLowerCase().trim()
      const suffix = message.substring(PREFIX.length + command.length).trim()

      // Process the commands.
      switch (command) {
        case 'play':
          return play(msg, suffix)
        case 'skip':
          return skip(msg, suffix)
        case 'queue':
          return queue(msg, suffix)
        case 'pause':
          return pause(msg, suffix)
        case 'resume':
          return resume(msg, suffix)
        case 'volume':
          return volume(msg, suffix)
        case 'leave':
          return leave(msg, suffix)
        case 'clearqueue':
          return clearqueue(msg, suffix)
      }
      if (CLEAR_INVOKER) {
        msg.delete()
      }
    }
  })

  /**
	 * Checks if a user is an admin.
	 *
	 * @param {GuildMember} member - The guild member
	 * @returns {boolean} -
	 */
  function isAdmin (member) {
    return member.hasPermission('ADMINISTRATOR')
  }

  /**
	 * Checks if the user can skip the song.
	 *
	 * @param {GuildMember} member - The guild member
	 * @param {array} queue - The current queue
	 * @returns {boolean} - If the user can skip
	 */
  function canSkip (member, queue) {
    if (ALLOW_ALL_SKIP) return true
    else if (queue[0].requester === member.id) return true
    else if (isAdmin(member)) return true
    else return false
  }

  /**
	 * Gets the song queue of the server.
	 *
	 * @param {integer} server - The server id.
	 * @returns {object} - The song queue.
	 */
  function getQueue (server) {
    // Check if global queues are enabled.
    if (GLOBAL) server = '_' // Change to global queue.

    // Return the queue.
    if (!queues[server]) queues[server] = []
    return queues[server]
  }

  /**
	 * The command for adding a song to the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response edit.
	 */
  function play (msg, suffix) {
    // Make sure the user is in a voice channel.
    if (msg.member.voiceChannel === undefined) return msg.channel.sendMessage(wrap('Tu n\'es pas dans un salon vocale.'))

    // Make sure the suffix exists.
    if (!suffix) return msg.channel.sendMessage(wrap('Aucune vidéo spécifié'))

    // Get the queue.
    const queue = getQueue(msg.guild.id)

    // Check if the queue has reached its maximum size.
    if (queue.length >= MAX_QUEUE_SIZE) {
      return msg.channel.sendMessage(wrap('Queue maximum attente'))
    }

    // Get the video information.
    msg.channel.sendMessage(wrap('Recherche...')).then(response => {
      var searchstring = suffix
      if (!suffix.toLowerCase().startsWith('http')) {
        searchstring = 'gvsearch1:' + suffix
      }

      YoutubeDL.getInfo(searchstring, ['-q', '--no-warnings', '--force-ipv4'], (err, info) => {
        // Verify the info.
        if (err || info.format_id === undefined || info.format_id.startsWith('0')) {
          return response.edit(wrap('Vidéo invalide !'))
        }

        info.requester = msg.author.id

        // Queue the video.
        response.edit(wrap('Mis en attente: ' + info.title)).then(() => {
          queue.push(info)
          // Play if only one element in the queue.
          if (queue.length === 1) executeQueue(msg, queue)
        }).catch(console.log)
      })
    }).catch(console.log)
  }

  /**
	 * The command for skipping a song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function skip (msg, suffix) {
    // Get the voice connection.
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('Aucune musique jouer.'))

    // Get the queue.
    const queue = getQueue(msg.guild.id)

    if (!canSkip(msg.member, queue)) {
      return msg.channel.sendMessage(wrap('Tu ne peux pas passer sa car tu ne l\'as pas mis.')).then((response) => {
        response.delete(5000)
      })
    }

    // Get the number to skip.
    let toSkip = 1 // Default 1.
    if (!isNaN(suffix) && parseInt(suffix) > 0) {
      toSkip = parseInt(suffix)
    }
    toSkip = Math.min(toSkip, queue.length)

    // Skip.
    queue.splice(0, toSkip - 1)

    // Resume and stop playing.
    const dispatcher = voiceConnection.player.dispatcher
    if (voiceConnection.paused) dispatcher.resume()
    dispatcher.end()

    msg.channel.sendMessage(wrap('Passer ' + toSkip + ' !'))
  }

  /**
	 * The command for listing the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 */
  function queue (msg, suffix) {
    // Get the queue.
    const queue = getQueue(msg.guild.id)

    // Get the queue text.
    const text = queue.map((video, index) => (
      (index + 1) + ': ' + video.title
    )).join('\n')

    // Get the status of the queue.
    let queueStatus = 'Stopped'
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection !== null) {
      const dispatcher = voiceConnection.player.dispatcher
      queueStatus = dispatcher.paused ? 'Mis en pause' : 'Jouer'
    }

    // Send the queue and status.
    msg.channel.sendMessage(wrap('Queue (' + queueStatus + '):\n' + text))
  }

  /**
	 * The command for pausing the current song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function pause (msg, suffix) {
    // Get the voice connection.
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('Aucune musique jouer.'))

    if (!isAdmin(msg.member)) { return msg.channel.sendMessage(wrap('Tu n\'es pas autorisé a utiliser cela.')) }

    // Pause.
    msg.channel.sendMessage(wrap('Playback mis en pause.'))
    const dispatcher = voiceConnection.player.dispatcher
    if (!dispatcher.paused) dispatcher.pause()
  }

  /**
	 * The command for leaving the channel and clearing the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function leave (msg, suffix) {
    if (isAdmin(msg.member)) {
      const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
      if (voiceConnection === null) return msg.channel.sendMessage(wrap('Je suis dans aucun salon.'))
      // Clear the queue.
      const queue = getQueue(msg.guild.id)
      queue.splice(0, queue.length)

      // End the stream and disconnect.
      voiceConnection.player.dispatcher.end()
      voiceConnection.disconnect()
    } else {
      msg.channel.sendMessage(wrap('Tu n\'as pas les permissions pour utiliser cela'))
    }
  }

  /**
	 * The command for clearing the song queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 */
  function clearqueue (msg, suffix) {
    if (isAdmin(msg.member)) {
      const queue = getQueue(msg.guild.id)

      queue.splice(0, queue.length)
      msg.channel.sendMessage(wrap('Queue vider!'))
    } else {
      msg.channel.sendMessage(wrap('Tu n\'as pas les permissions pour utiliser cela'))
    }
  }

  /**
	 * The command for resuming the current song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function resume (msg, suffix) {
    // Get the voice connection.
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('Aucune musique jouer.'))

    if (!isAdmin(msg.member)) { return msg.channel.sendMessage(wrap('Tu n\'as pas les permissions pour utiliser cela')) }

    // Resume.
    msg.channel.sendMessage(wrap('Playback remis.'))
    const dispatcher = voiceConnection.player.dispatcher
    if (dispatcher.paused) dispatcher.resume()
  }

  /**
	 * The command for changing the song volume.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function volume (msg, suffix) {
    // Get the voice connection.
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('Aucune musique jouer'))

    if (!isAdmin(msg.member)) { return msg.channel.sendMessage(wrap('Tu n\'as pas les permissions pour utiliser cela')) }

    // Get the dispatcher
    const dispatcher = voiceConnection.player.dispatcher

    if (suffix > 200 || suffix < 0) {
      return msg.channel.sendMessage(wrap('Volume out of range!')).then((response) => {
        response.delete(5000)
      })
    }

    msg.channel.sendMessage(wrap('Volume mis à ' + suffix))
    dispatcher.setVolume((suffix / 100))
  }

  /**
	 * Executes the next song in the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {object} queue - The song queue for this server.
	 * @returns {<promise>} - The voice channel.
	 */
  function executeQueue (msg, queue) {
    // If the queue is empty, finish.
    if (queue.length === 0) {
      msg.channel.sendMessage(wrap('Playback finis.'))

      // Leave the voice channel.
      const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
      if (voiceConnection !== null) return voiceConnection.disconnect()
    }

    new Promise((resolve, reject) => {
      // Join the voice channel if not already in one.
      const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
      if (voiceConnection === null) {
        // Check if the user is in a voice channel.
        if (msg.member.voiceChannel) {
          msg.member.voiceChannel.join().then(connection => {
            resolve(connection)
          }).catch((error) => {
            console.log(error)
          })
        } else {
          // Otherwise, clear the queue and do nothing.
          queue.splice(0, queue.length)
          reject()
        }
      } else {
        resolve(voiceConnection)
      }
    }).then(connection => {
      // Get the first item in the queue.
      const video = queue[0]

      console.log(video.webpage_url)

      // Play the video.
      msg.channel.sendMessage(wrap('En cours: ' + video.title)).then(() => {
        let dispatcher = connection.playStream(ytdl(video.webpage_url, {filter: 'audioonly'}), {seek: 0, volume: (DEFAULT_VOLUME / 100)})

        connection.on('error', (error) => {
          // Skip to the next song.
          console.log(error)
          queue.shift()
          executeQueue(msg, queue)
        })

        dispatcher.on('error', (error) => {
          // Skip to the next song.
          console.log(error)
          queue.shift()
          executeQueue(msg, queue)
        })

        dispatcher.on('end', () => {
          // Wait a second.
          setTimeout(() => {
            if (queue.length > 0) {
              // Remove the song from the queue.
              queue.shift()
              // Play the next song in the queue.
              executeQueue(msg, queue)
            }
          }, 1000)
        })
      }).catch((error) => {
        console.log(error)
      })
    }).catch((error) => {
      console.log(error)
    })
  }
}

/**
 * Wrap text in a code block and escape grave characters.
 *
 * @param {string} text - The input text.
 * @returns {string} - The wrapped text.
 */
function wrap (text) {
  return '```\n' + text.replace(/`/g, '`' + String.fromCharCode(8203)) + '\n```'
}
<commit_msg>Update index.js<commit_after>const fs = require('fs')
const YoutubeDL = require('youtube-dl')
const ytdl = require('ytdl-core')
const ficherConfig = JSON.parse(fs.readFileSync('./module/config.json', 'utf8'))
const prefixConfig = ficherConfig.prefix

/**
 * Takes a discord.js client and turns it into a music bot.
 * Thanks to 'derekmartinez18' for helping.
 *
 * @param {Client} client - The discord.js client.
 * @param {object} options - (Optional) Options to configure the music bot. Acceptable options are:
 * 							prefix: The prefix to use for the commands (default '!').
 * 							global: Whether to use a global queue instead of a server-specific queue (default false).
 * 							maxQueueSize: The maximum queue size (default 20).
 * 							anyoneCanSkip: Allow anybody to skip the song.
 * 							clearInvoker: Clear the command message.
 * 							volume: The default volume of the player.
 */
module.exports = function (client, options) {
  // Get all options.
  let PREFIX = '+'
  let GLOBAL = (options && options.global) || true
  let MAX_QUEUE_SIZE = (options && options.maxQueueSize) || 10
  let DEFAULT_VOLUME = (options && options.volume) || 50
  let ALLOW_ALL_SKIP = (options && options.anyoneCanSkip) || true
  let CLEAR_INVOKER = (options && options.clearInvoker) || true

  // Create an object of queues.
  let queues = {}

  // Catch message events.
  client.on('message', msg => {
    const message = msg.content.trim()

    // Check if the message is a command.
    if (message.toLowerCase().startsWith(PREFIX.toLowerCase())) {
      // Get the command and suffix.
      const command = message.substring(PREFIX.length).split(/[ \n]/)[0].toLowerCase().trim()
      const suffix = message.substring(PREFIX.length + command.length).trim()

      // Process the commands.
      switch (command) {
        case 'play':
          return play(msg, suffix)
        case 'skip':
          return skip(msg, suffix)
        case 'queue':
          return queue(msg, suffix)
        case 'pause':
          return pause(msg, suffix)
        case 'resume':
          return resume(msg, suffix)
        case 'volume':
          return volume(msg, suffix)
        case 'leave':
          return leave(msg, suffix)
        case 'clearqueue':
          return clearqueue(msg, suffix)
      }
      if (CLEAR_INVOKER) {
        msg.delete()
      }
    }
  })

  /**
	 * Checks if a user is an admin.
	 *
	 * @param {GuildMember} member - The guild member
	 * @returns {boolean} -
	 */
  function isAdmin (member) {
    return member.hasPermission('ADMINISTRATOR')
  }

  /**
	 * Checks if the user can skip the song.
	 *
	 * @param {GuildMember} member - The guild member
	 * @param {array} queue - The current queue
	 * @returns {boolean} - If the user can skip
	 */
  function canSkip (member, queue) {
    if (ALLOW_ALL_SKIP) return true
    else if (queue[0].requester === member.id) return true
    else if (isAdmin(member)) return true
    else return false
  }

  /**
	 * Gets the song queue of the server.
	 *
	 * @param {integer} server - The server id.
	 * @returns {object} - The song queue.
	 */
  function getQueue (server) {
    // Check if global queues are enabled.
    if (GLOBAL) server = '_' // Change to global queue.

    // Return the queue.
    if (!queues[server]) queues[server] = []
    return queues[server]
  }

  /**
	 * The command for adding a song to the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response edit.
	 */
  function play (msg, suffix) {
    // Make sure the user is in a voice channel.
    if (msg.member.voiceChannel === undefined) return msg.channel.sendMessage(wrap('Tu n\'es pas dans un salon vocale.'))

    // Make sure the suffix exists.
    if (!suffix) return msg.channel.sendMessage(wrap('Aucune vidéo spécifié'))

    // Get the queue.
    const queue = getQueue(msg.guild.id)

    // Check if the queue has reached its maximum size.
    if (queue.length >= MAX_QUEUE_SIZE) {
      return msg.channel.sendMessage(wrap('Queue maximum attente'))
    }

    // Get the video information.
    msg.channel.sendMessage(wrap('Recherche...')).then(response => {
      var searchstring = suffix
      if (!suffix.toLowerCase().startsWith('http')) {
        searchstring = 'gvsearch1:' + suffix
      }

      YoutubeDL.getInfo(searchstring, ['-q', '--no-warnings', '--force-ipv4'], (err, info) => {
        // Verify the info.
        if (err || info.format_id === undefined || info.format_id.startsWith('0')) {
          return response.edit(wrap('Vidéo invalide !'))
        }

        info.requester = msg.author.id

        // Queue the video.
        response.edit(wrap('Mis en attente: ' + info.title)).then(() => {
          queue.push(info)
          // Play if only one element in the queue.
          if (queue.length === 1) executeQueue(msg, queue)
        }).catch(console.log)
      })
    }).catch(console.log)
  }

  /**
	 * The command for skipping a song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function skip (msg, suffix) {
    // Get the voice connection.
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('Aucune musique jouer.'))

    // Get the queue.
    const queue = getQueue(msg.guild.id)

    if (!canSkip(msg.member, queue)) {
      return msg.channel.sendMessage(wrap('Tu ne peux pas passer sa car tu ne l\'as pas mis.')).then((response) => {
        response.delete(5000)
      })
    }

    // Get the number to skip.
    let toSkip = 1 // Default 1.
    if (!isNaN(suffix) && parseInt(suffix) > 0) {
      toSkip = parseInt(suffix)
    }
    toSkip = Math.min(toSkip, queue.length)

    // Skip.
    queue.splice(0, toSkip - 1)

    // Resume and stop playing.
    const dispatcher = voiceConnection.player.dispatcher
    if (voiceConnection.paused) dispatcher.resume()
    dispatcher.end()

    msg.channel.sendMessage(wrap('Passer ' + toSkip + ' !'))
  }

  /**
	 * The command for listing the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 */
  function queue (msg, suffix) {
    // Get the queue.
    const queue = getQueue(msg.guild.id)

    // Get the queue text.
    const text = queue.map((video, index) => (
      (index + 1) + ': ' + video.title
    )).join('\n')

    // Get the status of the queue.
    let queueStatus = 'Stopped'
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection !== null) {
      const dispatcher = voiceConnection.player.dispatcher
      queueStatus = dispatcher.paused ? 'Mis en pause' : 'Jouer'
    }

    // Send the queue and status.
    msg.channel.sendMessage(wrap('Queue (' + queueStatus + '):\n' + text))
  }

  /**
	 * The command for pausing the current song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function pause (msg, suffix) {
    // Get the voice connection.
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('Aucune musique jouer.'))

    if (!isAdmin(msg.member)) { return msg.channel.sendMessage(wrap('Tu n\'es pas autorisé a utiliser cela.')) }

    // Pause.
    msg.channel.sendMessage(wrap('Playback mis en pause.'))
    const dispatcher = voiceConnection.player.dispatcher
    if (!dispatcher.paused) dispatcher.pause()
  }

  /**
	 * The command for leaving the channel and clearing the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function leave (msg, suffix) {
    if (isAdmin(msg.member)) {
      const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
      if (voiceConnection === null) return msg.channel.sendMessage(wrap('Je suis dans aucun salon.'))
      // Clear the queue.
      const queue = getQueue(msg.guild.id)
      queue.splice(0, queue.length)

      // End the stream and disconnect.
      voiceConnection.player.dispatcher.end()
      voiceConnection.disconnect()
    } else {
      msg.channel.sendMessage(wrap('Tu n\'as pas les permissions pour utiliser cela'))
    }
  }

  /**
	 * The command for clearing the song queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 */
  function clearqueue (msg, suffix) {
    if (isAdmin(msg.member)) {
      const queue = getQueue(msg.guild.id)

      queue.splice(0, queue.length)
      msg.channel.sendMessage(wrap('Queue vider!'))
    } else {
      msg.channel.sendMessage(wrap('Tu n\'as pas les permissions pour utiliser cela'))
    }
  }

  /**
	 * The command for resuming the current song.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function resume (msg, suffix) {
    // Get the voice connection.
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('Aucune musique jouer.'))

    if (!isAdmin(msg.member)) { return msg.channel.sendMessage(wrap('Tu n\'as pas les permissions pour utiliser cela')) }

    // Resume.
    msg.channel.sendMessage(wrap('Playback remis.'))
    const dispatcher = voiceConnection.player.dispatcher
    if (dispatcher.paused) dispatcher.resume()
  }

  /**
	 * The command for changing the song volume.
	 *
	 * @param {Message} msg - Original message.
	 * @param {string} suffix - Command suffix.
	 * @returns {<promise>} - The response message.
	 */
  function volume (msg, suffix) {
    // Get the voice connection.
    const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('Aucune musique jouer'))

    if (!isAdmin(msg.member)) { return msg.channel.sendMessage(wrap('Tu n\'as pas les permissions pour utiliser cela')) }

    // Get the dispatcher
    const dispatcher = voiceConnection.player.dispatcher

    if (suffix > 200 || suffix < 0) {
      return msg.channel.sendMessage(wrap('Volume out of range!')).then((response) => {
        response.delete(5000)
      })
    }

    msg.channel.sendMessage(wrap('Volume mis à ' + suffix))
    dispatcher.setVolume((suffix / 100))
  }

  /**
	 * Executes the next song in the queue.
	 *
	 * @param {Message} msg - Original message.
	 * @param {object} queue - The song queue for this server.
	 * @returns {<promise>} - The voice channel.
	 */
  function executeQueue (msg, queue) {
    // If the queue is empty, finish.
    if (queue.length === 0) {
      msg.channel.sendMessage(wrap('Playback finis.'))

      // Leave the voice channel.
      const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
      if (voiceConnection !== null) return voiceConnection.disconnect()
    }

    new Promise((resolve, reject) => {
      // Join the voice channel if not already in one.
      const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id)
      if (voiceConnection === null) {
        // Check if the user is in a voice channel.
        if (msg.member.voiceChannel) {
          msg.member.voiceChannel.join().then(connection => {
            resolve(connection)
          }).catch((error) => {
            console.log(error)
          })
        } else {
          // Otherwise, clear the queue and do nothing.
          queue.splice(0, queue.length)
          reject()
        }
      } else {
        resolve(voiceConnection)
      }
    }).then(connection => {
      // Get the first item in the queue.
      const video = queue[0]

      console.log(video.webpage_url)

      // Play the video.
      msg.channel.sendMessage(wrap('En cours: ' + video.title)).then(() => {
        let dispatcher = connection.playStream(ytdl(video.webpage_url, {filter: 'audioonly'}), {seek: 0, volume: (DEFAULT_VOLUME / 100)})

        connection.on('error', (error) => {
          // Skip to the next song.
          console.log(error)
          queue.shift()
          executeQueue(msg, queue)
        })

        dispatcher.on('error', (error) => {
          // Skip to the next song.
          console.log(error)
          queue.shift()
          executeQueue(msg, queue)
        })

        dispatcher.on('end', () => {
          // Wait a second.
          setTimeout(() => {
            if (queue.length > 0) {
              // Remove the song from the queue.
              queue.shift()
              // Play the next song in the queue.
              executeQueue(msg, queue)
            }
          }, 1000)
        })
      }).catch((error) => {
        console.log(error)
      })
    }).catch((error) => {
      console.log(error)
    })
  }
}

/**
 * Wrap text in a code block and escape grave characters.
 *
 * @param {string} text - The input text.
 * @returns {string} - The wrapped text.
 */
function wrap (text) {
  return '```\n' + text.replace(/`/g, '`' + String.fromCharCode(8203)) + '\n```'
}
<|endoftext|>


<commit_before>const ethUtils = require('ethereumjs-util')

module.exports = class Address {
  constructor (value) {
    // Special case: duplicate
    if (value instanceof Address) {
      this._value = new Buffer(value._value)
      return
    }

    if (typeof value !== 'string') {
      throw new Error('Invalid input to address')
    }

    if (!ethUtils.isHexPrefixed(value)) {
      throw new Error('Invalid address format')
    }

    this._value = new Buffer(ethUtils.stripHexPrefix(value), 'hex')

    if (this._value.length !== 20) {
      throw new Error('Invalid address length')
    }
  }

  toString () {
    return '0x' + this._value.toString('hex')
  }

  isZero () {
    return this._value.equals(ethUtils.zeros(20))
  }
}
<commit_msg>Address: include toBuffer<commit_after>const ethUtils = require('ethereumjs-util')

module.exports = class Address {
  constructor (value) {
    // Special case: duplicate
    if (value instanceof Address) {
      this._value = new Buffer(value._value)
      return
    }

    if (typeof value !== 'string') {
      throw new Error('Invalid input to address')
    }

    if (!ethUtils.isHexPrefixed(value)) {
      throw new Error('Invalid address format')
    }

    this._value = new Buffer(ethUtils.stripHexPrefix(value), 'hex')

    if (this._value.length !== 20) {
      throw new Error('Invalid address length')
    }
  }

  toBuffer () {
    return this._value
  }

  toString () {
    return '0x' + this._value.toString('hex')
  }

  isZero () {
    return this._value.equals(ethUtils.zeros(20))
  }
}
<|endoftext|>