<commit_before>function Mushra(config) {

    this.config = config;
    this.pageCounter = 0;
    this.numberOfSounds = 0;
    this.numberOfPages = this.config.pages.length;
    this.have_seen_this_page_before = arrayFilledWith(false, this.numberOfPages);

    // Order of pages
    this.pageOrder = fromAToBArray(0, this.numberOfPages);
    if (this.config.randomise_pages)
        shuffle(this.pageOrder);

    // Order of sounds within page
    this.soundOrder = [];
    for (var i = 0; i < this.numberOfPages; ++i)
    {
        var numberOfSounds = this.config.pages[this.pageOrder[i]].sounds.length;
        var order = fromAToBArray(0, numberOfSounds);
        if (this.config.randomise_sounds_within_page)
            shuffle(order);
        this.soundOrder.push(order);
    }

    this.configureNextAndBackButton();
    this.loadPage();
}

Mushra.prototype.onNextOrBackButtonClick = function(direction)
{
    // If we are on the submission page, only allow previous test
    if (this.pageCounter == this.numberOfPages)
    {
        if(direction < 0)
        {
            this.pageCounter += direction;
            this.loadPage();
        }
    }
    // If final test page, allow complete
    else if (this.pageCounter == (this.numberOfPages - 1) && direction > 0)
    {
        this.fillConfig();
        this.pageCounter += direction;
        this.complete();
    }
    // Otherwise allow back or forward
    else
    {
        this.fillConfig();
        this.pageCounter += direction;
        if (this.pageCounter < 0)
            this.pageCounter = 0;
        else
            this.loadPage();
    }
}

Mushra.prototype.configureNextAndBackButton = function()
{
    $activePage ('.next-test').on("click", function(){

        if (this.loader.haveAllBuffersPlayed() ||
            !this.config.must_play_all_samples_to_continue)
        {
            this.onNextOrBackButtonClick(1);
        }
        else
        {
            $activePage (".listen-to-all-samples-popup").popup("open");
            setTimeout(function(){
                $activePage (".listen-to-all-samples-popup").popup("close");
            }, 5000);
        }

    }.bind(this));

    $activePage ('.previous-test').on("click", function(){
        this.onNextOrBackButtonClick(-1);
    }.bind(this));
}

Mushra.prototype.loadPage = function()
{
    this.updatePageCounter();

    // Remove sliders and stop current audio (if any)
    if (this.loader)
        this.loader.stop();

    this.currentPage = this.pageOrder[this.pageCounter];
    this.currentPageSoundOrder = this.soundOrder[this.pageCounter];
    var numberOfSounds = this.currentPageSoundOrder.length;

    this.urls = new Array(numberOfSounds);

    for (var i = 0; i < numberOfSounds; ++i)
    {
        var thisSound = this.config.pages[this.currentPage].sounds[this.currentPageSoundOrder[i]];
        this.urls[i] = this.config.siteURL + '/' + thisSound.url;
    }

    // Add the url to the reference audio. No need to store id here.
    this.urls.push(
        this.config.siteURL + '/' + this.config.pages[this.currentPage].reference_url);

    // Configure the audio loader
    this.loader = new AudioLoader(this.urls, null);
    this.loader.continuousPlayback = this.config.continuous_playback;
    this.loader.loopPlayback = this.config.loop_playback;
    this.loader.load();

    // Stop audio
    $activePage ('.mushra-stop').on("click", this.loader.stop.bind(this.loader));

    // Reference
    $activePage ('.mushra-reference').on("click", function(i){
        this.loader.play(i);
    }.bind(this, numberOfSounds));

    this.createSliders();

    if (!this.have_seen_this_page_before[this.pageCounter])
        this.have_seen_this_page_before[this.pageCounter] = true;
}

Mushra.prototype.createSliders = function()
{
    $activePage ('.mushra-slider-container').empty();

    var numberOfSounds = this.currentPageSoundOrder.length;
    for (var i = 0; i < numberOfSounds; ++i)
    {
        var startVal = 0;
        if (this.have_seen_this_page_before[this.pageCounter])
            startVal = this.config.pages[this.currentPage].sounds[this.currentPageSoundOrder[i]].rating;
        else if (this.config.randomise_slider_handle)
            startVal = randomNumber(0, 100, true);

        // The slider, triggers audio when user makes adjustment.
        var inputHTML = "<input type='range' name='slider' " +
        "value='" + startVal + "' min='0' max='100'";

        if (this.config.include_number_box)
            inputHTML += "/>";
        else
            inputHTML += "class='ui-hidden-accessible'/>";

        $activePage ('.mushra-slider-container').append(inputHTML);
    }

    $activePage ('.mushra-slider-container').enhanceWithin();

    // Play audio when slider is moved
    var playFunc = function (i) {
            this.loader.play(i)
    }.bind(this);

    $activePage (".ui-slider").each(function (i) {

        $(this).on('slidestart', function (i) {

            // play this audio file
            playFunc (i);
            // change handle colour when slider is moved
            $(this).find('a').addClass('slider-handle-active');
            // Give focus to the handle even if handle is clicked
            $(this).find('a').focus();

        }.bind(this, i));
    });
}

Mushra.prototype.fillConfig = function()
{
    var setRating = function(i, value) {
        this.config.pages[this.currentPage].sounds[this.currentPageSoundOrder[i]].rating = value;
    }.bind(this);

    $activePage (".mushra-slider").each( function (i) {
        setRating (i, $(this).val());
    });
}

Mushra.prototype.complete = function()
{
    // Build an array of arrays for the ratings
    var values = '[';
    var sounds = '[';
    var pages = '[';

    for (var i = 0; i < this.numberOfPages; ++i)
    {
        values += '[';
        sounds += '[';

        var numSounds = this.config.pages[i].sounds.length;

        for (var j = 0; j < numSounds; ++j)
        {
            values += this.config.pages[i].sounds[j].rating;
            sounds += this.config.pages[i].sounds[j].name;

            if (j == numSounds - 1)
            {
                values += ']';
                sounds += ']';
            }
            else
            {
                values += ',';
                sounds += ',';
            }
        }

        pages += this.config.pages[i].name;
        if (i == this.numberOfPages - 1)
        {
            pages += ']';
            values += ']';
            sounds += ']';
        }
        else
        {
            pages += ',';
            values += '],';
            sounds += '],';
        }
    }

    // Append inputs to the form
    $('<input>').attr({
            type: 'hidden',
            name: 'fields[data]',
            value: values,
        }).appendTo ('div.submit-popup > form');

    $('<input>').attr({
            type: 'hidden',
            name: 'fields[sounds]',
            value: sounds,
        }).appendTo ('div.submit-popup > form');

    $('<input>').attr({
            type: 'hidden',
            name: 'fields[pages]',
            value: pages,
        }).appendTo ('div.submit-popup > form');

    $activePage ('.submit-popup').popup('open');
}

Mushra.prototype.updatePageCounter = function()
{
   $activePage ('.title').html((this.pageCounter + 1) + ' / ' + this.numberOfPages);
}
<commit_msg>Fixed rating capture<commit_after>function Mushra(config) {

    this.config = config;
    this.pageCounter = 0;
    this.numberOfSounds = 0;
    this.numberOfPages = this.config.pages.length;
    this.have_seen_this_page_before = arrayFilledWith(false, this.numberOfPages);

    // Order of pages
    this.pageOrder = fromAToBArray(0, this.numberOfPages);
    if (this.config.randomise_pages)
        shuffle(this.pageOrder);

    // Order of sounds within page
    this.soundOrder = [];
    for (var i = 0; i < this.numberOfPages; ++i)
    {
        var numberOfSounds = this.config.pages[this.pageOrder[i]].sounds.length;
        var order = fromAToBArray(0, numberOfSounds);
        if (this.config.randomise_sounds_within_page)
            shuffle(order);
        this.soundOrder.push(order);
    }

    this.configureNextAndBackButton();
    this.loadPage();
}

Mushra.prototype.onNextOrBackButtonClick = function(direction)
{
    // If we are on the submission page, only allow previous test
    if (this.pageCounter == this.numberOfPages)
    {
        if(direction < 0)
        {
            this.pageCounter += direction;
            this.loadPage();
        }
    }
    // If final test page, allow complete
    else if (this.pageCounter == (this.numberOfPages - 1) && direction > 0)
    {
        this.fillConfig();
        this.pageCounter += direction;
        this.complete();
    }
    // Otherwise allow back or forward
    else
    {
        this.fillConfig();
        this.pageCounter += direction;
        if (this.pageCounter < 0)
            this.pageCounter = 0;
        else
            this.loadPage();
    }
}

Mushra.prototype.configureNextAndBackButton = function()
{
    $activePage ('.next-test').on("click", function(){

        if (this.loader.haveAllBuffersPlayed() ||
            !this.config.must_play_all_samples_to_continue)
        {
            this.onNextOrBackButtonClick(1);
        }
        else
        {
            $activePage (".listen-to-all-samples-popup").popup("open");
            setTimeout(function(){
                $activePage (".listen-to-all-samples-popup").popup("close");
            }, 5000);
        }

    }.bind(this));

    $activePage ('.previous-test').on("click", function(){
        this.onNextOrBackButtonClick(-1);
    }.bind(this));
}

Mushra.prototype.loadPage = function()
{
    this.updatePageCounter();

    // Remove sliders and stop current audio (if any)
    if (this.loader)
        this.loader.stop();

    this.currentPage = this.pageOrder[this.pageCounter];
    this.currentPageSoundOrder = this.soundOrder[this.pageCounter];
    var numberOfSounds = this.currentPageSoundOrder.length;

    this.urls = new Array(numberOfSounds);

    for (var i = 0; i < numberOfSounds; ++i)
    {
        var thisSound = this.config.pages[this.currentPage].sounds[this.currentPageSoundOrder[i]];
        this.urls[i] = this.config.siteURL + '/' + thisSound.url;
    }

    // Add the url to the reference audio. No need to store id here.
    this.urls.push(
        this.config.siteURL + '/' + this.config.pages[this.currentPage].reference_url);

    // Configure the audio loader
    this.loader = new AudioLoader(this.urls, null);
    this.loader.continuousPlayback = this.config.continuous_playback;
    this.loader.loopPlayback = this.config.loop_playback;
    this.loader.load();

    // Stop audio
    $activePage ('.mushra-stop').on("click", this.loader.stop.bind(this.loader));

    // Reference
    $activePage ('.mushra-reference').on("click", function(i){
        this.loader.play(i);
    }.bind(this, numberOfSounds));

    this.createSliders();

    if (!this.have_seen_this_page_before[this.pageCounter])
        this.have_seen_this_page_before[this.pageCounter] = true;
}

Mushra.prototype.createSliders = function()
{
    $activePage ('.mushra-slider-container').empty();

    var numberOfSounds = this.currentPageSoundOrder.length;
    for (var i = 0; i < numberOfSounds; ++i)
    {
        var startVal = 0;
        if (this.have_seen_this_page_before[this.pageCounter])
            startVal = this.config.pages[this.currentPage].sounds[this.currentPageSoundOrder[i]].rating;
        else if (this.config.randomise_slider_handle)
            startVal = randomNumber(0, 100, true);

        // The slider, triggers audio when user makes adjustment.
        var inputHTML = "<input type='range' name='slider' " +
        "value='" + startVal + "' min='0' max='100'";

        if (this.config.include_number_box)
            inputHTML += "/>";
        else
            inputHTML += "class='ui-hidden-accessible'/>";

        $activePage ('.mushra-slider-container').append(inputHTML);
    }

    $activePage ('.mushra-slider-container').enhanceWithin();

    // Play audio when slider is moved
    var playFunc = function (i) {
            this.loader.play(i)
    }.bind(this);

    $activePage (".ui-slider").each(function (i) {

        $(this).on('slidestart', function (i) {

            // play this audio file
            playFunc (i);
            // change handle colour when slider is moved
            $(this).find('a').addClass('slider-handle-active');
            // Give focus to the handle even if handle is clicked
            $(this).find('a').focus();

        }.bind(this, i));
    });
}

Mushra.prototype.fillConfig = function()
{
    var setRating = function(i, value) {
        this.config.pages[this.currentPage].sounds[this.currentPageSoundOrder[i]].rating = value;
    }.bind(this);

    $activePage (".ui-slider input").each( function (i) {
        setRating (i, $(this).val());
    });
}

Mushra.prototype.complete = function()
{
    // Build an array of arrays for the ratings
    var values = '[';
    var sounds = '[';
    var pages = '[';

    for (var i = 0; i < this.numberOfPages; ++i)
    {
        values += '[';
        sounds += '[';

        var numSounds = this.config.pages[i].sounds.length;

        for (var j = 0; j < numSounds; ++j)
        {
            values += this.config.pages[i].sounds[j].rating;
            sounds += this.config.pages[i].sounds[j].name;

            if (j == numSounds - 1)
            {
                values += ']';
                sounds += ']';
            }
            else
            {
                values += ',';
                sounds += ',';
            }
        }

        pages += this.config.pages[i].name;
        if (i == this.numberOfPages - 1)
        {
            pages += ']';
            values += ']';
            sounds += ']';
        }
        else
        {
            pages += ',';
            values += '],';
            sounds += '],';
        }
    }

    // Append inputs to the form
    $('<input>').attr({
            type: 'hidden',
            name: 'fields[data]',
            value: values,
        }).appendTo ('div.submit-popup > form');

    $('<input>').attr({
            type: 'hidden',
            name: 'fields[sounds]',
            value: sounds,
        }).appendTo ('div.submit-popup > form');

    $('<input>').attr({
            type: 'hidden',
            name: 'fields[pages]',
            value: pages,
        }).appendTo ('div.submit-popup > form');

    $activePage ('.submit-popup').popup('open');
}

Mushra.prototype.updatePageCounter = function()
{
   $activePage ('.title').html((this.pageCounter + 1) + ' / ' + this.numberOfPages);
}
<|endoftext|>


<commit_before>/* bender-tags: editor,unit */
/* bender-ckeditor-plugins: wysiwygarea,structuredheadings,toolbar,basicstyles,dialog,richcombo */

// Clean up all instances been created on the page.
(function () {

  var comboName = "NumFormats";

  bender.editor = {
    allowedForTests: "h1; h2; p"
  };

  bender.test({
    setUp: function () {
      //Anything to be run before each test if needed
    },

    "if no headings in document, the new heading is autonumbered": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click h2
        combo.onClick("h2");
        // the new h2 has autonumbering set, since no prior heading exists
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied h2 block autonumberstyle"
        );
      });
    },

    "if previous heading is autonumber, the new heading is autonumbered": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
bar

^foo
");

      bot.combo(comboName, function (combo) {
        // click h2
        combo.onClick("h2");
        // the new h2 has autonumbering set, at the next level from h1
        assert.areSame(
            "
bar
" +
            "
^foo
",
            bot.htmlWithSelection(),
            "applied h2 block autonumber style"
        );
      });
    },

    "if previous heading is not autonumber, the new heading is not autonumbered": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
bar

^foo
");

      bot.combo(comboName, function (combo) {
        // click h2
        combo.onClick("h2");
        // the new heading doesn't have autonumbering, since the prior heading did not
        assert.areSame(
            "
bar

^foo
",
            bot.htmlWithSelection(),
            "applied h2 block non-autonumbered style"
        );
      });
    },

    "p option no-ops": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click p
        combo.onClick("p");
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied p to p"
        );
      });
    },

    "p on autonumbered heading removes classes": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click p
        combo.onClick("p");
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied p to h1"
        );
      });
    },
    "pre option on a p": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click pre
        combo.onClick("pre");
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied pre to p"
        );
      });
    },

    "pre on autonumbered heading removes autonumbering classes": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click pre
        combo.onClick("pre");
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied pre to h1"
        );
      });
    }

  });
})();
<commit_msg>i assume we need the undo to be able to test undo<commit_after>/* eslint-disable */
/* bender-tags: editor,unit */
/* bender-ckeditor-plugins: wysiwygarea,structuredheadings,toolbar,basicstyles,dialog,richcombo,undo */
/* eslint-enable */

// Clean up all instances been created on the page.
(function () {

  var comboName = "NumFormats";

  bender.editor = {
    allowedForTests: "h1; h2; p"
  };

  bender.test({
    setUp: function () {
      //Anything to be run before each test if needed
    },

    "if no headings in document, the new heading is autonumbered": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click h2
        combo.onClick("h2");
        // the new h2 has autonumbering set, since no prior heading exists
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied h2 block autonumberstyle"
        );
      });
    },

    "if previous heading is autonumber, the new heading is autonumbered": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
bar

^foo
");

      bot.combo(comboName, function (combo) {
        // click h2
        combo.onClick("h2");
        // the new h2 has autonumbering set, at the next level from h1
        assert.areSame(
            "
bar
" +
            "
^foo
",
            bot.htmlWithSelection(),
            "applied h2 block autonumber style"
        );
      });
    },

    "if previous heading is not autonumber, the new heading is not autonumbered": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
bar

^foo
");

      bot.combo(comboName, function (combo) {
        // click h2
        combo.onClick("h2");
        // the new heading doesn't have autonumbering, since the prior heading did not
        assert.areSame(
            "
bar

^foo
",
            bot.htmlWithSelection(),
            "applied h2 block non-autonumbered style"
        );
      });
    },

    "p option no-ops": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click p
        combo.onClick("p");
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied p to p"
        );
      });
    },

    "p on autonumbered heading removes classes": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click p
        combo.onClick("p");
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied p to h1"
        );
      });
    },
    "pre option on a p": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click pre
        combo.onClick("pre");
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied pre to p"
        );
      });
    },

    "pre on autonumbered heading removes autonumbering classes": function () {
      var bot = this.editorBot;
      bot.setHtmlWithSelection("
^foo
");

      bot.combo(comboName, function (combo) {
        // click pre
        combo.onClick("pre");
        assert.areSame(
            "
^foo
",
            bot.htmlWithSelection(),
            "applied pre to h1"
        );
      });
    }

  });
})();
<|endoftext|>


<commit_before>const React = require('react');
const h = require('react-hyperscript');
const Link = require('react-router-dom').Link;
const queryString = require('query-string');
const _ = require('lodash');
const classNames = require('classnames');

const { fetch } = require('../../../util');
const { MAX_SIF_NODES, NS_HGNC_SYMBOL, NS_GENECARDS, NS_NCBI_GENE, NS_UNIPROT } = require('../../../config');

const ENTITY_OTHER_NAMES_LIMIT = 4;
const ENTITY_SUMMARY_DISPLAY_LIMIT = 6;

const SUPPORTED_COLLECTIONS = new Map([
  [NS_GENECARDS, 'GeneCards'],
  [NS_HGNC_SYMBOL, 'HGNC'],
  [NS_NCBI_GENE, 'NCBI Gene'],
  [NS_UNIPROT, 'UniProt']
]);

const getHgncFromXref = xrefLinks => {
  let symbol;
  const hgncXrefLink = _.find( xrefLinks, link  => link.namespace === NS_HGNC_SYMBOL );
  if( hgncXrefLink ) symbol = _.last( _.compact( hgncXrefLink.uri.split('/') ) );
  return symbol;
};

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

    this.state = {
      expanded: props.expanded || false
    };

  }
  render(){
    let { summary } = this.props;
    let { displayName, description, aliasIds, xrefLinks } = summary;
    const hgncSymbol = getHgncFromXref( xrefLinks );

    let sortedLinks = xrefLinks.sort( (p1, p2) => p1.namespace > p2.namespace ? 1: -1 )
        .map( link => h( 'a.plain-link', { href: link.uri, target:'_blank' }, SUPPORTED_COLLECTIONS.get( link.namespace ) ) );

    let moreInfo = h('div.entity-more-info',[
      h('div.entity-names', [
        h('div.entity-other-names', [
          h('h5', 'Other Names'),
          aliasIds.slice(0, ENTITY_OTHER_NAMES_LIMIT).join(', ')
        ])
      ]),
      description != '' ? h('div.entity-description', [
        h('h5', 'Description'),
        h('div', [ description ])
      ]) : null
    ]);

    return (
      h('div.entity-summary-box', [
        h('div.entity-summary-title', { onClick: () => this.setState({ expanded: !this.state.expanded }) }, [
          h('h3.entity-title', `${hgncSymbol}: ${displayName}`),
          ...sortedLinks,
          this.state.expanded ? h('i.material-icons', 'expand_more') : h('i.material-icons', 'keyboard_arrow_right')
        ]),
        this.state.expanded ? moreInfo : null
      ])
    );

  }
}

// props:
//  - entityQuery (List of strings representing genes)
class EntitySummaryBoxList extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      img: ''
    };
  }

  getInteractionsPreviewImage( sources ){
    let { img } = this.state;
    if( img ){ return `url(${img})`; }

    let numSources = sources.length;

    if( numSources === 1 ){
      return `url(${'/img/interactions-placeholder-single.png'})`;
    }

    if( numSources === 2 ){
      return `url(${'/img/interactions-placeholder-double.png'})`;
    }

    if( numSources === 3 ){
      return `url(${'img/interactions-placeholder-triple.png'})`;
    }
  }

  componentDidMount(){
    let { entitySummaryResults } = this.props;
    let hgncSymbols = entitySummaryResults.map( summaryResult => getHgncFromXref( _.get( summaryResult, ['summary', 'xrefLinks'] ) ) );

    fetch('/api/interactions/image?' + queryString.stringify({ sources: hgncSymbols })).then( r => r.json() ).then( res => {
      let { img } = res;
      this.setState({ img });
    });
  }

  render(){
    let { entitySummaryResults } = this.props;
    let sources = entitySummaryResults.map( summaryResult => getHgncFromXref( _.get( summaryResult, ['summary', 'xrefLinks'] ) ) );
    let singleSrcLabel = `View interactions between ${sources[0]} and top ${MAX_SIF_NODES} genes`;
    let multiSrcLabel = `View iteractions between ${sources.slice(0, sources.length - 1).join(', ')} and ${sources.slice(-1)}`;
    let interactionsLinkLabel = sources.length === 1 ? singleSrcLabel : multiSrcLabel;

    let entitySummaryBoxes = entitySummaryResults
       .slice( 0, ENTITY_SUMMARY_DISPLAY_LIMIT )
       .map( summaryResult => {
         const summary = _.get( summaryResult, 'summary' );
         let props = { summary };
         return h(EntitySummaryBox, props);
       });

    let img = this.getInteractionsPreviewImage(sources);

    return h('div.entity-summary-list', [
      h('div.entity-summary-view-interactions', [
        h(Link, {
          target: '_blank',
          className: 'entity-summary-interactions-snapshot-container',
          to: {
            pathname: '/interactions',
            search: queryString.stringify({ source: sources.join(',') })
          }
        }, [
          h('div.entity-summary-interactions-snapshot', { style: { backgroundImage: img } }),
          h('button.entity-summary-interactions-snapshot-button', {
            className: classNames('entity-summary-interactions-snapshot-button', sources.length === 1 ? 'snapshot-button-center' : 'snapshot-button-left')
          }, [
            h('div', interactionsLinkLabel)
          ])
        ]),
        h('div.entity-summary-list-entries', entitySummaryBoxes),
      ])
    ]);
  }
}

module.exports = EntitySummaryBoxList;
<commit_msg>add dummy link to enrichment from the search app<commit_after>const React = require('react');
const h = require('react-hyperscript');
const Link = require('react-router-dom').Link;
const queryString = require('query-string');
const _ = require('lodash');
const classNames = require('classnames');

const { fetch } = require('../../../util');
const { MAX_SIF_NODES, NS_HGNC_SYMBOL, NS_GENECARDS, NS_NCBI_GENE, NS_UNIPROT } = require('../../../config');

const ENTITY_OTHER_NAMES_LIMIT = 4;
const ENTITY_SUMMARY_DISPLAY_LIMIT = 6;

const SUPPORTED_COLLECTIONS = new Map([
  [NS_GENECARDS, 'GeneCards'],
  [NS_HGNC_SYMBOL, 'HGNC'],
  [NS_NCBI_GENE, 'NCBI Gene'],
  [NS_UNIPROT, 'UniProt']
]);

const getHgncFromXref = xrefLinks => {
  let symbol;
  const hgncXrefLink = _.find( xrefLinks, link  => link.namespace === NS_HGNC_SYMBOL );
  if( hgncXrefLink ) symbol = _.last( _.compact( hgncXrefLink.uri.split('/') ) );
  return symbol;
};

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

    this.state = {
      expanded: props.expanded || false
    };

  }
  render(){
    let { summary } = this.props;
    let { displayName, description, aliasIds, xrefLinks } = summary;
    const hgncSymbol = getHgncFromXref( xrefLinks );

    let sortedLinks = xrefLinks.sort( (p1, p2) => p1.namespace > p2.namespace ? 1: -1 )
        .map( link => h( 'a.plain-link', { href: link.uri, target:'_blank' }, SUPPORTED_COLLECTIONS.get( link.namespace ) ) );

    let moreInfo = h('div.entity-more-info',[
      h('div.entity-names', [
        h('div.entity-other-names', [
          h('h5', 'Other Names'),
          aliasIds.slice(0, ENTITY_OTHER_NAMES_LIMIT).join(', ')
        ])
      ]),
      description != '' ? h('div.entity-description', [
        h('h5', 'Description'),
        h('div', [ description ])
      ]) : null
    ]);

    return (
      h('div.entity-summary-box', [
        h('div.entity-summary-title', { onClick: () => this.setState({ expanded: !this.state.expanded }) }, [
          h('h3.entity-title', `${hgncSymbol}: ${displayName}`),
          ...sortedLinks,
          this.state.expanded ? h('i.material-icons', 'expand_more') : h('i.material-icons', 'keyboard_arrow_right')
        ]),
        this.state.expanded ? moreInfo : null
      ])
    );

  }
}

// props:
//  - entityQuery (List of strings representing genes)
class EntitySummaryBoxList extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      img: ''
    };
  }

  getInteractionsPreviewImage( sources ){
    let { img } = this.state;
    if( img ){ return `url(${img})`; }

    let numSources = sources.length;

    if( numSources === 1 ){
      return `url(${'/img/interactions-placeholder-single.png'})`;
    }

    if( numSources === 2 ){
      return `url(${'/img/interactions-placeholder-double.png'})`;
    }

    if( numSources === 3 ){
      return `url(${'img/interactions-placeholder-triple.png'})`;
    }
  }

  componentDidMount(){
    let { entitySummaryResults } = this.props;
    let hgncSymbols = entitySummaryResults.map( summaryResult => getHgncFromXref( _.get( summaryResult, ['summary', 'xrefLinks'] ) ) );

    fetch('/api/interactions/image?' + queryString.stringify({ sources: hgncSymbols })).then( r => r.json() ).then( res => {
      let { img } = res;
      this.setState({ img });
    });
  }

  render(){
    let { entitySummaryResults } = this.props;
    let sources = entitySummaryResults.map( summaryResult => getHgncFromXref( _.get( summaryResult, ['summary', 'xrefLinks'] ) ) );
    let singleSrcLabel = `View interactions between ${sources[0]} and top ${MAX_SIF_NODES} genes`;
    let multiSrcLabel = `View iteractions between ${sources.slice(0, sources.length - 1).join(', ')} and ${sources.slice(-1)}`;
    let interactionsLinkLabel = sources.length === 1 ? singleSrcLabel : multiSrcLabel;

    let entitySummaryBoxes = entitySummaryResults
       .slice( 0, ENTITY_SUMMARY_DISPLAY_LIMIT )
       .map( summaryResult => {
         const summary = _.get( summaryResult, 'summary' );
         let props = { summary };
         return h(EntitySummaryBox, props);
       });

    let img = this.getInteractionsPreviewImage(sources);

    return h('div.entity-summary-list', [
      h('div.enrichment-link', [
        h(Link, {
          target: '_blank',
          to: {
            pathname: '/enrichment',
            search: queryString.stringify({ source: sources.join(',')})
          }
        }, 'Enrichment')
      ]),
      h('div.entity-summary-view-interactions', [
        h(Link, {
          target: '_blank',
          className: 'entity-summary-interactions-snapshot-container',
          to: {
            pathname: '/interactions',
            search: queryString.stringify({ source: sources.join(',') })
          }
        }, [
          h('div.entity-summary-interactions-snapshot', { style: { backgroundImage: img } }),
          h('button.entity-summary-interactions-snapshot-button', {
            className: classNames('entity-summary-interactions-snapshot-button', sources.length === 1 ? 'snapshot-button-center' : 'snapshot-button-left')
          }, [
            h('div', interactionsLinkLabel)
          ])
        ]),
        h('div.entity-summary-list-entries', entitySummaryBoxes)
      ])
    ]);
  }
}

module.exports = EntitySummaryBoxList;
<|endoftext|>


<commit_before>Mapeditor.Minimap = {};

Mapeditor.Minimap.loaded = false;

Mapeditor.Minimap.loadStatic = function(){
  jQuery('#minimap .content')
    .html('<img />');
  jQuery('#minimap img')
    .attr('src', Mapeditor.config.urls.backend + 'map/' + Mapeditor.map.meta.id + '/minimap?' + new Date().getTime())
    .css({
        'max-width': 'none',
        position: 'relative',
        left: (100)-(Mapeditor.map.meta.width/2),
        top: (100)-(Mapeditor.map.meta.height/2)
      });
  Mapeditor.Minimap.loaded = true;
}
<commit_msg>Move to coordinate when clicked<commit_after>Mapeditor.Minimap = {};

Mapeditor.Minimap.loaded = false;

Mapeditor.Minimap.loadStatic = function(){
  jQuery('#minimap .content')
    .html('<img />');
  jQuery('#minimap img')
    .attr('src', Mapeditor.config.urls.backend + 'map/' + Mapeditor.map.meta.id + '/minimap?' + new Date().getTime())
    .css({
        'max-width': 'none',
        position: 'relative',
        left: (100)-(Mapeditor.map.meta.width/2),
        top: (100)-(Mapeditor.map.meta.height/2)
      }).click(function(e){
        var pos_x = e.offsetX ? (e.offsetX) : e.pageX-this.offsetLeft;
        var pos_y = e.offsetY ? (e.offsetY) : e.pageY-this.offsetTop;
        jQuery(this).css({
          left: (100 - pos_x),
          top: (100 - pos_y)
        });
        Mapeditor.internals.infinitedrag.center(pos_x, pos_y);
      });
  Mapeditor.Minimap.loaded = true;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

const CLI = require('commander');
const PKG = require('../package.json');

const LOG = console.log;

/**
 * Установка флагов/параметров для командной строки
 */
CLI
  .version(PKG.version, '-v, --version')
  .description(PKG.description)
  .on('--help', () => {
    LOG(`\nCommands help:\n  ${PKG.name} [command] --help\n  mmd [command] --help`);
  });

/**
 * инициализация нового проекта
 */
CLI
  .command('init [dir]')
  .description('initialize new project')
  .option('-t, --test', 'required for testing')
  .option('--bootstrap [donor]', 'initialize new project with bootstrap included', false)
  .option('-c, --css [styl,scss,sass]', 'set stylesheet <engine> support', 'styl')
  .action((dir, opts) => {
    require('../commands/init')(dir, opts);
  });

/**
 * старт сервера разработки
 */
//
CLI
  .command('dev')
  .description('run development server')
  .option('-a, --auth [user@password]', 'set user@password for authorization')
  .option('--proxy-mod', 'proxy mode with copy files from build')
  .option('--build', 'build project once')
  .option('--minify', 'minify js and css')
  .action((dev) => {
    require('../commands/dev')(dev);
  })
  .on('--help', () => {
    // console.log();
  });

/**
 * создание страницы
 */
CLI
  .command('cp <name>')
  .description('create new page')
  .action((pageName) => {
    require('../commands/cp')(pageName);
  });

/**
 * создание блока
 */
CLI
  .command('cb <name>')
  .description('create new block')
  .option('-t, --techs [html,js,css,json]', 'Files extensions for new block')
  .action((pageName, opts) => {
    require('../commands/cb')(pageName, opts.techs);
  });

/**
 * линтера сборки
 */
CLI
  .command('lint')
  .description('lint project')
  .action((opts) => {
    require('../commands/lint')(opts.techs);
  });

/**
 * Prettier
 */
CLI
  .command('format')
  .description('Format project code (HTML only temporarily)')
  .action((opts) => {
    require('../commands/format')(opts);
  });

/**
 * Archive
 */
CLI
  .command('pack [name]')
  .description('Archive project source code (default:tar.gz)')
  .option('-z, --zip', 'ZIP archive')
  .option('--nodt', 'No Date and Time in name postfix')
  .option('-f, --folders [marmelad,static]', 'Folders to archive', 'marmelad,static')
  .action((name, opts) => {
    require('../commands/pack')(name, opts);
  });

/**
 * парсим аргументы командной строки
 */
CLI.parse(process.argv);

/**
 * В случае если не передан ни один аргумент,
 * показываем справку
 */
if (!CLI.args.length) {
  CLI.help();
}
<commit_msg>Добавил вывод местонахождения исходных файлов сборщика в --help<commit_after>#!/usr/bin/env node

const CLI = require('commander');
const PKG = require('../package.json');

const LOG = console.log;

/**
 * Установка флагов/параметров для командной строки
 */
CLI
  .version(PKG.version, '-v, --version')
  .description(PKG.description)
  .on('--help', () => {
    LOG(`\nCommands help:\n  ${PKG.name} [command] --help\n  mmd [command] --help`);
    LOG(`\nSource files:\n  ${__filename}`);
  });

/**
 * инициализация нового проекта
 */
CLI
  .command('init [dir]')
  .description('initialize new project')
  .option('-t, --test', 'required for testing')
  .option('--bootstrap [donor]', 'initialize new project with bootstrap included', false)
  .option('-c, --css [styl,scss,sass]', 'set stylesheet <engine> support', 'styl')
  .action((dir, opts) => {
    require('../commands/init')(dir, opts);
  });

/**
 * старт сервера разработки
 */
//
CLI
  .command('dev')
  .description('run development server')
  .option('-a, --auth [user@password]', 'set user@password for authorization')
  .option('--proxy-mod', 'proxy mode with copy files from build')
  .option('--build', 'build project once')
  .option('--minify', 'minify js and css')
  .action((dev) => {
    require('../commands/dev')(dev);
  })
  .on('--help', () => {
    // console.log();
  });

/**
 * создание страницы
 */
CLI
  .command('cp <name>')
  .description('create new page')
  .action((pageName) => {
    require('../commands/cp')(pageName);
  });

/**
 * создание блока
 */
CLI
  .command('cb <name>')
  .description('create new block')
  .option('-t, --techs [html,js,css,json]', 'Files extensions for new block')
  .action((pageName, opts) => {
    require('../commands/cb')(pageName, opts.techs);
  });

/**
 * линтера сборки
 */
CLI
  .command('lint')
  .description('lint project')
  .action((opts) => {
    require('../commands/lint')(opts.techs);
  });

/**
 * Prettier
 */
CLI
  .command('format')
  .description('Format project code (HTML only temporarily)')
  .action((opts) => {
    require('../commands/format')(opts);
  });

/**
 * Archive
 */
CLI
  .command('pack [name]')
  .description('Archive project source code (default:tar.gz)')
  .option('-z, --zip', 'ZIP archive')
  .option('--nodt', 'No Date and Time in name postfix')
  .option('-f, --folders [marmelad,static]', 'Folders to archive', 'marmelad,static')
  .action((name, opts) => {
    require('../commands/pack')(name, opts);
  });

/**
 * парсим аргументы командной строки
 */
CLI.parse(process.argv);

/**
 * В случае если не передан ни один аргумент,
 * показываем справку
 */
if (!CLI.args.length) {
  CLI.help();
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

"use strict"

var pkgFiles = require('../')
var path = require('path')
var argv = require('minimist')(process.argv.slice(2))
var columnify = require('columnify')
var bytes = require('pretty-bytes')

var dir = argv._[0] || process.cwd()

if (argv.help) {
  usage()
  process.exit(1)
}

function usage() {
  console.error('')
  console.error('Usage: pkgfiles [--sort=size|name|pkgfiles] [--json] [dir]')
  console.error('')
  console.error('  pkgfiles                 # List all files which would be published in current directory.')
  console.error('  pkgfiles ./mypkg         # List all files which would be published in `./mypkg`.')
  console.error('  pkgfiles --json          # Render JSON output')
  console.error('  pkgfiles --sort=size     # Sort files by size [default]')
  console.error('  pkgfiles --sort=name     # Sort files by name')
  console.error('  pkgfiles --sort=diskSize # Sort files by size on disk')
  console.error('')
}

argv.sort = argv.sort || 'size'
if (argv.sort === 'name') argv.sort = 'file'

pkgFiles.summary(dir, function(err, result) {
  console.error()
  if (err) return error(err)
  result.entries = result.entries.sort(sortBy(argv.sort))
  if (argv.json) {
    return console.info(JSON.stringify(result, null, 2))
  }
  var total = result.entries.length

  var summary = [
    {
      key: 'total',
      title: 'Number of Files',
      value: total
    },
    {
      key: 'publishSize',
      title: 'Publishable Size',
      value: "~" + bytes(result.publishSize)
    },
    {
      key: 'publishDiskSize',
      title: 'Publishable Size on Disk',
      value: "~" + bytes(result.publishDiskSize)
    },
    {
      key: 'extractedSize',
      title: 'Size with Dependencies',
      value: "~" + bytes(result.extractedSize)
    },
    {
      key: 'extractedDiskSize',
      title: 'Size on Disk with Dependencies',
      value: "~" + bytes(result.extractedDiskSize)
    }
  ].reverse()

  var entries = result.entries
  .map(function(entry) {
    entry.file = path.relative(dir, entry.file)
    if (!entry.exists) {
      entry.percent = ''
      entry.percentDisk = ''
      entry.size = 'N/A'
      entry.diskSize = ''
      return entry
    }
    entry.percent = percent(entry.size/result.publishSize)
    entry.percentDisk = percent(entry.diskSize/result.publishDiskSize)
    entry.size = bytes(entry.size)
    entry.diskSize = bytes(entry.diskSize)
    return entry
  })
  .sort(sortBy(argv.sort))

  console.info(columnify(result.entries, {columnSplitter: '  ', columns: ['file', 'size', 'percent', 'diskSize', 'percentDisk'], headingTransform: function(header) {
    if (header === 'percent') return '%'
    if (header === 'diskSize') return 'DISK SIZE'
    if (header === 'percentDisk') return 'DISK SIZE %'
    return header.toUpperCase()
  }}))
  console.info('\nPKGFILES SUMMARY')
  console.info(columnify(summary, {columnSplitter: '  ', columns: ['title', 'value'], showHeaders: false}))
})

function percent(amount) {
  return (Math.round(amount * 100)) + '%'
}

function error(err) {
  if (err) {
    console.error(err.message)
    console.trace()
    process.exit(1)
  }
}

function sortBy(key) {
  return function(a, b) {
    if (typeof a[key] === 'string') {
      return a[key].localeCompare(b[key])
    } else {
      return a[key] - b[key]
    }
  }
}
<commit_msg>Hide size on disk results behind --disk.<commit_after>#!/usr/bin/env node

"use strict"

var pkgFiles = require('../')
var path = require('path')
var argv = require('minimist')(process.argv.slice(2))
var columnify = require('columnify')
var bytes = require('pretty-bytes')

var dir = argv._[0] || process.cwd()

if (argv.help) {
  usage()
  process.exit(1)
}

function usage() {
  console.error('')
  console.error('Usage: pkgfiles [--sort=size|name|pkgfiles] [--json] [dir]')
  console.error('')
  console.error('  pkgfiles                 # List all files which would be published in current directory.')
  console.error('  pkgfiles ./mypkg         # List all files which would be published in `./mypkg`.')
  console.error('  pkgfiles --json          # Render JSON output')
  console.error('  pkgfiles --sort=size     # Sort files by size [default]')
  console.error('  pkgfiles --sort=name     # Sort files by name')
  console.error('  pkgfiles --sort=diskSize # Sort files by size on disk')
  console.error('')
}

argv.sort = argv.sort || 'size'
if (argv.sort === 'name') argv.sort = 'file'

pkgFiles.summary(dir, function(err, result) {
  console.error()
  if (err) return error(err)
  result.entries = result.entries.sort(sortBy(argv.sort))
  if (argv.json) {
    return console.info(JSON.stringify(result, null, 2))
  }
  var total = result.entries.length

  var summary = [
    {
      key: 'total',
      title: 'Number of Files',
      value: total
    },
    {
      key: 'publishSize',
      title: 'Publishable Size',
      value: "~" + bytes(result.publishSize)
    },
    {
      key: 'publishDiskSize',
      title: 'Publishable Size on Disk',
      value: "~" + bytes(result.publishDiskSize)
    },
    {
      key: 'extractedSize',
      title: 'Size with Dependencies',
      value: "~" + bytes(result.extractedSize)
    },
    {
      key: 'extractedDiskSize',
      title: 'Size on Disk with Dependencies',
      value: "~" + bytes(result.extractedDiskSize)
    }
  ].reverse()

  var entries = result.entries
  .map(function(entry) {
    entry.file = path.relative(dir, entry.file)
    if (!entry.exists) {
      entry.percent = ''
      entry.percentDisk = ''
      entry.size = 'N/A'
      entry.diskSize = ''
      return entry
    }
    entry.percent = percent(entry.size/result.publishSize)
    entry.percentDisk = percent(entry.diskSize/result.publishDiskSize)
    entry.size = bytes(entry.size)
    entry.diskSize = bytes(entry.diskSize)
    return entry
  })
  .sort(sortBy(argv.sort))

  var columns = ['file', 'size', 'percent',]
  if (argv.disk) {
    columns.push('diskSize', 'percentDisk')
  } else {
    summary = summary.filter(function(item) {
      return !(/Disk/.test(item.key))
    })
  }

  console.info(columnify(result.entries, {columnSplitter: '  ', columns: columns, headingTransform: function(header) {
    if (header === 'percent') return '%'
    if (header === 'diskSize') return 'DISK SIZE'
    if (header === 'percentDisk') return 'DISK SIZE %'
    return header.toUpperCase()
  }}))
  console.info('\nPKGFILES SUMMARY')
  console.info(columnify(summary, {columnSplitter: '  ', columns: ['title', 'value'], showHeaders: false}))
})

function percent(amount) {
  return (Math.round(amount * 100)) + '%'
}

function error(err) {
  if (err) {
    console.error(err.message)
    console.trace()
    process.exit(1)
  }
}

function sortBy(key) {
  return function(a, b) {
    if (typeof a[key] === 'string') {
      return a[key].localeCompare(b[key])
    } else {
      return a[key] - b[key]
    }
  }
}
<|endoftext|>


<commit_before>import Utils from '../../../utils/utils';

export default function () {
  const swiper = this;
  const {
    activeIndex, initialized, loopedSlides = 0, params,
  } = swiper;
  const breakpoints = params.breakpoints;
  if (!breakpoints || (breakpoints && Object.keys(breakpoints).length === 0)) return;
  // Set breakpoint for window width and update parameters
  const breakpoint = swiper.getBreakpoint(breakpoints);
  if (breakpoint && swiper.currentBreakpoint !== breakpoint) {
    // Unless 'auto', these values must be integers, we must do math operations, not string concatenations.
    if (breakpoint in breakpoints && typeof breakpoints[breakpoint].slidesPerView !== 'undefined') {
      // If it's 'auto' cannot make it an integer but we can make it lowercase.
      if (breakpoints[breakpoint].slidesPerView === 'auto' || breakpoints[breakpoint].slidesPerView === 'AUTO') {
        breakpoints[breakpoint].slidesPerView = breakpoints[breakpoint].slidesPerView.toLowerCase();
      } else {
        // Force slidesPerView to an integer using parseInt(x, 10) (base 10).
        breakpoints[breakpoint].slidesPerView = parseInt(breakpoints[breakpoint].slidesPerView, 10);
      }
    }
    if (breakpoint in breakpoints && typeof breakpoints[breakpoint].spaceBetween !== 'undefined') {
      // Force spaceBetween to an integer using parseInt(x, 10) (base 10).
      breakpoints[breakpoint].spaceBetween = parseInt(breakpoints[breakpoint].spaceBetween, 10);
    }
    if (breakpoint in breakpoints && typeof breakpoints[breakpoint].slidesPerGroup !== 'undefined') {
      // Force slidesPerGroup to an integer using parseInt(x, 10) (base 10).
      breakpoints[breakpoint].slidesPerGroup = parseInt(breakpoints[breakpoint].slidesPerGroup, 10);
    }
    const breakPointsParams = breakpoint in breakpoints ? breakpoints[breakpoint] : swiper.originalParams;
    const needsReLoop = params.loop && (breakPointsParams.slidesPerView !== params.slidesPerView);

    Utils.extend(swiper.params, breakPointsParams);

    Utils.extend(swiper, {
      allowTouchMove: swiper.params.allowTouchMove,
      allowSlideNext: swiper.params.allowSlideNext,
      allowSlidePrev: swiper.params.allowSlidePrev,
    });

    swiper.currentBreakpoint = breakpoint;

    if (typeof breakPointsParams.slidesPerGroup !== 'undefined') {
      // Use the breakpoint slidesPerGroup, otherwise we'd get the default desktop setting.
      swiper.params.slidesPerGroup = breakPointsParams.slidesPerGroup;
    }
    if (typeof breakPointsParams.slidesPerView !== 'undefined') {
      // Use the breakpoint slidesPerView, otherwise we'd get the default desktop setting.
      swiper.params.slidesPerView = breakPointsParams.slidesPerView;
    }
    if (typeof breakPointsParams.spaceBetween !== 'undefined') {
      // Use the breakpoint spaceBetween, otherwise we'd get the default desktop setting.
      swiper.params.spaceBetween = breakPointsParams.spaceBetween;
    }
    if (needsReLoop && initialized) {
      swiper.loopDestroy();
      swiper.loopCreate();
      swiper.updateSlides();
      swiper.slideTo((activeIndex - loopedSlides) + swiper.loopedSlides, 0, false);
    }
    swiper.emit('breakpoint', breakPointsParams);
  }
}
<commit_msg>Tweaks<commit_after>import Utils from '../../../utils/utils';

export default function () {
  const swiper = this;
  const {
    activeIndex, initialized, loopedSlides = 0, params,
  } = swiper;
  const breakpoints = params.breakpoints;
  if (!breakpoints || (breakpoints && Object.keys(breakpoints).length === 0)) return;

  // Set breakpoint for window width and update parameters
  const breakpoint = swiper.getBreakpoint(breakpoints);

  if (breakpoint && swiper.currentBreakpoint !== breakpoint) {
    const breakpointOnlyParams = breakpoint in breakpoints ? breakpoints[breakpoint] : undefined;
    if (breakpointOnlyParams) {
      ['slidesPerView', 'spaceBetween', 'slidesPerGroup'].forEach((param) => {
        const paramValue = breakpointOnlyParams[param];
        if (typeof paramValue === 'undefined') return;
        if (param === 'slidesPerView' && (paramValue === 'AUTO' || paramValue === 'auto')) {
          breakpointOnlyParams[param] = 'auto';
        } else if (param === 'slidesPerView') {
          breakpointOnlyParams[param] = parseFloat(paramValue);
        } else {
          breakpointOnlyParams[param] = parseInt(paramValue, 10);
        }
      });
    }

    const breakpointParams = breakpointOnlyParams || swiper.originalParams;
    const needsReLoop = params.loop && (breakpointParams.slidesPerView !== params.slidesPerView);

    Utils.extend(swiper.params, breakpointParams);

    Utils.extend(swiper, {
      allowTouchMove: swiper.params.allowTouchMove,
      allowSlideNext: swiper.params.allowSlideNext,
      allowSlidePrev: swiper.params.allowSlidePrev,
    });

    swiper.currentBreakpoint = breakpoint;

    if (needsReLoop && initialized) {
      swiper.loopDestroy();
      swiper.loopCreate();
      swiper.updateSlides();
      swiper.slideTo((activeIndex - loopedSlides) + swiper.loopedSlides, 0, false);
    }
    swiper.emit('breakpoint', breakpointParams);
  }
}
<|endoftext|>


<commit_before>"use strict";

process.title = 'Scriptor';

var options = require( 'commander' );
var Module = require( 'module' );
var glob = require( 'glob' );
var package_json = require( './../package.json' );

var ScriptorCommon = require( './../build/common.js' );
var ScriptorCLI = require( './../build/cli.js' );

function diff_ms(start) {
    var diff = process.hrtime( start );
    var ms = diff[0] * 1e3 + diff[1] * 1e-6;
    return ms.toFixed( 3 ) + 'ms';
}

//Process status codes
var EXIT_SUCCESS = 0,
    EXIT_FAILURE = 1;

options
    .version( package_json.version )
    .usage( '[options] files...' )
    .option( '-d, --dir <path>', 'Directory to run Scriptor in' )
    .option( '-a, --async', 'Run scripts asynchronously' )
    .option( '-c, --concurrency <n>',
    'Limit script concurrency to n when executed asynchronously (default: max_recursion + 1)' )
    .option( '-q, --close', 'End the process when all scripts finish' )
    .option( '-l, --long_stack_traces', 'Display long stack trace for asynchronous errors' )
    .option( '-r, --repeat <n>', 'Run script n times (in parallel if async)' )
    .option( '-u, --unique', 'Only run unique scripts (will ignore duplicates in file arguments)' )
    .option( '--use_strict', 'Enforce strict mode' )
    .option( '--max_recursion <n>', 'Set the maximum recursion depth of scripts (default: ' +
                                    ScriptorCommon.default_max_recursion + ')' )
    .option( '-v, --verbose [n]', 'Print out extra status information (0 - normal, 1 - info, 2 - verbose)' )
    .option( '-w, --watch', 'Watch scripts for changes and re-run them when changed' )
    .option( '--cork', 'Cork stdout before calling scripts' )
    .option( '-e, --ext', 'Disable use of custom extensions with AMD injection' )
    .option( '-s, --silent', 'Do not echo anything' )
    .option( '--no_signal', 'Do not intercept process signals' )
    .option( '--no_glob', 'Do not match glob patterns' );

module.exports = function(argv) {
    options.parse( argv );

    if( options.use_strict ) {
        Module.wrapper[0] += '"use strict";';
        Object.freeze( Module.wrap );
    }

    //The default log_level is LOG_NORMAL
    var log_level = ScriptorCLI.LogLevel.LOG_NORMAL;

    //If silent mode is enabled, it overrides verbose mode
    if( options.silent ) {
        log_level = ScriptorCLI.LogLevel.LOG_SILENT;

    } else if( options.verbose ) {
        //If using the -v shorthand, it is essentially --verbose 2
        if( typeof options.verbose === 'boolean' ) {
            log_level = ScriptorCLI.LogLevel.LOG_VERBOSE;

        } else {
            log_level = parseInt( options.verbose );

            if( isNaN( log_level ) ) {
                log_level = ScriptorCLI.LogLevel.LOG_NORMAL;
            }
        }
    }

    //Create the logger
    var logger = new ScriptorCLI.Logger( log_level );

    //Unhandled errors are printed and the process is killed
    var onError = function(error) {
        logger.error( error.stack || error );
        process.exit( EXIT_FAILURE );
    };

    var scripts;

    if( !options.no_glob ) {
        scripts = [];

        for( var it in options.args ) {
            if( options.args.hasOwnProperty( it ) ) {
                if( glob.hasMagic( options.args[it] ) ) {
                    scripts = scripts.concat( glob.sync( options.args[it] ) );
                } else {
                    scripts.push( options.args[it] );
                }
            }
        }

    } else {
        scripts = options.args;
    }

    if( options.unique ) {
        logger.info( 'Only executing unique scripts' );
        var uniqueScripts = [];

        scripts.forEach( function(script) {
            if( uniqueScripts.indexOf( script ) === -1 ) {
                uniqueScripts.push( script );
            }
        } );

        scripts = uniqueScripts;
    }

    if( options.repeat ) {
        var count = parseInt( options.repeat );

        if( !isNaN( count ) && count > 1 ) {
            logger.info( 'Repeating script execution %d times', count );

            var newScripts = [];

            for( var i = 0; i < count; i++ ) {
                newScripts = newScripts.concat( scripts );
            }

            scripts = newScripts;
        }
    }

    if( scripts.length > 0 ) {
        var Scriptor = require( './../' + (options.async ? 'async.js' : 'sync.js') );

        if( !options.ext ) {
            logger.info( 'Custom extensions enabled.' );
            Scriptor.enableCustomExtensions();
        }

        if( options.async && options.long_stack_traces ) {
            Scriptor.Promise.longStackTraces();
            logger.info( 'Long Stack Traces enabled' );
        }

        var manager = new Scriptor.Manager();

        if( typeof options.dir === 'string' ) {
            manager.chdir( options.dir );
        }

        var maxRecursion, concurrency, watch;

        //Basically, if both max_recursion and concurrency are set, they have to play along
        //Otherwise, each will increase or whatever to not crash the application
        if( options.max_recursion ) {
            maxRecursion = parseInt( options.max_recursion );

            if( options.concurrency ) {
                concurrency = parseInt( options.concurrency );

                if( concurrency > maxRecursion ) {
                    console.error( 'Concurrency set higher than max_recursion.\n\tScriptor will report false positives for exceeded recursion limits.' );
                    process.exit( EXIT_FAILURE );
                }

            } else {
                concurrency = maxRecursion + 1;
            }

        } else {
            if( options.concurrency ) {
                concurrency = parseInt( options.concurrency );

                maxRecursion = concurrency - 1;

                if( maxRecursion > ScriptorCommon.default_max_recursion ) {
                    logger.warn( 'Increasing max_recursion to %d to handle increased concurrency', maxRecursion );
                }

            } else {
                maxRecursion = Scriptor.default_max_recursion;

                concurrency = maxRecursion + 1;
            }
        }

        //Close overrides watch, so if it is set to close, don't even both watching the scripts
        if( options.watch && !options.close ) {
            watch = true;
        }

        var run_script,
            script_start = process.hrtime(),
            place = 0,
            instances = [];

        if( !options.no_signal ) {
            var onClose = function() {
                for( var it in instances ) {
                    if( instances.hasOwnProperty( it ) ) {
                        instances[it].unload();
                    }
                }

                //Close on the next tick so close events can propagate.
                //Exit code for Ctrl-C signals is 130 according to http://www.tldp.org/LDP/abs/html/exitcodes.html
                process.nextTick( process.exit.bind( null, 130 ) );
            };

            process.on( 'SIGINT', onClose );
            process.on( 'SIGTERM', onClose );
        }

        if( options.async ) {
            logger.info( 'Asynchronous execution selected' );

            run_script = function(instance, script, num) {
                var start = process.hrtime();

                instance.maxRecursion = maxRecursion;

                if( log_level === ScriptorCLI.LogLevel.LOG_SILENT || options.cork ) {
                    process.stdout.cork();
                }

                return instance.call().then( function() {
                    logger.verbose( 'Finished script #%d, %s in %s.', num, script, diff_ms( start ) );
                } );
            };

            var mapper = function(script) {
                var num = place++;

                logger.verbose( 'Running script #%d, %s.', num, script );

                var instance = manager.add( script, false );

                instances.push( instance );

                if( watch ) {
                    instance.watch( true );

                    instance.on( 'change', function() {
                        logger.verbose( 'Re-running script #%d, %s', num, script );
                        run_script( instance, script, num );
                    } );
                }

                return run_script( instance, script, num );
            };

            logger.info( 'Concurrency set at %s', concurrency );

            Scriptor.Promise.map( scripts, mapper, {concurrency: concurrency} ).catch( onError ).then( function() {
                logger.log( 'All scripts successfully executed in %s', diff_ms( script_start ) );

                if( options.close ) {
                    process.exit( EXIT_SUCCESS );
                }
            } );

        } else {
            logger.info( 'Synchronous execution selected.' );

            run_script = function(instance, script, num) {
                var start = process.hrtime();

                instance.maxRecursion = maxRecursion;

                if( log_level === ScriptorCLI.LogLevel.LOG_SILENT || options.cork ) {
                    process.stdout.cork();
                }

                instance.call();

                logger.verbose( 'Finished script #%d, %s in %s.', num, script, diff_ms( start ) );
            };

            scripts.forEach( function(script) {
                var num = place++;

                logger.verbose( 'Running script #%d, %s.', num, script );

                try {
                    var instance = manager.add( script, false );

                    instances.push( instance );

                    if( watch ) {
                        instance.watch( true );

                        instance.on( 'change', function() {
                            logger.verbose( 'Re-running script #%d, %s.', num, script );
                            run_script( instance, script, num );
                        } );
                    }

                    run_script( instance, script, num );

                } catch( error ) {
                    onError( error );
                }
            } );

            logger.log( 'All scripts successfully executed in %s', diff_ms( script_start ) );

            if( options.close ) {
                process.exit( EXIT_SUCCESS );
            }
        }

    } else {
        options.help();
    }
};

<commit_msg>Improved signal handling<commit_after>"use strict";

process.title = 'Scriptor';

var options = require( 'commander' );
var Module = require( 'module' );
var glob = require( 'glob' );
var package_json = require( './../package.json' );

var constants = process.binding( 'constants' );

var ScriptorCommon = require( './../build/common.js' );
var ScriptorCLI = require( './../build/cli.js' );

function diff_ms(start) {
    var diff = process.hrtime( start );
    var ms = diff[0] * 1e3 + diff[1] * 1e-6;
    return ms.toFixed( 3 ) + 'ms';
}

//Process status codes
var EXIT_SUCCESS = 0,
    EXIT_FAILURE = 1;

options
    .version( package_json.version )
    .usage( '[options] files...' )
    .option( '-d, --dir <path>', 'Directory to run Scriptor in' )
    .option( '-a, --async', 'Run scripts asynchronously' )
    .option( '-c, --concurrency <n>',
    'Limit script concurrency to n when executed asynchronously (default: max_recursion + 1)' )
    .option( '-q, --close', 'End the process when all scripts finish' )
    .option( '-l, --long_stack_traces', 'Display long stack trace for asynchronous errors' )
    .option( '-r, --repeat <n>', 'Run script n times (in parallel if async)' )
    .option( '-u, --unique', 'Only run unique scripts (will ignore duplicates in file arguments)' )
    .option( '--use_strict', 'Enforce strict mode' )
    .option( '--max_recursion <n>', 'Set the maximum recursion depth of scripts (default: ' +
                                    ScriptorCommon.default_max_recursion + ')' )
    .option( '-v, --verbose [n]', 'Print out extra status information (0 - normal, 1 - info, 2 - verbose)' )
    .option( '-w, --watch', 'Watch scripts for changes and re-run them when changed' )
    .option( '--cork', 'Cork stdout before calling scripts' )
    .option( '-e, --ext', 'Disable use of custom extensions with AMD injection' )
    .option( '-s, --silent', 'Do not echo anything' )
    .option( '--no_signal', 'Do not intercept process signals' )
    .option( '--no_glob', 'Do not match glob patterns' );

module.exports = function(argv) {
    options.parse( argv );

    if( options.use_strict ) {
        Module.wrapper[0] += '"use strict";';
        Object.freeze( Module.wrap );
    }

    //The default log_level is LOG_NORMAL
    var log_level = ScriptorCLI.LogLevel.LOG_NORMAL;

    //If silent mode is enabled, it overrides verbose mode
    if( options.silent ) {
        log_level = ScriptorCLI.LogLevel.LOG_SILENT;

    } else if( options.verbose ) {
        //If using the -v shorthand, it is essentially --verbose 2
        if( typeof options.verbose === 'boolean' ) {
            log_level = ScriptorCLI.LogLevel.LOG_VERBOSE;

        } else {
            log_level = parseInt( options.verbose );

            if( isNaN( log_level ) ) {
                log_level = ScriptorCLI.LogLevel.LOG_NORMAL;
            }
        }
    }

    //Create the logger
    var logger = new ScriptorCLI.Logger( log_level );

    //Unhandled errors are printed and the process is killed
    var onError = function(error) {
        logger.error( error.stack || error );
        process.exit( EXIT_FAILURE );
    };

    var scripts;

    if( !options.no_glob ) {
        scripts = [];

        for( var it in options.args ) {
            if( options.args.hasOwnProperty( it ) ) {
                if( glob.hasMagic( options.args[it] ) ) {
                    scripts = scripts.concat( glob.sync( options.args[it] ) );
                } else {
                    scripts.push( options.args[it] );
                }
            }
        }

    } else {
        scripts = options.args;
    }

    if( options.unique ) {
        logger.info( 'Only executing unique scripts' );
        var uniqueScripts = [];

        scripts.forEach( function(script) {
            if( uniqueScripts.indexOf( script ) === -1 ) {
                uniqueScripts.push( script );
            }
        } );

        scripts = uniqueScripts;
    }

    if( options.repeat ) {
        var count = parseInt( options.repeat );

        if( !isNaN( count ) && count > 1 ) {
            logger.info( 'Repeating script execution %d times', count );

            var newScripts = [];

            for( var i = 0; i < count; i++ ) {
                newScripts = newScripts.concat( scripts );
            }

            scripts = newScripts;
        }
    }

    if( scripts.length > 0 ) {
        var Scriptor = require( './../' + (options.async ? 'async.js' : 'sync.js') );

        if( !options.ext ) {
            logger.info( 'Custom extensions enabled.' );
            Scriptor.enableCustomExtensions();
        }

        if( options.async && options.long_stack_traces ) {
            Scriptor.Promise.longStackTraces();
            logger.info( 'Long Stack Traces enabled' );
        }

        var manager = new Scriptor.Manager();

        if( typeof options.dir === 'string' ) {
            manager.chdir( options.dir );
        }

        var maxRecursion, concurrency, watch;

        //Basically, if both max_recursion and concurrency are set, they have to play along
        //Otherwise, each will increase or whatever to not crash the application
        if( options.max_recursion ) {
            maxRecursion = parseInt( options.max_recursion );

            if( options.concurrency ) {
                concurrency = parseInt( options.concurrency );

                if( concurrency > maxRecursion ) {
                    console.error( 'Concurrency set higher than max_recursion.\n\tScriptor will report false positives for exceeded recursion limits.' );
                    process.exit( EXIT_FAILURE );
                }

            } else {
                concurrency = maxRecursion + 1;
            }

        } else {
            if( options.concurrency ) {
                concurrency = parseInt( options.concurrency );

                maxRecursion = concurrency - 1;

                if( maxRecursion > ScriptorCommon.default_max_recursion ) {
                    logger.warn( 'Increasing max_recursion to %d to handle increased concurrency', maxRecursion );
                }

            } else {
                maxRecursion = Scriptor.default_max_recursion;

                concurrency = maxRecursion + 1;
            }
        }

        //Close overrides watch, so if it is set to close, don't even both watching the scripts
        if( options.watch && !options.close ) {
            watch = true;
        }

        var run_script,
            script_start = process.hrtime(),
            place = 0,
            instances = [];

        if( !options.no_signal ) {
            var closed = false;

            var onClose = function(signal) {
                if( !closed ) {

                    for( var it in instances ) {
                        if( instances.hasOwnProperty( it ) ) {
                            instances[it].unload();
                        }
                    }

                    //Close on the next tick so close events can propagate.
                    //Exit code for Ctrl-C signals is 128 + sig according to http://www.tldp.org/LDP/abs/html/exitcodes.html
                    process.nextTick( process.exit.bind( null, 128 + signal ) );

                    closed = true;
                }
            };

            process.on( 'SIGINT', onClose.bind( null, constants.SIGINT ) );
            process.on( 'SIGTERM', onClose.bind( null, constants.SIGTERM ) );
        }

        if( options.async ) {
            logger.info( 'Asynchronous execution selected' );

            run_script = function(instance, script, num) {
                var start = process.hrtime();

                instance.maxRecursion = maxRecursion;

                if( log_level === ScriptorCLI.LogLevel.LOG_SILENT || options.cork ) {
                    process.stdout.cork();
                }

                return instance.call().then( function() {
                    logger.verbose( 'Finished script #%d, %s in %s.', num, script, diff_ms( start ) );
                } );
            };

            var mapper = function(script) {
                var num = place++;

                logger.verbose( 'Running script #%d, %s.', num, script );

                var instance = manager.add( script, false );

                instances.push( instance );

                if( watch ) {
                    instance.watch( true );

                    instance.on( 'change', function() {
                        logger.verbose( 'Re-running script #%d, %s', num, script );
                        run_script( instance, script, num );
                    } );
                }

                return run_script( instance, script, num );
            };

            logger.info( 'Concurrency set at %s', concurrency );

            Scriptor.Promise.map( scripts, mapper, {concurrency: concurrency} ).catch( onError ).then( function() {
                logger.log( 'All scripts successfully executed in %s', diff_ms( script_start ) );

                if( options.close ) {
                    process.exit( EXIT_SUCCESS );
                }
            } );

        } else {
            logger.info( 'Synchronous execution selected.' );

            run_script = function(instance, script, num) {
                var start = process.hrtime();

                instance.maxRecursion = maxRecursion;

                if( log_level === ScriptorCLI.LogLevel.LOG_SILENT || options.cork ) {
                    process.stdout.cork();
                }

                instance.call();

                logger.verbose( 'Finished script #%d, %s in %s.', num, script, diff_ms( start ) );
            };

            scripts.forEach( function(script) {
                var num = place++;

                logger.verbose( 'Running script #%d, %s.', num, script );

                try {
                    var instance = manager.add( script, false );

                    instances.push( instance );

                    if( watch ) {
                        instance.watch( true );

                        instance.on( 'change', function() {
                            logger.verbose( 'Re-running script #%d, %s.', num, script );
                            run_script( instance, script, num );
                        } );
                    }

                    run_script( instance, script, num );

                } catch( error ) {
                    onError( error );
                }
            } );

            logger.log( 'All scripts successfully executed in %s', diff_ms( script_start ) );

            if( options.close ) {
                process.exit( EXIT_SUCCESS );
            }
        }

    } else {
        options.help();
    }
};

<|endoftext|>


<commit_before>/**
 * Get all arguments.
 */
var argv = require('optimist')
    .usage(
        'Installs a Skeletor Application to the specified directory.' +
        '\nUsage: $0')
    .demand('a')
    .alias('a', 'appName')
    .describe('a', 'Sets the name application.')
    .demand('p')
    .alias('p', 'path')
    .describe('a', 'Sets the path to install to.')
    .argv;

/**
 * Main function for the installer script.
 * @constructor
 */
function Install() {
  /**
   * @private
   */
  this.path_ = argv.path;

  /**
   * @private
   */
  this.app_ = argv.appName;

  // Initialize the installation.
  this.findOrCreatePath_();
}

/**
 * @const {Object.<string, Array>}
 * @private
 */
Install.STRUCTURE_ = {
  app: [
    'controllers',
    'helpers',
    'models',
    'views'
  ],
  config: [
    'environment'
  ],
  public: [
    'css',
    'images',
    'js'
  ]
};

/**
 * Looks up a path and creates it if it does not exist.
 * @private
 */
Install.prototype.findOrCreatePath_ = function() {
  if (fs.lstatSync(this.path_).isDirectory()) {
    this.deployAllFiles_();
  } else {
    // First, try to create the path, then...
    // ...complain that this is NOT a directory, or it cannot be found.
  }
};

/**
 * Copies all files over to the new directory.
 * @private
 */
Install.prototype.deployAllFiles_ = function() {
  // Start with the root files.
  // Next load the rest of the structure - overwrite as necessary.
};

/**
 * Expose the `Install` Constructor.
 */
module.exports = new Install();
<commit_msg>Added some more of the guts for the install script.<commit_after>var fs = require('fs');

/**
 * Get all arguments.
 */
var argv = require('optimist')
    .usage(
        'Installs a Skeletor Application to the specified directory.' +
        '\nUsage: $0')
    .demand('a')
    .alias('a', 'appName')
    .describe('a', 'Sets the name application.')
    .demand('p')
    .alias('p', 'path')
    .describe('a', 'Sets the path to install to.')
    .argv;

/**
 * Main function for the installer script.
 * @constructor
 */
function Install() {
  /**
   * @private
   */
  this.path_ = argv.path;

  /**
   * @private
   */
  this.app_ = argv.appName;

  this.initialize_();
}

/**
 * @const {Object.<string, Array>}
 * @private
 */
Install.STRUCTURE_ = {
  app: [
    'controllers',
    'helpers',
    'models',
    'views'
  ],
  config: [
    'environment'
  ],
  public: [
    'css',
    'images',
    'js'
  ]
};

/**
 * Kicks off the install process.
 * @private
 */
Install.prototype.initialize_ = function() {
  var dir = this.path_ + this.app_.toLowerCase();
  var self = this;
  // Create the application directory.
  this.findOrCreatePath_(dir, function(err) {
    if (err) throw ('Could not create the directory:\t' + dir);
    // Start deploying the new files to the application.
    self.deployAllFiles_();
  });
};

/**
 * Looks up a path and creates it if it does not exist.
 * @param dir {string}
 * @private
 */
Install.prototype.findOrCreatePath_ = function(dir, done) {
  var self = this;
  fs.lstat(dir, function(err, stat) {
    if (err) {
      fs.mkdir(dir, function(err) {
        if (err) {
          done(err);
        } else {
          self.findOrCreatePath_(dir, done);
        }
      });
    } else {
      done();
    }
  });
};

/**
 * Copies all files over to the new directory.
 * @private
 */
Install.prototype.deployAllFiles_ = function() {
  console.log('Creating all files.');
  // Start with the root files.
  // Next load the rest of the structure - overwrite as necessary.
};

/**
 * Expose the `Install` Constructor.
 */
module.exports = new Install();
<|endoftext|>


<commit_before><commit_msg>Remove typescript annotation<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";
var getStdin = require("get-stdin");
var logSymbols = require("log-symbols");
var useStdIn = (process.argv.indexOf("--stdin") > -1);
var isDebug = (process.argv.indexOf("--debug") > -1);
if (isDebug) {
    require("debug").enable("textlint*");
}
// must do this initialization *before* other requires in order to work
var cli = require("../lib/cli");
var setRunningCLI = require("../lib/util/throw-log").setRunningCLI;
// it is for --experimental logger
// update state
setRunningCLI(!module.parent);
/**
 * show error message for user
 * @param {Error} error
 */
function showError(error) {
    console.error(logSymbols.error, "Error");
    console.error(error.message + "\n");
    console.error(logSymbols.error, "Stack trace");
    console.error(error.stack);
}
// Always start as promise
Promise.resolve().then(function() {
    if (useStdIn) {
        return getStdin().then(function(text) {
            return cli.execute(process.argv, text);
        });
    }
    return cli.execute(process.argv);
}).then(function(exitStatus) {
    if (typeof exitStatus === "number") {
        process.exitCode = exitStatus;
    }
}).catch(function(error) {
    showError(error);
    process.exit(error.code || 1);
});

// Catch throw error
process.on("uncaughtException", function(error) {
    showError(error);
    process.exit(1);
});
process.on("unhandledRejection", (error) => {
    showError(error);
    process.exit(1);
});
<commit_msg>fix(bin): not use Arrow Function<commit_after>#!/usr/bin/env node
"use strict";
var getStdin = require("get-stdin");
var logSymbols = require("log-symbols");
var useStdIn = (process.argv.indexOf("--stdin") > -1);
var isDebug = (process.argv.indexOf("--debug") > -1);
if (isDebug) {
    require("debug").enable("textlint*");
}
// must do this initialization *before* other requires in order to work
var cli = require("../lib/cli");
var setRunningCLI = require("../lib/util/throw-log").setRunningCLI;
// it is for --experimental logger
// update state
setRunningCLI(!module.parent);
/**
 * show error message for user
 * @param {Error} error
 */
function showError(error) {
    console.error(logSymbols.error, "Error");
    console.error(error.message + "\n");
    console.error(logSymbols.error, "Stack trace");
    console.error(error.stack);
}
// Always start as promise
Promise.resolve().then(function() {
    if (useStdIn) {
        return getStdin().then(function(text) {
            return cli.execute(process.argv, text);
        });
    }
    return cli.execute(process.argv);
}).then(function(exitStatus) {
    if (typeof exitStatus === "number") {
        process.exitCode = exitStatus;
    }
}).catch(function(error) {
    showError(error);
    process.exit(error.code || 1);
});

// Catch throw error
process.on("uncaughtException", function(error) {
    showError(error);
    process.exit(1);
});
process.on("unhandledRejection", function(error) {
    showError(error);
    process.exit(1);
});
<|endoftext|>


<commit_before>var debug = require('debug')('ios-bindings');

var events = require('events');
var util = require('util');

var {
  DeviceEventEmitter,
  NativeModules: { RNBLE },
} = require('react-native');

var Buffer = require('buffer').Buffer;

/**
 *  NobleBindings for react native
 */
var NobleBindings = function() {
  DeviceEventEmitter.addListener('ble.connect', this.onConnect.bind(this));
  DeviceEventEmitter.addListener('ble.disconnect', this.onDisconnect.bind(this));
  DeviceEventEmitter.addListener('ble.discover', this.onDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.rssiUpdate', this.onRssiUpdate.bind(this));
  DeviceEventEmitter.addListener('ble.servicesDiscover', this.onServicesDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.includedServicesDiscover', this.onIncludedServicesDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.characteristicsDiscover', this.onCharacteristicsDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.descriptorsDiscover', this.onDescriptorsDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.stateChange', this.onStateChange.bind(this));
  DeviceEventEmitter.addListener('ble.data', this.onData.bind(this));
  DeviceEventEmitter.addListener('ble.write', this.onWrite.bind(this));
  DeviceEventEmitter.addListener('ble.notify', this.onNotify.bind(this));
};

util.inherits(NobleBindings, events.EventEmitter);

NobleBindings.prototype.onConnect = function({ peripheralUuid, error = null }) {
  this.emit('connect', peripheralUuid, error);
};

NobleBindings.prototype.onDisconnect = function({ peripheralUuid, error = null }) {
  this.emit('disconnect', peripheralUuid, error);
};

NobleBindings.prototype.onRssiUpdate = function({ peripheralUuid, rssi }) {
  this.emit('rssiUpdate', peripheralUuid, rssi);
};

NobleBindings.prototype.onServicesDiscover = function({ peripheralUuid, serviceUuids }) {
  this.emit('servicesDiscover', peripheralUuid, serviceUuids);
};

NobleBindings.prototype.onIncludedServicesDiscover = function({ peripheralUuid, serviceUuid, includedServiceUuids }) {
  this.emit('includedServicesDiscover', peripheralUuid, serviceUuid, includedServiceUuids);
};

NobleBindings.prototype.onCharacteristicsDiscover = function({ peripheralUuid, serviceUuid, characteristics }) {
  this.emit(
    'characteristicsDiscover',
    peripheralUuid,
    serviceUuid,
    characteristics
  );
};

NobleBindings.prototype.onDescriptorsDiscover = function({ peripheralUuid, serviceUuid, characteristicUuid, descriptors }) {
  this.emit('descriptorsDiscover', peripheralUuid, serviceUuid, characteristicUuid, descriptors);
};

NobleBindings.prototype.onData = function({ peripheralUuid, serviceUuid, characteristicUuid, data, isNotification }) {
  var processedData = new Buffer(data, 'base64');
  this.emit('data', peripheralUuid, serviceUuid, characteristicUuid, processedData, isNotification);
  this.emit('read', peripheralUuid, serviceUuid, characteristicUuid, processedData, isNotification);
};

NobleBindings.prototype.onWrite = function({ peripheralUuid, serviceUuid, characteristicUuid }) {
  this.emit('write', peripheralUuid, serviceUuid, characteristicUuid);
};

NobleBindings.prototype.onNotify = function({ peripheralUuid, serviceUuid, characteristicUuid, state }) {
  this.emit('notify', peripheralUuid, serviceUuid, characteristicUuid, state);
};

NobleBindings.prototype.onDiscover = function({ peripheralUuid, advertisement, connectable, rssi }) {
  debug('peripheral ' + peripheralUuid + ' discovered');

  if (advertisement.manufacturerData) {
    advertisement.manufacturerData = new Buffer(advertisement.manufacturerData, 'base64');
  }

  if (advertisement.serviceData) {
    advertisement.serviceData = advertisement.serviceData.map(({ uuid, data }) => ({
      uuid,
      data: new Buffer(data, 'base64'),
    }));
  }

  // We don't know these values because iOS doesn't want to give us
  // this information. Only random UUIDs are generated from them
  // under the hood
  var address = 'unknown';
  var addressType = 'unknown';

  this.emit('discover', peripheralUuid, address, addressType, connectable, advertisement, rssi);
};

NobleBindings.prototype.onStateChange = function(state) {
  // var state = ['unknown', 'resetting', 'unsupported', 'unauthorized', 'poweredOff', 'poweredOn'][args.kCBMsgArgState];
  debug('state change ' + state);
  this.emit('stateChange', state);
};

var nobleBindings = new NobleBindings();

/**
 * Start scanning
 * @param  {Array} serviceUuids     Scan for these UUIDs, if undefined then scan for all
 * @param  {Bool}  allowDuplicates  Scan can return duplicates
 *
 * @discussion tested
 */
nobleBindings.startScanning = function(serviceUuids, allowDuplicates) {

  var duplicates = allowDuplicates || false;

  RNBLE.startScanning(serviceUuids, duplicates);
  this.emit('scanStart');
};

/**
 * Stop scanning
 *
 * @discussion tested
 */
nobleBindings.stopScanning = function() {
  RNBLE.stopScanning();
  this.emit('scanStop');
};

nobleBindings.init = function() {
  RNBLE.getState();
};

nobleBindings.connect = function(deviceUuid) {
  RNBLE.connect(deviceUuid);
};

nobleBindings.disconnect = function(deviceUuid) {
  RNBLE.disconnect(deviceUuid);
};

nobleBindings.updateRssi = function(deviceUuid) {
  RNBLE.updateRssi(deviceUuid);
};

nobleBindings.discoverServices = function(deviceUuid, uuids) {
  RNBLE.discoverServices(deviceUuid, uuids);
};

nobleBindings.discoverIncludedServices = function(deviceUuid, serviceUuid, serviceUuids) {
  RNBLE.discoverIncludedServices(deviceUuid, serviceUuid, serviceUuids);
};

nobleBindings.discoverCharacteristics = function(deviceUuid, serviceUuid, characteristicUuids) {
  RNBLE.discoverCharacteristics(deviceUuid, serviceUuid);
};

nobleBindings.read = function(deviceUuid, serviceUuid, characteristicUuid) {
  RNBLE.read(deviceUuid, serviceUuid, characteristicUuid);
};

nobleBindings.write = function(deviceUuid, serviceUuid, characteristicUuid, data, withoutResponse) {
  RNBLE.write(deviceUuid, serviceUuid, characteristicUuid, data.toString('base64'), withoutResponse);
};

nobleBindings.broadcast = function(deviceUuid, serviceUuid, characteristicUuid, broadcast) {
  throw new Error('broadcast not yet implemented');
};

nobleBindings.notify = function(deviceUuid, serviceUuid, characteristicUuid, notify) {
  RNBLE.notify(deviceUuid, serviceUuid, characteristicUuid, notify);
};

nobleBindings.discoverDescriptors = function(deviceUuid, serviceUuid, characteristicUuid) {
  RNBLE.discoverDescriptors(deviceUuid, serviceUuid, characteristicUuid);
};

nobleBindings.readValue = function(deviceUuid, serviceUuid, characteristicUuid, descriptorUuid) {
  throw new Error('readValue not yet implemented');
};

nobleBindings.writeValue = function(deviceUuid, serviceUuid, characteristicUuid, descriptorUuid, data) {
  throw new Error('writeValue not yet implemented');
};

nobleBindings.readHandle = function(deviceUuid, handle) {
  throw new Error('readHandle not yet implemented');
};

nobleBindings.writeHandle = function(deviceUuid, handle, data, withoutResponse) {
  throw new Error('writeHandle not yet implemented');
};

// Exports
module.exports = nobleBindings;<commit_msg>terrible hack in order to receive initial statechange<commit_after>var debug = require('debug')('ios-bindings');

var events = require('events');
var util = require('util');

var {
  DeviceEventEmitter,
  NativeModules: { RNBLE },
} = require('react-native');

var Buffer = require('buffer').Buffer;

/**
 *  NobleBindings for react native
 */
var NobleBindings = function() {
  DeviceEventEmitter.addListener('ble.connect', this.onConnect.bind(this));
  DeviceEventEmitter.addListener('ble.disconnect', this.onDisconnect.bind(this));
  DeviceEventEmitter.addListener('ble.discover', this.onDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.rssiUpdate', this.onRssiUpdate.bind(this));
  DeviceEventEmitter.addListener('ble.servicesDiscover', this.onServicesDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.includedServicesDiscover', this.onIncludedServicesDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.characteristicsDiscover', this.onCharacteristicsDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.descriptorsDiscover', this.onDescriptorsDiscover.bind(this));
  DeviceEventEmitter.addListener('ble.stateChange', this.onStateChange.bind(this));
  DeviceEventEmitter.addListener('ble.data', this.onData.bind(this));
  DeviceEventEmitter.addListener('ble.write', this.onWrite.bind(this));
  DeviceEventEmitter.addListener('ble.notify', this.onNotify.bind(this));
};

util.inherits(NobleBindings, events.EventEmitter);

NobleBindings.prototype.onConnect = function({ peripheralUuid, error = null }) {
  this.emit('connect', peripheralUuid, error);
};

NobleBindings.prototype.onDisconnect = function({ peripheralUuid, error = null }) {
  this.emit('disconnect', peripheralUuid, error);
};

NobleBindings.prototype.onRssiUpdate = function({ peripheralUuid, rssi }) {
  this.emit('rssiUpdate', peripheralUuid, rssi);
};

NobleBindings.prototype.onServicesDiscover = function({ peripheralUuid, serviceUuids }) {
  this.emit('servicesDiscover', peripheralUuid, serviceUuids);
};

NobleBindings.prototype.onIncludedServicesDiscover = function({ peripheralUuid, serviceUuid, includedServiceUuids }) {
  this.emit('includedServicesDiscover', peripheralUuid, serviceUuid, includedServiceUuids);
};

NobleBindings.prototype.onCharacteristicsDiscover = function({ peripheralUuid, serviceUuid, characteristics }) {
  this.emit(
    'characteristicsDiscover',
    peripheralUuid,
    serviceUuid,
    characteristics
  );
};

NobleBindings.prototype.onDescriptorsDiscover = function({ peripheralUuid, serviceUuid, characteristicUuid, descriptors }) {
  this.emit('descriptorsDiscover', peripheralUuid, serviceUuid, characteristicUuid, descriptors);
};

NobleBindings.prototype.onData = function({ peripheralUuid, serviceUuid, characteristicUuid, data, isNotification }) {
  var processedData = new Buffer(data, 'base64');
  this.emit('data', peripheralUuid, serviceUuid, characteristicUuid, processedData, isNotification);
  this.emit('read', peripheralUuid, serviceUuid, characteristicUuid, processedData, isNotification);
};

NobleBindings.prototype.onWrite = function({ peripheralUuid, serviceUuid, characteristicUuid }) {
  this.emit('write', peripheralUuid, serviceUuid, characteristicUuid);
};

NobleBindings.prototype.onNotify = function({ peripheralUuid, serviceUuid, characteristicUuid, state }) {
  this.emit('notify', peripheralUuid, serviceUuid, characteristicUuid, state);
};

NobleBindings.prototype.onDiscover = function({ peripheralUuid, advertisement, connectable, rssi }) {
  debug('peripheral ' + peripheralUuid + ' discovered');

  if (advertisement.manufacturerData) {
    advertisement.manufacturerData = new Buffer(advertisement.manufacturerData, 'base64');
  }

  if (advertisement.serviceData) {
    advertisement.serviceData = advertisement.serviceData.map(({ uuid, data }) => ({
      uuid,
      data: new Buffer(data, 'base64'),
    }));
  }

  // We don't know these values because iOS doesn't want to give us
  // this information. Only random UUIDs are generated from them
  // under the hood
  var address = 'unknown';
  var addressType = 'unknown';

  this.emit('discover', peripheralUuid, address, addressType, connectable, advertisement, rssi);
};

NobleBindings.prototype.onStateChange = function(state) {
  // var state = ['unknown', 'resetting', 'unsupported', 'unauthorized', 'poweredOff', 'poweredOn'][args.kCBMsgArgState];
  debug('state change ' + state);
  this.emit('stateChange', state);
};

var nobleBindings = new NobleBindings();

/**
 * Start scanning
 * @param  {Array} serviceUuids     Scan for these UUIDs, if undefined then scan for all
 * @param  {Bool}  allowDuplicates  Scan can return duplicates
 *
 * @discussion tested
 */
nobleBindings.startScanning = function(serviceUuids, allowDuplicates) {

  var duplicates = allowDuplicates || false;

  RNBLE.startScanning(serviceUuids, duplicates);
  this.emit('scanStart');
};

/**
 * Stop scanning
 *
 * @discussion tested
 */
nobleBindings.stopScanning = function() {
  RNBLE.stopScanning();
  this.emit('scanStop');
};

nobleBindings.init = function() {
  setTimeout(function() {
    RNBLE.getState();
  }, 1000);
};

nobleBindings.connect = function(deviceUuid) {
  RNBLE.connect(deviceUuid);
};

nobleBindings.disconnect = function(deviceUuid) {
  RNBLE.disconnect(deviceUuid);
};

nobleBindings.updateRssi = function(deviceUuid) {
  RNBLE.updateRssi(deviceUuid);
};

nobleBindings.discoverServices = function(deviceUuid, uuids) {
  RNBLE.discoverServices(deviceUuid, uuids);
};

nobleBindings.discoverIncludedServices = function(deviceUuid, serviceUuid, serviceUuids) {
  RNBLE.discoverIncludedServices(deviceUuid, serviceUuid, serviceUuids);
};

nobleBindings.discoverCharacteristics = function(deviceUuid, serviceUuid, characteristicUuids) {
  RNBLE.discoverCharacteristics(deviceUuid, serviceUuid);
};

nobleBindings.read = function(deviceUuid, serviceUuid, characteristicUuid) {
  RNBLE.read(deviceUuid, serviceUuid, characteristicUuid);
};

nobleBindings.write = function(deviceUuid, serviceUuid, characteristicUuid, data, withoutResponse) {
  RNBLE.write(deviceUuid, serviceUuid, characteristicUuid, data.toString('base64'), withoutResponse);
};

nobleBindings.broadcast = function(deviceUuid, serviceUuid, characteristicUuid, broadcast) {
  throw new Error('broadcast not yet implemented');
};

nobleBindings.notify = function(deviceUuid, serviceUuid, characteristicUuid, notify) {
  RNBLE.notify(deviceUuid, serviceUuid, characteristicUuid, notify);
};

nobleBindings.discoverDescriptors = function(deviceUuid, serviceUuid, characteristicUuid) {
  RNBLE.discoverDescriptors(deviceUuid, serviceUuid, characteristicUuid);
};

nobleBindings.readValue = function(deviceUuid, serviceUuid, characteristicUuid, descriptorUuid) {
  throw new Error('readValue not yet implemented');
};

nobleBindings.writeValue = function(deviceUuid, serviceUuid, characteristicUuid, descriptorUuid, data) {
  throw new Error('writeValue not yet implemented');
};

nobleBindings.readHandle = function(deviceUuid, handle) {
  throw new Error('readHandle not yet implemented');
};

nobleBindings.writeHandle = function(deviceUuid, handle, data, withoutResponse) {
  throw new Error('writeHandle not yet implemented');
};

// Exports
module.exports = nobleBindings;<|endoftext|>