<commit_before>/*******************************************************************************
 * Name: QuizziPedia::Front-End::Controllers::CreateQuestionnaireController;
 * Description: Controller che gestisce la creazione dei questionari;
 *
 *
 * Creation data: 03-05-2016;
 * Author: Simone Magagna;
 * License: MIT.
 ********************************************************************************
 * Updates history
 *-------------------------------------------------------------------------------
 * ID: CreateQuestionnaireController_20160504;
 * Update data: 04-05-2016;
 * Description: Ultimata la classe ci metodi createQMLQuestion(),
 * createQuestionnaire() e noFilter();
 * Author: Alberto Ferrara.
 *-------------------------------------------------------------------------------
 * ID: AppController_20160502;
 * Update data: 02-05-2016;
 * Description: Scritti i metodi getTopic(), resetFilters(), filterByYours(),
 * addQuestion(), deleteQuestion();
 * Author: Matteo Granzotto.
 *-------------------------------------------------------------------------------
 * ID: CreateQuestionnaireController_2016426;
 * Update data: 26-04-2016;
 * Description: Creata la classe e i metodi showAllQuestions();
 * Author: Simone Magagna.
 *-------------------------------------------------------------------------------
 *******************************************************************************/

app.controller('CreateQuestionnaireController', CreateQuestionnaireController);

CreateQuestionnaireController.$inject = ['$scope', '$rootScope', '$routeParams', '$location', '$mdDialog', '$cookies', '$timeout', '$mdSidenav','filterFilter', 'ErrorInfoModel', 'QuizService', 'UserDetailsModel'];

function CreateQuestionnaireController ($scope, $rootScope, $routeParams, $location, $mdDialog, $cookies, $timeout, $mdSidenav,filterFilter, ErrorInfoModel, QuizService, UserDetailsModel) {

  /*Variabili*/
  $scope.questions_selected=[];

  $scope.quiz = {
      title: '',
      author: $rootScope.userLogged.getId(),
      keyword: '',
      topic: undefined,
      questions: []
  };

  $scope.filter = {};

  /*Costruttore*/
  QuizService.getTopic($routeParams.lang)
      .then(function(result){
          if(result.data != undefined) {
              $scope.topics = result.data;

          }
      } ,function (err){
          $scope.error = new ErrorInfoModel("8", "Errore", "Caricamento domande non andato a buon fine");
          alert = $mdDialog.alert()
              .title($scope.error.getTitle())
              .content($scope.error.getMessage())
              .ok('Ok');
          $mdDialog
              .show( alert )
              .finally(function() {
                  alert = undefined;
              });
    });

    $scope.showAllQuestions(null,null);

    /*Funzioni pubbliche*/
    $scope.resetFilters = function () {
        // needs to be a function or it won't trigger a $watch
        $scope.search = {};
    };

    $scope.showAllQuestions=function(topic,keyword) {
        QuizService.showAllQuestions(topic, keyword, $routeParams.lang)
            .then(function (result) {
                if (result.data != undefined) {
                    $scope.questions = result.data;
                    $scope.currentPage= 1;
                    $scope.numPerPage = 10;
                    $scope.totalItems = $scope.questions.length;
                    $scope.maxSize  = Math.ceil($scope.totalItems / $scope.numPerPage);

                    $scope.$watch('search', function(newVal, oldVal) {
                        $scope.filtered = filterFilter($scope.questions, newVal);
                        $scope.totalItems = $scope.filtered.length;
                        $scope.maxSize  = Math.ceil($scope.totalItems / $scope.numPerPage);
                        $scope.currentPage = 1;
                    },true);

                }
            }, function (err) {
                $scope.error = new ErrorInfoModel("8", "Errore", "Caricamento domande non andato a buon fine");
                alert = $mdDialog.alert()
                    .title($scope.error.getTitle())
                    .content($scope.error.getMessage())
                    .ok('Ok');
                $mdDialog
                    .show(alert)
                    .finally(function () {
                        alert = undefined;
                    });
            });
    }

    $scope.filterByYours = function (question) {
        return $scope.filter[question.author] || noFilter($scope.filter);
    };

    $scope.addQuestion=function(question){
        $scope.questions_selected.push(question);
        $scope.quiz.questions.push(question._id);
        var idx = $scope.questions.indexOf(question);
        if (idx > -1) {
            $scope.questions.splice(idx, 1);
        }
    }

    $scope.deleteQuestion=function(question){
        $scope.questions.push(question);
        var idx = $scope.questions_selected.indexOf(question);
        if (idx > -1) {
            $scope.questions_selected.splice(idx, 1);
            $scope.quiz.questions.push(idx,1)
        }
    }

    $scope.createQMLQuestion = function() {
        $location.path('/'+$routeParams.lang+'/QML');
    }

    $scope.createQuestionnaire = function(quiz) {
        QuizService.createQuestionnaire(quiz.title, quiz.author, quiz.keyword, quiz.topic,quiz.questions, $routeParams.lang)
            .then(function (result) {
                if (result) {
                    $scope.error = new ErrorInfoModel();
                    if($routeParams.lang === 'it') {
                        alert = $mdDialog.alert()
                            .title("Operazione completata con successo")
                            .content("Il questionario è stato creato!")
                            .ok('Ok');
                    } else{
                        alert = $mdDialog.alert()
                            .title("Successfully completed operation")
                            .content("Quiz is created!")
                            .ok('Ok');
                    }
                    $mdDialog
                        .show(alert)
                        .finally(function () {
                            alert = undefined;
                        });
                    $location.path('/' + $routeParams.lang + '/questionnairemanagement');
                }
            }, function (err) {
                $scope.error = new ErrorInfoModel();
                if($routeParams.lang === 'it') {
                    alert = $mdDialog.alert()
                        .title("Errore")
                        .content("Il questionario non è stato crato!")
                        .ok('Ok');
                } else {
                    alert = $mdDialog.alert()
                        .title("Error")
                        .content("Quiz is not created!")
                        .ok('Ok');
                }
                $mdDialog
                    .show(alert)
                    .finally(function () {
                        alert = undefined;
                    });
            });
    }

    /*Funzioni private*/
    function noFilter(filterObj) {
        for (var key in filterObj) {
            if (filterObj[key]) {
                return false;
            }
        }
        return true;
    }

}
<commit_msg>updated create questionnaire controller<commit_after>/*******************************************************************************
 * Name: QuizziPedia::Front-End::Controllers::CreateQuestionnaireController;
 * Description: Controller che gestisce la creazione dei questionari;
 *
 *
 * Creation data: 03-05-2016;
 * Author: Simone Magagna;
 * License: MIT.
 ********************************************************************************
 * Updates history
 *-------------------------------------------------------------------------------
 * ID: CreateQuestionnaireController_20160504;
 * Update data: 04-05-2016;
 * Description: Ultimata la classe ci metodi createQMLQuestion(),
 * createQuestionnaire() e noFilter();
 * Author: Alberto Ferrara.
 *-------------------------------------------------------------------------------
 * ID: AppController_20160502;
 * Update data: 02-05-2016;
 * Description: Scritti i metodi getTopic(), resetFilters(), filterByYours(),
 * addQuestion(), deleteQuestion();
 * Author: Matteo Granzotto.
 *-------------------------------------------------------------------------------
 * ID: CreateQuestionnaireController_2016426;
 * Update data: 26-04-2016;
 * Description: Creata la classe e i metodi showAllQuestions();
 * Author: Simone Magagna.
 *-------------------------------------------------------------------------------
 *******************************************************************************/

app.controller('CreateQuestionnaireController', CreateQuestionnaireController);

CreateQuestionnaireController.$inject = ['$scope', '$rootScope', '$routeParams', '$location', '$mdDialog', '$cookies', '$timeout', '$mdSidenav','filterFilter', 'ErrorInfoModel', 'QuizService', 'UserDetailsModel'];

function CreateQuestionnaireController ($scope, $rootScope, $routeParams, $location, $mdDialog, $cookies, $timeout, $mdSidenav,filterFilter, ErrorInfoModel, QuizService, UserDetailsModel) {
  /*Variabili*/
  $scope.questions_selected=[];

  $scope.quiz = {
      title: '',
      author: $rootScope.userLogged.getId(),
      keyword: '',
      topic: undefined,
      questions: []
  };

  $scope.filter = {};

  /*Costruttore*/
  QuizService.getTopic($routeParams.lang)
      .then(function(result){
          if(result.data != undefined) {
              $scope.topics = result.data;

          }
      } ,function (err){
          $scope.error = new ErrorInfoModel("8", "Errore", "Caricamento domande non andato a buon fine");
          alert = $mdDialog.alert()
              .title($scope.error.getTitle())
              .content($scope.error.getMessage())
              .ok('Ok');
          $mdDialog
              .show( alert )
              .finally(function() {
                  alert = undefined;
              });
    });

    /*Funzioni pubbliche*/
    $scope.resetFilters = function () {
        // needs to be a function or it won't trigger a $watch
        $scope.search = {};
    };

    $scope.currentPage= 1;
    $scope.numPerPage = 10;

    $scope.update = function()
    {
        $scope.filtered = filterFilter($scope.questions, $scope.search);
        $scope.totalItems = $scope.filtered.length;
        $scope.maxSize  = Math.ceil($scope.totalItems / $scope.numPerPage);
    }

    $scope.updateSearch = function () {
        $scope.filtered = filterFilter($scope.questions, {name: $scope.search.name});
        $scope.maxSize  = Math.ceil($scope.questions / $scope.numPerPage);
    };

    $scope.showAllQuestions=function(topic,keyword) {
        QuizService.showAllQuestions(topic, keyword, $routeParams.lang)
            .then(function (result) {
                if (result.data != undefined) {
                    $scope.questions = result.data;
                    $scope.update();
                }
            }, function (err) {
                $scope.error = new ErrorInfoModel("8", "Errore", "Caricamento domande non andato a buon fine");
                alert = $mdDialog.alert()
                    .title($scope.error.getTitle())
                    .content($scope.error.getMessage())
                    .ok('Ok');
                $mdDialog
                    .show(alert)
                    .finally(function () {
                        alert = undefined;
                    });
            });
    }

    $scope.showAllQuestions(null,null);

    $scope.filterByYours = function (question) {
        return $scope.filter[question.author] || noFilter($scope.filter);
    };

    $scope.addQuestion=function(question){
        $scope.questions_selected.push(question);
        $scope.quiz.questions.push(question._id);
        var idx = $scope.questions.indexOf(question);
        if (idx > -1) {
            $scope.questions.splice(idx, 1);
        }
    }

    $scope.deleteQuestion=function(question){
        $scope.questions.push(question);
        var idx = $scope.questions_selected.indexOf(question);
        if (idx > -1) {
            $scope.questions_selected.splice(idx, 1);
            $scope.quiz.questions.push(idx,1)
        }
    }

    $scope.createQMLQuestion = function() {
        $location.path('/'+$routeParams.lang+'/QML');
    }

    $scope.createQuestionnaire = function(quiz) {
        QuizService.createQuestionnaire(quiz.title, quiz.author, quiz.keyword, quiz.topic,quiz.questions, $routeParams.lang)
            .then(function (result) {
                if (result) {
                    $scope.error = new ErrorInfoModel();
                    if($routeParams.lang === 'it') {
                        alert = $mdDialog.alert()
                            .title("Operazione completata con successo")
                            .content("Il questionario è stato creato!")
                            .ok('Ok');
                    } else{
                        alert = $mdDialog.alert()
                            .title("Successfully completed operation")
                            .content("Quiz is created!")
                            .ok('Ok');
                    }
                    $mdDialog
                        .show(alert)
                        .finally(function () {
                            alert = undefined;
                        });
                    $location.path('/' + $routeParams.lang + '/questionnairemanagement');
                }
            }, function (err) {
                $scope.error = new ErrorInfoModel();
                if($routeParams.lang === 'it') {
                    alert = $mdDialog.alert()
                        .title("Errore")
                        .content("Il questionario non è stato crato!")
                        .ok('Ok');
                } else {
                    alert = $mdDialog.alert()
                        .title("Error")
                        .content("Quiz is not created!")
                        .ok('Ok');
                }
                $mdDialog
                    .show(alert)
                    .finally(function () {
                        alert = undefined;
                    });
            });
    }

    /*Funzioni private*/
    function noFilter(filterObj) {
        for (var key in filterObj) {
            if (filterObj[key]) {
                return false;
            }
        }
        return true;
    }

}
<|endoftext|>


<commit_before>var styles = {
    log: "#2a53cd",
    info: "#228B22",
    warn: "#dd6a16",
    error: "#dc352e"
};
var alerts = [];
var clean = Cleanup(alerts);
var build = function () {
    var sum = 0;
    alerts.forEach(function (elem) {
        if (parseInt(elem.style.top) !== sum);
        elem.style.top = sum + "px";
        sum += elem.offsetHeight;
    });
};
var fontSize = 16 * renderPixelRatio;
var singleHeight = fontSize * 2.6 | 0;
var _text = function (color, parameters) {
    var box = createElement(div);
    var boxWidth = 720 * renderPixelRatio;
    if (boxWidth > innerWidth) {
        boxWidth = +innerWidth;
    }
    css(box, `width:${boxWidth}px;top:${singleHeight * alerts.length}px;margin-left:-${boxWidth >> 1}px;transition:all 0.1s ease-out;left:50%;height:${singleHeight}pt;line-height:${singleHeight}pt;font-size:${fontSize}px;background-color:${color};position:absolute;color:#fff;text-align:center;`);
    text(box, [].slice.call(parameters, 0).join(", "));
    box.initialStyle = `margin-top:-${singleHeight}px;opacity:0;`;
    return box;
};
function alert() {
    var color, text, autoclose = true, onclose;
    var color_reg = /^#(?:\w6|\w3)$/;
    [].map.call(arguments, function (arg) {
        switch (typeof arg) {
            case "string":
                if (!text) {
                    text = arg;
                } else if (color_reg.test(text)) {
                    color = text;
                    text = arg;
                } else if (text in styles) {
                    color = styles[text];
                    text = arg;
                } else if (arg in styles) {
                    color = styles[arg];
                } else if (color_reg.test(arg)) {
                    color = arg;
                }
                break;
            case "boolean":
            case "number":
                autoclose = arg;
                break;
            case "function":
                onclose = arg;
        }
    });
    var elem;

    if (color_reg.test(color)) {
        elem = _text(color, text);
    } else {
        elem = _text(styles.log, arguments);
    }
    var _onclose = function (event) {
        if (onclose) {
            onclose.call(this, event);
        }
        clean(this);
        build();
        if (close_timer) clearTimeout(close_timer);
    }
    onremove(elem, _onclose);
    if (autoclose) {
        if (autoclose === true) {
            autoclose = text.length * 200 + 400;
        } else if (autoclose < 100) {
            autoclose = autoclose * 1000;
        }
        var close_timer = setTimeout(function () {
            remove(elem);
        }, autoclose);
    }
    alerts.push(elem);
    popup(elem);
    return elem;
}
for (var k in styles) {
    alert[k] = new Function(`return this(${JSON.stringify(styles[k])},arguments);`);
}
<commit_msg>alert颜色设置失败的问题解决<commit_after>var styles = {
    log: "#2a53cd",
    info: "#228B22",
    warn: "#dd6a16",
    error: "#dc352e"
};
var alerts = [];
var clean = Cleanup(alerts);
var build = function () {
    var sum = 0;
    alerts.forEach(function (elem) {
        if (parseInt(elem.style.top) !== sum);
        elem.style.top = sum + "px";
        sum += elem.offsetHeight;
    });
};
var fontSize = 16 * renderPixelRatio;
var singleHeight = fontSize * 2.6 | 0;
var _text = function (color, parameters) {
    var box = createElement(div);
    var boxWidth = 720 * renderPixelRatio;
    if (boxWidth > innerWidth) {
        boxWidth = +innerWidth;
    }
    css(box, `width:${boxWidth}px;top:${singleHeight * alerts.length}px;margin-left:-${boxWidth >> 1}px;transition:all 0.1s ease-out;left:50%;height:${singleHeight}pt;line-height:${singleHeight}pt;font-size:${fontSize}px;background-color:${color};position:absolute;color:#fff;text-align:center;`);
    text(box, [].slice.call(parameters, 0).join(", "));
    box.initialStyle = `margin-top:-${singleHeight}px;opacity:0;`;
    return box;
};
function alert() {
    var color = String(this), text, autoclose = true, onclose;
    var color_reg = /^#(?:\w{6}|\w{3})$/;
    [].map.call(arguments, function (arg) {
        switch (typeof arg) {
            case "string":
                if (!text) {
                    text = arg;
                } else if (color_reg.test(text)) {
                    color = text;
                    text = arg;
                } else if (text in styles) {
                    color = styles[text];
                    text = arg;
                } else if (arg in styles) {
                    color = styles[arg];
                } else if (color_reg.test(arg)) {
                    color = arg;
                }
                break;
            case "boolean":
            case "number":
                autoclose = arg;
                break;
            case "function":
                onclose = arg;
        }
    });
    var elem;

    if (color_reg.test(color)) {
        elem = _text(color, [text]);
    } else {
        elem = _text(styles.log, arguments);
    }
    var _onclose = function (event) {
        if (onclose) {
            onclose.call(this, event);
        }
        clean(this);
        build();
        if (close_timer) clearTimeout(close_timer);
    }
    onremove(elem, _onclose);
    if (autoclose) {
        if (autoclose === true) {
            autoclose = text.length * 200 + 400;
        } else if (autoclose < 100) {
            autoclose = autoclose * 1000;
        }
        var close_timer = setTimeout(function () {
            remove(elem);
        }, autoclose);
    }
    alerts.push(elem);
    popup(elem);
    return elem;
}
for (var k in styles) {
    alert[k] = new Function(`return this.apply(${JSON.stringify(styles[k])},arguments);`);
}
<|endoftext|>


<commit_before>import React, {Component,PropTypes} from 'react';
import DropdownList from 'react-widgets/lib/DropdownList';
import {RelatedTests} from '../../containers';

class MapSetMotionLockModeTest extends Component {
  constructor(props) {
    super(props);

    let selectedMapId = '';
    if (props.maps.length > 0) {
      selectedMapId = _.first(props.maps).geoId;
    }

    this.state = {
      selectedMapId: selectedMapId,
      lockMode: emp3.api.enums.MapMotionLockEnum.NO_MOTION
    };

    this.lockMap = this.lockMap.bind(this);
    this.unlockMap = this.unlockMap.bind(this);
  }

  lockMap() {
    const {maps} = this.props;
    const map = _.find(maps, {geoId: this.state.selectedMapId});

    try {
      map.setMotionLockMode({mode: this.state.lockMode});
      toastr.info('Locking ' + map.container);
    } catch (err) {
      toastr.error(err.message, 'map.setMotionLockMode: Critical');
    }
  }

  unlockMap() {
    const {maps} = this.props;
    const map = _.find(maps, {geoId: this.state.selectedMapId});

    try {
      map.setMotionLockMode({mode: emp3.api.enums.MapMotionLockEnum.UNLOCKED});
      toastr.info('Unlocking ' + map.container);
    } catch (err) {
      toastr.error(err.message, 'map.setMotionLockMode: Critical');
    }
  }

  render() {
    const {maps} = this.props;

    return (

        map.setMotionLockMode

          <DropdownList
            data={maps}
            className='mdl-cell mdl-cell--12-col'
            textField='container'
            valueField='geoId'
            value={this.state.selectedMapId}
            onChange={map => this.setState({selectedMapId: map.geoId})}/>

          <button
            className='mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdl-button--colored mdl-cell mdl-cell--12-col'
            disabled={this.state.selectedMapId === ''}
            onClick={this.lockMap}>
             Lock
          </button>

          <button
            className='mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdl-button--colored mdl-cell mdl-cell--12-col'
            disabled={this.state.selectedMapId === ''}
            onClick={this.unlockMap}>
             Unlock
          </button>

          <RelatedTests relatedTests={[

          ]}/>

    );
  }
}

MapSetMotionLockModeTest.propTypes = {
  maps: PropTypes.array
};

export default MapSetMotionLockModeTest;
<commit_msg>updated the validation test to handle all of the lock states #35<commit_after>import React, {Component, PropTypes} from 'react';
import DropdownList from 'react-widgets/lib/DropdownList';
import {RelatedTests} from '../../containers';

class MapSetMotionLockModeTest extends Component {
  constructor(props) {
    super(props);

    let selectedMapId = '';
    if (props.maps.length > 0) {
      selectedMapId = _.first(props.maps).geoId;
    }

    this.state = {
      selectedMapId: selectedMapId
    };

    this.setLockState = this.setLockState.bind(this);
  }

  componentWillReceiveProps(props) {
    if (this.state.selectedMapId === '' && props.maps.length > 0) {
      this.setState({selectedMapId: _.first(props.maps).geoId});
    }
  }

  setLockState(lockState) {
    const {maps} = this.props;
    const map = _.find(maps, {geoId: this.state.selectedMapId});

    try {
      map.setMotionLockMode({mode: lockState});
      toastr.info('Set Lock State to ' + lockState);
    } catch (err) {
      toastr.error(err.message, 'map.setMotionLockMode: Critical');
    }
  }

  render() {
    const {maps} = this.props;

    return (

        map.setMotionLockMode

          <DropdownList
            data={maps}
            className='mdl-cell mdl-cell--12-col'
            textField='container'
            valueField='geoId'
            value={this.state.selectedMapId}
            onChange={map => this.setState({selectedMapId: map.geoId})}/>

          {_.map(emp3.api.enums.MapMotionLockEnum, (value, key) => {
            return (
              <button
                key={key}
                className='mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdl-button--colored mdl-cell mdl-cell--12-col'
                disabled={this.state.selectedMapId === ''}
                onClick={this.setLockState.bind(this, value)}>
                {_.replace(key, /_/g, " ")}
              </button>);
          })}

          <RelatedTests relatedTests={[]}/>

    );
  }
}

MapSetMotionLockModeTest.propTypes = {
  maps: PropTypes.array
};

export default MapSetMotionLockModeTest;
<|endoftext|>


<commit_before>import d3Scale from 'd3-scale';
// import LayerTimeContext from './layer-time-context';
import ns from './namespace';
// import TimeContextBehavior from '../behaviors/time-context-behavior';
// import TrackTimeContext from './track-time-context';

/**
* As a temporal representation, a track establishes a relation between *time* in seconds and *space* in pixels.
*
* A `Track` instance can have multiple `Layer` instances.
*
* Tracks inside a timeline
*
* A temporal representation can be rendered upon multiple DOM elements, the tracks (eg multiple <li> for a DAW like representation) that belong to the same timeline using the `add` method. These tracks are like windows on the overall and basically unending timeline.
*
* A timeline with 3 tracks:
*
* +-----------------+-------------------------------+-- - -  -  -   -
* |track 1          |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
* +-----------------+-------------------------------+-- - -  -  -   -
* |track 2          |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
* +-----------------+-------------------------------+-- - -  -  -   -
* |track 3          |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
* +-------------------------------------------------+-- - -  -  -   -
*
* +----------------->
* timeline.timeContext.xScale(timeline.timeContext.offset)
*
*                   <------------------------------->
*                   timeline's tracks defaults to 1000px
*                   with a default pixelsPerSecond of 100px/s.
*                   and a default `stretchRatio = 1`
*                   track1 shows 10 seconds of the timeline
*
* Layers inside a track
*
* Within a track, a `Layer` keeps up-to-date and renders the data. The track's `add` method adds a `Layer` instance to a track. A Layer
*
* The track renderingContext
*
* When one modify the timeline renderingContext:
* - timeline.renderingContext.offset (in seconds) modify the containers track x position
* - timeline.renderingContext.stretchRatio modify timeline's zoom
* Each time you set new value of offset or stretchRatio, you need to do `timeline.update()` to update the values.
* Track SVG structure
* <svg>
*  <defs> Unused for the moment, could be used to define custom shapes for use with layers
*  </defs>
*  <g class="offset">
*   <g class="layout"> The layers are inserted here
*   </g>
*  </g>
*  <g class="interactions"> Placeholder to visualize interactions (eg. brush)
*  </g>
* </svg>
*/

export default class Track {
  constructor($el, height = 100) {
    this.$el = $el;
    this.layers = [];
    this._height = height;

    // are set when added to the timeline
    this.renderingContext = null;

    this._createContainer();
  }

  get height() {
    return this._height;
  }

  set height(value) {
    this._height = value;
    // @NOTE: propagate to layers, keeping ratio ?
  }

  /**
   *  This method is called when the track is added to the timeline
   *  The track cannot be updated without being added to a timeline
   */
  configure(renderingContext) {
    this.renderingContext = renderingContext;
  }

  /**
   *  Destroy a track
   *  The layers from this track can still be reused elsewhere
   */
  destroy() {
    // detatch everything from the DOM
    this.$el.removeChild(this.$svg);
    this.layers.forEach((layer) => this.$layout.removeChild(layer.$el));
    // clean references
    this.$el = null;
    this.renderingContext = null;
    this.layers.length = 0;
  }

  /**
   *  Creates the container for the track
   */
  _createContainer() {
    const $svg = document.createElementNS(ns, 'svg');
    $svg.setAttributeNS(null, 'shape-rendering', 'optimizeSpeed');
    $svg.setAttributeNS(null, 'height', this.height);
    $svg.setAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml');

    const $background = document.createElementNS(ns, 'rect');
    $background.setAttributeNS(null, 'height', '100%');
    $background.setAttributeNS(null, 'width', '100%')

    const $defs = document.createElementNS(ns, 'defs');

    const $offsetGroup = document.createElementNS(ns, 'g');
    $offsetGroup.classList.add('offset');

    const $layoutGroup = document.createElementNS(ns, 'g');
    $layoutGroup.classList.add('layout');

    const $interactionsGroup = document.createElementNS(ns, 'g');
    $interactionsGroup.classList.add('interactions');

    $svg.appendChild($defs);
    $svg.appendChild($background);
    $offsetGroup.appendChild($layoutGroup);
    $svg.appendChild($offsetGroup);
    $svg.appendChild($interactionsGroup);

    this.$el.appendChild($svg);
    // removes additionnal height added who knows why...
    this.$el.style.fontSize = 0;
    // fixes one of the (many ?) weird canvas rendering bugs in Chrome
    this.$el.style.transform = 'translateZ(0)';

    this.$layout = $layoutGroup;
    this.$offset = $offsetGroup;
    this.$interactions = $interactionsGroup;
    this.$svg = $svg;
    this.$background = $background
  }

  /**
   * Adds a layer to the track
   */
  add(layer) {
    this.layers.push(layer);
    // Create a default renderingContext for the layer if missing
    this.$layout.appendChild(layer.$el);
  }

  /**
   * Removes a layer
   */
  remove(layer) {
    this.layers.splice(this.layers.indexOf(layer), 1);
    // Removes layer from its container
    this.$layout.removeChild(layer.$el);
  }

  /**
   * Draw tracks, and the layers in cascade
   */
  render() {
    for (let layer of this) { layer.render(); }
  }

  /**
   * Update the layers
   */
  update(layers = null) {
    this.updateContainer();
    this.updateLayers(layers);
  }

  updateContainer() {
    const $svg = this.$svg;
    const $offset = this.$offset;
    // should be in some update layout
    const renderingContext = this.renderingContext;
    const height  = this.height;
    const width   = renderingContext.visibleWidth;
    const offsetX = renderingContext.xScale(renderingContext.offset);
    const translate = `translate(${offsetX}, 0)`;

    $svg.setAttributeNS(null, 'height', height);
    $svg.setAttributeNS(null, 'width', width);
    $svg.setAttributeNS(null, 'viewbox', `0 0 ${width} ${height}`);

    $offset.setAttributeNS(null, 'transform', translate);
  }

  updateLayers(layers = null) {
    layers = (layers === null) ? this.layers : layers;

    layers.forEach((layer) => {
      if (this.layers.indexOf(layer) === -1) { return; }
      layer.update();
    });
  }

  *[Symbol.iterator]() {
    yield* this.layers[Symbol.iterator]()
  }
}
<commit_msg>opacity null for track background<commit_after>import d3Scale from 'd3-scale';
// import LayerTimeContext from './layer-time-context';
import ns from './namespace';
// import TimeContextBehavior from '../behaviors/time-context-behavior';
// import TrackTimeContext from './track-time-context';

/**
* As a temporal representation, a track establishes a relation between *time* in seconds and *space* in pixels.
*
* A `Track` instance can have multiple `Layer` instances.
*
* Tracks inside a timeline
*
* A temporal representation can be rendered upon multiple DOM elements, the tracks (eg multiple <li> for a DAW like representation) that belong to the same timeline using the `add` method. These tracks are like windows on the overall and basically unending timeline.
*
* A timeline with 3 tracks:
*
* +-----------------+-------------------------------+-- - -  -  -   -
* |track 1          |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
* +-----------------+-------------------------------+-- - -  -  -   -
* |track 2          |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
* +-----------------+-------------------------------+-- - -  -  -   -
* |track 3          |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
* +-------------------------------------------------+-- - -  -  -   -
*
* +----------------->
* timeline.timeContext.xScale(timeline.timeContext.offset)
*
*                   <------------------------------->
*                   timeline's tracks defaults to 1000px
*                   with a default pixelsPerSecond of 100px/s.
*                   and a default `stretchRatio = 1`
*                   track1 shows 10 seconds of the timeline
*
* Layers inside a track
*
* Within a track, a `Layer` keeps up-to-date and renders the data. The track's `add` method adds a `Layer` instance to a track. A Layer
*
* The track renderingContext
*
* When one modify the timeline renderingContext:
* - timeline.renderingContext.offset (in seconds) modify the containers track x position
* - timeline.renderingContext.stretchRatio modify timeline's zoom
* Each time you set new value of offset or stretchRatio, you need to do `timeline.update()` to update the values.
* Track SVG structure
* <svg>
*  <defs> Unused for the moment, could be used to define custom shapes for use with layers
*  </defs>
*  <g class="offset">
*   <g class="layout"> The layers are inserted here
*   </g>
*  </g>
*  <g class="interactions"> Placeholder to visualize interactions (eg. brush)
*  </g>
* </svg>
*/

export default class Track {
  constructor($el, height = 100) {
    this.$el = $el;
    this.layers = [];
    this._height = height;

    // are set when added to the timeline
    this.renderingContext = null;

    this._createContainer();
  }

  get height() {
    return this._height;
  }

  set height(value) {
    this._height = value;
    // @NOTE: propagate to layers, keeping ratio ?
  }

  /**
   *  This method is called when the track is added to the timeline
   *  The track cannot be updated without being added to a timeline
   */
  configure(renderingContext) {
    this.renderingContext = renderingContext;
  }

  /**
   *  Destroy a track
   *  The layers from this track can still be reused elsewhere
   */
  destroy() {
    // detatch everything from the DOM
    this.$el.removeChild(this.$svg);
    this.layers.forEach((layer) => this.$layout.removeChild(layer.$el));
    // clean references
    this.$el = null;
    this.renderingContext = null;
    this.layers.length = 0;
  }

  /**
   *  Creates the container for the track
   */
  _createContainer() {
    const $svg = document.createElementNS(ns, 'svg');
    $svg.setAttributeNS(null, 'shape-rendering', 'optimizeSpeed');
    $svg.setAttributeNS(null, 'height', this.height);
    $svg.setAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml');

    const $background = document.createElementNS(ns, 'rect');
    $background.setAttributeNS(null, 'height', '100%');
    $background.setAttributeNS(null, 'width', '100%');
    $background.setAttributeNS(null, 'style', 'fill-opacity:0');

    const $defs = document.createElementNS(ns, 'defs');

    const $offsetGroup = document.createElementNS(ns, 'g');
    $offsetGroup.classList.add('offset');

    const $layoutGroup = document.createElementNS(ns, 'g');
    $layoutGroup.classList.add('layout');

    const $interactionsGroup = document.createElementNS(ns, 'g');
    $interactionsGroup.classList.add('interactions');

    $svg.appendChild($defs);
    $svg.appendChild($background);
    $offsetGroup.appendChild($layoutGroup);
    $svg.appendChild($offsetGroup);
    $svg.appendChild($interactionsGroup);

    this.$el.appendChild($svg);
    // removes additionnal height added who knows why...
    this.$el.style.fontSize = 0;
    // fixes one of the (many ?) weird canvas rendering bugs in Chrome
    this.$el.style.transform = 'translateZ(0)';

    this.$layout = $layoutGroup;
    this.$offset = $offsetGroup;
    this.$interactions = $interactionsGroup;
    this.$svg = $svg;
    this.$background = $background
  }

  /**
   * Adds a layer to the track
   */
  add(layer) {
    this.layers.push(layer);
    // Create a default renderingContext for the layer if missing
    this.$layout.appendChild(layer.$el);
  }

  /**
   * Removes a layer
   */
  remove(layer) {
    this.layers.splice(this.layers.indexOf(layer), 1);
    // Removes layer from its container
    this.$layout.removeChild(layer.$el);
  }

  /**
   * Draw tracks, and the layers in cascade
   */
  render() {
    for (let layer of this) { layer.render(); }
  }

  /**
   * Update the layers
   */
  update(layers = null) {
    this.updateContainer();
    this.updateLayers(layers);
  }

  updateContainer() {
    const $svg = this.$svg;
    const $offset = this.$offset;
    // should be in some update layout
    const renderingContext = this.renderingContext;
    const height  = this.height;
    const width   = renderingContext.visibleWidth;
    const offsetX = renderingContext.xScale(renderingContext.offset);
    const translate = `translate(${offsetX}, 0)`;

    $svg.setAttributeNS(null, 'height', height);
    $svg.setAttributeNS(null, 'width', width);
    $svg.setAttributeNS(null, 'viewbox', `0 0 ${width} ${height}`);

    $offset.setAttributeNS(null, 'transform', translate);
  }

  updateLayers(layers = null) {
    layers = (layers === null) ? this.layers : layers;

    layers.forEach((layer) => {
      if (this.layers.indexOf(layer) === -1) { return; }
      layer.update();
    });
  }

  *[Symbol.iterator]() {
    yield* this.layers[Symbol.iterator]()
  }
}
<|endoftext|>


<commit_before>'use strict';

const slackr = require('slackr');
const Router = require('express').Router;
const route = new Router();

const ApiUser = require('./model').ApiUser;
const filters = require('./filters');
const keygen = require('../../lib/keygen');

const APPS_FREE = process.env.APPS_FREE || 1;

if (module.parent.exports.nunjucks) {
  Object.keys(filters).forEach(filter => {
    module.parent.exports.nunjucks.addFilter(filter, filters[filter]);
  });
}

// get api user for authenticated user
route.use('/', (req, res, next) => {
  const query = {
    'owner.userId': req.session.auth.userId,
  };

  ApiUser.findOne(query, (err, api) => {
    if (err) { return next(err); }
    req.api = api;
    return next();
  });
});

// redirect user to profile
route.use('/', (req, res, next) => {
  if (!req.api || req.api.validateSync()) {
    return res.redirect('/profile');
  }

  return next();
});

route.use('/', (req, res, next) => {
  if (req.api.apps.length === 0 && /^\/app\/?$/.test(req.originalUrl)) {
    return res.redirect('/app/new');
  }

  return next();
});

route.get('/', (req, res) => {
  const error = req.session.message;
  delete req.session.message;

  res.render('app/index.html', { req, keys: req.api.apps, error });
});

route.get('/new', (req, res) => {
  let error = req.session.message;
  delete req.session.message;

  if (!error && req.api.apps.length >= APPS_FREE) {
    error = {
      class: 'info',
      title: 'Godkjenning kreves',
      message: 'Nye applikasjoner gå gjennom godkjenning før de blir aktiv.',
    };
  }

  res.render('app/new.html', { req, error });
});

route.post('/new', (req, res, next) => {
  const app = req.api.apps.create({
    name: req.body.name,
    url: req.body.url || undefined,
    desc: req.body.desc,
    active: req.api.apps.length < APPS_FREE,
    approved: req.api.apps.length < APPS_FREE,
  });

  // Add the new application to the user
  req.api.apps.push(app);

  const error = req.api.validateSync();
  if (error) {
    const key = Object.keys(error.errors)[0];
    req.session.message = error.errors[key];

    res.set('x-app-status', 'failure');
    res.set('x-app-message', 'validation_error');
    res.redirect(303, '/app/new');
    return;
  }

  req.api.save(err => {
    if (err) { next(err); return; }

    // Construct Slack notification message
    const message = {
      text: 'En ny applikasjon har blitt registrert :tada:',
      attachments: [app.slackAttachment()],
    };

    // Warn about pending app approval.
    if (app.isPending) {
      req.session.message = {
        class: 'info',
        title: 'Venter på godkjenning',
        message: 'Din applikasjon venter på godkjenning.',
      };

      res.set('x-app-message', 'pending');

      // Add interactive Slack buttons for easy approval
      message.attachments.push(app.slackRequestApproval());

    // Inform about app created.
    } else {
      req.session.message = {
        class: 'positive',
        title: 'App opprettet',
        message: 'Din applikasjon ble suksessfullt opprettet.',
      };
    }

    // Post message to Slack
    slackr(message);

    res.set('x-app-status', 'success');
    res.redirect(303, '/app');
  });
});

route.param('id', (req, res, next, id) => {
  req.app = req.api.apps.id(id);

  if (!req.app) {
    req.session.message = {
      title: 'Lagring feilet',
      message: 'Applikasjon ble ikke funnet!',
    };

    res.set('x-app-status', 'failure');
    res.set('x-app-message', 'app_not_found');
    res.redirect(303, '/app');

    return;
  }

  next();
});

route.post('/:id', (req, res, next) => {
  req.app.set('name', req.body.name);
  req.app.set('url', req.body.url || undefined);
  req.app.set('desc', req.body.desc);

  if (req.body.generate_key_dev) {
    req.app.set('key.dev', keygen());
  }

  if (req.body.generate_key_prod) {
    req.app.set('key.prod', keygen());
  }

  // Prod rate-limit change request
  if (parseInt(req.body.limit_prod, 10) !== req.app.limit.prod) {
    req.app.limit.prodRequest = parseInt(req.body.limit_prod, 10);
  } else {
    req.app.limit.prodRequest = undefined;
  }

  // Dev rate-limit change request
  if (parseInt(req.body.limit_dev, 10) !== req.app.limit.dev) {
    req.app.limit.devRequest = parseInt(req.body.limit_dev, 10);
  } else {
    req.app.limit.devRequest = undefined;
  }

  const error = req.api.validateSync();
  if (error) {
    req.session.message = error[0];

    res.set('x-app-status', 'failure');
    res.set('x-app-message', 'validation_error');
    res.redirect(303, '/app');

    return;
  }

  req.api.save(saveErr => {
    if (saveErr) { next(saveErr); return; }

    req.session.message = {
      class: 'positive',
      title: 'App ppdatert',
      message: `Applikasjon "${req.body.name}" ble oppdatert suksessfullt.`,
      app: req.app._id,
    };

    res.set('x-app-status', 'success');
    res.redirect(303, '/app');

    return;
  });

  return;
});

route.post('/:id/disable', (req, res, next) => {
  req.app.active = false;
  req.api.save(saveErr => {
    if (saveErr) { next(saveErr); return; }

    req.session.message = {
      class: 'positive',
      title: 'App deaktivert',
      message: `Applikasjon "${req.app.name}" ble deaktivert!`,
      app: req.app._id,
    };

    res.set('x-app-status', 'success');
    res.redirect(303, '/app');

    return;
  });
});

route.get('*', (req, res) => res.redirect('/app'));

module.exports = route;
<commit_msg>chore(app): fix minor typo<commit_after>'use strict';

const slackr = require('slackr');
const Router = require('express').Router;
const route = new Router();

const ApiUser = require('./model').ApiUser;
const filters = require('./filters');
const keygen = require('../../lib/keygen');

const APPS_FREE = process.env.APPS_FREE || 1;

if (module.parent.exports.nunjucks) {
  Object.keys(filters).forEach(filter => {
    module.parent.exports.nunjucks.addFilter(filter, filters[filter]);
  });
}

// get api user for authenticated user
route.use('/', (req, res, next) => {
  const query = {
    'owner.userId': req.session.auth.userId,
  };

  ApiUser.findOne(query, (err, api) => {
    if (err) { return next(err); }
    req.api = api;
    return next();
  });
});

// redirect user to profile
route.use('/', (req, res, next) => {
  if (!req.api || req.api.validateSync()) {
    return res.redirect('/profile');
  }

  return next();
});

route.use('/', (req, res, next) => {
  if (req.api.apps.length === 0 && /^\/app\/?$/.test(req.originalUrl)) {
    return res.redirect('/app/new');
  }

  return next();
});

route.get('/', (req, res) => {
  const error = req.session.message;
  delete req.session.message;

  res.render('app/index.html', { req, keys: req.api.apps, error });
});

route.get('/new', (req, res) => {
  let error = req.session.message;
  delete req.session.message;

  if (!error && req.api.apps.length >= APPS_FREE) {
    error = {
      class: 'info',
      title: 'Godkjenning kreves',
      message: 'Nye applikasjoner gå gjennom godkjenning før de blir aktiv.',
    };
  }

  res.render('app/new.html', { req, error });
});

route.post('/new', (req, res, next) => {
  const app = req.api.apps.create({
    name: req.body.name,
    url: req.body.url || undefined,
    desc: req.body.desc,
    active: req.api.apps.length < APPS_FREE,
    approved: req.api.apps.length < APPS_FREE,
  });

  // Add the new application to the user
  req.api.apps.push(app);

  const error = req.api.validateSync();
  if (error) {
    const key = Object.keys(error.errors)[0];
    req.session.message = error.errors[key];

    res.set('x-app-status', 'failure');
    res.set('x-app-message', 'validation_error');
    res.redirect(303, '/app/new');
    return;
  }

  req.api.save(err => {
    if (err) { next(err); return; }

    // Construct Slack notification message
    const message = {
      text: 'En ny applikasjon har blitt registrert :tada:',
      attachments: [app.slackAttachment()],
    };

    // Warn about pending app approval.
    if (app.isPending) {
      req.session.message = {
        class: 'info',
        title: 'Venter på godkjenning',
        message: 'Din applikasjon venter på godkjenning.',
      };

      res.set('x-app-message', 'pending');

      // Add interactive Slack buttons for easy approval
      message.attachments.push(app.slackRequestApproval());

    // Inform about app created.
    } else {
      req.session.message = {
        class: 'positive',
        title: 'App opprettet',
        message: 'Din applikasjon ble suksessfullt opprettet.',
      };
    }

    // Post message to Slack
    slackr(message);

    res.set('x-app-status', 'success');
    res.redirect(303, '/app');
  });
});

route.param('id', (req, res, next, id) => {
  req.app = req.api.apps.id(id);

  if (!req.app) {
    req.session.message = {
      title: 'Lagring feilet',
      message: 'Applikasjon ble ikke funnet!',
    };

    res.set('x-app-status', 'failure');
    res.set('x-app-message', 'app_not_found');
    res.redirect(303, '/app');

    return;
  }

  next();
});

route.post('/:id', (req, res, next) => {
  req.app.set('name', req.body.name);
  req.app.set('url', req.body.url || undefined);
  req.app.set('desc', req.body.desc);

  if (req.body.generate_key_dev) {
    req.app.set('key.dev', keygen());
  }

  if (req.body.generate_key_prod) {
    req.app.set('key.prod', keygen());
  }

  // Prod rate-limit change request
  if (parseInt(req.body.limit_prod, 10) !== req.app.limit.prod) {
    req.app.limit.prodRequest = parseInt(req.body.limit_prod, 10);
  } else {
    req.app.limit.prodRequest = undefined;
  }

  // Dev rate-limit change request
  if (parseInt(req.body.limit_dev, 10) !== req.app.limit.dev) {
    req.app.limit.devRequest = parseInt(req.body.limit_dev, 10);
  } else {
    req.app.limit.devRequest = undefined;
  }

  const error = req.api.validateSync();
  if (error) {
    req.session.message = error[0];

    res.set('x-app-status', 'failure');
    res.set('x-app-message', 'validation_error');
    res.redirect(303, '/app');

    return;
  }

  req.api.save(saveErr => {
    if (saveErr) { next(saveErr); return; }

    req.session.message = {
      class: 'positive',
      title: 'App oppdatert',
      message: `Applikasjonen «${req.body.name}» ble oppdatert.`,
      app: req.app._id,
    };

    res.set('x-app-status', 'success');
    res.redirect(303, '/app');

    return;
  });

  return;
});

route.post('/:id/disable', (req, res, next) => {
  req.app.active = false;
  req.api.save(saveErr => {
    if (saveErr) { next(saveErr); return; }

    req.session.message = {
      class: 'positive',
      title: 'App deaktivert',
      message: `Applikasjonen «${req.app.name}» ble deaktivert!`,
      app: req.app._id,
    };

    res.set('x-app-status', 'success');
    res.redirect(303, '/app');

    return;
  });
});

route.get('*', (req, res) => res.redirect('/app'));

module.exports = route;
<|endoftext|>


<commit_before>#!/usr/bin/env node
const path = require('path');
const { createWorker } = require('../../');

const [,, imagePath] = process.argv;
const image = path.resolve(__dirname, (imagePath || '../../tests/assets/images/cosmic.png'));

console.log(`Recognizing ${image}`);
const worker = createWorker({
  logger: m => console.log(m),
});

(async () => {
  await worker.load();
  await worker.loadLanguage('eng');
  await worker.initialize('eng');
  await worker.setParameters({
    user_defined_dpi: '300',
  });
  const { data: { text } } = await worker.recognize(image);
  console.log(text);
  await worker.terminate();
})();
<commit_msg>Update example/recognize.js<commit_after>#!/usr/bin/env node
const path = require('path');
const { createWorker } = require('../../');

const [,, imagePath] = process.argv;
const image = path.resolve(__dirname, (imagePath || '../../tests/assets/images/cosmic.png'));

console.log(`Recognizing ${image}`);
const worker = createWorker({
  logger: m => console.log(m),
});

(async () => {
  await worker.load();
  await worker.loadLanguage('eng');
  await worker.initialize('eng');
  const { data: { text } } = await worker.recognize(image);
  console.log(text);
  await worker.terminate();
})();
<|endoftext|>


<commit_before>// @flow

/**
 * Like parallel.js, this was used to manage xhr requests, but to ensure that
 * they would run in series (only call the next function, after the previous
 * finishes
 * This is mostly deprecated also in favour for Promises
 *
 * Given an array of functions, it will call every function,
 * once at a time, sequentially.
 * Every function will have a trigger function as its last argument,
 * that should be called when the function is done.
 * If arguments are given to this trigger function, those will be passed
 * to the next function.
 *
 * e.g.:
 *
 * series([
 *  (next) => setTimeout(() => next(1)),
 *  (num, next) => setTimeout() => next()),
 *  (next) => next()
 * ]);
 *
 */
export default (fns: Function[]): void =>
  (function next(...args) {
    return fns.length ? fns.shift()(...[...args, next]) : undefined;
  })();
<commit_msg>fix(async/series): Update flowtype definition for series function<commit_after>// @flow

import type { VariadicFn } from '../functional/types.js.flow';

/**
 * Like parallel.js, this was used to manage xhr requests, but to ensure that
 * they would run in series (only call the next function, after the previous
 * finishes
 * This is mostly deprecated also in favour for Promises
 *
 * Given an array of functions, it will call every function,
 * once at a time, sequentially.
 * Every function will have a trigger function as its last argument,
 * that should be called when the function is done.
 * If arguments are given to this trigger function, those will be passed
 * to the next function.
 *
 * e.g.:
 *
 * series([
 *  (next) => setTimeout(() => next(1)),
 *  (num, next) => setTimeout() => next()),
 *  (next) => next()
 * ]);
 *
 */
export default (fns: VariadicFn<*, *>[]): void =>
  (function next(...args) {
    return fns.length ? fns.shift()(...[...args, next]) : undefined;
  })();
<|endoftext|>


<commit_before>/*global require, exports*/
(function() {
    "use strict";

    var CLIEngine = require("./node_modules/eslint/lib/cli-engine");

    function lintFile(options) {
        try {
            var engine = new CLIEngine(options.options);
            var result = engine.executeOnFiles(options.files);
            var messages = result.results.map(function(file) {
                return {
                    file: file.file,
                    messages: file.messages.map(function(message) {
                        delete message.node;
                        return message;
                    })
                };
            });
            return JSON.stringify(messages);
        } catch (e) {
            return JSON.stringify(e);
        }
    }

    exports.init = function init(domainManager) {
        if (!domainManager.hasDomain("ESLintWrapper")) {
            domainManager.registerDomain("ESLintWrapper", { major: 0, minor: 1 });
        }
        domainManager.registerCommand(
            "ESLintWrapper",
            "lint",
            lintFile,
            false,
            "Returns lint warnings and errors",
            [{
                name: "options",
                type: "object",
                description: "Options to invoke ESLint with"
            }]
        );
    };
}());
<commit_msg>Tabs > Spaces<commit_after>/*global require, exports*/
(function() {
"use strict";

	var CLIEngine = require("./node_modules/eslint/lib/cli-engine");

	function lintFile(options) {
		try {
			var engine = new CLIEngine(options.options);
			var result = engine.executeOnFiles(options.files);
			var messages = result.results.map(function(file) {
				return {
					file: file.file,
					messages: file.messages.map(function(message) {
						delete message.node;
						return message;
					})
				};
			});
			return JSON.stringify(messages);
		} catch (e) {
			return JSON.stringify(e);
		}
	}

	exports.init = function init(domainManager) {
		if (!domainManager.hasDomain("ESLintWrapper")) {
			domainManager.registerDomain("ESLintWrapper", { major: 0, minor: 1 });
		}
		domainManager.registerCommand(
			"ESLintWrapper",
			"lint",
			lintFile,
			false,
			"Returns lint warnings and errors",
			[{
				name: "options",
				type: "object",
				description: "Options to invoke ESLint with"
			}]
		);
	};
}());
<|endoftext|>


<commit_before>import { isNumber } from '../common/utils'

import Atomic from '../atomic'

// 2n ** (64n - 1n) - 1n
const INT64_MAX = BigInt(9223372036854775807)

/**
 * 64-bit big-endian two's complement integer OSC Atomic Data Type
 */
export default class AtomicInt64 extends Atomic {
  /**
   * Create an AtomicInt64 instance
   * @param {number} [value] Initial integer value
   */
  constructor(value) {
    if (typeof value !== 'bigint') {
      throw new Error('OSC AtomicInt64 constructor expects value of type number')
    }

    if (value > INT64_MAX) {
      throw new Error('OSC AtomicInt64 value is out of bounds')
    }

    super(BigInt.asIntN(64, value))
  }

  /**
   * Interpret the given number as packed binary data
   * @return {Uint8Array} Packed binary data
   */
  pack() {
    return super.pack('setBigInt64', 8)
  }

  /**
   * Unpack binary data from DataView and read a Int64 number
   * @param {DataView} dataView The DataView holding the binary representation of the value
   * @param {number} [initialOffset=0] Offset of DataView before unpacking
   * @return {number} Offset after unpacking
   */
  unpack(dataView, initialOffset = 0) {
    return super.unpack(dataView, 'getBigInt64', 8, initialOffset)
  }
}
<commit_msg>Fix AtomicInt64 constructor<commit_after>import { isNumber } from '../common/utils'

import Atomic from '../atomic'

// 2n ** (64n - 1n) - 1n
const INT64_MAX = BigInt(9223372036854775807)

/**
 * 64-bit big-endian two's complement integer OSC Atomic Data Type
 */
export default class AtomicInt64 extends Atomic {
  /**
   * Create an AtomicInt64 instance
   * @param {number} [value] Initial integer value
   */
  constructor(value) {
    if (value && typeof value !== 'bigint') {
      throw new Error('OSC AtomicInt64 constructor expects value of type BigInt')
    }

    if (value && value > INT64_MAX) {
      throw new Error('OSC AtomicInt64 value is out of bounds')
    }

    if (value) {
      value = BigInt.asIntN(64, value)
    }

    super(value)
  }

  /**
   * Interpret the given number as packed binary data
   * @return {Uint8Array} Packed binary data
   */
  pack() {
    return super.pack('setBigInt64', 8)
  }

  /**
   * Unpack binary data from DataView and read a Int64 number
   * @param {DataView} dataView The DataView holding the binary representation of the value
   * @param {number} [initialOffset=0] Offset of DataView before unpacking
   * @return {number} Offset after unpacking
   */
  unpack(dataView, initialOffset = 0) {
    return super.unpack(dataView, 'getBigInt64', 8, initialOffset)
  }
}
<|endoftext|>


<commit_before>var {defineSupportCode} = require('cucumber');
const {pushNewScreenshots} = require('../support/utils/updateSnaphots');

defineSupportCode(function({Before, After, registerHandler}) {

  Before(function(scenarioResult) {
    const before = (this.config.before) ? this.config.before : (() => Promise.resolve());

    return before(this.caps)
      .then(() => this.driver.init(this.caps))
      .then(() => {
        this.driver.setAsyncScriptTimeout(30000)
        return Promise.resolve();
      })
  })
  After(function() {
    if (this.config.after) {
      return this.config.after(this.caps)
        .then(() => this.driver.quit())
        .catch(e => {
          console.log(e);
          return this.driver.quit();
        })
    }
    return this.driver.quit();
  });
  const world = this;
  registerHandler('AfterFeatures', function(features, callback) {
    pushNewScreenshots()
      .then(callback)
      .catch(callback)
  });
});<commit_msg>Ignore error if push new screenshots exited with non-0 code<commit_after>var {defineSupportCode} = require('cucumber');
const {pushNewScreenshots} = require('../support/utils/updateSnaphots');

defineSupportCode(function({Before, After, registerHandler}) {

  Before(function(scenarioResult) {
    const before = (this.config.before) ? this.config.before : (() => Promise.resolve());

    return before(this.caps)
      .then(() => this.driver.init(this.caps))
      .then(() => {
        this.driver.setAsyncScriptTimeout(30000)
        return Promise.resolve();
      })
  })
  After(function() {
    if (this.config.after) {
      return this.config.after(this.caps)
        .then(() => this.driver.quit())
        .catch(e => {
          console.log(e);
          return this.driver.quit();
        })
    }
    return this.driver.quit();
  });
  const world = this;
  registerHandler('AfterFeatures', function(features, callback) {
    pushNewScreenshots()
      .then(callback)
      .catch(() => callback())
  });
});<|endoftext|>


<commit_before>if (typeof define !== 'function') { var define = require('amdefine')(module) }
define( function(require,exports,module){

    var $         = require('jquery');
    var t         = require('../templates');
    var RefBinder = require('ref-binder');
    var View      = require('backbone').View;
    var self;

    var TableCopyAndPasteFeature = module.exports = View.extend({

        events: {
            'mousedown .es-table-cell': 'cellsSelectionMousedown',
            'mouseover .es-table-cell': 'cellsSelectionMouseover',
            'mouseup .es-table-cell'  : 'cellsSelectionMouseup',
            'keydown': 'inputKeypress'
        },

        es: null,
        table: null,
        data: null,
        model: null,
        isMouseDown: false,
        startColIndex: 0,
        startRowIndex:  0,
        rowStart: 0,
        rowEnd: 0,
        riwIndex: null,
        colStart: 0,
        colEnd: 0,
        colIndex: 0,
        current_cell: null,

        initialize: function(o){
            this.models = new RefBinder(this);
            this.table = o.table;
            this.data  = o.data;
            this.es    = o.es;
            this.setSheet(o.data.sheets.get(o.data.users.getCurrentUser().getCurrentSheetId()) || null);
            self = this;

            //set copy and paste handlers
            ['copy','paste'].forEach(function(event) {
                document.addEventListener(event, function(e) {
                    switch(event) {
                        case 'copy':
                            self.onCopy(e);
                            break;
                        case 'paste':
                            self.onPaste(e);
                            break;
                    }
                });
            });

            //bind keyword event
            this.es.keyboard.on('37',this.cellsSelectionKeydown);
            this.es.keyboard.on('38',this.cellsSelectionKeydown);
            this.es.keyboard.on('39',this.cellsSelectionKeydown);
            this.es.keyboard.on('40',this.cellsSelectionKeydown);
            this.es.keyboard.on('shift_37',this.cellsSelectionKeydown);
            this.es.keyboard.on('shift_38',this.cellsSelectionKeydown);
            this.es.keyboard.on('shift_39',this.cellsSelectionKeydown);
            this.es.keyboard.on('shift_40',this.cellsSelectionKeydown);
            this.es.keyboard.on('13',this.cellsSelectionKeydown);//enter
            this.es.keyboard.on('27',this.cellsSelectionKeydown);//escape
            this.es.keyboard.on('46',this.cellsSelectionKeydown);//canc
        },

        getSheet: function(){
            return this.models.get('sheet');
        },

        setSheet: function(sheet){
            this.models.set('sheet',sheet);
        },

        getId: function(){
            //userd to get cid
            return this.data.users.getCurrentUser().getCurrentSheetId();
        },

        selectTo: function(cell) {
            var currentColIndex = cell.index();
            currentColIndex = (currentColIndex < 0) ? this.startColIndex : currentColIndex;
            var currentRowIndex = cell.parent().index();
            currentRowIndex = (currentRowIndex < 0) ? this.startRowIndex : currentRowIndex;

            if (currentRowIndex < this.startRowIndex) {
                this.rowStart = currentRowIndex;
                this.rowEnd = this.startRowIndex;
            } else {
                this.rowStart = this.startRowIndex;
                this.rowEnd = currentRowIndex;
            }

            if (currentColIndex < this.startColIndex) {
                this.colStart = currentColIndex;
                this.colEnd = this.startColIndex;
            } else {
                this.colStart = this.startColIndex;
                this.colEnd = currentColIndex;
            }

            for (var i = this.rowStart; i <= this.rowEnd; i++) {
                var rowCells = $('#es-grid-'+this.getId()).find("tr").eq(i).find("td");
                for (var j = this.colStart; j <= this.colEnd; j++) {
                    rowCells.eq(j).addClass("cpselected");
                }
            }
        },

        resetSelection: function(cell){
            this.current_cell = cell;
            this.table.$grid.find(".cpselected").removeClass("cpselected"); // deselect everything
            cell.addClass("cpselected");
            this.colIndex  = this.colStart = this.colEnd = this.startColIndex = cell.index();
            this.rowIndex  = this.rowStart = this.rowEnd = this.startRowIndex = cell.parent().index();
        },

        cellsSelectionMousedown: function(e)
        {
            //user try to resize the cell
            this.table.setCellDragTarget(e);
            if (this.table.isDraggingCell()){
                return false;
            }

            if(e.which == 3){
                this.table.$grid.find(".cpselected").removeClass("cpselected"); // deselect everything
                this.table.showCellMenu(e);
                return false;
            }

            this.table.clearOverlays();
            this.isMouseDown = true;
            this.editingCell = false;

            if (e.shiftKey) {
                this.selectTo(cell);
            } else {
                this.resetSelection( $(e.currentTarget));
            }
            return true; // prevent text selection
        },

        cellsSelectionMouseover: function(e){
            if (!this.isMouseDown) return;
            this.table.$grid.find(".cpselected").removeClass("cpselected");
            this.selectTo($(e.currentTarget));
        },

        cellsSelectionMouseup: function(e){
            if(this.table.isDraggingCell()) this.table.cellMouseUp(e);
            this.isMouseDown = false;
        },

        //KEYBOARD EVENTS STUFFS

        //hendler for cell editing
        inputKeypress: function(e){
            //return unless code is 'enter' or 'tab'
            var code = (e.keyCode ? e.keyCode : e.which);
            if(code != 13 && code != 9 && code != 27) return;

            //to fix
            /*var cells = this.table.getLocalSelection().getCells();
            _.each(cells, function(cell){
                self.getSheet().commitCell(cell.row_id.toString(), cell.col_id.toString());
            }, this);*/

            switch(code){
                case 13://ENTER
                    self.table.moveSelection(e,1,0);
                    break;
                case 9://TAB
                    self.table.moveSelection(e,0,1);//right
                    break;
                case 27://ESC
                    self.table.clearOverlays();
                    self.editingCell = false;
                    self.resetSelection(self.current_cell);
                    break;
            }
            return false;
        },

        //Keypress when cell in not active. Just for copy & paste feature.
        cellsSelectionKeydown: function(e){

            if(self.editingCell == true){
                $('textarea')._onKeyDown(e);
                return false;
            }

            var code = (e.keyCode ? e.keyCode : e.which);

            //to fix
            /*var cells = self.table.getLocalSelection();
            _.each(cells, function(cell){
                self.getSheet().commitCell(cell.row_id.toString(), cell.col_id.toString());
            }, self);*/

            var cell = null;
            var sheet_table =  $('#es-grid-'+self.getId());
            sheet_table.find(".cpselected").removeClass("cpselected");

            switch(code){
                case 37://LEFT ARROW
                    cell = sheet_table.find("tr").eq(self.rowIndex).find("td").eq( (self.colIndex <= 0) ? 0 : --self.colIndex );
                    break;
                case 38://UP ARROW
                    cell = sheet_table.find("tr").eq((self.rowIndex <= 0) ? 0 :  --self.rowIndex).find("td").eq(self.colIndex);
                    break;
                case 39://RIGHT ARROW
                    cell = sheet_table.find("tr").eq(self.rowIndex).find("td").eq( (self.colIndex < self.getSheet().cols.length) ? ++self.colIndex : self.colIndex );
                    break;
                case 40://DOWN ARROW
                    cell = sheet_table.find("tr").eq( (self.rowIndex < self.getSheet().rows.length) ? ++self.rowIndex : self.rowIndex ).find("td").eq(self.colIndex);
                    break;
                case 13://ENTER
                    //user's dragging a cell to resize it
                    if (self.table.isDraggingCell()) return;

                    cell = sheet_table.find("tr").eq(self.rowIndex).find("td").eq(self.colIndex);
                    self.table.clearOverlays();
                    self.table.getLocalSelection().addCell(self.getSheet().id,$(cell).data().row_id.toString(),$(cell).data().col_id.toString());
                    self.current_cell = cell;
                    self.editingCell = true;
                    break;
                case 46://CANC
                    for (var i = self.rowStart; i <= self.rowEnd; i++) {
                        for (var j = self.colStart; j <= self.colEnd; j++) {
                            cell = self.table.$grid.find("tr").eq(i).find("td").eq(j);
                            self.getSheet().updateCell($(cell).attr('data-row_id'), $(cell).attr('data-col_id'),"");
                        }
                    }
                    break;
            }

            if (e.shiftKey) {
                self.selectTo(cell);
            } else {
                self.resetSelection(cell)
            }

            return false;
        },

        //COPY AND PASTE HANDLERS

        onPaste: function(e){
            var cell = null;
            try {
                var clipRows = e.clipboardData.getData('text/plain').split(String.fromCharCode(13));
                for (var i = 0; (i < clipRows.length && i + this.startColIndex < this.getSheet().rowCount()); i++) {
                    clipRows[i] = clipRows[i].split(String.fromCharCode(9));
                    for (var j = 0; (j < clipRows[i].length && j + this.startColIndex < this.getSheet().colCount()); j++) {
                        cell = this.table.$grid.find("tr").eq(i + this.startRowIndex).find("td").eq(j + this.startColIndex);
                        this.getSheet().updateCell($(cell).attr('data-row_id'), $(cell).attr('data-col_id'), clipRows[i][j]);
                    }
                }
            }catch(e){
                console.log("onPaste error : " + e);
            }
        },

        onCopy: function(e){
            try {
                e.clipboardData.setData('text/plain', "");
                var cbData = "";
                for (var i = this.rowStart; i <= this.rowEnd; i++) {
                    var rowCells = this.table.$grid.find("tr").eq(i).find("td");
                    for (var j = this.colStart; j <= this.colEnd; j++)
                        cbData += $(rowCells.eq(j)).html() + ((j != this.colEnd) ? String.fromCharCode(9) : "");

                    if(i != this.rowEnd)cbData += String.fromCharCode(13);
                }
                e.clipboardData.setData('text/plain', cbData);
                e.preventDefault();
            }catch(e){
                console.log("onCopy error : " + e);
            }
        }

    })
});
<commit_msg>Ethersheet copy and paste bug fixing<commit_after>if (typeof define !== 'function') { var define = require('amdefine')(module) }
define( function(require,exports,module){

    var $         = require('jquery');
    var t         = require('../templates');
    var RefBinder = require('ref-binder');
    var View      = require('backbone').View;
    var self;

    var TableCopyAndPasteFeature = module.exports = View.extend({

        events: {
            'mousedown .es-table-cell': 'cellsSelectionMousedown',
            'mouseover .es-table-cell': 'cellsSelectionMouseover',
            'mouseup .es-table-cell'  : 'cellsSelectionMouseup',
            'dblclick .es-table-cell': 'cellClicked',
            'keydown': 'inputKeypress'
        },

        es: null,
        table: null,
        data: null,
        model: null,
        isMouseDown: false,
        startColIndex: 0,
        startRowIndex:  0,
        rowStart: 0,
        rowEnd: 0,
        riwIndex: null,
        colStart: 0,
        colEnd: 0,
        colIndex: 0,
        current_cell: null,

        initialize: function(o){
            this.models = new RefBinder(this);
            this.table = o.table;
            this.data  = o.data;
            this.es    = o.es;
            this.setSheet(o.data.sheets.get(o.data.users.getCurrentUser().getCurrentSheetId()) || null);
            self = this;

            //set copy and paste handlers
            ['copy','paste'].forEach(function(event) {
                document.addEventListener(event, function(e) {
                    switch(event) {
                        case 'copy':
                            self.onCopy(e);
                            break;
                        case 'paste':
                            self.onPaste(e);
                            break;
                    }
                });
            });

            //bind keyword event
            this.es.keyboard.on('37',this.cellsSelectionKeydown);
            this.es.keyboard.on('38',this.cellsSelectionKeydown);
            this.es.keyboard.on('39',this.cellsSelectionKeydown);
            this.es.keyboard.on('40',this.cellsSelectionKeydown);
            this.es.keyboard.on('shift_37',this.cellsSelectionKeydown);
            this.es.keyboard.on('shift_38',this.cellsSelectionKeydown);
            this.es.keyboard.on('shift_39',this.cellsSelectionKeydown);
            this.es.keyboard.on('shift_40',this.cellsSelectionKeydown);
            this.es.keyboard.on('13',this.cellsSelectionKeydown);//enter
            this.es.keyboard.on('27',this.cellsSelectionKeydown);//escape
            this.es.keyboard.on('46',this.cellsSelectionKeydown);//canc
        },

        getSheet: function(){
            return this.models.get('sheet');
        },

        setSheet: function(sheet){
            this.models.set('sheet',sheet);
        },

        getId: function(){
            //userd to get cid
            return this.data.users.getCurrentUser().getCurrentSheetId();
        },

        selectTo: function(cell) {
            var currentColIndex = cell.index();
            currentColIndex = (currentColIndex < 0) ? this.startColIndex : currentColIndex;
            var currentRowIndex = cell.parent().index();
            currentRowIndex = (currentRowIndex < 0) ? this.startRowIndex : currentRowIndex;

            if (currentRowIndex < this.startRowIndex) {
                this.rowStart = currentRowIndex;
                this.rowEnd = this.startRowIndex;
            } else {
                this.rowStart = this.startRowIndex;
                this.rowEnd = currentRowIndex;
            }

            if (currentColIndex < this.startColIndex) {
                this.colStart = currentColIndex;
                this.colEnd = this.startColIndex;
            } else {
                this.colStart = this.startColIndex;
                this.colEnd = currentColIndex;
            }

            for (var i = this.rowStart; i <= this.rowEnd; i++) {
                var rowCells = $('#es-grid-'+this.getId()).find("tr").eq(i).find("td");
                for (var j = this.colStart; j <= this.colEnd; j++) {
                    rowCells.eq(j).addClass("cpselected");
                }
            }
        },

        resetSelection: function(cell){
            this.current_cell = cell;
            this.table.$grid.find(".cpselected").removeClass("cpselected"); // deselect everything
            cell.addClass("cpselected");
            this.colIndex  = this.colStart = this.colEnd = this.startColIndex = cell.index();
            this.rowIndex  = this.rowStart = this.rowEnd = this.startRowIndex = cell.parent().index();
        },

        cellsSelectionMousedown: function(e)
        {
            //user try to resize the cell
            this.table.setCellDragTarget(e);
            if (this.table.isDraggingCell()){
                return false;
            }

            if(e.which == 3){
                this.table.$grid.find(".cpselected").removeClass("cpselected"); // deselect everything
                this.table.showCellMenu(e);
                return false;
            }

            this.table.clearOverlays();
            this.isMouseDown = true;
            this.editingCell = false;

            if (e.shiftKey) {
                this.selectTo(cell);
            } else {
                this.resetSelection( $(e.currentTarget));
            }
            return true; // prevent text selection
        },

        cellsSelectionMouseover: function(e){
            if (!this.isMouseDown) return;
            this.table.$grid.find(".cpselected").removeClass("cpselected");
            this.selectTo($(e.currentTarget));
        },

        cellsSelectionMouseup: function(e){
            if(this.table.isDraggingCell()) this.table.cellMouseUp(e);
            this.isMouseDown = false;
        },

        cellClicked: function(e){
           this.editingCell = true;
        },

        //KEYBOARD EVENTS STUFFS

        //hendler for cell editing
        inputKeypress: function(e){
            //return unless code is 'enter' or 'tab'
            var code = (e.keyCode ? e.keyCode : e.which);
            if(code != 13 && code != 9 && code != 27) return;

            //to fix
            /*var cells = this.table.getLocalSelection().getCells();
            _.each(cells, function(cell){
                self.getSheet().commitCell(cell.row_id.toString(), cell.col_id.toString());
            }, this);*/

            switch(code){
                case 13://ENTER
                    self.table.moveSelection(e,1,0);
                    break;
                case 9://TAB
                    self.table.moveSelection(e,0,1);//right
                    break;
                case 27://ESC
                    self.table.clearOverlays();
                    self.editingCell = false;
                    self.resetSelection(self.current_cell);
                    break;
            }
            return false;
        },

        //Keypress when cell in not active. Just for copy & paste feature.
        cellsSelectionKeydown: function(e){

            if(self.editingCell == true){
                $('textarea')._onKeyDown(e);
                return false;
            }

            var code = (e.keyCode ? e.keyCode : e.which);

            //to fix
            /*var cells = self.table.getLocalSelection();
            _.each(cells, function(cell){
                self.getSheet().commitCell(cell.row_id.toString(), cell.col_id.toString());
            }, self);*/

            var cell = null;
            var sheet_table =  $('#es-grid-'+self.getId());
            sheet_table.find(".cpselected").removeClass("cpselected");

            switch(code){
                case 37://LEFT ARROW
                    cell = sheet_table.find("tr").eq(self.rowIndex).find("td").eq( (self.colIndex <= 0) ? 0 : --self.colIndex );
                    break;
                case 38://UP ARROW
                    cell = sheet_table.find("tr").eq((self.rowIndex <= 0) ? 0 :  --self.rowIndex).find("td").eq(self.colIndex);
                    break;
                case 39://RIGHT ARROW
                    cell = sheet_table.find("tr").eq(self.rowIndex).find("td").eq( (self.colIndex < self.getSheet().cols.length) ? ++self.colIndex : self.colIndex );
                    break;
                case 40://DOWN ARROW
                    cell = sheet_table.find("tr").eq( (self.rowIndex < self.getSheet().rows.length) ? ++self.rowIndex : self.rowIndex ).find("td").eq(self.colIndex);
                    break;
                case 13://ENTER
                    //user's dragging a cell to resize it
                    if (self.table.isDraggingCell()) return;

                    cell = sheet_table.find("tr").eq(self.rowIndex).find("td").eq(self.colIndex);
                    self.table.clearOverlays();
                    self.table.getLocalSelection().addCell(self.getSheet().id,$(cell).data().row_id.toString(),$(cell).data().col_id.toString());
                    self.current_cell = cell;
                    self.editingCell = true;
                    break;
                case 46://CANC
                    for (var i = self.rowStart; i <= self.rowEnd; i++) {
                        for (var j = self.colStart; j <= self.colEnd; j++) {
                            cell = self.table.$grid.find("tr").eq(i).find("td").eq(j);
                            self.getSheet().updateCell($(cell).attr('data-row_id'), $(cell).attr('data-col_id'),"");
                        }
                    }
                    break;
            }

            if (e.shiftKey) {
                self.selectTo(cell);
            } else {
                self.resetSelection(cell)
            }

            return false;
        },

        //COPY AND PASTE HANDLERS

        onPaste: function(e){
            var cell = null;
            try {
                var clipRows = e.clipboardData.getData('text/plain').split(String.fromCharCode(13));
                for (var i = 0; (i < clipRows.length && i + this.startColIndex < this.getSheet().rowCount()); i++) {
                    clipRows[i] = clipRows[i].split(String.fromCharCode(9));
                    for (var j = 0; (j < clipRows[i].length && j + this.startColIndex < this.getSheet().colCount()); j++) {
                        cell = this.table.$grid.find("tr").eq(i + this.startRowIndex).find("td").eq(j + this.startColIndex);
                        this.getSheet().updateCell($(cell).attr('data-row_id'), $(cell).attr('data-col_id'), clipRows[i][j]);
                    }
                }
            }catch(e){
                console.log("onPaste error : " + e);
            }
        },

        onCopy: function(e){
            try {
                e.clipboardData.setData('text/plain', "");
                var cbData = "";
                for (var i = this.rowStart; i <= this.rowEnd; i++) {
                    var rowCells = this.table.$grid.find("tr").eq(i).find("td");
                    for (var j = this.colStart; j <= this.colEnd; j++)
                        cbData += $(rowCells.eq(j)).html() + ((j != this.colEnd) ? String.fromCharCode(9) : "");

                    if(i != this.rowEnd)cbData += String.fromCharCode(13);
                }
                e.clipboardData.setData('text/plain', cbData);
                e.preventDefault();
            }catch(e){
                console.log("onCopy error : " + e);
            }
        }

    })
});
<|endoftext|>


<commit_before>export const SEARCHING = 'searching';
export const SUCCESS = 'success';
export const ERROR = 'error';
export const INITIALISE = 'initialise';

export const initialSearchState = {
  isSearching: false,
  hasErrors: false
};

export const reducer = (state, { type, results }) => {
  switch (type) {
    case SEARCHING:
      return {
        ...state,
        hasErrors: false,
        isSearching: true
      };
    case SUCCESS:
      return {
        ...state,
        isSearching: false,
        results
      };
    case ERROR:
      return {
        ...state,
        hasErrors: true,
        isSearching: false
      };
    case INITIALISE:
      return initialSearchState;
    default:
      throw new Error();
  }
};
<commit_msg>Empty results after searching / error<commit_after>export const SEARCHING = 'searching';
export const SUCCESS = 'success';
export const ERROR = 'error';
export const INITIALISE = 'initialise';

export const initialSearchState = {
  isSearching: false,
  hasErrors: false,
  results: [],
};

export const reducer = (state, { type, results }) => {
  switch (type) {
    case SEARCHING:
      return {
        ...state,
        hasErrors: false,
        isSearching: true,
        results: [],
      };
    case SUCCESS:
      return {
        ...state,
        isSearching: false,
        results
      };
    case ERROR:
      return {
        ...state,
        hasErrors: true,
        isSearching: false,
        results: [],
      };
    case INITIALISE:
      return initialSearchState;
    default:
      throw new Error();
  }
};
<|endoftext|>


<commit_before>import React from 'react';

import AttributesKit from '../../src';
import EditorComponent from './Editor';
import JsonFormatterComponent from './JsonFormatter';
import actionTypes from '../actions/types';
import dispatcher from '../dispatcher';

class Playground extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      title: true,
      collapseByDefault: true,
      maxInheritanceDepth: undefined,
      namedTypes: false,
      includedProperties: 'show',
      inheritedProperties: 'show',
      parseResult: {
        dataStructures: [],
        errors: [],
      },
    };

    this.dispatcherIds = [];
  };

  componentDidMount() {
    this.dispatcherIds.push(dispatcher.register(this.onChange));
  };

  componentWillUnmount() {
    this.dispatcherIds.forEach((id) => dispatcher.unregister(id));
  };

  onChange = (payload) => {
    if (payload.type === actionTypes.MSON_PARSED) {
      this.setState({ parseResult: payload });
    }
  };

  onElementLinkClick = (parentName) => {
    alert(`Element ‘${parentName}’ clicked!`);
  };

  toggleTitle = (eventObject) => {
    const value = eventObject.currentTarget.value;
    console.debug(`Setting the ‘title’ option to ‘${value}’...`);
    this.setState({
      title: value,
    });
  };

  toggleInheritedProperties = (eventObject) => {
    const value = eventObject.currentTarget.value;
    console.debug(`Setting the ‘inheritedProperties’ option to ‘${value}’...`);
    this.setState({
      inheritedProperties: value,
    });
  };

  toggleIncludedProperties = (eventObject) => {
    const value = eventObject.currentTarget.value;
    console.debug(`Setting the ‘includedProperties’ option to ‘${value}’...`);
    this.setState({
      includedProperties: value,
    });
  };

  toggleIncludedProperties = (eventObject) => {
    const value = eventObject.currentTarget.value;
    console.debug(`Setting the ‘includedProperties’ option to ‘${value}’...`);
    this.setState({
      includedProperties: value,
    });
  };

  toggleInheritanceDepth = (eventObject) => {
    const value = parseInt(eventObject.currentTarget.value, 10);
    console.debug(`Setting the ‘maxInheritanceDepth’ option to ‘${value}’...`);
    this.setState({
      maxInheritanceDepth: value,
    });
  };

  toggleCollapseByDefault = () => {
    this.setState({
      collapseByDefault: !this.state.collapseByDefault,
    });
  };

  toggleNamedTypes = () => {
    this.setState({
      namedTypes: !this.state.namedTypes,
    });
  };

  render() {
    const dataStructures = this.state.parseResult.dataStructures || [];

    return (

          <EditorComponent
            errors={this.state.parseResult.errors}
          />

          {
            dataStructures.length > 0 &&
              <JsonFormatterComponent
                element={this.state.parseResult.dataStructures[0]}
                dataStructures={dataStructures}
              />
          }

Options

                Title

              <select
                id="titleSelect"
                onChange={this.toggleTitle}
              >
                <option value="show">Show</option>
                <option value="hide">Hide</option>
              </select>

                Inherited Properties

              <select
                id="inheritedPropertiesSelect"
                onChange={this.toggleInheritedProperties}
              >
                <option value="show">Show</option>
                <option value="hide">Hide</option>
                <option value="group">Group</option>
                <option value="tag">Tag</option>
                <option value="placeholder">Placeholder</option>
              </select>

                Included Properties

              <select
                id="includedPropertiesSelect"
                onChange={this.toggleIncludedProperties}
              >
                <option value="show">Show</option>
                <option value="hide">Hide</option>
                <option value="group">Group</option>
                <option value="tag">Tag</option>
                <option value="placeholder">Placeholder</option>
              </select>

                Inheritance Depth

              <input
                type="text"
                id="inheritanceDepthInput"
                onChange={this.toggleInheritanceDepth}
                placeholder="Infinity"
              />

                Named Types

              <input
                type="checkbox"
                id="namedTypesCheckbox"
                onChange={this.toggleNamedTypes}
              />

                Collapse by default

              <input
                defaultChecked
                type="checkbox"
                id="collapseByDefaultCheckbox"
                onChange={this.toggleCollapseByDefault}
              />

          {
            dataStructures.length > 0 &&
              <AttributesKit.Attributes
                collapseByDefault={this.state.collapseByDefault}
                dataStructures={dataStructures}
                element={this.state.parseResult.dataStructures[0]}
                includedProperties={this.state.includedProperties}
                inheritedProperties={this.state.inheritedProperties}
                maxInheritanceDepth={this.state.maxInheritanceDepth}
                onElementLinkClick={this.onElementLinkClick}
                title={this.state.title}
                namedTypes={this.state.namedTypes}
              />
          }

    );
  };
}

export default Playground;
<commit_msg>Temporary remove the ‘maxInheritanceDepth’ option from Playground, we'll get back to that.<commit_after>import React from 'react';

import AttributesKit from '../../src';
import EditorComponent from './Editor';
import JsonFormatterComponent from './JsonFormatter';
import actionTypes from '../actions/types';
import dispatcher from '../dispatcher';

class Playground extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      title: true,
      collapseByDefault: true,
      namedTypes: false,
      includedProperties: 'show',
      inheritedProperties: 'show',
      parseResult: {
        dataStructures: [],
        errors: [],
      },
    };

    this.dispatcherIds = [];
  };

  componentDidMount() {
    this.dispatcherIds.push(dispatcher.register(this.onChange));
  };

  componentWillUnmount() {
    this.dispatcherIds.forEach((id) => dispatcher.unregister(id));
  };

  onChange = (payload) => {
    if (payload.type === actionTypes.MSON_PARSED) {
      this.setState({ parseResult: payload });
    }
  };

  onElementLinkClick = (parentName) => {
    alert(`Element ‘${parentName}’ clicked!`);
  };

  toggleTitle = (eventObject) => {
    const value = eventObject.currentTarget.value;
    console.debug(`Setting the ‘title’ option to ‘${value}’...`);
    this.setState({
      title: value,
    });
  };

  toggleInheritedProperties = (eventObject) => {
    const value = eventObject.currentTarget.value;
    console.debug(`Setting the ‘inheritedProperties’ option to ‘${value}’...`);
    this.setState({
      inheritedProperties: value,
    });
  };

  toggleIncludedProperties = (eventObject) => {
    const value = eventObject.currentTarget.value;
    console.debug(`Setting the ‘includedProperties’ option to ‘${value}’...`);
    this.setState({
      includedProperties: value,
    });
  };

  toggleIncludedProperties = (eventObject) => {
    const value = eventObject.currentTarget.value;
    console.debug(`Setting the ‘includedProperties’ option to ‘${value}’...`);
    this.setState({
      includedProperties: value,
    });
  };

  toggleCollapseByDefault = () => {
    this.setState({
      collapseByDefault: !this.state.collapseByDefault,
    });
  };

  toggleNamedTypes = () => {
    this.setState({
      namedTypes: !this.state.namedTypes,
    });
  };

  render() {
    const dataStructures = this.state.parseResult.dataStructures || [];

    return (

          <EditorComponent
            errors={this.state.parseResult.errors}
          />

          {
            dataStructures.length > 0 &&
              <JsonFormatterComponent
                element={this.state.parseResult.dataStructures[0]}
                dataStructures={dataStructures}
              />
          }

Options

                Title

              <select
                id="titleSelect"
                onChange={this.toggleTitle}
              >
                <option value="show">Show</option>
                <option value="hide">Hide</option>
              </select>

                Inherited Properties

              <select
                id="inheritedPropertiesSelect"
                onChange={this.toggleInheritedProperties}
              >
                <option value="show">Show</option>
                <option value="hide">Hide</option>
                <option value="group">Group</option>
                <option value="tag">Tag</option>
                <option value="placeholder">Placeholder</option>
              </select>

                Included Properties

              <select
                id="includedPropertiesSelect"
                onChange={this.toggleIncludedProperties}
              >
                <option value="show">Show</option>
                <option value="hide">Hide</option>
                <option value="group">Group</option>
                <option value="tag">Tag</option>
                <option value="placeholder">Placeholder</option>
              </select>

                Named Types

              <input
                type="checkbox"
                id="namedTypesCheckbox"
                onChange={this.toggleNamedTypes}
              />

                Collapse by default

              <input
                defaultChecked
                type="checkbox"
                id="collapseByDefaultCheckbox"
                onChange={this.toggleCollapseByDefault}
              />

          {
            dataStructures.length > 0 &&
              <AttributesKit.Attributes
                collapseByDefault={this.state.collapseByDefault}
                dataStructures={dataStructures}
                element={this.state.parseResult.dataStructures[0]}
                includedProperties={this.state.includedProperties}
                inheritedProperties={this.state.inheritedProperties}
                onElementLinkClick={this.onElementLinkClick}
                title={this.state.title}
                namedTypes={this.state.namedTypes}
              />
          }

    );
  };
}

export default Playground;
<|endoftext|>