<commit_before>export const latestRuns = [{
    'latestRun': {
        'changeSet': [{
            'author': {
                'email': 'tscherler@cloudbees.com',
                'fullName': 'tscherler',
                'id': 'tscherler'
            },
            'affectedPaths': [
                'Jenkinsfile'
            ],
            'commitId': '21552ff3072684cc1d593376b7cc7023deb15e1c',
            'comment': 'Update Jenkinsfile\n',
            'date': '2016-03-15 00:35:58 +0100',
            'id': '21552ff3072684cc1d593376b7cc7023deb15e1c',
            'msg': 'Update Jenkinsfile',
            'paths': [{
                'editType': 'edit',
                'file': 'Jenkinsfile'
            }],
            'timestamp': '2016-03-15T00:35:58.000+0100'
        }, {
            'author': {
                'email': 'tscherler@cloudbees.com',
                'fullName': 'tscherler',
                'id': 'tscherler'
            },
            'affectedPaths': [
                'Jenkinsfile'
            ],
            'commitId': 'eb92e0df899ff742b002a3ea652f4eb406ea83b8',
            'comment': 'Update Jenkinsfile\n',
            'date': '2016-03-15 00:33:40 +0100',
            'id': 'eb92e0df899ff742b002a3ea652f4eb406ea83b8',
            'msg': 'Update Jenkinsfile',
            'paths': [{
                'editType': 'edit',
                'file': 'Jenkinsfile'
            }],
            'timestamp': '2016-03-15T00:33:40.000+0100'
        }],
        'durationInMillis': 18678,
        'enQueueTime': '2016-03-15T00:38:33.890+0100',
        'endTime': '2016-03-15T00:38:52.606+0100',
        'id': '2',
        'organization': 'jenkins',
        'pipeline': 'master',
        'result': 'SUCCESS',
        'runSummary': 'stable',
        'startTime': '2016-03-15T00:38:33.928+0100',
        'state': 'FINISHED',
        'type': 'WorkflowRun',
        'commitId': '09794ca7e2e98cdc5e2f0f02117d79f5b112c7c1'
    },
    'name': 'master',
    'weatherScore': 100,
    'pullRequest': null
}, {
    'latestRun': {
        'changeSet': [],
        'durationInMillis': 25636,
        'enQueueTime': '2016-03-15T00:38:35.964+0100',
        'endTime': '2016-03-15T00:39:01.616+0100',
        'id': '1',
        'organization': 'jenkins',
        'pipeline': 'PR-6',
        'result': 'FAILURE',
        'runSummary': 'broken since this build',
        'startTime': '2016-03-15T00:38:35.980+0100',
        'state': 'FINISHED',
        'type': 'WorkflowRun',
        'commitId': 'c38ab8e9275c2ee03e14e1bbfc9f44f2eddcff19'
    },
    'name': 'PR-6',
    'weatherScore': 0,
    'pullRequest': {
        'author': 'target-x',
        'id': '6',
        'title': 'Feature/yyy',
        'url': 'https://github.com/cloudbees/blueocean-pr-testing/pull/6'
    }
}];
<commit_msg>[UX-75] add artifacts to test data<commit_after>export const latestRuns = [{
    'latestRun': {
        'artifacts':[
            {
                'name':'hey',
                'size':4,
                'url':'/jenkins/job/jenkinsfile-experiments/branch/master/1/artifact/hey'
            }
        ],
        'changeSet':[{
            'author': {
                'email': 'tscherler@cloudbees.com',
                'fullName': 'tscherler',
                'id': 'tscherler'
            },
            'affectedPaths': [
                'Jenkinsfile'
            ],
            'commitId': '21552ff3072684cc1d593376b7cc7023deb15e1c',
            'comment': 'Update Jenkinsfile\n',
            'date': '2016-03-15 00:35:58 +0100',
            'id': '21552ff3072684cc1d593376b7cc7023deb15e1c',
            'msg': 'Update Jenkinsfile',
            'paths': [{
                'editType': 'edit',
                'file': 'Jenkinsfile'
            }],
            'timestamp': '2016-03-15T00:35:58.000+0100'
        }, {
            'author': {
                'email': 'tscherler@cloudbees.com',
                'fullName': 'tscherler',
                'id': 'tscherler'
            },
            'affectedPaths': [
                'Jenkinsfile'
            ],
            'commitId': 'eb92e0df899ff742b002a3ea652f4eb406ea83b8',
            'comment': 'Update Jenkinsfile\n',
            'date': '2016-03-15 00:33:40 +0100',
            'id': 'eb92e0df899ff742b002a3ea652f4eb406ea83b8',
            'msg': 'Update Jenkinsfile',
            'paths': [{
                'editType': 'edit',
                'file': 'Jenkinsfile'
            }],
            'timestamp': '2016-03-15T00:33:40.000+0100'
        }],
        'durationInMillis': 18678,
        'enQueueTime': '2016-03-15T00:38:33.890+0100',
        'endTime': '2016-03-15T00:38:52.606+0100',
        'id': '2',
        'organization': 'jenkins',
        'pipeline': 'master',
        'result': 'SUCCESS',
        'runSummary': 'stable',
        'startTime': '2016-03-15T00:38:33.928+0100',
        'state': 'FINISHED',
        'type': 'WorkflowRun',
        'commitId': '09794ca7e2e98cdc5e2f0f02117d79f5b112c7c1'
    },
    'name': 'master',
    'weatherScore': 100,
    'pullRequest': null
}, {
    'latestRun': {
        'changeSet': [],
        'durationInMillis': 25636,
        'enQueueTime': '2016-03-15T00:38:35.964+0100',
        'endTime': '2016-03-15T00:39:01.616+0100',
        'id': '1',
        'organization': 'jenkins',
        'pipeline': 'PR-6',
        'result': 'FAILURE',
        'runSummary': 'broken since this build',
        'startTime': '2016-03-15T00:38:35.980+0100',
        'state': 'FINISHED',
        'type': 'WorkflowRun',
        'commitId': 'c38ab8e9275c2ee03e14e1bbfc9f44f2eddcff19'
    },
    'name': 'PR-6',
    'weatherScore': 0,
    'pullRequest': {
        'author': 'target-x',
        'id': '6',
        'title': 'Feature/yyy',
        'url': 'https://github.com/cloudbees/blueocean-pr-testing/pull/6'
    }
}];
<|endoftext|>


<commit_before>/*
Language: Swift
Author: Chris Eidhof <chris@eidhof.nl>
Contributors: Nate Cook <natecook@gmail.com>
*/

function(hljs) {
  var SWIFT_KEYWORDS = {
      keyword: 'class deinit enum extension func import init let protocol static ' +
        'struct subscript typealias var break case continue default do ' +
        'else fallthrough if in for return switch where while as dynamicType ' +
        'is new super self Self Type __COLUMN__ __FILE__ __FUNCTION__ ' +
        '__LINE__ associativity didSet get infix inout left mutating none ' +
        'nonmutating operator override postfix precedence prefix right set '+
        'unowned unowned safe unsafe weak willSet',
      literal: 'true false nil',
      built_in: 'abs advance alignof alignofValue assert bridgeFromObjectiveC ' +
        'bridgeFromObjectiveCUnconditional bridgeToObjectiveC ' +
        'bridgeToObjectiveCUnconditional c contains count countElements ' +
        'countLeadingZeros debugPrint debugPrintln distance dropFirst dropLast dump ' +
        'encodeBitsAsWords enumerate equal false filter find getBridgedObjectiveCType ' +
        'getVaList indices insertionSort isBridgedToObjectiveC ' +
        'isBridgedVerbatimToObjectiveC isUniquelyReferenced join ' +
        'lexicographicalCompare map max maxElement min minElement nil numericCast ' +
        'partition posix print println quickSort reduce reflect reinterpretCast ' +
        'reverse roundUpToAlignment sizeof sizeofValue sort split startsWith strideof ' +
        'strideofValue swap swift toString transcode true underestimateCount ' +
        'unsafeReflect withExtendedLifetime withObjectAtPlusZero withUnsafePointer ' +
        'withUnsafePointerToObject withUnsafePointers withVaList'
    };

  var TYPE = {
    className: 'type',
    begin: '\\b[A-Z][\\w\']*',
    relevance: 0
  };
  var BLOCK_COMMENT = {
    className: 'comment',
    begin: '/\\*', end: '\\*/',
    contains: [hljs.PHRASAL_WORDS_MODE, 'self']
  };
  var SUBST = {
    className: 'subst',
    begin: /\\\(/, end: '\\)',
    keywords: SWIFT_KEYWORDS,
    contains: [] // assigned later
  };
  var NUMBERS = {
      className: 'number',
      begin: '\\b([\\d_]+(\\.[\\deE_]+)?|0x[a-fA-F0-9_]+(\\.[a-fA-F0-9p_]+)?|0b[01_]+|0o[0-7_]+)\\b',
      relevance: 0
  };
  var QUOTE_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    contains: [SUBST, hljs.BACKSLASH_ESCAPE]
  });
  SUBST.contains = [NUMBERS];

  return {
    keywords: SWIFT_KEYWORDS,
    contains: [
      QUOTE_STRING_MODE,
      hljs.C_LINE_COMMENT_MODE,
      BLOCK_COMMENT,
      TYPE,
      NUMBERS,
      {
        className: 'func',
        beginKeywords: 'func', excludeEnd: true,
        contains: [
          hljs.inherit(hljs.TITLE_MODE, {
            begin: /[A-Za-z$_][0-9A-Za-z$_]*/,
            illegal: /\(/
          }),
          {
            className: 'generics',
            begin: /\</, end: /\>/,
            illegal: /\>/
          },
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            contains: [
              hljs.C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE
            ],
            illegal: /["']/
          }
        ],
        illegal: /\[|%/
      },
      {
        className: 'class',
        keywords: 'struct protocol class extension enum',
        begin: '(struct|protocol|class(?! (func|var))|extension|enum)',
        end: '\\{',
        excludeEnd: true,
        contains: [
          hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/})
        ]
      },
      {
        className: 'preprocessor', // @attributes
        begin: '(@assignment|@class_protocol|@exported|@final|@lazy|@noreturn|' +
                  '@NSCopying|@NSManaged|@objc|@optional|@required|@auto_closure|' +
                  '@noreturn|@IBAction|@IBDesignable|@IBInspectable|@IBOutlet|' +
                  '@infix|@prefix|@postfix)'
      },
    ]
  };
}
<commit_msg>':' in Swift function params.<commit_after>/*
Language: Swift
Author: Chris Eidhof <chris@eidhof.nl>
Contributors: Nate Cook <natecook@gmail.com>
*/

function(hljs) {
  var SWIFT_KEYWORDS = {
      keyword: 'class deinit enum extension func import init let protocol static ' +
        'struct subscript typealias var break case continue default do ' +
        'else fallthrough if in for return switch where while as dynamicType ' +
        'is new super self Self Type __COLUMN__ __FILE__ __FUNCTION__ ' +
        '__LINE__ associativity didSet get infix inout left mutating none ' +
        'nonmutating operator override postfix precedence prefix right set '+
        'unowned unowned safe unsafe weak willSet',
      literal: 'true false nil',
      built_in: 'abs advance alignof alignofValue assert bridgeFromObjectiveC ' +
        'bridgeFromObjectiveCUnconditional bridgeToObjectiveC ' +
        'bridgeToObjectiveCUnconditional c contains count countElements ' +
        'countLeadingZeros debugPrint debugPrintln distance dropFirst dropLast dump ' +
        'encodeBitsAsWords enumerate equal false filter find getBridgedObjectiveCType ' +
        'getVaList indices insertionSort isBridgedToObjectiveC ' +
        'isBridgedVerbatimToObjectiveC isUniquelyReferenced join ' +
        'lexicographicalCompare map max maxElement min minElement nil numericCast ' +
        'partition posix print println quickSort reduce reflect reinterpretCast ' +
        'reverse roundUpToAlignment sizeof sizeofValue sort split startsWith strideof ' +
        'strideofValue swap swift toString transcode true underestimateCount ' +
        'unsafeReflect withExtendedLifetime withObjectAtPlusZero withUnsafePointer ' +
        'withUnsafePointerToObject withUnsafePointers withVaList'
    };

  var TYPE = {
    className: 'type',
    begin: '\\b[A-Z][\\w\']*',
    relevance: 0
  };
  var BLOCK_COMMENT = {
    className: 'comment',
    begin: '/\\*', end: '\\*/',
    contains: [hljs.PHRASAL_WORDS_MODE, 'self']
  };
  var SUBST = {
    className: 'subst',
    begin: /\\\(/, end: '\\)',
    keywords: SWIFT_KEYWORDS,
    contains: [] // assigned later
  };
  var NUMBERS = {
      className: 'number',
      begin: '\\b([\\d_]+(\\.[\\deE_]+)?|0x[a-fA-F0-9_]+(\\.[a-fA-F0-9p_]+)?|0b[01_]+|0o[0-7_]+)\\b',
      relevance: 0
  };
  var QUOTE_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    contains: [SUBST, hljs.BACKSLASH_ESCAPE]
  });
  SUBST.contains = [NUMBERS];

  return {
    keywords: SWIFT_KEYWORDS,
    contains: [
      QUOTE_STRING_MODE,
      hljs.C_LINE_COMMENT_MODE,
      BLOCK_COMMENT,
      TYPE,
      NUMBERS,
      {
        className: 'func',
        beginKeywords: 'func', end: '{', excludeEnd: true,
        contains: [
          hljs.inherit(hljs.TITLE_MODE, {
            begin: /[A-Za-z$_][0-9A-Za-z$_]*/,
            illegal: /\(/
          }),
          {
            className: 'generics',
            begin: /\</, end: /\>/,
            illegal: /\>/
          },
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            keywords: SWIFT_KEYWORDS,
            contains: [
              'self',
              NUMBERS,
              QUOTE_STRING_MODE,
              hljs.C_BLOCK_COMMENT_MODE,
              {begin: ':'} // relevance booster
            ],
            illegal: /["']/
          }
        ],
        illegal: /\[|%/
      },
      {
        className: 'class',
        keywords: 'struct protocol class extension enum',
        begin: '(struct|protocol|class(?! (func|var))|extension|enum)',
        end: '\\{',
        excludeEnd: true,
        contains: [
          hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/})
        ]
      },
      {
        className: 'preprocessor', // @attributes
        begin: '(@assignment|@class_protocol|@exported|@final|@lazy|@noreturn|' +
                  '@NSCopying|@NSManaged|@objc|@optional|@required|@auto_closure|' +
                  '@noreturn|@IBAction|@IBDesignable|@IBInspectable|@IBOutlet|' +
                  '@infix|@prefix|@postfix)'
      },
    ]
  };
}
<|endoftext|>


<commit_before>/*
 * Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Ensembl.LayoutManager = new Base();

Ensembl.LayoutManager.extend({
  constructor: null,

  /**
   * Creates events on elements outside of the domain of panels
   */
  initialize: function () {
    this.id = 'LayoutManager';

    Ensembl.EventManager.register('reloadPage',    this, this.reloadPage);
    Ensembl.EventManager.register('validateForms', this, this.validateForms);
    Ensembl.EventManager.register('makeZMenu',     this, this.makeZMenu);
    Ensembl.EventManager.register('hashChange',    this, this.hashChange);
    Ensembl.EventManager.register('toggleContent', this, this.toggleContent);
    Ensembl.EventManager.register('changeWidth',   this, this.changeWidth);

    $('#page_nav .tool_buttons > p').show();

    $('#header a:not(#tabs a)').addClass('constant');

    if (window.location.hash.match(Ensembl.locationMatch)) {
      $('.ajax_load').val(function (i, val) {
        return Ensembl.urlFromHash(val);
      });

      this.hashChange(Ensembl.urlFromHash(window.location.href, true));
    }

    $(document).find('#static').externalLinks();

    $(document).on('click', '.modal_link', function () {
      if (Ensembl.EventManager.trigger('modalOpen', this)) {
        return false;
      }
    }).on('click', '.popup', function () {
      if (window.name.match(/^popup_/)) {
        return true;
      }

      window.open(this.href, 'popup_' + window.name, 'width=950,height=500,resizable,scrollbars');
      return false;
    }).on('click', 'a[rel="external"]', function () {
      this.target = '_blank';
    }).on('click', 'a.update_panel', function () {
      var panelId = this.rel;
      var url     = Ensembl.updateURL({ update_panel: 1 }, this.href);

      if (Ensembl.PanelManager.panels[panelId] && this.href.split('?')[0].match(Ensembl.PanelManager.panels[panelId].params.updateURL.split('?')[0])) {
        var params = {};

        if (!$('.update_url', this).add($(this).siblings('.update_url')).each(function () { params[this.name] = this.value; }).length) {
          params = undefined;
        }

        Ensembl.EventManager.triggerSpecific('updatePanel', panelId, url, null, { updateURL: this.href }, params);
      } else {
        $.ajax({
          url: url,
          success: function () {
            Ensembl.EventManager.triggerSpecific('updatePanel', panelId);
          }
        });
      }

      return false;
    }).on('submit', 'form.update_panel', function (e) {
      var params    = $(this).serializeArray();
      var urlParams = {};
      var panelId, url, el;

      for (var i in params) {
        switch (params[i].name) {
          case 'panel_id': panelId = params[i].value; break;
          case 'url'     : url     = params[i].value; break;
          case 'element' : el      = params[i].value; break;
          default        : urlParams[params[i].name] = params[i].value; break;
        }
      }

      url = Ensembl.updateURL($.extend({ update_panel: 1 }, urlParams), url);

      Ensembl.EventManager.triggerSpecific('updatePanel', panelId, url, el, null, urlParams);

      return false;
    }).on({
      'keyup.ensembl': function (event) {
        if (event.keyCode === 27) {
          Ensembl.EventManager.trigger('modalClose', true); // Close modal window if the escape key is pressed
        }
      },
      'mouseup.ensembl': function (e) {
        // only fired on left click
        if (!e.which || e.which === 1) {
          Ensembl.EventManager.trigger('mouseUp', e);
        }
      }
    });

    $('.modal_link').show();

    this.validateForms(document);

    $(window).on({
      'resize.ensembl': function (e) {
        if (window.name.match(/^popup_/)) {
          return false;
        }

        // jquery ui resizable events cause window.resize to fire (all events bubble to window)
        // if target has no tagName it is window or document. Don't resize unless this is the case
        if (!e.target.tagName) {
          var width = Ensembl.width;

          if (Ensembl.dynamicWidth) {
            Ensembl.setWidth(undefined, true);
          }

          Ensembl.cookie.set('WINDOW_WIDTH', $(window).width());
          Ensembl.EventManager.trigger('windowResize');

          if (Ensembl.dynamicWidth && Ensembl.width !== width) {
            Ensembl.LayoutManager.changeWidth();
            Ensembl.EventManager.trigger('imageResize');
          }
        }
      },
      'hashchange.ensembl': $.proxy(this.popState, this),
      'popstate.ensembl'  : $.proxy(this.popState, this)
    });

    this.showMobileMessage();
    this.showCookieMessage();
    this.handleMirrorRedirect();
  },

  reloadPage: function (args, url) {
    if (typeof args === 'string') {
      Ensembl.EventManager.triggerSpecific('updatePanel', args);
    } else if (typeof args === 'object') {
      for (var i in args) {
        Ensembl.EventManager.triggerSpecific('updatePanel', i);
      }
    } else {
      return Ensembl.redirect(url);
    }

    $('.session_messages').hide();
  },

  validateForms: function (context) {
    $('form._check', context).validate().on('submit', function () {
      var form = $(this);

      if (form.parents('#modal_panel').length) {
        var panels = form.parents('.js_panel').map(function () { return this.id; }).toArray();
        var rtn;

        while (panels.length && typeof rtn === 'undefined') {
          rtn = Ensembl.EventManager.triggerSpecific('modalFormSubmit', panels.shift(), form);
        }

        return rtn;
      }
    });
  },

  makeZMenu: function (id, params) {
    if (!$('#' + id).length) {
      Ensembl.Panel.ZMenu.template.clone().attr('id', id).appendTo('body');
    }

    Ensembl.EventManager.trigger('addPanel', id, 'ZMenu', undefined, undefined, params, 'showExistingZMenu');
  },

  popState: function () {
    if (
      Ensembl.historyReady && // stops popState executing on initial page load in Chrome. This value is set to true in Ensembl.updateLocation
      // there is an r param in the hash/search EXCEPT WHEN the browser supports history API, and there is a hash which doesn't have an r param (ajax added content)
      ((window.location[Ensembl.locationURL].match(Ensembl.locationMatch) && !(Ensembl.locationURL === 'search' && window.location.hash && !window.location.hash.match(Ensembl.locationMatch))) ||
      (!window.location.hash && Ensembl.hash.match(Ensembl.locationMatch))) // there is no location.hash, but Ensembl.hash (previous hash value) had an r param (going back from no hash url to hash url)
    ) {
      Ensembl.setCoreParams();
      Ensembl.EventManager.trigger('hashChange', Ensembl.urlFromHash(window.location.href, true));
    }
  },

  hashChange: function (r) {
    if (!r) {
      return;
    }

    r = decodeURIComponent(r);

    var text = r.split(/\W/);
        text = text[0] + ': ' + Ensembl.thousandify(text[1]) + '-' + Ensembl.thousandify(text[2]);

    $('a:not(.constant)').attr('href', function () {
      var r;

      if (this.title === 'UCSC') {
        this.href = this.href.replace(/(&?position=)[^&]+(.?)/, '$1chr' + Ensembl.urlFromHash(this.href, true) + '$2');
      } else if (this.title === 'NCBI') {
        r = Ensembl.urlFromHash(this.href, true).split(/[:\-]/);
        this.href = this.href.replace(/(&?CHR=).+&BEG=.+&END=[^&]+(.?)/, '$1' + r[0] + '&BEG=' + r[1] + '&END=' + r[2] + '$2');
      } else {
        return Ensembl.urlFromHash(this.href);
      }
    });

    $('input[name=r]', 'form:not(#core_params)').val(r);

    $('h1.summary-heading').html(function (i, html) {
      return html.replace(/^(Chromosome ).+/, '$1' + text);
    });

    document.title = document.title.replace(/(Chromosome ).+/, '$1' + text);
  },

  toggleContent: function (rel, delay) {
    if (rel) {
      window.setTimeout(function() {
        $('a.toggle[rel="' + rel + '"]').toggleClass('open closed');
      }, delay && $('a.toggle[rel="' + rel + '"]').hasClass('open') ? delay : 0);
    }
  },

  changeWidth: function () {
    var modal = $('#modal_panel');
    $('.navbar, div.info, div.hint, div.warning, div.error').not('.fixed_width').not(function () { return modal.find(this).length; }).width(Ensembl.width);
    modal = null;
  },

  handleMirrorRedirect: function() {

    var redirectCode  = unescape(Ensembl.cookie.get('redirect_mirror'));
    var redirectURI   = unescape(Ensembl.cookie.get('redirect_mirror_url'));

    Ensembl.cookie.set('redirect_mirror_url');

    var noRedirectURI = function(uri) {
      uri = uri.replace(/(\&|\;)?redirect=[^\&\;]+/, '').replace(/(\&|\;)?debugip=[^\&\;]+/, '').replace(/\?[\;\&]+/, '?').replace(/\?$/, '');
      uri = uri + (uri.match(/\?/) ? ';redirect=no' : '?redirect=no');
      return uri;
    };

    if (redirectCode && redirectCode !== 'no') {
      redirectCode      = redirectCode.split(/\|/);
      if (redirectCode.length >= 2) {
        var currentURI    = noRedirectURI(window.location.href);
        var mirrorName    = redirectCode.shift();
        var remainingTime = parseInt(redirectCode.shift());
        var mirrorURI     = (redirectURI ? noRedirectURI($('').attr('href', redirectURI).prop('href')) : currentURI).replace(window.location.host, mirrorName);
        var messageDiv    = $([
          '
',
          '
You are being redirected to ', mirrorName, ' in ', remainingTime, ' seconds. Click here if you don\'t wish to be redirected.
',
          '
'
        ].join('')).appendTo($('body').prepend($('

').slideDown())).slideDown().find('a._redirect_no').on('click', function (e) {
          e.preventDefault();
          Ensembl.cookie.set('redirect_mirror', 'no');
          clearInterval(messageDiv.data('countdown'));
          window.location.replace(messageDiv.data('currentURI'));
        }).end().data({
          remainingTime : remainingTime,
          mirrorURI     : mirrorURI,
          currentURI    : currentURI,
          countdown     : setInterval(function() {
            var time  = messageDiv.data('remainingTime') - 1;
            messageDiv.data('remainingTime', time).find('._redirect_countdown').html(time > 0 ? time > 1 ? 'in ' + time + ' seconds' : 'in 1 second' : 'now');
            if (time <= 0) {
              clearInterval(messageDiv.data('countdown'));
              window.location.href = messageDiv.data('mirrorURI');
            }
          }, 1000)
        });
      }
    }
  },

  showCookieMessage: function() {
    var cookiesAccepted = Ensembl.cookie.get('cookies_ok');

    if (!cookiesAccepted) {
      $(['
',
        '

',
        '
We use cookies to enhance the usability of our website. If you continue, we\'ll assume that you are happy to receive all cookies.
',
        '
<button>Don\'t show this again</button>
',
        '
Further details about our privacy and cookie policy can be found here.
',
        '
'
      ].join(''))
        .appendTo(document.body).show().find('button,div').on('click', function (e) {
          Ensembl.cookie.set('cookies_ok', 'yes');
          $(this).parents('div').first().fadeOut(200);
      }).filter('div').helptip({content:"Don't show this again"});
      return true;
    }

    return false;
  },

  showMobileMessage: function() { }

});
<commit_msg>Update all link with the new hlr param when region highlighting changes<commit_after>/*
 * Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Ensembl.LayoutManager = new Base();

Ensembl.LayoutManager.extend({
  constructor: null,

  /**
   * Creates events on elements outside of the domain of panels
   */
  initialize: function () {
    this.id = 'LayoutManager';

    Ensembl.EventManager.register('reloadPage',         this, this.reloadPage);
    Ensembl.EventManager.register('validateForms',      this, this.validateForms);
    Ensembl.EventManager.register('makeZMenu',          this, this.makeZMenu);
    Ensembl.EventManager.register('hashChange',         this, this.hashChange);
    Ensembl.EventManager.register('highlightLocation',  this, this.updateHighlightParam);
    Ensembl.EventManager.register('toggleContent',      this, this.toggleContent);
    Ensembl.EventManager.register('changeWidth',        this, this.changeWidth);

    $('#page_nav .tool_buttons > p').show();

    $('#header a:not(#tabs a)').addClass('constant');

    if (window.location.hash.match(Ensembl.locationMatch)) {
      $('.ajax_load').val(function (i, val) {
        return Ensembl.urlFromHash(val);
      });

      this.hashChange(Ensembl.urlFromHash(window.location.href, true));
    }

    $(document).find('#static').externalLinks();

    $(document).on('click', '.modal_link', function () {
      if (Ensembl.EventManager.trigger('modalOpen', this)) {
        return false;
      }
    }).on('click', '.popup', function () {
      if (window.name.match(/^popup_/)) {
        return true;
      }

      window.open(this.href, 'popup_' + window.name, 'width=950,height=500,resizable,scrollbars');
      return false;
    }).on('click', 'a[rel="external"]', function () {
      this.target = '_blank';
    }).on('click', 'a.update_panel', function () {
      var panelId = this.rel;
      var url     = Ensembl.updateURL({ update_panel: 1 }, this.href);

      if (Ensembl.PanelManager.panels[panelId] && this.href.split('?')[0].match(Ensembl.PanelManager.panels[panelId].params.updateURL.split('?')[0])) {
        var params = {};

        if (!$('.update_url', this).add($(this).siblings('.update_url')).each(function () { params[this.name] = this.value; }).length) {
          params = undefined;
        }

        Ensembl.EventManager.triggerSpecific('updatePanel', panelId, url, null, { updateURL: this.href }, params);
      } else {
        $.ajax({
          url: url,
          success: function () {
            Ensembl.EventManager.triggerSpecific('updatePanel', panelId);
          }
        });
      }

      return false;
    }).on('submit', 'form.update_panel', function (e) {
      var params    = $(this).serializeArray();
      var urlParams = {};
      var panelId, url, el;

      for (var i in params) {
        switch (params[i].name) {
          case 'panel_id': panelId = params[i].value; break;
          case 'url'     : url     = params[i].value; break;
          case 'element' : el      = params[i].value; break;
          default        : urlParams[params[i].name] = params[i].value; break;
        }
      }

      url = Ensembl.updateURL($.extend({ update_panel: 1 }, urlParams), url);

      Ensembl.EventManager.triggerSpecific('updatePanel', panelId, url, el, null, urlParams);

      return false;
    }).on({
      'keyup.ensembl': function (event) {
        if (event.keyCode === 27) {
          Ensembl.EventManager.trigger('modalClose', true); // Close modal window if the escape key is pressed
        }
      },
      'mouseup.ensembl': function (e) {
        // only fired on left click
        if (!e.which || e.which === 1) {
          Ensembl.EventManager.trigger('mouseUp', e);
        }
      }
    });

    $('.modal_link').show();

    this.validateForms(document);

    $(window).on({
      'resize.ensembl': function (e) {
        if (window.name.match(/^popup_/)) {
          return false;
        }

        // jquery ui resizable events cause window.resize to fire (all events bubble to window)
        // if target has no tagName it is window or document. Don't resize unless this is the case
        if (!e.target.tagName) {
          var width = Ensembl.width;

          if (Ensembl.dynamicWidth) {
            Ensembl.setWidth(undefined, true);
          }

          Ensembl.cookie.set('WINDOW_WIDTH', $(window).width());
          Ensembl.EventManager.trigger('windowResize');

          if (Ensembl.dynamicWidth && Ensembl.width !== width) {
            Ensembl.LayoutManager.changeWidth();
            Ensembl.EventManager.trigger('imageResize');
          }
        }
      },
      'hashchange.ensembl': $.proxy(this.popState, this),
      'popstate.ensembl'  : $.proxy(this.popState, this)
    });

    this.showMobileMessage();
    this.showCookieMessage();
    this.handleMirrorRedirect();
  },

  reloadPage: function (args, url) {
    if (typeof args === 'string') {
      Ensembl.EventManager.triggerSpecific('updatePanel', args);
    } else if (typeof args === 'object') {
      for (var i in args) {
        Ensembl.EventManager.triggerSpecific('updatePanel', i);
      }
    } else {
      return Ensembl.redirect(url);
    }

    $('.session_messages').hide();
  },

  validateForms: function (context) {
    $('form._check', context).validate().on('submit', function () {
      var form = $(this);

      if (form.parents('#modal_panel').length) {
        var panels = form.parents('.js_panel').map(function () { return this.id; }).toArray();
        var rtn;

        while (panels.length && typeof rtn === 'undefined') {
          rtn = Ensembl.EventManager.triggerSpecific('modalFormSubmit', panels.shift(), form);
        }

        return rtn;
      }
    });
  },

  makeZMenu: function (id, params) {
    if (!$('#' + id).length) {
      Ensembl.Panel.ZMenu.template.clone().attr('id', id).appendTo('body');
    }

    Ensembl.EventManager.trigger('addPanel', id, 'ZMenu', undefined, undefined, params, 'showExistingZMenu');
  },

  popState: function () {
    if (
      Ensembl.historyReady && // stops popState executing on initial page load in Chrome. This value is set to true in Ensembl.updateLocation
      // there is an r param in the hash/search EXCEPT WHEN the browser supports history API, and there is a hash which doesn't have an r param (ajax added content)
      ((window.location[Ensembl.locationURL].match(Ensembl.locationMatch) && !(Ensembl.locationURL === 'search' && window.location.hash && !window.location.hash.match(Ensembl.locationMatch))) ||
      (!window.location.hash && Ensembl.hash.match(Ensembl.locationMatch))) // there is no location.hash, but Ensembl.hash (previous hash value) had an r param (going back from no hash url to hash url)
    ) {
      Ensembl.setCoreParams();
      Ensembl.EventManager.trigger('hashChange', Ensembl.urlFromHash(window.location.href, true));
    }
  },

  hashChange: function (r) {
    if (!r) {
      return;
    }

    r = decodeURIComponent(r);

    var text = r.split(/\W/);
        text = text[0] + ': ' + Ensembl.thousandify(text[1]) + '-' + Ensembl.thousandify(text[2]);

    $('a:not(.constant)').attr('href', function () {
      var r;

      if (this.title === 'UCSC') {
        this.href = this.href.replace(/(&?position=)[^&]+(.?)/, '$1chr' + Ensembl.urlFromHash(this.href, true) + '$2');
      } else if (this.title === 'NCBI') {
        r = Ensembl.urlFromHash(this.href, true).split(/[:\-]/);
        this.href = this.href.replace(/(&?CHR=).+&BEG=.+&END=[^&]+(.?)/, '$1' + r[0] + '&BEG=' + r[1] + '&END=' + r[2] + '$2');
      } else {
        return Ensembl.urlFromHash(this.href);
      }
    });

    $('input[name=r]', 'form:not(#core_params)').val(r);

    $('h1.summary-heading').html(function (i, html) {
      return html.replace(/^(Chromosome ).+/, '$1' + text);
    });

    document.title = document.title.replace(/(Chromosome ).+/, '$1' + text);
  },

  updateHighlightParam: function (hlr) {
    $('a:not(.constant)').filter(function () { // only for the links that have r param
      return this.hostname === window.location.hostname && !!this.href.match(Ensembl.locationMatch);
    }).attr('href', function () {
      return Ensembl.updateURL({hlr: hlr && hlr[0]}, this.href);
    });
  },

  toggleContent: function (rel, delay) {
    if (rel) {
      window.setTimeout(function() {
        $('a.toggle[rel="' + rel + '"]').toggleClass('open closed');
      }, delay && $('a.toggle[rel="' + rel + '"]').hasClass('open') ? delay : 0);
    }
  },

  changeWidth: function () {
    var modal = $('#modal_panel');
    $('.navbar, div.info, div.hint, div.warning, div.error').not('.fixed_width').not(function () { return modal.find(this).length; }).width(Ensembl.width);
    modal = null;
  },

  handleMirrorRedirect: function() {

    var redirectCode  = unescape(Ensembl.cookie.get('redirect_mirror'));
    var redirectURI   = unescape(Ensembl.cookie.get('redirect_mirror_url'));

    Ensembl.cookie.set('redirect_mirror_url');

    var noRedirectURI = function(uri) {
      uri = uri.replace(/(\&|\;)?redirect=[^\&\;]+/, '').replace(/(\&|\;)?debugip=[^\&\;]+/, '').replace(/\?[\;\&]+/, '?').replace(/\?$/, '');
      uri = uri + (uri.match(/\?/) ? ';redirect=no' : '?redirect=no');
      return uri;
    };

    if (redirectCode && redirectCode !== 'no') {
      redirectCode      = redirectCode.split(/\|/);
      if (redirectCode.length >= 2) {
        var currentURI    = noRedirectURI(window.location.href);
        var mirrorName    = redirectCode.shift();
        var remainingTime = parseInt(redirectCode.shift());
        var mirrorURI     = (redirectURI ? noRedirectURI($('').attr('href', redirectURI).prop('href')) : currentURI).replace(window.location.host, mirrorName);
        var messageDiv    = $([
          '
',
          '
You are being redirected to ', mirrorName, ' in ', remainingTime, ' seconds. Click here if you don\'t wish to be redirected.
',
          '
'
        ].join('')).appendTo($('body').prepend($('

').slideDown())).slideDown().find('a._redirect_no').on('click', function (e) {
          e.preventDefault();
          Ensembl.cookie.set('redirect_mirror', 'no');
          clearInterval(messageDiv.data('countdown'));
          window.location.replace(messageDiv.data('currentURI'));
        }).end().data({
          remainingTime : remainingTime,
          mirrorURI     : mirrorURI,
          currentURI    : currentURI,
          countdown     : setInterval(function() {
            var time  = messageDiv.data('remainingTime') - 1;
            messageDiv.data('remainingTime', time).find('._redirect_countdown').html(time > 0 ? time > 1 ? 'in ' + time + ' seconds' : 'in 1 second' : 'now');
            if (time <= 0) {
              clearInterval(messageDiv.data('countdown'));
              window.location.href = messageDiv.data('mirrorURI');
            }
          }, 1000)
        });
      }
    }
  },

  showCookieMessage: function() {
    var cookiesAccepted = Ensembl.cookie.get('cookies_ok');

    if (!cookiesAccepted) {
      $(['
',
        '

',
        '
We use cookies to enhance the usability of our website. If you continue, we\'ll assume that you are happy to receive all cookies.
',
        '
<button>Don\'t show this again</button>
',
        '
Further details about our privacy and cookie policy can be found here.
',
        '
'
      ].join(''))
        .appendTo(document.body).show().find('button,div').on('click', function (e) {
          Ensembl.cookie.set('cookies_ok', 'yes');
          $(this).parents('div').first().fadeOut(200);
      }).filter('div').helptip({content:"Don't show this again"});
      return true;
    }

    return false;
  },

  showMobileMessage: function() { }

});
<|endoftext|>


<commit_before>//Part of the DuskWolf engine
//Licensed under the MIT license, see COPYING.txt for details
"use strict";

load.provide("tests.animation", (function() {
	load.require("dusk.sgui.DynamicGrid");
	load.require("dusk.input.sgui.ControlConfig");
	load.require("dusk.sgui.Label");
	load.require("dusk.sgui.Image");
	load.require("dusk.particles.particleEffects.core.spread");
	load.require("dusk.sgui.FpsMeter");
	load.require("dusk.sgui.PlusText");
	load.require("dusk.entities.sgui.EntityWorkshop");
	load.require("dusk.sgui.TextBack");
	load.require("dusk.tiles.sgui.Tile");
	load.require("dusk.tiles.sgui.extras.AnimatedTile");
	var atTypes = load.require("dusk.tiles.sgui.extras.animationTypes");

	var SaveSpec = load.require("dusk.save.SaveSpec");
	var checkpoints = load.require("dusk.checkpoints");

	var dplat = load.require("dusk.rooms.plat");
	var entities = load.require("dusk.entities");
	var dusk = load.require("dusk");
	var sgui = load.require("dusk.sgui");
	var c = load.require("dusk.sgui.c");
	var controls = load.require("dusk.input.controls");
	var frameTicker = load.require("dusk.utils.frameTicker");
	var Range = load.require("dusk.utils.Range");

	window.root = sgui.get("default", true);

	root.update({
		"children":{
			"gr":{
				"type":"Grid",
				"rows":10,
				"cols":10,
				"width":320,
				"height":320,
				"globals":{
					"type":"Tile",
					"tile":"1,0",
					"swidth":16,
					"sheight":16,
					"src":"testTiles.png mono;tiles:16x16",
					"width":32,
					"height":32,
					"extras":{
						"animation":{
							"type":"AnimatedTile",
							"animations":[
								["default", [
									atTypes.setTile(0, 0), atTypes.setTile(1, 0)
								], {"trigger":function(){return true}}],
								["rand", [
									atTypes.removeTrans("cor:0.5"), atTypes.setTile(0, 1), atTypes.setTile(1, 1),
									atTypes.cond(function() {return Math.random() > 0.5;}, 1),
									atTypes.addTrans("cor:0.5", true)
								], {"trigger":function(){return Math.random() > 0.99}, "loops":true}],
								["test", [

								], {}],
							]
						},
					}
				},
				"populate":{}
			}
		}
	});

	window.at = root.get("gr").get("0,0").getExtra("animation");

	dusk.startGame();
})());
<commit_msg>Animation test now has rate<commit_after>//Part of the DuskWolf engine
//Licensed under the MIT license, see COPYING.txt for details
"use strict";

load.provide("tests.animation", (function() {
	load.require("dusk.sgui.DynamicGrid");
	load.require("dusk.input.sgui.ControlConfig");
	load.require("dusk.sgui.Label");
	load.require("dusk.sgui.Image");
	load.require("dusk.particles.particleEffects.core.spread");
	load.require("dusk.sgui.FpsMeter");
	load.require("dusk.sgui.PlusText");
	load.require("dusk.entities.sgui.EntityWorkshop");
	load.require("dusk.sgui.TextBack");
	load.require("dusk.tiles.sgui.Tile");
	load.require("dusk.tiles.sgui.extras.AnimatedTile");
	var atTypes = load.require("dusk.tiles.sgui.extras.animationTypes");

	var SaveSpec = load.require("dusk.save.SaveSpec");
	var checkpoints = load.require("dusk.checkpoints");

	var dplat = load.require("dusk.rooms.plat");
	var entities = load.require("dusk.entities");
	var dusk = load.require("dusk");
	var sgui = load.require("dusk.sgui");
	var c = load.require("dusk.sgui.c");
	var controls = load.require("dusk.input.controls");
	var frameTicker = load.require("dusk.utils.frameTicker");
	var Range = load.require("dusk.utils.Range");

	window.root = sgui.get("default", true);

	root.update({
		"children":{
			"gr":{
				"type":"Grid",
				"rows":10,
				"cols":10,
				"width":320,
				"height":320,
				"globals":{
					"type":"Tile",
					"tile":"1,0",
					"swidth":16,
					"sheight":16,
					"src":"testTiles.png mono;tiles:16x16",
					"width":32,
					"height":32,
					"extras":{
						"animation":{
							"type":"AnimatedTile",
							"rate":30,
							"animations":[
								["default", [
									atTypes.setTile(0, 0), atTypes.setTile(1, 0)
								], {"trigger":function(){return true}}],
								["rand", [
									atTypes.removeTrans("cor:0.5"), atTypes.setTile(0, 1), atTypes.setTile(1, 1),
									atTypes.cond(function() {return Math.random() > 0.5;}, 1),
									atTypes.addTrans("cor:0.5", true)
								], {"trigger":function(){return Math.random() > 0.99}, "loops":true}],
								["test", [

								], {}],
							]
						},
					}
				},
				"populate":{}
			}
		}
	});

	window.at = root.get("gr").get("0,0").getExtra("animation");

	dusk.startGame();
})());
<|endoftext|>


<commit_before>// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

module("Contrast Ratio", {
  setup: function () {
    var fixture = document.createElement('div');
    document.getElementById('qunit-fixture').appendChild(fixture);
    this.fixture_ = fixture;
    this.black_ = {"red": 0, "green": 0, "blue": 0, "alpha": 1};
    this.white_ = {"red": 255, "green": 255, "blue": 255, "alpha": 1};
  }
});
test("Black and white.", function () {
  equal(axs.color.calculateContrastRatio(this.white_, this.black_), 21);
  equal(axs.color.calculateContrastRatio(this.black_, this.white_), 21);
});
test("Same color === no contrast.", function () {
  equal(axs.color.calculateContrastRatio(this.white_, this.white_), 1);
  equal(axs.color.calculateContrastRatio(this.black_, this.black_), 1);
});
test("Transparent foreground === no contrast.", function () {
  equal(axs.color.calculateContrastRatio({"red": 0, "green": 0, "blue": 0, "alpha": 0}, this.white_), 1);
});

module("parseColor");
test("parses alpha values correctly", function() {
  var colorString = 'rgba(255, 255, 255, .47)';
  var color = axs.color.parseColor(colorString);
  equal(color.red, 255);
  equal(color.blue, 255);
  equal(color.green, 255);
  equal(color.alpha, .47);
});

test("handles rgba transparent value correctly", function() {
  var colorString = 'rgba(0, 0, 0, 0)';
  var color = axs.color.parseColor(colorString);
  equal(color.red, 0);
  equal(color.blue, 0);
  equal(color.green, 0);
  equal(color.alpha, 0);
});

test("handles xbrowser 'transparent' value correctly", function() {
  // Firefox, IE11, Project Spartan (MS Edge Release Candidate)
  var colorString = 'transparent';
  var color = axs.color.parseColor(colorString);
  equal(color.red, 0);
  equal(color.blue, 0);
  equal(color.green, 0);
  equal(color.alpha, 0);
});

module("suggestColors");
test("suggests correct grey values", function() {
  var white = new axs.color.Color(255, 255, 255, 1)
  var desiredContrastRatios = { AA: 4.5, AAA: 7.0 };
  var suggestions = axs.color.suggestColors(white, white, desiredContrastRatios);
  deepEqual(suggestions, { AA: { bg: "#ffffff", contrast: "4.54", fg: "#767676" },
                           AAA: { bg: "#ffffff", contrast: "7.00", fg: "#595959" } });
});
<commit_msg>Linked test to GitHub issue as requested<commit_after>// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

module("Contrast Ratio", {
  setup: function () {
    var fixture = document.createElement('div');
    document.getElementById('qunit-fixture').appendChild(fixture);
    this.fixture_ = fixture;
    this.black_ = {"red": 0, "green": 0, "blue": 0, "alpha": 1};
    this.white_ = {"red": 255, "green": 255, "blue": 255, "alpha": 1};
  }
});
test("Black and white.", function () {
  equal(axs.color.calculateContrastRatio(this.white_, this.black_), 21);
  equal(axs.color.calculateContrastRatio(this.black_, this.white_), 21);
});
test("Same color === no contrast.", function () {
  equal(axs.color.calculateContrastRatio(this.white_, this.white_), 1);
  equal(axs.color.calculateContrastRatio(this.black_, this.black_), 1);
});
test("Transparent foreground === no contrast.", function () {
  equal(axs.color.calculateContrastRatio({"red": 0, "green": 0, "blue": 0, "alpha": 0}, this.white_), 1);
});

module("parseColor");
test("parses alpha values correctly", function() {
  var colorString = 'rgba(255, 255, 255, .47)';
  var color = axs.color.parseColor(colorString);
  equal(color.red, 255);
  equal(color.blue, 255);
  equal(color.green, 255);
  equal(color.alpha, .47);
});

test("handles rgba transparent value correctly", function() {
  var colorString = 'rgba(0, 0, 0, 0)';
  var color = axs.color.parseColor(colorString);
  equal(color.red, 0);
  equal(color.blue, 0);
  equal(color.green, 0);
  equal(color.alpha, 0);
});

test("handles xbrowser 'transparent' value correctly", function() {
  // Firefox, IE11, Project Spartan (MS Edge Release Candidate)
  // See #180 https://github.com/GoogleChrome/accessibility-developer-tools/issues/180
  var colorString = 'transparent';
  var color = axs.color.parseColor(colorString);
  equal(color.red, 0);
  equal(color.blue, 0);
  equal(color.green, 0);
  equal(color.alpha, 0);
});

module("suggestColors");
test("suggests correct grey values", function() {
  var white = new axs.color.Color(255, 255, 255, 1)
  var desiredContrastRatios = { AA: 4.5, AAA: 7.0 };
  var suggestions = axs.color.suggestColors(white, white, desiredContrastRatios);
  deepEqual(suggestions, { AA: { bg: "#ffffff", contrast: "4.54", fg: "#767676" },
                           AAA: { bg: "#ffffff", contrast: "7.00", fg: "#595959" } });
});
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("REST API call control")
description("This will return the REST APIn call control")
base_component_id("rest_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "REST API Call",
            type:       "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    180,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    70,
            type:       "Number"
        }
        ,
        {
            id:             "callDefaultRestApi",
            pre_snippet:    `await `,
            snippet:        `callDefaultRestApi()`,
            name:           "Execute Command",
            type:           "Action"
        }
        ,
        {
            id:         "callRestApi",
            pre_snippet:    `await `,
            snippet:    `callRestApi("http://INSERT_URL_HERE")`,
            name:       "Execute Command",
            type:       "Action"
        }
        ,
        {
            id:         "URL",
            name:       "URL",
            default:    "https://raw.githubusercontent.com/typicode/demo/master/db.json",
            type:       "String"
        }

    ]
)//properties
logo_url("/driver_icons/rest.png")
*/

function isMap(o) {
    try {
        Map.prototype.has.call(o); // throws if o is not an object or has no [[MapData]]
        return true;
    } catch(e) {
        if (typeof o === 'object') {
            return true
        }
        return false;
    }
}

    Vue.component("rest_control",{

        props: ["meta", "args","design_mode","refresh"]

        ,

        template:

`

        {{args.text}}

        <button    class="btn btn-primary"
                   v-on:click="testDefaultRestApi()">

              Call API

        </button>

{{args.URL}}

                   {{jsonPath}}

Filtered Result

{{filteredJson}}

Result

{{tempResult}}

           {{args.text}}

{{args.URL}}

            <slot v-bind:refresh='refresh'>
            </slot>

`

        ,

        data: function() {
            return {
                    tempResult: "",
                    allPaths:    new Object(),
                    jsonPaths:   [],
                    filteredJson: new Object()
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

        }
        ,

        methods: {
            callRestApiInternal: async function() {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "rest_call_service",
                    method_name: "rest_call_service"
                }
                ,
                {
                    URL:    mm.args.URL
                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            callDefaultRestApi: async function() {

                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            callRestApi: async function(urlToCall) {

                var mm = this
                if (urlToCall) {
                    mm.args.URL = urlToCall
                }
                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            testDefaultRestApi: async function(urlToCall) {

                this.allPaths     = new Object()
                this.filteredJson = new Object()
                var rrr           = await this.callDefaultRestApi()
                this.tempResult   = rrr

                this.findJsonPaths(  [], rrr)
                //alert(JSON.stringify(Object.keys(this.allPaths),null,2))
                this.jsonPaths = Object.keys(this.allPaths)

                this.filterJsonPaths(  [], rrr)

            }
            ,

            addToPaths: function(path) {

                var cpath = this.pathToString(path)
                if (!this.allPaths[cpath]) {

                    this.allPaths[cpath] = {
                        count: 0,
                        path: path
                    }
                }

                this.allPaths[cpath].count ++
            }
            ,
            filterJsonPaths: function (currentPath,jsonNode) {
                this.filteredJson = jsonNode

                if (Array.isArray(jsonNode)) {
                    //console.log("Found node: " )
                    for (var k = 0 ; k < jsonNode.length ; k++) {

                        //console.log("Key: " + k)
                        var newPath = currentPath.concat(["[]"])
                        this.filterJsonPaths( newPath, jsonNode[k])
                    }

                }  else if (isMap(jsonNode)) {
                    var keys = Object.keys(jsonNode)
                    //console.log("Found map:.. " + keys.length)
                    for (var k = 0 ; k < keys.length ; k++) {

                        //console.log("Key: " + keys[k])
                        var newPath = currentPath.concat([keys[k]])

                        this.filterJsonPaths( newPath, jsonNode[keys[k]])
                    }

                }  else if (typeof jsonNode === 'object') {
                    //console.log("Found object: " )

                } else {
                    //console.log("Found other: " + JSON.stringify(jsonNode,null,2))
                }
            }
            ,
            findJsonPaths: function (currentPath,jsonNode) {
                this.addToPaths(currentPath)

                if (Array.isArray(jsonNode)) {
                    //console.log("Found node: " )
                    for (var k = 0 ; k < jsonNode.length ; k++) {

                        //console.log("Key: " + k)
                        var newPath = currentPath.concat(["[]"])
                        this.findJsonPaths( newPath, jsonNode[k])
                    }

                }  else if (isMap(jsonNode)) {
                    var keys = Object.keys(jsonNode)
                    //console.log("Found map:.. " + keys.length)
                    for (var k = 0 ; k < keys.length ; k++) {

                        //console.log("Key: " + keys[k])
                        var newPath = currentPath.concat([keys[k]])

                        this.findJsonPaths( newPath, jsonNode[keys[k]])
                    }

                }  else if (typeof jsonNode === 'object') {
                    //console.log("Found object: " )

                } else {
                    //console.log("Found other: " + JSON.stringify(jsonNode,null,2))
                }
            }
            ,

            pathToString: function (pp) {
                var s = ""
                for (  var aa = 0  ;  aa < pp.length  ;  aa ++  ) {
                    s += pp[aa]
                    if (aa < pp.length -1) {
                        s += "."
                    }
                }
                return s
            }

        }

    })
}
<commit_msg>Cleaned up the REST API GUI a bit<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("REST API call control")
description("This will return the REST APIn call control")
base_component_id("rest_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:         "text",
            name:       "Dev text",
            default:    "REST API Call",
            type:       "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    180,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    70,
            type:       "Number"
        }
        ,
        {
            id:             "callDefaultRestApi",
            pre_snippet:    `await `,
            snippet:        `callDefaultRestApi()`,
            name:           "Execute Command",
            type:           "Action"
        }
        ,
        {
            id:         "callRestApi",
            pre_snippet:    `await `,
            snippet:    `callRestApi("http://INSERT_URL_HERE")`,
            name:       "Execute Command",
            type:       "Action"
        }
        ,
        {
            id:         "URL",
            name:       "URL",
            default:    "https://raw.githubusercontent.com/typicode/demo/master/db.json",
            type:       "String"
        }

    ]
)//properties
logo_url("/driver_icons/rest.png")
*/

function isMap(o) {
    try {
        Map.prototype.has.call(o); // throws if o is not an object or has no [[MapData]]
        return true;
    } catch(e) {
        if (typeof o === 'object') {
            return true
        }
        return false;
    }
}

    Vue.component("rest_control",{

        props: ["meta", "args","design_mode","refresh"]

        ,

        template:

`

        {{args.text}}

        <button    class="btn btn-primary"
                   v-on:click="testDefaultRestApi()">

              Call API

        </button>

{{args.URL}}

List of Paths

                   {{jsonPath}}

Filtered Result

{{filteredJson}}

Result

{{tempResult}}

           {{args.text}}

{{args.URL}}

            <slot v-bind:refresh='refresh'>
            </slot>

`

        ,

        data: function() {
            return {
                    tempResult: "",
                    allPaths:    new Object(),
                    jsonPaths:   [],
                    filteredJson: new Object()
            }
        }

        ,

        mounted: async function() {
            registerComponent(this)

        }
        ,

        methods: {
            callRestApiInternal: async function() {
                var mm = this

                var result = await callFunction(
                {
                    driver_name: "rest_call_service",
                    method_name: "rest_call_service"
                }
                ,
                {
                    URL:    mm.args.URL
                })

                if (result) {
                    return result
                }
                return null
            }
            ,

            callDefaultRestApi: async function() {

                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            callRestApi: async function(urlToCall) {

                var mm = this
                if (urlToCall) {
                    mm.args.URL = urlToCall
                }
                var qwe = await this.callRestApiInternal()
                return qwe
            }
            ,

            testDefaultRestApi: async function(urlToCall) {

                this.allPaths     = new Object()
                this.filteredJson = new Object()
                var rrr           = await this.callDefaultRestApi()
                this.tempResult   = rrr

                this.findJsonPaths(  [], rrr)
                //alert(JSON.stringify(Object.keys(this.allPaths),null,2))
                this.jsonPaths = Object.keys(this.allPaths)

                this.filterJsonPaths(  this.filteredJson, [], rrr)

            }
            ,

            addToPaths: function(path) {

                var cpath = this.pathToString(path)
                if (!this.allPaths[cpath]) {

                    this.allPaths[cpath] = {
                        count: 0,
                        path: path
                    }
                }

                this.allPaths[cpath].count ++
            }
            ,
            filterJsonPaths: function (jsonCurrentNode, currentPath,jsonNode) {
                debugger

                if (Array.isArray(jsonNode)) {
                    //console.log("Found node: " )
                    jsonCurrentNode = []
                    for (var k = 0 ; k < jsonNode.length ; k++) {

                        //console.log("Key: " + k)
                        var newPath = currentPath.concat(["[]"])
                        this.filterJsonPaths( jsonCurrentNode, newPath, jsonNode[k])
                    }

                }  else if (isMap(jsonNode)) {
                    jsonCurrentNode = new Object()
                    var keys = Object.keys(jsonNode)
                    //console.log("Found map:.. " + keys.length)
                    for (var k = 0 ; k < keys.length ; k++) {

                        //console.log("Key: " + keys[k])
                        var newPath = currentPath.concat([keys[k]])

                        this.filterJsonPaths( jsonCurrentNode,newPath, jsonNode[keys[k]])
                    }

                }  else if (typeof jsonNode === 'object') {
                    //console.log("Found object: " )

                } else {
                    //console.log("Found other: " + JSON.stringify(jsonNode,null,2))
                }
            }
            ,
            findJsonPaths: function (currentPath,jsonNode) {
                this.addToPaths(currentPath)

                if (Array.isArray(jsonNode)) {
                    //console.log("Found node: " )
                    for (var k = 0 ; k < jsonNode.length ; k++) {

                        //console.log("Key: " + k)
                        var newPath = currentPath.concat(["[]"])
                        this.findJsonPaths( newPath, jsonNode[k])
                    }

                }  else if (isMap(jsonNode)) {
                    var keys = Object.keys(jsonNode)
                    //console.log("Found map:.. " + keys.length)
                    for (var k = 0 ; k < keys.length ; k++) {

                        //console.log("Key: " + keys[k])
                        var newPath = currentPath.concat([keys[k]])

                        this.findJsonPaths( newPath, jsonNode[keys[k]])
                    }

                }  else if (typeof jsonNode === 'object') {
                    //console.log("Found object: " )

                } else {
                    //console.log("Found other: " + JSON.stringify(jsonNode,null,2))
                }
            }
            ,

            pathToString: function (pp) {
                var s = ""
                for (  var aa = 0  ;  aa < pp.length  ;  aa ++  ) {
                    s += pp[aa]
                    if (aa < pp.length -1) {
                        s += "."
                    }
                }
                return s
            }

        }

    })
}
<|endoftext|>


<commit_before>/**
 * @fileoverview Rule to flag non-camelcased identifiers except for the "opt_" prefix
 */
'use strict';

var utils = require('../utils');
var types = require('../types');

/**
 * Valid options for the camelcase rule
 * @typedef {{
 *   allowVarArgs: boolean,
 *   allowOptPrefix: boolean,
 *   allowLeadingUnderscore: boolean,
 *   allowTrailingUnderscore: boolean,
 * }}
 */
let CamelCaseRuleOptions;

/**
 * An object to describe an underscored identifier.
 * @typedef {{
 *   node: !Espree.Identifier,
 *   message: string,
 *   hasError: boolean,
 * }}
 */
let UnderscoreReport;

/** @const {!CamelCaseRuleOptions} */
const DEFAULT_CAMELCASE_OPTIONS = {
  allowVarArgs: false,
  allowOptPrefix: false,
  allowLeadingUnderscore: true,
  allowTrailingUnderscore: true,
  checkObjectProperties: true,
}

/**
 * Flags identifiers that have incorrect underscores.
 * @param {!Espree.Identifier} node The node to check.
 * @param {!CamelCaseRuleOptions} options The ESLint camelcase rule options.
 * @return {!UnderscoreReport} Message describing the underscore identifier.
 *     If incorrectly underscored, the `message` field describes the error and
 *     `hasError` is set to True.  If the identifier is correct, `message` is
 *     the empty string and `hasError` is set to false.
 * @private
 */
function describeIncorrectUnderscores_(node, options) {

  /** @const {!UnderscoreReport} */
  const validReport = {
    node,
    message: '',
    hasError: false,
  };

  /** @const {!UnderscoreReport} */
  const invalidReport = {
    node,
    message: '',
    hasError: true
  }

  /**
   * @param {string} message
   * @return {!UnderscoreReport}
   */
  function makeReport(message) {
    return /** @type {UnderscoreReport} */ (Object.assign(invalidReport,
                                                          {message}));
  }

  /**
   * @param {string} effectiveName
   * @param {string} message
   * @return {!UnderscoreReport}
   */
  function checkAndReport(effectiveName, message) {
    if (isCorrectlyUnderscored_(effectiveName, node, options)) {
      return validReport;
    } else {
      return makeReport(message);
    }
  }

  switch (utils.categorizeUnderscoredIdentifier(node.name)) {
    case types.UnderscoreForm.CONSTANT:
      return validReport;

    case types.UnderscoreForm.LEADING:
      if (options.allowLeadingUnderscore) {
        return checkAndReport(
            node.name.replace(/^_+/g, ''),
            `Identifier '${node.name}' is not in camel case after the leading `
            + `underscore.`
        );
      } else {
        return makeReport('Leading underscores are not allowed.');
      }
    case types.UnderscoreForm.NO_UNDERSCORE:
      return validReport;

    case types.UnderscoreForm.MIDDLE:
      return checkAndReport(
          node.name,
          `Identifier '${node.name}' is not in camel case.`
      );

    case types.UnderscoreForm.OPT_PREFIX:
      if (options.allowOptPrefix) {
        return checkAndReport(
            node.name.replace(/^opt_/g, ''),
            `Identifier '${node.name}' is not in camel case after the opt_ `
            + `prefix.`
        );
      } else {
        return makeReport(`The opt_ prefix is not allowed in '${node.name}'`);
      }

    case types.UnderscoreForm.TRAILING:
      if (options.allowTrailingUnderscore) {
        return checkAndReport(
          node.name.replace(/_+$/g, ''),
            `Identifier '${node.name}' is not in camel case before the trailing`
            + ` underscore.`
        );
      } else {
        return makeReport('Trailing underscores are not allowed.');
      }

    case types.UnderscoreForm.VAR_ARGS:
      if (options.allowVarArgs) {
        return validReport;
      } else {
        return makeReport('The var_args identifier is not allowed.');
      }

    default:
      throw new Error('Unknown undercore form: ' + node.name);
  }
}

/**
 * Report names that have incorrect underscores.
 * @param {string} effectiveNodeName The node name with valid underscores
 *     removed.
 * @param {!Espree.Identifier} node The node to check.
 * @param {!CamelCaseRuleOptions} options The ESLint camelcase rule options.
 * @return {boolean} If the node is correctly underscored.
 * @private
 */
function isCorrectlyUnderscored_(effectiveNodeName, node, options) {
  let parent = node.parent;
  const isCorrect = true;
  const isWrong = false;

  if (!utils.isUnderscored(effectiveNodeName)) {
    return isCorrect;
  }

  switch (parent.type) {
    case 'MemberExpression':
      parent = /** @type {!Espree.MemberExpression} */ (node.parent);

      // Never check properties of a MemberExpression, i.e. baz.foo_bar.
      if (!options.checkObjectProperties) {
        return isCorrect;
      }
      break;

    case 'Property':
      parent = /** @type {!Espree.Property} */ (node.parent);

      // Properties have their own rules.  Properties are just defined in object
      // literals.
      if (!options.checkObjectProperties) {
        return isCorrect;
      }

      // An ObjectPattern is a destructuring pattern, e.g.
      // var {a, b} = require('module');
      if (parent.parent && parent.parent.type === "ObjectPattern") {
        // If we're assigning to a new variable name with destructuring then
        // don't check the original name because we don't control that
        // name.  For example, we wouldn't want to check original_name below.
        // var {original_name: newName} = require('module);
        if (parent.key === node && parent.value !== node) {
          return isCorrect;
        }
      }
      break;

    case 'CallExpression':
      // Ignore method or function calls.
      return isCorrect;

    default:
      return isWrong;
  }
  return isWrong;
}

/** @const {!ESLint.RuleDefinition} */
const CAMELCASE_RULE = {
  meta: {
    docs: {
      description: 'check identifiers for camel case with options for opt_ '
          + 'prefix and var_args identifiers',
      category:  'Stylistic Issues',
      recommended: true,
    },
    schema: [
      {
        type: "object",
        properties: {
          allowVarArgs: {
            type: "boolean",
          },
          allowOptPrefix: {
            type: "boolean",
          },
          allowLeadingUnderscore: {
            type: "boolean",
          },
          allowTrailingUnderscore: {
            type: "boolean",
          },
          checkObjectProperties: {
            type: "boolean",
          }
        },
        additionalProperties: false
      }
    ],
  },

  /**
   * @param {!ESLint.RuleContext} context
   * @return {!Object<!Espree.NodeType, function(!ESLint.ASTNode)>}
   */
  create(context) {

    /**
     * Reports incorrectly underscored identifiers.
     * @param {!Espree.Identifier} node The node to check.
     */
    function reportIncorrectUnderscores(node) {

      const userOptions = /** @const {!Object} */ (context.options[0]) || {};
      const options = /** @type {!CamelCaseRuleOptions}*/
            (Object.assign(DEFAULT_CAMELCASE_OPTIONS, userOptions));
      const underscoreMessage = describeIncorrectUnderscores_(node, options);
      if (underscoreMessage.hasError) {
        context.report({
          node: underscoreMessage.node,
          message: underscoreMessage.message,
        });
      }
    }

    return {
      Identifier: reportIncorrectUnderscores,
    };
  },
};

module.exports = CAMELCASE_RULE;
<commit_msg>fix(plugin): fix member expression parsing<commit_after>/**
 * @fileoverview Rule to flag non-camelcased identifiers except for the "opt_" prefix
 */
'use strict';

var utils = require('../utils');
var types = require('../types');

/**
 * Valid options for the camelcase rule
 * @typedef {{
 *   allowVarArgs: boolean,
 *   allowOptPrefix: boolean,
 *   allowLeadingUnderscore: boolean,
 *   allowTrailingUnderscore: boolean,
 * }}
 */
let CamelCaseRuleOptions;

/**
 * An object to describe an underscored identifier.
 * @typedef {{
 *   node: !Espree.Identifier,
 *   message: string,
 *   hasError: boolean,
 * }}
 */
let UnderscoreReport;

/** @const {!CamelCaseRuleOptions} */
const DEFAULT_CAMELCASE_OPTIONS = {
  allowVarArgs: false,
  allowOptPrefix: false,
  allowLeadingUnderscore: true,
  allowTrailingUnderscore: true,
  checkObjectProperties: true,
}

/**
 * Flags identifiers that have incorrect underscores.
 * @param {!Espree.Identifier} node The node to check.
 * @param {!CamelCaseRuleOptions} options The ESLint camelcase rule options.
 * @return {!UnderscoreReport} Message describing the underscore identifier.
 *     If incorrectly underscored, the `message` field describes the error and
 *     `hasError` is set to True.  If the identifier is correct, `message` is
 *     the empty string and `hasError` is set to false.
 * @private
 */
function describeIncorrectUnderscores_(node, options) {

  /** @const {!UnderscoreReport} */
  const validReport = {
    node,
    message: '',
    hasError: false,
  };

  /** @const {!UnderscoreReport} */
  const invalidReport = {
    node,
    message: '',
    hasError: true
  }

  /**
   * @param {string} message
   * @return {!UnderscoreReport}
   */
  function makeReport(message) {
    return /** @type {UnderscoreReport} */ (Object.assign(invalidReport,
                                                          {message}));
  }

  /**
   * @param {string} effectiveName
   * @param {string} message
   * @return {!UnderscoreReport}
   */
  function checkAndReport(effectiveName, message) {
    if (isCorrectlyUnderscored_(effectiveName, node, options)) {
      return validReport;
    } else {
      return makeReport(message);
    }
  }

  switch (utils.categorizeUnderscoredIdentifier(node.name)) {
    case types.UnderscoreForm.CONSTANT:
      return validReport;

    case types.UnderscoreForm.LEADING:
      if (options.allowLeadingUnderscore) {
        return checkAndReport(
            node.name.replace(/^_+/g, ''),
            `Identifier '${node.name}' is not in camel case after the leading `
            + `underscore.`
        );
      } else {
        return makeReport('Leading underscores are not allowed.');
      }
    case types.UnderscoreForm.NO_UNDERSCORE:
      return validReport;

    case types.UnderscoreForm.MIDDLE:
      return checkAndReport(
          node.name,
          `Identifier '${node.name}' is not in camel case.`
      );

    case types.UnderscoreForm.OPT_PREFIX:
      if (options.allowOptPrefix) {
        return checkAndReport(
            node.name.replace(/^opt_/g, ''),
            `Identifier '${node.name}' is not in camel case after the opt_ `
            + `prefix.`
        );
      } else {
        return makeReport(`The opt_ prefix is not allowed in '${node.name}'`);
      }

    case types.UnderscoreForm.TRAILING:
      if (options.allowTrailingUnderscore) {
        return checkAndReport(
          node.name.replace(/_+$/g, ''),
            `Identifier '${node.name}' is not in camel case before the trailing`
            + ` underscore.`
        );
      } else {
        return makeReport('Trailing underscores are not allowed.');
      }

    case types.UnderscoreForm.VAR_ARGS:
      if (options.allowVarArgs) {
        return validReport;
      } else {
        return makeReport('The var_args identifier is not allowed.');
      }

    default:
      throw new Error('Unknown undercore form: ' + node.name);
  }
}

/**
 * Report names that have incorrect underscores.
 * @param {string} effectiveNodeName The node name with valid underscores
 *     removed.
 * @param {!Espree.Identifier} node The node to check.
 * @param {!CamelCaseRuleOptions} options The ESLint camelcase rule options.
 * @return {boolean} If the node is correctly underscored.
 * @private
 */
function isCorrectlyUnderscored_(effectiveNodeName, node, options) {
  let parent = node.parent;
  const isCorrect = true;
  const isWrong = false;

  if (!utils.isUnderscored(effectiveNodeName)) {
    return isCorrect;
  }

  switch (parent.type) {
    case 'MemberExpression':
      parent = /** @type {!Espree.MemberExpression} */ (node.parent);

      if (!options.checkObjectProperties) {
        return isCorrect;
      }

      // Using a camelcased identifier on an object is okay since we don't
      // control the name, e.g. `foo.bar_baz`.
      if (parent.property === node) {
        // But it's not okay if we're defining a new variable, e.g.
        // `foo.bar_baz = 2`;
        if (parent.parent && parent.parent.type === 'AssignmentExpression') {
          let grandParent =
              /** @type {!Espree.AssignmentExpression} */ (parent.parent);
          // But it's okay if the identifier is on the right side.  If it's on
          // the left, it's wrong.
          return grandParent.right === parent;
        } else {
          return isCorrect;
        }
      }
      break;

    case 'Property':
      parent = /** @type {!Espree.Property} */ (node.parent);

      // Properties have their own rules.  Properties are just defined in object
      // literals.
      if (!options.checkObjectProperties) {
        return isCorrect;
      }

      // An ObjectPattern is a destructuring pattern, e.g.
      // var {a, b} = require('module');
      if (parent.parent && parent.parent.type === "ObjectPattern") {
        // If we're assigning to a new variable name with destructuring then
        // don't check the original name because we don't control that
        // name.  For example, we wouldn't want to check original_name below.
        // var {original_name: newName} = require('module);
        if (parent.key === node && parent.value !== node) {
          return isCorrect;
        }
      }
      break;

    case 'CallExpression':
      // Ignore method or function calls.
      return isCorrect;

    default:
      return isWrong;
  }
  return isWrong;
}

/** @const {!ESLint.RuleDefinition} */
const CAMELCASE_RULE = {
  meta: {
    docs: {
      description: 'check identifiers for camel case with options for opt_ '
          + 'prefix and var_args identifiers',
      category:  'Stylistic Issues',
      recommended: true,
    },
    schema: [
      {
        type: "object",
        properties: {
          allowVarArgs: {
            type: "boolean",
          },
          allowOptPrefix: {
            type: "boolean",
          },
          allowLeadingUnderscore: {
            type: "boolean",
          },
          allowTrailingUnderscore: {
            type: "boolean",
          },
          checkObjectProperties: {
            type: "boolean",
          }
        },
        additionalProperties: false
      }
    ],
  },

  /**
   * @param {!ESLint.RuleContext} context
   * @return {!Object<!Espree.NodeType, function(!ESLint.ASTNode)>}
   */
  create(context) {

    /**
     * Reports incorrectly underscored identifiers.
     * @param {!Espree.Identifier} node The node to check.
     */
    function reportIncorrectUnderscores(node) {

      const userOptions = /** @const {!Object} */ (context.options[0]) || {};
      const options = /** @type {!CamelCaseRuleOptions}*/
            (Object.assign(DEFAULT_CAMELCASE_OPTIONS, userOptions));
      const underscoreMessage = describeIncorrectUnderscores_(node, options);
      if (underscoreMessage.hasError) {
        context.report({
          node: underscoreMessage.node,
          message: underscoreMessage.message,
        });
      }
    }

    return {
      Identifier: reportIncorrectUnderscores,
    };
  },
};

module.exports = CAMELCASE_RULE;
<|endoftext|>


<commit_before>// $Revision$

Ensembl.Panel.MultiSelector = Ensembl.Panel.extend({
  constructor: function (id) {
    this.base(id);

    Ensembl.EventManager.register('updateConfiguration', this, this.updateSpecies);
    Ensembl.EventManager.register('modalPanelResize', this, this.style);
  },

  init: function () {
    var myself = this;

    this.base();

    this.initialSpecies = '';
    this.species = [];

    this.elLk.content = $('.modal_wrapper', this.el);
    this.elLk.list = $('.multi_selector_list', this.elLk.content);

    var ul = $('ul', this.elLk.list);
    var spans = $('span', ul)

    this.elLk.spans = spans.filter(':not(.switch)');
    this.elLk.form = $('form', this.elLk.content);
    this.elLk.included = ul.filter('.included');
    this.elLk.excluded = ul.filter('.excluded');

    this.setSpecies(true);

    this.elLk.included.sortable({
      containment: myself.elLk.included.parent(),
      stop: function () { myself.setSpecies(); }
    });

    this.buttonWidth = spans.filter('.switch').click(function () {
      var li = $(this).parent();

      if (li.parent().hasClass('included')) {
        var excluded = $('li', myself.elLk.excluded);
        var i = excluded.length;

        while (i--) {
          if ($(excluded[i]).text() < li.text()) {
            $(excluded[i]).after(li);
            break;
          }
        }

        // species to be added is closer to the start of the alphabet than anything in the excluded list
        if (i == -1) {
          myself.elLk.excluded.prepend(li);
        }

        myself.setSpecies();

        excluded = null;
      } else {
        myself.elLk.included.append(li);
        myself.species.push(li.attr('className'));
      }

      li = null;
    }).width();

    this.style();

    ul = null;
  },

  style: function () {
    var width = 0;

    this.elLk.spans.each(function () {
      var w = $(this).width();

      if (w > width) {
        width = w;
      }
    });

    this.elLk.list.width('');
    this.elLk.list.width(this.elLk.list.width() < width + this.buttonWidth ? '100%' : '');
  },

  setSpecies: function (init) {
    this.species = $.map($('li', this.elLk.included), function (li, i) {
      return li.className;
    });

    if (init === true) {
      this.initialSpecies = this.species.join(',');
    }
  },

  updateSpecies: function () {
    var existingSpecies = {};
    var i, j;

    for (i in Ensembl.multiSpecies) {
      existingSpecies[Ensembl.multiSpecies[i].s] = parseInt(i);
    }

    var params = [];

    for (i = 0; i < this.species.length; i++) {
      j = existingSpecies[this.species[i]];

      if (typeof j != 'undefined') {
        $.each(['r', 'g', 's'], function () {
          if (Ensembl.multiSpecies[j][this]) {
            params.push(this + (i + 1) + '=' + Ensembl.multiSpecies[j][this]);
          }
        });
      } else {
        params.push('s' + (i + 1) + '=' + this.species[i]);
      }
    }

    if (this.species.join(',') != this.initialSpecies) {
      Ensembl.redirect(this.elLk.form.attr('action') + '?' + Ensembl.cleanURL(this.elLk.form.serialize() + ';' + params.join(';')));
    }

    return true;
  }
});<commit_msg>make it actually be generic<commit_after>// $Revision$

Ensembl.Panel.MultiSelector = Ensembl.Panel.extend({
  constructor: function (id, params) {
    this.base(id);
    this.urlParam = params.urlParam;

    Ensembl.EventManager.register('updateConfiguration', this, this.updateSelection);
    Ensembl.EventManager.register('modalPanelResize', this, this.style);
  },

  init: function () {
    var myself = this;

    this.base();

    this.initialSelection = '';
    this.selection = [];

    this.elLk.content = $('.modal_wrapper', this.el);
    this.elLk.list = $('.multi_selector_list', this.elLk.content);

    var ul = $('ul', this.elLk.list);
    var spans = $('span', ul)

    this.elLk.spans = spans.filter(':not(.switch)');
    this.elLk.form = $('form', this.elLk.content);
    this.elLk.included = ul.filter('.included');
    this.elLk.excluded = ul.filter('.excluded');

    this.setSelection(true);

    this.elLk.included.sortable({
      containment: myself.elLk.included.parent(),
      stop: function () { myself.setSelection(); }
    });

    this.buttonWidth = spans.filter('.switch').click(function () {
      var li = $(this).parent();

      if (li.parent().hasClass('included')) {
        var excluded = $('li', myself.elLk.excluded);
        var i = excluded.length;

        while (i--) {
          if ($(excluded[i]).text() < li.text()) {
            $(excluded[i]).after(li);
            break;
          }
        }

        // item to be added is closer to the start of the alphabet than anything in the excluded list
        if (i == -1) {
          myself.elLk.excluded.prepend(li);
        }

        myself.setSelection();

        excluded = null;
      } else {
        myself.elLk.included.append(li);
        myself.selection.push(li.attr('className'));
      }

      li = null;
    }).width();

    this.style();

    ul = null;
  },

  style: function () {
    var width = 0;

    this.elLk.spans.each(function () {
      var w = $(this).width();

      if (w > width) {
        width = w;
      }
    });

    this.elLk.list.width('');
    this.elLk.list.width(this.elLk.list.width() < width + this.buttonWidth ? '100%' : '');
  },

  setSelection: function (init) {
    this.selection = $.map($('li', this.elLk.included), function (li, i) {
      return li.className;
    });

    if (init === true) {
      this.initialSelection = this.selection.join(',');
    }
  },

  updateSelection: function () {
    var params = [];
    var i;

    for (i = 0; i < this.selection.length; i++) {
      params.push(this.urlParam + (i + 1) + '=' + this.selection[i]);
    }

    if (this.selection.join(',') != this.initialSelection) {
      Ensembl.redirect(this.elLk.form.attr('action') + '?' + Ensembl.cleanURL(this.elLk.form.serialize() + ';' + params.join(';')));
    }

    return true;
  }
});<|endoftext|>


<commit_before>L.TileLayer = L.Class.extend({
	includes: L.Mixin.Events,

	options: {
		tileSize: 256,
		minZoom: 0,
		maxZoom: 18,
		subdomains: 'abc',
		copyright: ''
	},

	initialize: function(url, options) {
		L.Util.extend(this.options, options);

		this._url = url;

		if (typeof this.options.subdomains == 'string') {
			this.options.subdomains = this.options.subdomains.split('');
		}
	},

	onAdd: function(map) {
		this._map = map;

		this._container = document.createElement('div');
		this._container.className = 'leaflet-layer';
		this._map.getPanes().tilePane.appendChild(this._container);

		this._tileImg = document.createElement('img');

		L.Util.extend(this._tileImg, {
			className: 'leaflet-tile',
			galleryimg: 'no'
		});

		var tileSize = this.options.tileSize;

		L.Util.extend(this._tileImg.style, {
			width: tileSize + 'px',
			height: tileSize + 'px',
			visibility: 'hidden'
		});
	},

	draw: function() {
		this._tileLoaded = {};
		this._container.innerHTML = '';
		//TODO draw?
	},

	load: function() {
		var bounds = this._map.getPixelBounds(),
			tileSize = this.options.tileSize;

		var nwTilePoint = new L.Point(
				Math.floor(bounds.min.x / tileSize),
				Math.floor(bounds.min.y / tileSize)),
			seTilePoint = new L.Point(
				Math.floor(bounds.max.x / tileSize),
				Math.floor(bounds.max.y / tileSize));

		this._loadTiles(nwTilePoint, seTilePoint);
		//TODO fire layerload?
	},

	getTileUrl: function(tilePoint, zoom) {
		var url = this._url;

		var subdomains = this.options.subdomains,
			s = this.options.subdomains[(tilePoint.x + tilePoint.y) % subdomains.length];

		return this._url
				.replace('{s}', s)
				.replace('{z}', zoom)
				.replace('{x}', tilePoint.x)
				.replace('{y}', tilePoint.y);
	},

	_loadTiles: function(nwTilePoint, seTilePoint) {
		//TODO load from center
		for (var j = nwTilePoint.y; j <= seTilePoint.y; j++) {
			for (var i = nwTilePoint.x; i <= seTilePoint.x; i++) {
				this._loadTile(new L.Point(i, j));
			}
		}
	},

	_loadTile: function(tilePoint) {
		var origin = this._map.getPixelOrigin(),
			tileSize = this.options.tileSize,
			tilePos = tilePoint.multiplyBy(tileSize).subtract(origin),
			zoom = this._map.getZoom();

		var key = tilePoint.x + ':' + tilePoint.y;
		if (key in this._tileLoaded) { return; }
		this._tileLoaded[key] = true;

		var tileLimit = (1 << zoom);
		tilePoint.x = ((tilePoint.x % tileLimit) + tileLimit) % tileLimit;
		if (tilePoint.y < 0 || tilePoint.y >= tileLimit) { return; }

		var tile = this._tileImg.cloneNode(false);

		tile.style.left = tilePos.x + 'px';
		tile.style.top = tilePos.y + 'px';

		tile.onload = this._tileOnLoad;
		tile.onselectstart = tile.onmousemove = L.Util.falseFn;
		tile._leaflet_layer = this;

		tile.src = this.getTileUrl(tilePoint, zoom);

		this._container.appendChild(tile);
		//TODO tile queue
	},

	_tileOnLoad: function() {
		this.style.visibility = 'visible';
		this._leaflet_layer.fire('tileload', {tile: this});
	}
});<commit_msg>TileLayer optimizations for mobile<commit_after>L.TileLayer = L.Class.extend({
	includes: L.Mixin.Events,

	options: {
		tileSize: 256,
		minZoom: 0,
		maxZoom: 18,
		subdomains: 'abc',
		copyright: '',
		unloadInvisibleTiles: false || L.Browser.mobileWebkit
	},

	initialize: function(url, options) {
		L.Util.extend(this.options, options);

		this._url = url;

		if (typeof this.options.subdomains == 'string') {
			this.options.subdomains = this.options.subdomains.split('');
		}
	},

	onAdd: function(map) {
		this._map = map;

		this._container = document.createElement('div');
		this._container.className = 'leaflet-layer';
		this._map.getPanes().tilePane.appendChild(this._container);

		this._tileImg = document.createElement('img');

		L.Util.extend(this._tileImg, {
			className: 'leaflet-tile',
			galleryimg: 'no'
		});

		var tileSize = this.options.tileSize;

		L.Util.extend(this._tileImg.style, {
			width: tileSize + 'px',
			height: tileSize + 'px',
			visibility: 'hidden'
		});
	},

	draw: function() {
		this._tiles = {};
		this._container.innerHTML = '';
	},

	load: function() {
		var bounds = this._map.getPixelBounds(),
			tileSize = this.options.tileSize;

		var nwTilePoint = new L.Point(
				Math.floor(bounds.min.x / tileSize),
				Math.floor(bounds.min.y / tileSize)),
			seTilePoint = new L.Point(
				Math.floor(bounds.max.x / tileSize),
				Math.floor(bounds.max.y / tileSize));

		this._loadTiles(nwTilePoint, seTilePoint);

		if (this.options.unloadInvisibleTiles) {
			this._unloadOtherTiles(nwTilePoint, seTilePoint);
		}
		//TODO fire layerload?
	},

	getTileUrl: function(tilePoint, zoom) {
		var url = this._url;

		var subdomains = this.options.subdomains,
			s = this.options.subdomains[(tilePoint.x + tilePoint.y) % subdomains.length];

		return this._url
				.replace('{s}', s)
				.replace('{z}', zoom)
				.replace('{x}', tilePoint.x)
				.replace('{y}', tilePoint.y);
	},

	_loadTiles: function(nwTilePoint, seTilePoint) {
		//TODO load from center
		for (var j = nwTilePoint.y; j <= seTilePoint.y; j++) {
			for (var i = nwTilePoint.x; i <= seTilePoint.x; i++) {
				this._loadTile(new L.Point(i, j));
			}
		}
	},

	_unloadOtherTiles: function(nwTilePoint, seTilePoint) {
		var k, x, y, key;
		for (key in this._tiles) {
			kArr = key.split(':'),
			x = parseInt(kArr[0]),
			y = parseInt(kArr[1]);

			if (x < nwTilePoint.x || x > seTilePoint.x || y < nwTilePoint.y || y > seTilePoint.y) {
				this._container.removeChild(this._tiles[key]);
				delete this._tiles[key];
			}
		}
	},

	_loadTile: function(tilePoint) {
		var origin = this._map.getPixelOrigin(),
			tileSize = this.options.tileSize,
			tilePos = tilePoint.multiplyBy(tileSize).subtract(origin),
			zoom = this._map.getZoom();

		var key = tilePoint.x + ':' + tilePoint.y;
		if (key in this._tiles) { return; }

		var tileLimit = (1 << zoom);
		tilePoint.x = ((tilePoint.x % tileLimit) + tileLimit) % tileLimit;
		if (tilePoint.y < 0 || tilePoint.y >= tileLimit) { return; }

		var tile = this._tileImg.cloneNode(false);
		this._tiles[key] = tile;

		L.DomUtil.setPosition(tile, tilePos);

		tile.onload = this._tileOnLoad;
		tile.onselectstart = tile.onmousemove = L.Util.falseFn;
		tile._leaflet_layer = this;

		tile.src = this.getTileUrl(tilePoint, zoom);

		this._container.appendChild(tile);
		//TODO tile queue
	},

	_tileOnLoad: function() {
		this.style.visibility = 'visible';
		this._leaflet_layer.fire('tileload', {tile: this});
	}
});<|endoftext|>


<commit_before>import xfnode      from '../xflow-js-node-builder';
import LangUtil    from '../../util/lang';
import FlowUtil    from '../../util/flow';
import Assert      from '../../util/assert';

import BaseGenerator from './base_generator';

function assertCallXFlowNode(node) {
  FlowUtil.assertIsNode(node);

  Assert.equal(node.nodetype, 'callxflow');
  Assert.equal(node.action, 'call');

  Assert.hasProperty(node, 'parameters.xflowid');

  Assert.hasProperty(node, 'parameters.inputmatch');
  Assert.isArray(node.parameters.inputmatch);

  Assert.hasProperty(node, 'parameters.outputmatch');
  Assert.isArray(node.parameters.outputmatch);

  Assert.equal(
    node.parameters.inputmatch.length,
    node.parameters.outputmatch.length
  );
}

class CallXFlowGenerator extends BaseGenerator {

  generateFrom(node) {

    assertCallXFlowNode(node);

    var body = [];

    //
    // Copy all the relevant variables into a new Object for passing to the called XFlow
    //

    body.push(
      xfnode.VariableDeclaration(
        'inputvars',
        xfnode.ObjectExpression()
      )
    );

    node.parameters.inputmatch.forEach(
      (match)=> {
        body.push(
          xfnode.Assignment(
            xfnode.Member('inputvars', match[1]),
            xfnode.ScopeVariable(match[0])
          )
        );
      }
    );

    body.push(

      xfnode.VariableDeclaration(
        'xflowres',
        xfnode.ObjectExpression([])
      ),

      //
      // Call the XFlow
      //

      xfnode.Assignment(
        xfnode.Identifier('xflowres'),
        xfnode.CallExpression(
          xfnode.Identifier('CallXFlow'),
          [
            xfnode.Identifier(node.parameters.xflowid),
            xfnode.Identifier('inputvars')
          ]
        )
      )
    );

    //
    // Copy the results of the XFlow back into the scope object
    //

    node.parameters.outputmatch.forEach(
      (match)=> {
        body.push(
          xfnode.Assignment(
            xfnode.ScopeVariable(match[1]),
            xfnode.Member('xflowres', match[0])
          )
        );
      }
    );

    return xfnode.BlockStatement(body);
  }

}

export default CallXFlowGenerator;
<commit_msg>In generated code, call xflow by literal value<commit_after>import xfnode      from '../xflow-js-node-builder';
import LangUtil    from '../../util/lang';
import FlowUtil    from '../../util/flow';
import Assert      from '../../util/assert';

import BaseGenerator from './base_generator';

function assertCallXFlowNode(node) {
  FlowUtil.assertIsNode(node);

  Assert.equal(node.nodetype, 'callxflow');
  Assert.equal(node.action, 'call');

  Assert.hasProperty(node, 'parameters.xflowid');

  Assert.hasProperty(node, 'parameters.inputmatch');
  Assert.isArray(node.parameters.inputmatch);

  Assert.hasProperty(node, 'parameters.outputmatch');
  Assert.isArray(node.parameters.outputmatch);

  Assert.equal(
    node.parameters.inputmatch.length,
    node.parameters.outputmatch.length
  );
}

class CallXFlowGenerator extends BaseGenerator {

  generateFrom(node) {

    assertCallXFlowNode(node);

    var body = [];

    //
    // Copy all the relevant variables into a new Object for passing to the called XFlow
    //

    body.push(
      xfnode.VariableDeclaration(
        'inputvars',
        xfnode.ObjectExpression()
      )
    );

    node.parameters.inputmatch.forEach(
      (match)=> {
        body.push(
          xfnode.Assignment(
            xfnode.Member('inputvars', match[1]),
            xfnode.ScopeVariable(match[0])
          )
        );
      }
    );

    body.push(

      xfnode.VariableDeclaration(
        'xflowres',
        xfnode.ObjectExpression([])
      ),

      //
      // Call the XFlow
      //

      xfnode.Assignment(
        xfnode.Identifier('xflowres'),
        xfnode.CallExpression(
          xfnode.Identifier('CallXFlow'),
          [
            xfnode.Value(node.parameters.xflowid),
            xfnode.Identifier('inputvars')
          ]
        )
      )
    );

    //
    // Copy the results of the XFlow back into the scope object
    //

    node.parameters.outputmatch.forEach(
      (match)=> {
        body.push(
          xfnode.Assignment(
            xfnode.ScopeVariable(match[1]),
            xfnode.Member('xflowres', match[0])
          )
        );
      }
    );

    return xfnode.BlockStatement(body);
  }

}

export default CallXFlowGenerator;
<|endoftext|>