<commit_before>define('echoContent', ['utils'], function(utils) {
    'use strict';

    // ===================================
    // ECHO CONTENT
    // ===================================

    var _echoContent = function(posts) {
        var container = utils._getId('container'),
            miniPanel = null,
            title = null,
            link = null,
            postsContainer = null,
            pContainer = null,
            i = 0,
            entries = null,
            subDiv = null,
            subLink = null;

        if (!utils._isUnd(posts)) {
            miniPanel = utils._getId('echoMiniPanel');

            if (!utils._isUnd(miniPanel)) {
                title = utils._create('h5');
                link = utils._create('a');
                postsContainer = utils._create('div');
                pContainer = utils._getId('echoContentPanel');

                title.innerHTML = posts.title;
                utils._setAttr(link, 'href', posts.link + '.html');
                link.innerHTML = posts.link;
                postsContainer.className = 'postMenu';

                if (!utils._isUnd(posts.entries) && posts.entries.length > 0) {
                    entries = posts.entries.length;
                    for (i; i < entries; i++) {
                        subDiv = utils._create('div');
                        subLink = utils._create('a');
                        utils._setAttr(subLink, 'href', '#');
                        utils._setAttr(subLink, 'data', posts.entries[i].link);
                        subLink.className = 'subMenuLink';
                        subLink.innerHTML = posts.entries[i].title;

                        subDiv.appendChild(subLink);
                        postsContainer.appendChild(subDiv);
                    }
                }
                utils._appendArr(miniPanel, [title, link, postsContainer]);
                container.appendChild(miniPanel);

                window.setTimeout(function() {
                    if (miniPanel.childNodes.length > 0) {
                        var j = 0,
                            minLength = miniPanel.childNodes.length,
                            firstNode = null;
                        for (j; j < minLength; j++) {
                            if (typeof miniPanel.childNodes[j] === 'object' && miniPanel.childNodes[j].tagName === 'DIV') {
                                firstNode = miniPanel.childNodes[j].childNodes[0].childNodes[0].getAttribute('data');
                                break;
                            }
                        }
                        utils._appendContent(pContainer, firstNode);
                    }
                }, 100);
            }

            if (!utils._isUnd(utils._getClass('subMenuLink'))) {
                $('.subMenuLink').on('click', function(ev) {
                    utils._emptyContentContainer();

                    var panel = miniPanel.childNodes[2].childNodes,
                        currentLink = ev.currentTarget.attributes.data.value,
                        i = 0,
                        panelLength = panel.length,
                        links = null;

                    for (i; i < panelLength; i++) {
                        links = panel[i].childNodes[0];
                        if ($(links).hasClass('now')) {
                            $(links).removeClass('now');
                        }
                    }

                    $(this).addClass('selected');
                    $(this).addClass('now');
                    utils._appendContent(pContainer, currentLink);
                });
            }
        }
    };

    return {
        echoContent: _echoContent
    };
});
<commit_msg>jQuery dep<commit_after>define('echoContent', ['utils', 'jquery'], function(utils, $) {
    'use strict';

    // ===================================
    // ECHO CONTENT
    // ===================================

    var _echoContent = function(posts) {
        var container = utils._getId('container'),
            miniPanel = null,
            title = null,
            link = null,
            postsContainer = null,
            pContainer = null,
            i = 0,
            entries = null,
            subDiv = null,
            subLink = null;

        if (!utils._isUnd(posts)) {
            miniPanel = utils._getId('echoMiniPanel');

            if (!utils._isUnd(miniPanel)) {
                title = utils._create('h5');
                link = utils._create('a');
                postsContainer = utils._create('div');
                pContainer = utils._getId('echoContentPanel');

                title.innerHTML = posts.title;
                utils._setAttr(link, 'href', posts.link + '.html');
                link.innerHTML = posts.link;
                postsContainer.className = 'postMenu';

                if (!utils._isUnd(posts.entries) && posts.entries.length > 0) {
                    entries = posts.entries.length;
                    for (i; i < entries; i++) {
                        subDiv = utils._create('div');
                        subLink = utils._create('a');
                        utils._setAttr(subLink, 'href', '#');
                        utils._setAttr(subLink, 'data', posts.entries[i].link);
                        subLink.className = 'subMenuLink';
                        subLink.innerHTML = posts.entries[i].title;

                        subDiv.appendChild(subLink);
                        postsContainer.appendChild(subDiv);
                    }
                }
                utils._appendArr(miniPanel, [title, link, postsContainer]);
                container.appendChild(miniPanel);

                window.setTimeout(function() {
                    if (miniPanel.childNodes.length > 0) {
                        var j = 0,
                            minLength = miniPanel.childNodes.length,
                            firstNode = null;
                        for (j; j < minLength; j++) {
                            if (typeof miniPanel.childNodes[j] === 'object' && miniPanel.childNodes[j].tagName === 'DIV') {
                                firstNode = miniPanel.childNodes[j].childNodes[0].childNodes[0].getAttribute('data');
                                break;
                            }
                        }
                        utils._appendContent(pContainer, firstNode);
                    }
                }, 100);
            }

            if (!utils._isUnd(utils._getClass('subMenuLink'))) {
                $('.subMenuLink').on('click', function(ev) {
                    utils._emptyContentContainer();

                    var panel = miniPanel.childNodes[2].childNodes,
                        currentLink = ev.currentTarget.attributes.data.value,
                        i = 0,
                        panelLength = panel.length,
                        links = null;

                    for (i; i < panelLength; i++) {
                        links = panel[i].childNodes[0];
                        if ($(links).hasClass('now')) {
                            $(links).removeClass('now');
                        }
                    }

                    $(this).addClass('selected');
                    $(this).addClass('now');
                    utils._appendContent(pContainer, currentLink);
                });
            }
        }
    };

    return {
        echoContent: _echoContent
    };
});
<|endoftext|>


<commit_before>module.exports = Backbone.Model.extend({
    defaults: {
        csrf : undefined,
        loggedIn: false
    },
    isLoggedIn: function(){
    	return this.loggedIn;
    },
    initialize: function(){

    }
});<commit_msg>user login bugfix<commit_after>module.exports = Backbone.Model.extend({
    defaults: {
        csrf : undefined,
        loggedIn: false
    },
    isLoggedIn: function(){
    	return this.get('loggedIn');
    },
    initialize: function(){

    }
});<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var ALIGN_CONST = {

    /**
    * A constant representing a top-left alignment or position.
    * @constant
    * @name Phaser.Display.Align.TOP_LEFT
    * @since 3.0.0
    * @type {integer}
    */
    TOP_LEFT: 0,

    /**
    * A constant representing a top-center alignment or position.
    * @constant
    * @name Phaser.Display.Align.TOP_CENTER
    * @since 3.0.0
    * @type {integer}
    */
    TOP_CENTER: 1,

    /**
    * A constant representing a top-right alignment or position.
    * @constant
    * @name Phaser.Display.Align.TOP_RIGHT
    * @since 3.0.0
    * @type {integer}
    */
    TOP_RIGHT: 2,

    /**
    * A constant representing a left-top alignment or position.
    * @constant
    * @name Phaser.Display.Align.LEFT_TOP
    * @since 3.0.0
    * @type {integer}
    */
    LEFT_TOP: 3,

    /**
    * A constant representing a left-center alignment or position.
    * @constant
    * @name Phaser.Display.Align.LEFT_CENTER
    * @since 3.0.0
    * @type {integer}
    */
    LEFT_CENTER: 4,

    /**
    * A constant representing a left-bottom alignment or position.
    * @constant
    * @name Phaser.Display.Align.LEFT_BOTTOM
    * @since 3.0.0
    * @type {integer}
    */
    LEFT_BOTTOM: 5,

    /**
    * A constant representing a center alignment or position.
    * @constant
    * @name Phaser.Display.Align.CENTER
    * @since 3.0.0
    * @type {integer}
    */
    CENTER: 6,

    /**
    * A constant representing a right-top alignment or position.
    * @constant
    * @name Phaser.Display.Align.RIGHT_TOP
    * @since 3.0.0
    * @type {integer}
    */
    RIGHT_TOP: 7,

    /**
    * A constant representing a right-center alignment or position.
    * @constant
    * @name Phaser.Display.Align.RIGHT_CENTER
    * @since 3.0.0
    * @type {integer}
    */
    RIGHT_CENTER: 8,

    /**
    * A constant representing a right-bottom alignment or position.
    * @constant
    * @name Phaser.Display.Align.RIGHT_BOTTOM
    * @since 3.0.0
    * @type {integer}
    */
    RIGHT_BOTTOM: 9,

    /**
    * A constant representing a bottom-left alignment or position.
    * @constant
    * @name Phaser.Display.Align.BOTTOM_LEFT
    * @since 3.0.0
    * @type {integer}
    */
    BOTTOM_LEFT: 10,

    /**
    * A constant representing a bottom-center alignment or position.
    * @constant
    * @name Phaser.Display.Align.BOTTOM_CENTER
    * @since 3.0.0
    * @type {integer}
    */
    BOTTOM_CENTER: 11,

    /**
    * A constant representing a bottom-right alignment or position.
    * @constant
    * @name Phaser.Display.Align.BOTTOM_RIGHT
    * @since 3.0.0
    * @type {integer}
    */
    BOTTOM_RIGHT: 12

};

module.exports = ALIGN_CONST;
<commit_msg>Changed `Phaser.Display.Align` to `@enum`<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

/**
 * @name Phaser.Display.Align
 * @enum {integer}
 */

var ALIGN_CONST = {

    /**
    * A constant representing a top-left alignment or position.
    *
    * @name Phaser.Display.Align.TOP_LEFT
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    TOP_LEFT: 0,

    /**
    * A constant representing a top-center alignment or position.
    *
    * @name Phaser.Display.Align.TOP_CENTER
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    TOP_CENTER: 1,

    /**
    * A constant representing a top-right alignment or position.
    *
    * @name Phaser.Display.Align.TOP_RIGHT
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    TOP_RIGHT: 2,

    /**
    * A constant representing a left-top alignment or position.
    *
    * @name Phaser.Display.Align.LEFT_TOP
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    LEFT_TOP: 3,

    /**
    * A constant representing a left-center alignment or position.
    *
    * @name Phaser.Display.Align.LEFT_CENTER
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    LEFT_CENTER: 4,

    /**
    * A constant representing a left-bottom alignment or position.
    *
    * @name Phaser.Display.Align.LEFT_BOTTOM
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    LEFT_BOTTOM: 5,

    /**
    * A constant representing a center alignment or position.
    *
    * @name Phaser.Display.Align.CENTER
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    CENTER: 6,

    /**
    * A constant representing a right-top alignment or position.
    *
    * @name Phaser.Display.Align.RIGHT_TOP
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    RIGHT_TOP: 7,

    /**
    * A constant representing a right-center alignment or position.
    *
    * @name Phaser.Display.Align.RIGHT_CENTER
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    RIGHT_CENTER: 8,

    /**
    * A constant representing a right-bottom alignment or position.
    *
    * @name Phaser.Display.Align.RIGHT_BOTTOM
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    RIGHT_BOTTOM: 9,

    /**
    * A constant representing a bottom-left alignment or position.
    *
    * @name Phaser.Display.Align.BOTTOM_LEFT
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    BOTTOM_LEFT: 10,

    /**
    * A constant representing a bottom-center alignment or position.
    *
    * @name Phaser.Display.Align.BOTTOM_CENTER
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    BOTTOM_CENTER: 11,

    /**
    * A constant representing a bottom-right alignment or position.
    *
    * @name Phaser.Display.Align.BOTTOM_RIGHT
    * @constant
    * @type {integer}
    * @since 3.0.0
    */
    BOTTOM_RIGHT: 12

};

module.exports = ALIGN_CONST;
<|endoftext|>


<commit_before>
define(['plugins/factoids'], function() {
    return {
        name: 'factoids',
        reply: function(args) {
            if (args.rawInput.match(/^factoid braindump$/i)) {
                return [1, Rei.dumpFactoids()];
            }
            if (matching = args.rawInput.match(/^\s*(.*?)\sis\s(.*)$/i)) {
                var key = matching[1];
                var value = matching[2];
                if (!key.match(/^what$/i)) {
                    this.putFactoid(key, value);
                    return [1, "Ok. I've made a note of it"];
                }
            }
            var query = args.rawInput.replace(/\?$/, '').replace(/^What is/i, '');
            var result = this.getFactoid(query);
            if (result !== null) {
                return [1, result];
            } else {
                return [0, "Nothing there. Teach me?"];
            }
        },
        putFactoid: function(key, value) {
            // TODO - check for existing factoid with this name here
            Rei.putFactoid(key, value);
        },
        getFactoid: function(key) {
            return Rei.getFactoid(key);
        },
        dumpFactoids: function() {

        }

    }
});
<commit_msg>Rei can now learn factoids from infobot factoid files on the web<commit_after>
define(['plugins/factoids'], function() {
    return {
        name: 'factoids',
        reply: function(args) {
            if (matches = args.rawInput.match(/^factoid (?:grab|fetch)\s*(.*)$/i)) {
                return [1, this.learnFromURL(matches[1])];
            }
            if (args.rawInput.match(/^factoid braindump$/i)) {
                return [1, Rei.dumpFactoids()];
            }
            if (matching = args.rawInput.match(/^\s*(.*?)\sis\s(.*)$/i)) {
                var key = matching[1];
                var value = matching[2];
                if (!key.match(/^what$/i)) {
                    this.putFactoid(key, value);
                    return [1, "Ok. I've made a note of it"];
                }
            }
            var query = args.rawInput.replace(/\?$/, '').replace(/^What is/i, '');
            var result = this.getFactoid(query);
            if (result !== null) {
                return [1, result];
            } else {
                return [0, "Nothing there. Teach me?"];
            }
        },
        putFactoid: function(key, value) {
            // TODO - check for existing factoid with this name here
            Rei.putFactoid(key, value);
        },
        getFactoid: function(key) {
            return Rei.getFactoid(key);
        },
        dumpFactoids: function() {

        },
        learnFromURL: function(url) {
               handleResult = function (data, textStatus, jqXHR) {
                  arrayOfLines = data.match(/[^\r\n]+/g);
                  for (var i = 0; i < arrayOfLines.length; i++) {
                      if ( matches = arrayOfLines[i].match(/^\s*(.*?)=>\s*(.*)\s*$/)) {
                          Rei.putFactoid(matches[1], matches[2]);
                      }
                  }
                    return [1, "Learned "+arrayOfLines.length+ " factoids."];
                }

                jQuery.get( url, undefined, handleResult);
        }

    }
});
<|endoftext|>


<commit_before>function (keys, values, rereduce)
{
    if (rereduce)
    {
        return sum(values)
    }
    {
        /* We count one per user, not per play-event */
        return 1;
    }
}
<commit_msg>fix episode listener counts in CouchDB view<commit_after>function (keys, values, rereduce)
{
    function unique(arr) {
        var a = [];
        var l = arr.length;
        for(var i=0; i<l; i++) {
            for(var j=i+1; j<l; j++) {
                if (arr[i] === arr[j])
                    j = ++i;
            }
            a.push(arr[i]);
        }
        return a;
    };

    if (rereduce)
    {
        return sum(values)
    }
    {
        /* We count one per user, not per play-event */
        val = unique(values);
        return val.length;
    }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Finder Model - Main model that uses FinderJS
 *
 * @constructor
 */
var FinderModel = function (arg) {

    // Assign `this` through `riot.observable()`
    var self = riot.observable(this);

    // Store args
    self.args = arg;

    // Create an instance of `Applait.Finder`
    self.finder = new Applait.Finder({
        type: "sdcard",
        minSearchLength: 2,
        debugMode: arg.debug
    });

    // Current search results
    self.searchResults = [];

    /**
     * Reset all internals
     */
    self.reset = function () {
        self.searchResults = [];
        self.finder.reset();
        self.trigger("reset");
    };

    /**
     * Initiate search
     *
     * @param {string} key - The search string
     */
    self.search = function (key) {
        self.reset();
        self.finder.search(key);
    };

    /**
     * Subscribe to Finder's fileFound event
     */
    self.finder.on("fileFound", function (file) {
        self.searchResults.push(file);
    });

    /**
     * Subscribe to Finder's searchComplete event
     *
     * The `resultsFound` is triggered if any file is matched.
     * Else, `noResults` is triggered
     */
    self.finder.on("searchComplete", function () {
        if (self.searchResults.length && self.finder.filematchcount) {
            self.trigger("resultsFound");
        } else {
            self.trigger("noResults");
        }
    });

};
<commit_msg>Nobody's listening to a reset event. Remove it<commit_after>'use strict';

/**
 * Finder Model - Main model that uses FinderJS
 *
 * @constructor
 */
var FinderModel = function (arg) {

    // Assign `this` through `riot.observable()`
    var self = riot.observable(this);

    // Store args
    self.args = arg;

    // Create an instance of `Applait.Finder`
    self.finder = new Applait.Finder({
        type: "sdcard",
        minSearchLength: 2,
        debugMode: arg.debug
    });

    // Current search results
    self.searchResults = [];

    /**
     * Reset all internals
     */
    self.reset = function () {
        self.searchResults = [];
        self.finder.reset();
    };

    /**
     * Initiate search
     *
     * @param {string} key - The search string
     */
    self.search = function (key) {
        self.reset();
        self.finder.search(key);
    };

    /**
     * Subscribe to Finder's fileFound event
     */
    self.finder.on("fileFound", function (file) {
        self.searchResults.push(file);
    });

    /**
     * Subscribe to Finder's searchComplete event
     *
     * The `resultsFound` is triggered if any file is matched.
     * Else, `noResults` is triggered
     */
    self.finder.on("searchComplete", function () {
        if (self.searchResults.length && self.finder.filematchcount) {
            self.trigger("resultsFound");
        } else {
            self.trigger("noResults");
        }
    });

};
<|endoftext|>


<commit_before>'use strict';

angular.module('deckApp')
  .provider('states', function($stateProvider, $urlRouterProvider, stateHelperProvider) {
    this.setStates = function() {
      $urlRouterProvider.otherwise('/');
      $urlRouterProvider.when('/applications/{application}', '/applications/{application}/clusters');
      $urlRouterProvider.when('/', '/applications');

      var instanceDetails = {
        name: 'instanceDetails',
        url: '/instanceDetails?instanceId',
        views: {
          'detail@home.applications.application.insight': {
            templateUrl: 'views/application/instanceDetails.html',
            controller: 'InstanceDetailsCtrl as ctrl'
          }
        },
        resolve: {
          instance: ['$stateParams', function($stateParams) {
            return {
              instanceId: $stateParams.instanceId
            };
          }]
        },
        data: {
          pageTitleDetails: {
            title: 'Instance Details',
            nameParam: 'instanceId'
          }
        }
      };

      var serverGroupDetails = {
        name: 'serverGroup',
        url: '/serverGroupDetails?serverGroup&accountId&region',
        views: {
          'detail@home.applications.application.insight': {
            templateUrl: 'views/application/serverGroupDetails.html',
            controller: 'ServerGroupDetailsCtrl as ctrl'
          }
        },
        resolve: {
          serverGroup: ['$stateParams', function($stateParams) {
            return {
              name: $stateParams.serverGroup,
              accountId: $stateParams.accountId,
              region: $stateParams.region
            };
          }]
        },
        data: {
          pageTitleDetails: {
            title: 'Server Group Details',
            nameParam: 'serverGroup',
            accountParam: 'accountId',
            regionParam: 'region'
          }
        }
      };

      var loadBalancerDetails = {
        name: 'loadBalancerDetails',
        url: '/loadBalancerDetails?name&accountId&region',
        views: {
          'detail@home.applications.application.insight': {
            templateUrl: 'views/application/loadBalancer/loadBalancerDetails.html',
            controller: 'LoadBalancerDetailsCtrl as ctrl'
          }
        },
        resolve: {
          loadBalancer: ['$stateParams', function($stateParams) {
            return {
              name: $stateParams.name,
              accountId: $stateParams.accountId,
              region: $stateParams.region
            };
          }]
        },
        data: {
          pageTitleDetails: {
            title: 'Load Balancer Details',
            nameParam: 'name',
            accountParam: 'accountId',
            regionParam: 'region'
          }
        }
      };

      var securityGroupDetails = {
        name: 'securityGroupDetails',
        url: '/securityGroupDetails?name&accountId&region',
        views: {
          'detail@home.applications.application.insight': {
            templateUrl: 'views/application/connection/securityGroupDetails.html',
            controller: 'SecurityGroupDetailsCtrl as ctrl'
          }
        },
        resolve: {
          securityGroup: ['$stateParams', function($stateParams) {
            return {
              name: $stateParams.name,
              accountId: $stateParams.accountId,
              region: $stateParams.region
            };
          }]
        },
        data: {
          pageTitleDetails: {
            title: 'Security Group Details',
            nameParam: 'name',
            accountParam: 'accountId',
            regionParam: 'region'
          }
        }
      };

      var notFound = {
        name: '404',
        url: '/404',
        views: {
          'main@': {
            templateUrl: 'views/404.html',
            controller: angular.noop,
          }
        }
      };

      var taskDetails = {
        name: 'taskDetails',
        url: '/:taskId',
        views: {
          'task-details': {
            templateUrl: 'views/taskdetails.html',
            controller: 'TaskDetailsCtrl as ctrl',
          }
        },
        resolve: {
          taskId: ['$stateParams', function($stateParams) {
            return parseInt($stateParams.taskId);
          }]
        }
      };

      var insight = {
        name: 'insight',
        abstract: true,
        views: {
          'insight': {
            templateUrl: 'views/insight.html',
            controller: 'InsightCtrl as ctrl',
          }
        },
        children: [
          {
          name: 'clusters',
          url: '/clusters?primary&secondary&hideInstances&hideHealthy&hideDisabled',
          views: {
            'nav': {
              templateUrl: 'views/application/cluster/navigation.html',
              controller: 'ClustersNavCtrl as ctrl'
            },
            'master': {
              templateUrl: 'views/application/cluster/all.html',
              controller: 'AllClustersCtrl as ctrl'
            }
          },
          data: {
            pageTitleSection: {
              title: 'Clusters'
            }
          },
          children: [
            loadBalancerDetails,
            serverGroupDetails,
            instanceDetails,
            securityGroupDetails,
            {
              name: 'filteredClusters',
              url: '?q',
              reloadOnSearch: false,
              children: [
                loadBalancerDetails,
                serverGroupDetails,
                instanceDetails,
                securityGroupDetails
              ]
            },
            {
              name: 'cluster',
              url: '/:account/:cluster',
              views: {
                'master@home.applications.application.insight': {
                  templateUrl: 'views/application/cluster/single.html',
                  controller: 'ClusterCtrl as ctrl'
                }
              },
              resolve: {
                cluster: ['$stateParams', function ($stateParams) {
                  return {account: $stateParams.account, clusterName: $stateParams.cluster};
                }]
              },
              data: {
                pageTitleSection: {
                  title: 'Cluster',
                  nameParam: 'cluster',
                  accountParam: 'account'
                }
              },
              children: [loadBalancerDetails, serverGroupDetails, instanceDetails],
            }
          ],
        },
        {
          url: '/loadBalancers',
          name: 'loadBalancers',
          views: {
            'nav': {
              templateUrl: 'views/application/loadBalancer/navigation.html',
              controller: 'LoadBalancersNavCtrl as ctrl'
            },
            'master': {
              templateUrl: 'views/application/loadBalancer/all.html',
              controller: 'AllLoadBalancersCtrl as ctrl'
            }
          },
          data: {
            pageTitleSection: {
              title: 'Load Balancers'
            }
          },
          children: [
            loadBalancerDetails,
            serverGroupDetails,
            instanceDetails,
            securityGroupDetails,
            {
              url: '/:loadBalancerAccount/:loadBalancerRegion/:loadBalancer',
              name: 'loadBalancer',
              views: {
                'master@home.applications.application.insight': {
                  templateUrl: 'views/application/loadBalancer/single.html',
                  controller: 'LoadBalancerCtrl as ctrl'
                }
              },
              resolve: {
                loadBalancer: ['$stateParams', function($stateParams) {
                  return {
                    name: $stateParams.loadBalancer,
                    region: $stateParams.loadBalancerRegion,
                    account: $stateParams.loadBalancerAccount
                  };
                }]
              },
              data: {
                pageTitleMain: {
                  title: 'Load Balancer',
                  nameParam: 'loadBalancer',
                  accountParam: 'loadBalancerAccount',
                  regionParam: 'loadBalancerRegion'
                }
              },
              children: [loadBalancerDetails, serverGroupDetails, instanceDetails],
            }
          ],
        }, {
          url: '/connections',
          name: 'connections',
          views: {
            'nav': {
              templateUrl: 'views/application/connection/navigation.html',
              controller: 'SecurityGroupsNavCtrl as ctrl'
            },
            'master': {
              templateUrl: 'views/application/connection/all.html',
              controller: 'AllSecurityGroupsCtrl as ctrl'
            }
          },
          data: {
            pageTitleSection: {
              title: 'Security Groups'
            }
          },
          children: [
            loadBalancerDetails,
            serverGroupDetails,
            securityGroupDetails,
            {
              url: '/:securityGroupAccount/:securityGroupRegion/:securityGroup',
              name: 'connection',
              views: {
                'master@home.applications.application.insight': {
                  templateUrl: 'views/application/connection/single.html',
                  controller: 'SecurityGroupCtrl as ctrl'
                }
              },
              resolve: {
                securityGroup: ['$stateParams', function($stateParams) {
                  return {
                    account: $stateParams.securityGroupAccount,
                    name: $stateParams.securityGroup,
                    region: $stateParams.securityGroupRegion
                  };
                }]
              },
              data: {
                pageTitleSection: {
                  title: 'Security Group',
                  nameParam: 'securityGroup',
                  accountParam: 'securityGroupAccount',
                  regionParam: 'securityGroupRegion'
                }
              },
              children: [loadBalancerDetails, serverGroupDetails, securityGroupDetails]
            }
          ]
        }
        ]
      };

      var tasks = {
        name: 'tasks',
        url: '/tasks',
        views: {
          'insight': {
            templateUrl: 'views/tasks.html',
            controller: 'TasksCtrl',
          },
        },
        data: {
          pageTitleSection: {
            title: 'Tasks'
          }
        },
        children: [taskDetails],
      };

      var application = {
        name: 'application',
        url: '/:application',
        views: {
          'main@': {
            templateUrl: 'views/application.html',
            controller: 'ApplicationCtrl as ctrl'
          },
        },
        resolve: {
          application: ['$stateParams', 'oortService', function($stateParams, oortService) {
            return oortService.getApplication($stateParams.application);
          }]
        },
        data: {
          pageTitleMain: {
            field: 'application'
          }
        },
        children: [
          insight,
          tasks,
        ],
      };

      var applications = {
        name: 'applications',
        url: '/applications',
        views: {
          'main@': {
            templateUrl: 'views/applications.html',
            controller: 'ApplicationsCtrl as ctrl'
          }
        },
        data: {
          pageTitleMain: {
            label: 'Applications'
          }
        },
        children: [
          application
        ],
      };

      var infrastructure = {
        name: 'infrastructure',
        url: '/infrastructure?q',
        reloadOnSearch: false,
        views: {
          'main@': {
            templateUrl: 'views/infrastructure.html',
            controller: 'InfrastructureCtrl as ctrl',
          }
        },
        data: {
          pageTitleMain: {
            label: 'Infrastructure'
          }
        }
      };

      var home = {
        name: 'home',
        abstract: true,
        views: {
          'main@': {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl as ctrl'
          }
        },
        children: [
          notFound,
          applications,
          infrastructure
        ],
      };

      stateHelperProvider.setNestedState(home);

    };

    this.$get = angular.noop;

  });
<commit_msg>fix screen flash on filter (mostly)<commit_after>'use strict';

angular.module('deckApp')
  .provider('states', function($stateProvider, $urlRouterProvider, stateHelperProvider) {
    this.setStates = function() {
      $urlRouterProvider.otherwise('/');
      $urlRouterProvider.when('/applications/{application}', '/applications/{application}/clusters');
      $urlRouterProvider.when('/', '/applications');

      var instanceDetails = {
        name: 'instanceDetails',
        url: '/instanceDetails?instanceId',
        views: {
          'detail@home.applications.application.insight': {
            templateUrl: 'views/application/instanceDetails.html',
            controller: 'InstanceDetailsCtrl as ctrl'
          }
        },
        resolve: {
          instance: ['$stateParams', function($stateParams) {
            return {
              instanceId: $stateParams.instanceId
            };
          }]
        },
        data: {
          pageTitleDetails: {
            title: 'Instance Details',
            nameParam: 'instanceId'
          }
        }
      };

      var serverGroupDetails = {
        name: 'serverGroup',
        url: '/serverGroupDetails?serverGroup&accountId&region',
        views: {
          'detail@home.applications.application.insight': {
            templateUrl: 'views/application/serverGroupDetails.html',
            controller: 'ServerGroupDetailsCtrl as ctrl'
          }
        },
        resolve: {
          serverGroup: ['$stateParams', function($stateParams) {
            return {
              name: $stateParams.serverGroup,
              accountId: $stateParams.accountId,
              region: $stateParams.region
            };
          }]
        },
        data: {
          pageTitleDetails: {
            title: 'Server Group Details',
            nameParam: 'serverGroup',
            accountParam: 'accountId',
            regionParam: 'region'
          }
        }
      };

      var loadBalancerDetails = {
        name: 'loadBalancerDetails',
        url: '/loadBalancerDetails?name&accountId&region',
        views: {
          'detail@home.applications.application.insight': {
            templateUrl: 'views/application/loadBalancer/loadBalancerDetails.html',
            controller: 'LoadBalancerDetailsCtrl as ctrl'
          }
        },
        resolve: {
          loadBalancer: ['$stateParams', function($stateParams) {
            return {
              name: $stateParams.name,
              accountId: $stateParams.accountId,
              region: $stateParams.region
            };
          }]
        },
        data: {
          pageTitleDetails: {
            title: 'Load Balancer Details',
            nameParam: 'name',
            accountParam: 'accountId',
            regionParam: 'region'
          }
        }
      };

      var securityGroupDetails = {
        name: 'securityGroupDetails',
        url: '/securityGroupDetails?name&accountId&region',
        views: {
          'detail@home.applications.application.insight': {
            templateUrl: 'views/application/connection/securityGroupDetails.html',
            controller: 'SecurityGroupDetailsCtrl as ctrl'
          }
        },
        resolve: {
          securityGroup: ['$stateParams', function($stateParams) {
            return {
              name: $stateParams.name,
              accountId: $stateParams.accountId,
              region: $stateParams.region
            };
          }]
        },
        data: {
          pageTitleDetails: {
            title: 'Security Group Details',
            nameParam: 'name',
            accountParam: 'accountId',
            regionParam: 'region'
          }
        }
      };

      var notFound = {
        name: '404',
        url: '/404',
        views: {
          'main@': {
            templateUrl: 'views/404.html',
            controller: angular.noop,
          }
        }
      };

      var taskDetails = {
        name: 'taskDetails',
        url: '/:taskId',
        views: {
          'task-details': {
            templateUrl: 'views/taskdetails.html',
            controller: 'TaskDetailsCtrl as ctrl',
          }
        },
        resolve: {
          taskId: ['$stateParams', function($stateParams) {
            return parseInt($stateParams.taskId);
          }]
        }
      };

      var insight = {
        name: 'insight',
        abstract: true,
        views: {
          'insight': {
            templateUrl: 'views/insight.html',
            controller: 'InsightCtrl as ctrl',
          }
        },
        children: [
          {
          name: 'clusters',
          reloadOnSearch: false,
          url: '/clusters?q&primary&secondary&hideInstances&hideHealthy&hideDisabled',
          views: {
            'nav': {
              templateUrl: 'views/application/cluster/navigation.html',
              controller: 'ClustersNavCtrl as ctrl'
            },
            'master': {
              templateUrl: 'views/application/cluster/all.html',
              controller: 'AllClustersCtrl as ctrl'
            }
          },
          data: {
            pageTitleSection: {
              title: 'Clusters'
            }
          },
          children: [
            loadBalancerDetails,
            serverGroupDetails,
            instanceDetails,
            securityGroupDetails,
            {
              name: 'cluster',
              url: '/:account/:cluster',
              views: {
                'master@home.applications.application.insight': {
                  templateUrl: 'views/application/cluster/single.html',
                  controller: 'ClusterCtrl as ctrl'
                }
              },
              resolve: {
                cluster: ['$stateParams', function ($stateParams) {
                  return {account: $stateParams.account, clusterName: $stateParams.cluster};
                }]
              },
              data: {
                pageTitleSection: {
                  title: 'Cluster',
                  nameParam: 'cluster',
                  accountParam: 'account'
                }
              },
              children: [loadBalancerDetails, serverGroupDetails, instanceDetails],
            }
          ],
        },
        {
          url: '/loadBalancers',
          name: 'loadBalancers',
          views: {
            'nav': {
              templateUrl: 'views/application/loadBalancer/navigation.html',
              controller: 'LoadBalancersNavCtrl as ctrl'
            },
            'master': {
              templateUrl: 'views/application/loadBalancer/all.html',
              controller: 'AllLoadBalancersCtrl as ctrl'
            }
          },
          data: {
            pageTitleSection: {
              title: 'Load Balancers'
            }
          },
          children: [
            loadBalancerDetails,
            serverGroupDetails,
            instanceDetails,
            securityGroupDetails,
            {
              url: '/:loadBalancerAccount/:loadBalancerRegion/:loadBalancer',
              name: 'loadBalancer',
              views: {
                'master@home.applications.application.insight': {
                  templateUrl: 'views/application/loadBalancer/single.html',
                  controller: 'LoadBalancerCtrl as ctrl'
                }
              },
              resolve: {
                loadBalancer: ['$stateParams', function($stateParams) {
                  return {
                    name: $stateParams.loadBalancer,
                    region: $stateParams.loadBalancerRegion,
                    account: $stateParams.loadBalancerAccount
                  };
                }]
              },
              data: {
                pageTitleMain: {
                  title: 'Load Balancer',
                  nameParam: 'loadBalancer',
                  accountParam: 'loadBalancerAccount',
                  regionParam: 'loadBalancerRegion'
                }
              },
              children: [loadBalancerDetails, serverGroupDetails, instanceDetails],
            }
          ],
        }, {
          url: '/connections',
          name: 'connections',
          views: {
            'nav': {
              templateUrl: 'views/application/connection/navigation.html',
              controller: 'SecurityGroupsNavCtrl as ctrl'
            },
            'master': {
              templateUrl: 'views/application/connection/all.html',
              controller: 'AllSecurityGroupsCtrl as ctrl'
            }
          },
          data: {
            pageTitleSection: {
              title: 'Security Groups'
            }
          },
          children: [
            loadBalancerDetails,
            serverGroupDetails,
            securityGroupDetails,
            {
              url: '/:securityGroupAccount/:securityGroupRegion/:securityGroup',
              name: 'connection',
              views: {
                'master@home.applications.application.insight': {
                  templateUrl: 'views/application/connection/single.html',
                  controller: 'SecurityGroupCtrl as ctrl'
                }
              },
              resolve: {
                securityGroup: ['$stateParams', function($stateParams) {
                  return {
                    account: $stateParams.securityGroupAccount,
                    name: $stateParams.securityGroup,
                    region: $stateParams.securityGroupRegion
                  };
                }]
              },
              data: {
                pageTitleSection: {
                  title: 'Security Group',
                  nameParam: 'securityGroup',
                  accountParam: 'securityGroupAccount',
                  regionParam: 'securityGroupRegion'
                }
              },
              children: [loadBalancerDetails, serverGroupDetails, securityGroupDetails]
            }
          ]
        }
        ]
      };

      var tasks = {
        name: 'tasks',
        url: '/tasks',
        views: {
          'insight': {
            templateUrl: 'views/tasks.html',
            controller: 'TasksCtrl',
          },
        },
        data: {
          pageTitleSection: {
            title: 'Tasks'
          }
        },
        children: [taskDetails],
      };

      var application = {
        name: 'application',
        url: '/:application',
        views: {
          'main@': {
            templateUrl: 'views/application.html',
            controller: 'ApplicationCtrl as ctrl'
          },
        },
        resolve: {
          application: ['$stateParams', 'oortService', function($stateParams, oortService) {
            return oortService.getApplication($stateParams.application);
          }]
        },
        data: {
          pageTitleMain: {
            field: 'application'
          }
        },
        children: [
          insight,
          tasks,
        ],
      };

      var applications = {
        name: 'applications',
        url: '/applications',
        views: {
          'main@': {
            templateUrl: 'views/applications.html',
            controller: 'ApplicationsCtrl as ctrl'
          }
        },
        data: {
          pageTitleMain: {
            label: 'Applications'
          }
        },
        children: [
          application
        ],
      };

      var infrastructure = {
        name: 'infrastructure',
        url: '/infrastructure?q',
        reloadOnSearch: false,
        views: {
          'main@': {
            templateUrl: 'views/infrastructure.html',
            controller: 'InfrastructureCtrl as ctrl',
          }
        },
        data: {
          pageTitleMain: {
            label: 'Infrastructure'
          }
        }
      };

      var home = {
        name: 'home',
        abstract: true,
        views: {
          'main@': {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl as ctrl'
          }
        },
        children: [
          notFound,
          applications,
          infrastructure
        ],
      };

      stateHelperProvider.setNestedState(home);

    };

    this.$get = angular.noop;

  });
<|endoftext|>


<commit_before>import '../../testHelper';
import React from 'react';
import ReactTestUtils, { Simulate } from 'react-addons-test-utils';
import sinon from 'sinon';

import CourseTypeSelector from '../../../app/assets/javascripts/components/overview/course_type_selector.jsx';

describe('CourseTypeSelector', () => {
  const course = {
    type: 'ClassroomProgramCourse'
  };

  it('displays the course type when not editable', () => {
    const NonEditableCourseTypeSelector = ReactTestUtils.renderIntoDocument(
      <CourseTypeSelector
        course={course}
        editable={false}
      />
    );
    const typeListing = ReactTestUtils.findRenderedDOMComponentWithTag(NonEditableCourseTypeSelector, 'div');
    expect(typeListing.textContent).to.eq('Type: ClassroomProgramCourse');
  });

  it('calls updateCourse when selection changes', () => {
    const spy = sinon.spy();
    CourseTypeSelector.__Rewire__('CourseActions', {
      updateCourse: spy
    });
    const EditableCourseTypeSelector = ReactTestUtils.renderIntoDocument(
      <CourseTypeSelector
        course={course}
        editable={true}
      />
    );
    const selector = ReactTestUtils.findRenderedDOMComponentWithTag(EditableCourseTypeSelector, 'select');
    Simulate.change(selector, { target: { value: 'VisitingScholarship' } });
    expect(spy.callCount).to.eq(1);
  });
});
<commit_msg>Add test for CourseTypeSelector timeline date logic<commit_after>import '../../testHelper';
import React from 'react';
import ReactTestUtils, { Simulate } from 'react-addons-test-utils';
import sinon from 'sinon';

import CourseTypeSelector from '../../../app/assets/javascripts/components/overview/course_type_selector.jsx';

describe('CourseTypeSelector', () => {
  const course = {
    type: 'ClassroomProgramCourse'
  };

  it('displays the course type when not editable', () => {
    const NonEditableCourseTypeSelector = ReactTestUtils.renderIntoDocument(
      <CourseTypeSelector
        course={course}
        editable={false}
      />
    );
    const typeListing = ReactTestUtils.findRenderedDOMComponentWithTag(NonEditableCourseTypeSelector, 'div');
    expect(typeListing.textContent).to.eq('Type: ClassroomProgramCourse');
  });

  it('calls updateCourse when selection changes', () => {
    const spy = sinon.spy();
    CourseTypeSelector.__Rewire__('CourseActions', {
      updateCourse: spy
    });
    const EditableCourseTypeSelector = ReactTestUtils.renderIntoDocument(
      <CourseTypeSelector
        course={course}
        editable={true}
      />
    );
    const selector = ReactTestUtils.findRenderedDOMComponentWithTag(EditableCourseTypeSelector, 'select');
    Simulate.change(selector, { target: { value: 'VisitingScholarship' } });
    expect(spy.callCount).to.eq(1);
  });

  it('sets timeline start and end when switching to ClassroomProgramCourse type', () => {
    const basicCourse = {
      type: 'BasicCourse',
      start: '2016-01-01',
      end: '2016-06-03'
    };

    const EditableCourseTypeSelector = ReactTestUtils.renderIntoDocument(
      <CourseTypeSelector
        course={basicCourse}
        editable={true}
      />
    );
    const selector = ReactTestUtils.findRenderedDOMComponentWithTag(EditableCourseTypeSelector, 'select');
    expect(EditableCourseTypeSelector.props.course.timeline_start).to.be.undefined;
    expect(EditableCourseTypeSelector.props.course.timeline_end).to.be.undefined;
    Simulate.change(selector, { target: { value: 'ClassroomProgramCourse' } });
    expect(EditableCourseTypeSelector.props.course.timeline_start).to.eq('2016-01-01');
    expect(EditableCourseTypeSelector.props.course.timeline_end).to.eq('2016-06-03');
  });
});
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * 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.
 *****************************************************************************/

/*****************************************************************************/

var nfc = window.nfc = {};

nfc.reset = function() {
	nfc.busName = "org.neard";
	nfc.bus = null;
	nfc.uri = null;
	nfc.manager = null;
	nfc.adapter = null;
	nfc.defaultAdapter = null;
};

nfc.init = function(uri, manifest, successCB, errorCB) {
	nfc.reset();

	function onAdapterPropsOk(props) {
		nfc.adapter.props = props;
		nfc.defaultAdapter = new nfc.NFCAdapter(nfc.adapter);
		if (successCB)
			successCB();
	}

	function onAdapterOk() {
		nfc.adapter.GetProperties(onAdapterPropsOk, errorCB);
	}

	function onManagerPropsOk(props) {
		if (props.Adapters.length == 0)
			errorCB("No NFC Adapter found");
		else {
			nfc.adapter = nfc.bus.getObject(nfc.busName,
					props.Adapters[0],
					onAdapterOk,
					errorCB);
		}
	}

	function onManagerOk() {
		nfc.manager.GetProperties(onManagerPropsOk, errorCB);
	}

	function onConnectOk() {
		nfc.bus = cloudeebus.SystemBus();
		nfc.uri = uri;
		nfc.manager = nfc.bus.getObject(nfc.busName, "/", onManagerOk, errorCB);
	}

	cloudeebus.connect(uri, manifest, onConnectOk, errorCB);
};

nfc.getDefaultAdapter = function() {
	return nfc.defaultAdapter;
};

/*****************************************************************************/

nfc.NFCAdapter = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
		this.powered = proxy.props.Powered ? true : false;
		this.polling = proxy.props.Polling ? true : false;
	}
	return this;
};

nfc.NFCAdapter.prototype.setPowered = function(state, successCB, errorCB) {

	var self = this;

	function onPoweredOk() {
		self.powered = state;
		if (successCB)
			successCB();
	}

	self.proxy.SetProperty("Powered", state, onPoweredOk, errorCB);
};

nfc.NFCAdapter.prototype.setPolling = function(state, successCB, errorCB) {

	var self = this;

	function onPollingOk() {
		self.polling = state;
		if (successCB)
			successCB();
	}

	if (state)
		self.proxy.StartPollLoop("Initiator", onPollingOk, errorCB);
	else
		self.proxy.StopPollLoop(onPollingOk, errorCB);
};

nfc.NFCAdapter.prototype.setTagListener = function(detectCB, errorCB, tagFilter) {

	var self = this;

	var tag = null;

	if (self.connected)
		self.unsetTagListener();

	function onTagPropsOk(props) {
		tag.props = props;
		tag.type = props.Type;
		if (detectCB)
			detectCB.onattach(tag);
	}

	function onTagFound(tagId) {
		tag = new nfc.NFCTag(nfc.bus.getObject(nfc.busName, tagId));
		tag.proxy.callMethod("org.neard.Tag", "GetProperties",
				[], onTagPropsOk, errorCB);
	}

	function onPropertyChanged(key, table) {
		if (key == "Tags") {
			if (table.length == 0) {
				detectCB.ondetach();
				self.setPolling(true);
			}
			else
				onTagFound(table[0]);
		}
	}

	self.proxy.connectToSignal("org.neard.Adapter","PropertyChanged",
			onPropertyChanged);
	self.connected = true;
};

nfc.NFCAdapter.prototype.unsetTagListener = function() {
	this.proxy.disconnectSignal("org.neard.Adapter","PropertyChanged");
	this.connected = false;
};

/*****************************************************************************/

nfc.NFCTag = function(proxy) {
	this.proxy = proxy;
	this.type = "GENERIC_TARGET";
	if (proxy) {
		this.id = proxy.objectPath;
	}
	return this;
};

nfc.NFCTag.prototype.readNDEF = function(readCB, errorCB) {

	var self = this;

	if (!self.props)
		return errorCB("Tag properties unknown.");

	var records = [];

	function onRecPropsOk(props) {
		records.push(nfc.NDEFRecordForProps(props));
		if (records.length == self.props.Records.length && readCB)
			readCB(new NDEFMessage(records));
	}

	for (var i=0; i<self.props.Records.length; i++) {
		var recProxy = nfc.bus.getObject(nfc.busName, self.props.Records[i]);
		recProxy.callMethod("org.neard.Record", "GetProperties",
				[], onRecPropsOk, errorCB);
	}
};

nfc.NFCTag.prototype.writeNDEF = function(ndefMessage, successCB, errorCB) {
	var ndefRecord = ndefMessage.records[0];
	var rec = ndefRecord.neardRecord();
	this.proxy.callMethod("org.neard.Tag", "Write",
			[rec], successCB, errorCB);
};

/*****************************************************************************/

nfc.NDEFMessage = function() {
	return this;
};

NDEFMessage = function(records) {
	nfc.NDEFMessage.call(this);
	this.records = records;
	return this;
};

NDEFMessage.prototype = new nfc.NDEFMessage();
NDEFMessage.prototype.constructor = NDEFMessage;

/*****************************************************************************/

nfc.NDEFRecord = function(props) {
	return this;
};

nfc.NDEFRecord.prototype.neardRecord = function() {
	return {};
};

/*****************************************************************************/

nfc.NDEFRecordText = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.text = props.Representation;
		this.languageCode = props.Language;
		this.encoding = props.Encoding;
	}
	return this;
};

nfc.NDEFRecordText.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordText.prototype.constructor = nfc.NDEFRecordText;

nfc.NDEFRecordText.prototype.neardRecord = function() {
	return {
		Type: "Text",
		Representation: this.text,
		Language: this.languageCode,
		Encoding: this.encoding
	};
};

NDEFRecordText = function(text, languageCode, encoding) {
	nfc.NDEFRecordText.call(this);
	this.text = text;
	this.languageCode = languageCode ? languageCode : "en-US";
	this.encoding = encoding ? encoding : "UTF-8";
	return this;
};

NDEFRecordText.prototype = new nfc.NDEFRecordText();
NDEFRecordText.prototype.constructor = NDEFRecordText;

/*****************************************************************************/

nfc.NDEFRecordURI = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.uri = props.URI;
	}
	return this;
};

nfc.NDEFRecordURI.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordURI.prototype.constructor = nfc.NDEFRecordURI;

nfc.NDEFRecordURI.prototype.neardRecord = function() {
	return {
		Type: "URI",
		URI: this.uri
	};
};

NDEFRecordURI = function(uri) {
	nfc.NDEFRecordURI.call(this);
	this.uri = uri;
	return this;
};

NDEFRecordURI.prototype = new nfc.NDEFRecordURI();
NDEFRecordURI.prototype.constructor = NDEFRecordURI;

/*****************************************************************************/

nfc.NDEFRecordForProps = function(props) {
	if (props.Type == "Text")
		return new nfc.NDEFRecordText(props);
	if (props.Type == "URI")
		return new nfc.NDEFRecordURI(props);
	return new nfc.NDEFRecord(props);
};

<commit_msg>Trigger tag found callback only once on adapter property changed signal. Prevents loop on tag write<commit_after>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * 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.
 *****************************************************************************/

/*****************************************************************************/

var nfc = window.nfc = {};

nfc.reset = function() {
	nfc.busName = "org.neard";
	nfc.bus = null;
	nfc.uri = null;
	nfc.manager = null;
	nfc.adapter = null;
	nfc.defaultAdapter = null;
};

nfc.init = function(uri, manifest, successCB, errorCB) {
	nfc.reset();

	function onAdapterPropsOk(props) {
		nfc.adapter.props = props;
		nfc.defaultAdapter = new nfc.NFCAdapter(nfc.adapter);
		if (successCB)
			successCB();
	}

	function onAdapterOk() {
		nfc.adapter.GetProperties(onAdapterPropsOk, errorCB);
	}

	function onManagerPropsOk(props) {
		if (props.Adapters.length == 0)
			errorCB("No NFC Adapter found");
		else {
			nfc.adapter = nfc.bus.getObject(nfc.busName,
					props.Adapters[0],
					onAdapterOk,
					errorCB);
		}
	}

	function onManagerOk() {
		nfc.manager.GetProperties(onManagerPropsOk, errorCB);
	}

	function onConnectOk() {
		nfc.bus = cloudeebus.SystemBus();
		nfc.uri = uri;
		nfc.manager = nfc.bus.getObject(nfc.busName, "/", onManagerOk, errorCB);
	}

	cloudeebus.connect(uri, manifest, onConnectOk, errorCB);
};

nfc.getDefaultAdapter = function() {
	return nfc.defaultAdapter;
};

/*****************************************************************************/

nfc.NFCAdapter = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
		this.powered = proxy.props.Powered ? true : false;
		this.polling = proxy.props.Polling ? true : false;
	}
	return this;
};

nfc.NFCAdapter.prototype.setPowered = function(state, successCB, errorCB) {

	var self = this;

	function onPoweredOk() {
		self.powered = state;
		if (successCB)
			successCB();
	}

	self.proxy.SetProperty("Powered", state, onPoweredOk, errorCB);
};

nfc.NFCAdapter.prototype.setPolling = function(state, successCB, errorCB) {

	var self = this;

	function onPollingOk() {
		self.polling = state;
		if (successCB)
			successCB();
	}

	if (state)
		self.proxy.StartPollLoop("Initiator", onPollingOk, errorCB);
	else
		self.proxy.StopPollLoop(onPollingOk, errorCB);
};

nfc.NFCAdapter.prototype.setTagListener = function(detectCB, errorCB, tagFilter) {

	var self = this;

	var tag = null;

	if (self.connected)
		self.unsetTagListener();

	function onTagPropsOk(props) {
		tag.props = props;
		tag.type = props.Type;
		if (detectCB)
			detectCB.onattach(tag);
	}

	function onTagFound(tagId) {
		if (tag) /* trigger "found" callback only once */
			return;
		tag = new nfc.NFCTag(nfc.bus.getObject(nfc.busName, tagId));
		tag.proxy.callMethod("org.neard.Tag", "GetProperties",
				[], onTagPropsOk, errorCB);
	}

	function onPropertyChanged(key, table) {
		if (key == "Tags") {
			if (table.length == 0) {
				tag = null;
				detectCB.ondetach();
				self.setPolling(true);
			}
			else
				onTagFound(table[0]);
		}
	}

	self.proxy.connectToSignal("org.neard.Adapter","PropertyChanged",
			onPropertyChanged);
	self.connected = true;
};

nfc.NFCAdapter.prototype.unsetTagListener = function() {
	this.proxy.disconnectSignal("org.neard.Adapter","PropertyChanged");
	this.connected = false;
};

/*****************************************************************************/

nfc.NFCTag = function(proxy) {
	this.proxy = proxy;
	this.type = "GENERIC_TARGET";
	if (proxy) {
		this.id = proxy.objectPath;
	}
	return this;
};

nfc.NFCTag.prototype.readNDEF = function(readCB, errorCB) {

	var self = this;

	if (!self.props)
		return errorCB("Tag properties unknown.");

	var records = [];

	function onRecPropsOk(props) {
		records.push(nfc.NDEFRecordForProps(props));
		if (records.length == self.props.Records.length && readCB)
			readCB(new NDEFMessage(records));
	}

	for (var i=0; i<self.props.Records.length; i++) {
		var recProxy = nfc.bus.getObject(nfc.busName, self.props.Records[i]);
		recProxy.callMethod("org.neard.Record", "GetProperties",
				[], onRecPropsOk, errorCB);
	}
};

nfc.NFCTag.prototype.writeNDEF = function(ndefMessage, successCB, errorCB) {
	var ndefRecord = ndefMessage.records[0];
	var rec = ndefRecord.neardRecord();
	this.proxy.callMethod("org.neard.Tag", "Write",
			[rec], successCB, errorCB);
};

/*****************************************************************************/

nfc.NDEFMessage = function() {
	return this;
};

NDEFMessage = function(records) {
	nfc.NDEFMessage.call(this);
	this.records = records;
	return this;
};

NDEFMessage.prototype = new nfc.NDEFMessage();
NDEFMessage.prototype.constructor = NDEFMessage;

/*****************************************************************************/

nfc.NDEFRecord = function(props) {
	return this;
};

nfc.NDEFRecord.prototype.neardRecord = function() {
	return {};
};

/*****************************************************************************/

nfc.NDEFRecordText = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.text = props.Representation;
		this.languageCode = props.Language;
		this.encoding = props.Encoding;
	}
	return this;
};

nfc.NDEFRecordText.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordText.prototype.constructor = nfc.NDEFRecordText;

nfc.NDEFRecordText.prototype.neardRecord = function() {
	return {
		Type: "Text",
		Representation: this.text,
		Language: this.languageCode,
		Encoding: this.encoding
	};
};

NDEFRecordText = function(text, languageCode, encoding) {
	nfc.NDEFRecordText.call(this);
	this.text = text;
	this.languageCode = languageCode ? languageCode : "en-US";
	this.encoding = encoding ? encoding : "UTF-8";
	return this;
};

NDEFRecordText.prototype = new nfc.NDEFRecordText();
NDEFRecordText.prototype.constructor = NDEFRecordText;

/*****************************************************************************/

nfc.NDEFRecordURI = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.uri = props.URI;
	}
	return this;
};

nfc.NDEFRecordURI.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordURI.prototype.constructor = nfc.NDEFRecordURI;

nfc.NDEFRecordURI.prototype.neardRecord = function() {
	return {
		Type: "URI",
		URI: this.uri
	};
};

NDEFRecordURI = function(uri) {
	nfc.NDEFRecordURI.call(this);
	this.uri = uri;
	return this;
};

NDEFRecordURI.prototype = new nfc.NDEFRecordURI();
NDEFRecordURI.prototype.constructor = NDEFRecordURI;

/*****************************************************************************/

nfc.NDEFRecordForProps = function(props) {
	if (props.Type == "Text")
		return new nfc.NDEFRecordText(props);
	if (props.Type == "URI")
		return new nfc.NDEFRecordURI(props);
	return new nfc.NDEFRecord(props);
};

<|endoftext|>


<commit_before>const urls = require('../../../../../src/lib/urls')
const fixtures = require('../../fixtures/index')
const formSelectors = require('../../../../selectors/pipeline-form')

const { lambdaPlc } = fixtures.company
const tabPanelSelector = '[data-auto-id="pipelineSubTabNav"] [role="tabpanel"]'

function addAssertion(assertion) {
  return (content) => ({
    assertion,
    content,
  })
}

function assertTabListItem({ contain = [], notContain = [] }) {
  const checks = [
    ...contain.map(addAssertion('contain')),
    ...notContain.map(addAssertion('not.contain')),
  ]

  checks.reduce(
    ($tab, { assertion, content }) => $tab.should(assertion, content),
    cy
      .get(tabPanelSelector)
      .find('ol > li')
      .should('have.length', 1)
  )
}

describe('My Pipeline tab on the dashboard', () => {
  context('When there are no companies on the pipeline', () => {
    it('Should show an empty pipeline message for each status', () => {
      const tabs = [
        {
          url: urls.pipeline.index(),
          status: 'prospect',
        },
        {
          url: urls.pipeline.active(),
          status: 'active',
        },
        {
          url: urls.pipeline.won(),
          status: 'won',
        },
      ]

      tabs.forEach((tab) => {
        cy.visit(tab.url)
        cy.get(tabPanelSelector)
          .should(
            'contain',
            `There are no companies in the ${tab.status} section of your pipeline`
          )
          .contains(
            'a',
            'visit the help centre article on how to use My Pipeline'
          )
          .should('have.attr', 'href', urls.external.helpCentre.pipeline())
      })
    })
  })

  context('Adding a company as a lead', () => {
    const projectName = 'Test add project'

    it('Should add the company and return to the my pipeline tab', () => {
      cy.visit(urls.companies.pipelineAdd(lambdaPlc.id))

      cy.get(formSelectors.name).type(projectName)
      cy.get(formSelectors.status.prospect).click()
      cy.contains('button', 'Add').click()

      cy.url().should('include', urls.pipeline.index())
      assertTabListItem({ contain: [projectName] })
    })

    context('Edit a company on the pipeline', () => {
      context('Change the status from Prospect to Active', () => {
        it('Should change the status and go to the active tab', () => {
          cy.visit(urls.pipeline.index())

          cy.get(tabPanelSelector)
            .contains('a', 'Edit')
            .click()

          cy.get(formSelectors.status.active).click()
          cy.contains('button', 'Update').click()

          cy.url().should('include', urls.pipeline.active())
          assertTabListItem({ contain: [projectName] })
        })
      })

      context(
        'Change the status from Active to Won and edit the project name',
        () => {
          it('Should change the values and go to the won tab', () => {
            const newProjectName = projectName + ' edited'

            cy.visit(urls.pipeline.active())

            cy.get(tabPanelSelector)
              .contains('a', 'Edit')
              .click()

            cy.get(formSelectors.name)
              .clear()
              .type(newProjectName)
            cy.get(formSelectors.status.won).click()
            cy.contains('button', 'Update').click()

            cy.url().should('include', urls.pipeline.won())
            assertTabListItem({ contain: [newProjectName] })
          })
        }
      )

      context('Add the optional fields', () => {
        it('should save the values and go to the won tab', () => {
          cy.visit(urls.pipeline.won())

          cy.get(tabPanelSelector)
            .contains('a', 'Edit')
            .click()

          cy.get(formSelectors.likelihood.low).click()
          cy.get(formSelectors.fields.sector).selectTypeaheadOption('Aero')
          cy.get(formSelectors.fields.contact).selectTypeaheadOption('Dean')
          cy.get(formSelectors.value).type('1000')
          cy.get(formSelectors.fields.expectedWinDate)
            .find('input')
            .then((element) => {
              cy.wrap(element[0]).type('06')
              cy.wrap(element[1]).type('2025')
            })

          cy.contains('button', 'Update').click()

          cy.url().should('include', urls.pipeline.won())
          assertTabListItem({
            contain: [
              projectName + ' edited',
              'Project sectorAerospace',
              'Company contactDean Cox',
              'Potential export value£1,000',
              'Expected date for winJun 2025',
            ],
          })
        })
      })

      context('Edit optional fields to remove the values', () => {
        it('Should remove the values and go to the won tab', () => {
          cy.visit(urls.pipeline.won())

          cy.get(tabPanelSelector)
            .contains('a', 'Edit')
            .click()

          cy.get(formSelectors.fields.sector).removeAllTypeaheadValues()
          cy.get(formSelectors.fields.contact).removeAllTypeaheadValues()
          cy.get(formSelectors.value).clear()
          cy.get(formSelectors.fields.expectedWinDate)
            .find('input')
            .clear()

          cy.contains('button', 'Update').click()

          cy.url().should('include', urls.pipeline.won())
          assertTabListItem({
            contain: [projectName + ' edited', 'LOW'],
            notContain: [
              'Project sector',
              'Company contact',
              'Potential export value',
              'Expected date for win',
            ],
          })
        })
      })
    })
  })
})
<commit_msg>test:update e2e test<commit_after>const urls = require('../../../../../src/lib/urls')
const fixtures = require('../../fixtures/index')
const formSelectors = require('../../../../selectors/pipeline-form')

const { lambdaPlc } = fixtures.company
const tabPanelSelector = '[data-auto-id="pipelineSubTabNav"] [role="tabpanel"]'

function addAssertion(assertion) {
  return (content) => ({
    assertion,
    content,
  })
}

function assertTabListItem({ contain = [], notContain = [] }) {
  const checks = [
    ...contain.map(addAssertion('contain')),
    ...notContain.map(addAssertion('not.contain')),
  ]

  checks.reduce(
    ($tab, { assertion, content }) => $tab.should(assertion, content),
    cy
      .get(tabPanelSelector)
      .find('ol > li')
      .should('have.length', 1)
  )
}

describe('My Pipeline tab on the dashboard', () => {
  context('When there are no companies on the pipeline', () => {
    it('Should show an empty pipeline message for each status', () => {
      const tabs = [
        {
          url: urls.pipeline.index(),
          status: 'prospect',
        },
        {
          url: urls.pipeline.active(),
          status: 'active',
        },
        {
          url: urls.pipeline.won(),
          status: 'won',
        },
      ]

      tabs.forEach((tab) => {
        cy.visit(tab.url)
        cy.get(tabPanelSelector)
          .should(
            'contain',
            `There are no companies in the ${tab.status} section of your pipeline`
          )
          .contains(
            'a',
            'visit the help centre article on how to use My Pipeline'
          )
          .should('have.attr', 'href', urls.external.helpCentre.pipeline())
      })
    })
  })

  context('Adding a company as a lead', () => {
    const projectName = 'Test add project'

    it('Should add the company and return to the my pipeline tab', () => {
      cy.visit(urls.companies.pipelineAdd(lambdaPlc.id))

      cy.get(formSelectors.name).type(projectName)
      cy.get(formSelectors.status.prospect).click()
      cy.contains('button', 'Add').click()

      cy.url().should('include', urls.pipeline.index())
      assertTabListItem({ contain: [projectName] })
    })

    context('Edit a company on the pipeline', () => {
      context('Change the status from Prospect to Active', () => {
        it('Should change the status and go to the active tab', () => {
          cy.visit(urls.pipeline.index())

          cy.get(tabPanelSelector)
            .contains('a', 'Edit')
            .click()

          cy.get(formSelectors.status.active).click()
          cy.contains('button', 'Update').click()

          cy.url().should('include', urls.pipeline.active())
          assertTabListItem({ contain: [projectName] })
        })
      })

      context(
        'Change the status from Active to Won and edit the project name',
        () => {
          it('Should change the values and go to the won tab', () => {
            const newProjectName = projectName + ' edited'

            cy.visit(urls.pipeline.active())

            cy.get(tabPanelSelector)
              .contains('a', 'Edit')
              .click()

            cy.get(formSelectors.name)
              .clear()
              .type(newProjectName)
            cy.get(formSelectors.status.won).click()
            cy.contains('button', 'Update').click()

            cy.url().should('include', urls.pipeline.won())
            assertTabListItem({ contain: [newProjectName] })
          })
        }
      )

      context('Add the optional fields', () => {
        it('should save the values and go to the won tab', () => {
          cy.visit(urls.pipeline.won())

          cy.get(tabPanelSelector)
            .contains('a', 'Edit')
            .click()

          cy.get(formSelectors.likelihood.low).click()
          cy.get(formSelectors.fields.sector).selectTypeaheadOption('Aero')
          cy.get(formSelectors.fields.contact).selectTypeaheadOption('Dean')
          cy.get(formSelectors.value).type('1000')
          cy.get(formSelectors.fields.expectedWinDate)
            .find('input')
            .then((element) => {
              cy.wrap(element[0]).type('06')
              cy.wrap(element[1]).type('2025')
            })

          cy.contains('button', 'Update').click()

          cy.url().should('include', urls.pipeline.won())
          assertTabListItem({
            contain: [
              projectName + ' edited',
              'Export sectorAerospace',
              'Company contactDean Cox',
              'Potential export value£1,000',
              'Expected date for winJun 2025',
            ],
          })
        })
      })

      context('Edit optional fields to remove the values', () => {
        it('Should remove the values and go to the won tab', () => {
          cy.visit(urls.pipeline.won())

          cy.get(tabPanelSelector)
            .contains('a', 'Edit')
            .click()

          cy.get(formSelectors.fields.sector).removeAllTypeaheadValues()
          cy.get(formSelectors.fields.contact).removeAllTypeaheadValues()
          cy.get(formSelectors.value).clear()
          cy.get(formSelectors.fields.expectedWinDate)
            .find('input')
            .clear()

          cy.contains('button', 'Update').click()

          cy.url().should('include', urls.pipeline.won())
          assertTabListItem({
            contain: [projectName + ' edited', 'LOW'],
            notContain: [
              'Export sector',
              'Company contact',
              'Potential export value',
              'Expected date for win',
            ],
          })
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>/* Copyright 2012 Mozilla Foundation
 *
 * 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.
 */
/* globals __non_webpack_require__ */

let fs = __non_webpack_require__('fs');
let http = __non_webpack_require__('http');
let https = __non_webpack_require__('https');
let url = __non_webpack_require__('url');

import {
  AbortException, assert, createPromiseCapability
} from '../shared/util';
import { validateRangeRequestCapabilities } from './network_utils';

const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;

class PDFNodeStream {
  constructor(source) {
    this.source = source;
    this.url = url.parse(source.url);
    this.isHttp = this.url.protocol === 'http:' ||
                  this.url.protocol === 'https:';
    // Check if url refers to filesystem.
    this.isFsUrl = this.url.protocol === 'file:' || !this.url.host;
    this.httpHeaders = (this.isHttp && source.httpHeaders) || {};

    this._fullRequest = null;
    this._rangeRequestReaders = [];
  }

  getFullReader() {
    assert(!this._fullRequest);
    this._fullRequest = this.isFsUrl ?
      new PDFNodeStreamFsFullReader(this) :
      new PDFNodeStreamFullReader(this);
    return this._fullRequest;
  }

  getRangeReader(start, end) {
    let rangeReader = this.isFsUrl ?
      new PDFNodeStreamFsRangeReader(this, start, end) :
      new PDFNodeStreamRangeReader(this, start, end);
    this._rangeRequestReaders.push(rangeReader);
    return rangeReader;
  }

  cancelAllRequests(reason) {
    if (this._fullRequest) {
      this._fullRequest.cancel(reason);
    }

    let readers = this._rangeRequestReaders.slice(0);
    readers.forEach(function(reader) {
      reader.cancel(reason);
    });
  }
}

class BaseFullReader {
  constructor(stream) {
    this._url = stream.url;
    this._done = false;
    this._errored = false;
    this._reason = null;
    this.onProgress = null;
    let source = stream.source;
    this._contentLength = source.length; // optional
    this._loaded = 0;

    this._disableRange = source.disableRange || false;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }

    this._isStreamingSupported = !source.disableStream;
    this._isRangeSupported = !source.disableRange;

    this._readableStream = null;
    this._readCapability = createPromiseCapability();
    this._headersCapability = createPromiseCapability();
  }

  get headersReady() {
    return this._headersCapability.promise;
  }

  get contentLength() {
    return this._contentLength;
  }

  get isRangeSupported() {
    return this._isRangeSupported;
  }

  get isStreamingSupported() {
    return this._isStreamingSupported;
  }

  read() {
    return this._readCapability.promise.then(() => {
      if (this._done) {
        return Promise.resolve({ value: undefined, done: true, });
      }
      if (this._errored) {
        return Promise.reject(this._reason);
      }

      let chunk = this._readableStream.read();
      if (chunk === null) {
        this._readCapability = createPromiseCapability();
        return this.read();
      }
      this._loaded += chunk.length;
      if (this.onProgress) {
        this.onProgress({
          loaded: this._loaded,
          total: this._contentLength,
        });
      }
      // Ensure that `read()` method returns ArrayBuffer.
      let buffer = new Uint8Array(chunk).buffer;
      return Promise.resolve({ value: buffer, done: false, });
    });
  }

  cancel(reason) {
    // Call `this._error()` method when cancel is called
    // before _readableStream is set.
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }

  _error(reason) {
    this._errored = true;
    this._reason = reason;
    this._readCapability.resolve();
  }

  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on('readable', () => {
      this._readCapability.resolve();
    });

    readableStream.on('end', () => {
      // Destroy readable to minimize resource usage.
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });

    readableStream.on('error', (reason) => {
      this._error(reason);
    });

    // We need to stop reading when range is supported and streaming is
    // disabled.
    if (!this._isStreamingSupported && this._isRangeSupported) {
      this._error(new AbortException('streaming is disabled'));
    }

    // Destroy ReadableStream if already in errored state.
    if (this._errored) {
      this._readableStream.destroy(this._reason);
    }
  }
}

class BaseRangeReader {
  constructor(stream) {
    this._url = stream.url;
    this._done = false;
    this._errored = false;
    this._reason = null;
    this.onProgress = null;
    this._loaded = 0;
    this._readableStream = null;
    this._readCapability = createPromiseCapability();
    let source = stream.source;
    this._isStreamingSupported = !source.disableStream;
  }

  get isStreamingSupported() {
    return this._isStreamingSupported;
  }

  read() {
    return this._readCapability.promise.then(() => {
      if (this._done) {
        return Promise.resolve({ value: undefined, done: true, });
      }
      if (this._errored) {
        return Promise.reject(this._reason);
      }

      let chunk = this._readableStream.read();
      if (chunk === null) {
        this._readCapability = createPromiseCapability();
        return this.read();
      }
      this._loaded += chunk.length;
      if (this.onProgress) {
        this.onProgress({ loaded: this._loaded, });
      }
      // Ensure that `read()` method returns ArrayBuffer.
      let buffer = new Uint8Array(chunk).buffer;
      return Promise.resolve({ value: buffer, done: false, });
    });
  }

  cancel(reason) {
    // Call `this._error()` method when cancel is called
    // before _readableStream is set.
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }

  _error(reason) {
    this._errored = true;
    this._reason = reason;
    this._readCapability.resolve();
  }

  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on('readable', () => {
      this._readCapability.resolve();
    });

    readableStream.on('end', () => {
      // Destroy readableStream to minimize resource usage.
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });

    readableStream.on('error', (reason) => {
      this._error(reason);
    });

    // Destroy readableStream if already in errored state.
    if (this._errored) {
      this._readableStream.destroy(this._reason);
    }
  }
}

function createRequestOptions(url, headers) {
  return {
    protocol: url.protocol,
    auth: url.auth,
    host: url.hostname,
    port: url.port,
    path: url.path,
    method: 'GET',
    headers,
  };
}

class PDFNodeStreamFullReader extends BaseFullReader {
  constructor(stream) {
    super(stream);

    let handleResponse = (response) => {
      this._headersCapability.resolve();
      this._setReadableStream(response);

      let { allowRangeRequests, suggestedLength, } =
      validateRangeRequestCapabilities({
        getResponseHeader: (name) => {
          // Make sure that headers name are in lower case, as mentioned
          // here: https://nodejs.org/api/http.html#http_message_headers.
          return this._readableStream.headers[name.toLowerCase()];
        },
        isHttp: stream.isHttp,
        rangeChunkSize: this._rangeChunkSize,
        disableRange: this._disableRange,
      });

      if (allowRangeRequests) {
        this._isRangeSupported = true;
      }
      // Setting right content length.
      this._contentLength = suggestedLength;
    };

    this._request = null;
    if (this._url.protocol === 'http:') {
      this._request = http.request(
        createRequestOptions(this._url, stream.httpHeaders),
        handleResponse);
    } else {
      this._request = https.request(
        createRequestOptions(this._url, stream.httpHeaders),
        handleResponse);
    }

    this._request.on('error', (reason) => {
      this._errored = true;
      this._reason = reason;
      this._headersCapability.reject(reason);
    });
    // Note: `request.end(data)` is used to write `data` to request body
    // and notify end of request. But one should always call `request.end()`
    // even if there is no data to write -- (to notify the end of request).
    this._request.end();
  }
}

class PDFNodeStreamRangeReader extends BaseRangeReader {
  constructor(stream, start, end) {
    super(stream);

    this._httpHeaders = {};
    for (let property in stream.httpHeaders) {
      let value = stream.httpHeaders[property];
      if (typeof value === 'undefined') {
        continue;
      }
      this._httpHeaders[property] = value;
    }
    this._httpHeaders['Range'] = `bytes=${start}-${end - 1}`;

    this._request = null;
    if (this._url.protocol === 'http:') {
      this._request = http.request(createRequestOptions(
        this._url, this._httpHeaders), (response) => {
          this._setReadableStream(response);
        });
    } else {
      this._request = https.request(createRequestOptions(
        this._url, this._httpHeaders), (response) => {
          this._setReadableStream(response);
        });
    }

    this._request.on('error', (reason) => {
      this._errored = true;
      this._reason = reason;
    });
    this._request.end();
  }
}

class PDFNodeStreamFsFullReader extends BaseFullReader {
  constructor(stream) {
    super(stream);

    let path = decodeURI(this._url.path);

    // Remove the extra slash to get right path from url like `file:///C:/`
    if (fileUriRegex.test(this._url.href)) {
      path = path.replace(/^\//, '');
    }

    fs.lstat(path, (error, stat) => {
      if (error) {
        this._errored = true;
        this._reason = error;
        this._headersCapability.reject(error);
        return;
      }
      // Setting right content length.
      this._contentLength = stat.size;

      this._setReadableStream(fs.createReadStream(path));
      this._headersCapability.resolve();
    });
  }
}

class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  constructor(stream, start, end) {
    super(stream);

    let path = decodeURI(this._url.path);

    // Remove the extra slash to get right path from url like `file:///C:/`
    if (fileUriRegex.test(this._url.href)) {
      path = path.replace(/^\//, '');
    }

    this._setReadableStream(
      fs.createReadStream(path, { start, end: end - 1, }));
  }
}

export {
  PDFNodeStream,
};
<commit_msg>changed decodeURI to decodeURIComponent<commit_after>/* Copyright 2012 Mozilla Foundation
 *
 * 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.
 */
/* globals __non_webpack_require__ */

let fs = __non_webpack_require__('fs');
let http = __non_webpack_require__('http');
let https = __non_webpack_require__('https');
let url = __non_webpack_require__('url');

import {
  AbortException, assert, createPromiseCapability
} from '../shared/util';
import { validateRangeRequestCapabilities } from './network_utils';

const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;

class PDFNodeStream {
  constructor(source) {
    this.source = source;
    this.url = url.parse(source.url);
    this.isHttp = this.url.protocol === 'http:' ||
                  this.url.protocol === 'https:';
    // Check if url refers to filesystem.
    this.isFsUrl = this.url.protocol === 'file:' || !this.url.host;
    this.httpHeaders = (this.isHttp && source.httpHeaders) || {};

    this._fullRequest = null;
    this._rangeRequestReaders = [];
  }

  getFullReader() {
    assert(!this._fullRequest);
    this._fullRequest = this.isFsUrl ?
      new PDFNodeStreamFsFullReader(this) :
      new PDFNodeStreamFullReader(this);
    return this._fullRequest;
  }

  getRangeReader(start, end) {
    let rangeReader = this.isFsUrl ?
      new PDFNodeStreamFsRangeReader(this, start, end) :
      new PDFNodeStreamRangeReader(this, start, end);
    this._rangeRequestReaders.push(rangeReader);
    return rangeReader;
  }

  cancelAllRequests(reason) {
    if (this._fullRequest) {
      this._fullRequest.cancel(reason);
    }

    let readers = this._rangeRequestReaders.slice(0);
    readers.forEach(function(reader) {
      reader.cancel(reason);
    });
  }
}

class BaseFullReader {
  constructor(stream) {
    this._url = stream.url;
    this._done = false;
    this._errored = false;
    this._reason = null;
    this.onProgress = null;
    let source = stream.source;
    this._contentLength = source.length; // optional
    this._loaded = 0;

    this._disableRange = source.disableRange || false;
    this._rangeChunkSize = source.rangeChunkSize;
    if (!this._rangeChunkSize && !this._disableRange) {
      this._disableRange = true;
    }

    this._isStreamingSupported = !source.disableStream;
    this._isRangeSupported = !source.disableRange;

    this._readableStream = null;
    this._readCapability = createPromiseCapability();
    this._headersCapability = createPromiseCapability();
  }

  get headersReady() {
    return this._headersCapability.promise;
  }

  get contentLength() {
    return this._contentLength;
  }

  get isRangeSupported() {
    return this._isRangeSupported;
  }

  get isStreamingSupported() {
    return this._isStreamingSupported;
  }

  read() {
    return this._readCapability.promise.then(() => {
      if (this._done) {
        return Promise.resolve({ value: undefined, done: true, });
      }
      if (this._errored) {
        return Promise.reject(this._reason);
      }

      let chunk = this._readableStream.read();
      if (chunk === null) {
        this._readCapability = createPromiseCapability();
        return this.read();
      }
      this._loaded += chunk.length;
      if (this.onProgress) {
        this.onProgress({
          loaded: this._loaded,
          total: this._contentLength,
        });
      }
      // Ensure that `read()` method returns ArrayBuffer.
      let buffer = new Uint8Array(chunk).buffer;
      return Promise.resolve({ value: buffer, done: false, });
    });
  }

  cancel(reason) {
    // Call `this._error()` method when cancel is called
    // before _readableStream is set.
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }

  _error(reason) {
    this._errored = true;
    this._reason = reason;
    this._readCapability.resolve();
  }

  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on('readable', () => {
      this._readCapability.resolve();
    });

    readableStream.on('end', () => {
      // Destroy readable to minimize resource usage.
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });

    readableStream.on('error', (reason) => {
      this._error(reason);
    });

    // We need to stop reading when range is supported and streaming is
    // disabled.
    if (!this._isStreamingSupported && this._isRangeSupported) {
      this._error(new AbortException('streaming is disabled'));
    }

    // Destroy ReadableStream if already in errored state.
    if (this._errored) {
      this._readableStream.destroy(this._reason);
    }
  }
}

class BaseRangeReader {
  constructor(stream) {
    this._url = stream.url;
    this._done = false;
    this._errored = false;
    this._reason = null;
    this.onProgress = null;
    this._loaded = 0;
    this._readableStream = null;
    this._readCapability = createPromiseCapability();
    let source = stream.source;
    this._isStreamingSupported = !source.disableStream;
  }

  get isStreamingSupported() {
    return this._isStreamingSupported;
  }

  read() {
    return this._readCapability.promise.then(() => {
      if (this._done) {
        return Promise.resolve({ value: undefined, done: true, });
      }
      if (this._errored) {
        return Promise.reject(this._reason);
      }

      let chunk = this._readableStream.read();
      if (chunk === null) {
        this._readCapability = createPromiseCapability();
        return this.read();
      }
      this._loaded += chunk.length;
      if (this.onProgress) {
        this.onProgress({ loaded: this._loaded, });
      }
      // Ensure that `read()` method returns ArrayBuffer.
      let buffer = new Uint8Array(chunk).buffer;
      return Promise.resolve({ value: buffer, done: false, });
    });
  }

  cancel(reason) {
    // Call `this._error()` method when cancel is called
    // before _readableStream is set.
    if (!this._readableStream) {
      this._error(reason);
      return;
    }
    this._readableStream.destroy(reason);
  }

  _error(reason) {
    this._errored = true;
    this._reason = reason;
    this._readCapability.resolve();
  }

  _setReadableStream(readableStream) {
    this._readableStream = readableStream;
    readableStream.on('readable', () => {
      this._readCapability.resolve();
    });

    readableStream.on('end', () => {
      // Destroy readableStream to minimize resource usage.
      readableStream.destroy();
      this._done = true;
      this._readCapability.resolve();
    });

    readableStream.on('error', (reason) => {
      this._error(reason);
    });

    // Destroy readableStream if already in errored state.
    if (this._errored) {
      this._readableStream.destroy(this._reason);
    }
  }
}

function createRequestOptions(url, headers) {
  return {
    protocol: url.protocol,
    auth: url.auth,
    host: url.hostname,
    port: url.port,
    path: url.path,
    method: 'GET',
    headers,
  };
}

class PDFNodeStreamFullReader extends BaseFullReader {
  constructor(stream) {
    super(stream);

    let handleResponse = (response) => {
      this._headersCapability.resolve();
      this._setReadableStream(response);

      let { allowRangeRequests, suggestedLength, } =
      validateRangeRequestCapabilities({
        getResponseHeader: (name) => {
          // Make sure that headers name are in lower case, as mentioned
          // here: https://nodejs.org/api/http.html#http_message_headers.
          return this._readableStream.headers[name.toLowerCase()];
        },
        isHttp: stream.isHttp,
        rangeChunkSize: this._rangeChunkSize,
        disableRange: this._disableRange,
      });

      if (allowRangeRequests) {
        this._isRangeSupported = true;
      }
      // Setting right content length.
      this._contentLength = suggestedLength;
    };

    this._request = null;
    if (this._url.protocol === 'http:') {
      this._request = http.request(
        createRequestOptions(this._url, stream.httpHeaders),
        handleResponse);
    } else {
      this._request = https.request(
        createRequestOptions(this._url, stream.httpHeaders),
        handleResponse);
    }

    this._request.on('error', (reason) => {
      this._errored = true;
      this._reason = reason;
      this._headersCapability.reject(reason);
    });
    // Note: `request.end(data)` is used to write `data` to request body
    // and notify end of request. But one should always call `request.end()`
    // even if there is no data to write -- (to notify the end of request).
    this._request.end();
  }
}

class PDFNodeStreamRangeReader extends BaseRangeReader {
  constructor(stream, start, end) {
    super(stream);

    this._httpHeaders = {};
    for (let property in stream.httpHeaders) {
      let value = stream.httpHeaders[property];
      if (typeof value === 'undefined') {
        continue;
      }
      this._httpHeaders[property] = value;
    }
    this._httpHeaders['Range'] = `bytes=${start}-${end - 1}`;

    this._request = null;
    if (this._url.protocol === 'http:') {
      this._request = http.request(createRequestOptions(
        this._url, this._httpHeaders), (response) => {
          this._setReadableStream(response);
        });
    } else {
      this._request = https.request(createRequestOptions(
        this._url, this._httpHeaders), (response) => {
          this._setReadableStream(response);
        });
    }

    this._request.on('error', (reason) => {
      this._errored = true;
      this._reason = reason;
    });
    this._request.end();
  }
}

class PDFNodeStreamFsFullReader extends BaseFullReader {
  constructor(stream) {
    super(stream);

    let path = decodeURIComponent(this._url.path);

    // Remove the extra slash to get right path from url like `file:///C:/`
    if (fileUriRegex.test(this._url.href)) {
      path = path.replace(/^\//, '');
    }

    fs.lstat(path, (error, stat) => {
      if (error) {
        this._errored = true;
        this._reason = error;
        this._headersCapability.reject(error);
        return;
      }
      // Setting right content length.
      this._contentLength = stat.size;

      this._setReadableStream(fs.createReadStream(path));
      this._headersCapability.resolve();
    });
  }
}

class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  constructor(stream, start, end) {
    super(stream);

    let path = decodeURIComponent(this._url.path);

    // Remove the extra slash to get right path from url like `file:///C:/`
    if (fileUriRegex.test(this._url.href)) {
      path = path.replace(/^\//, '');
    }

    this._setReadableStream(
      fs.createReadStream(path, { start, end: end - 1, }));
  }
}

export {
  PDFNodeStream,
};
<|endoftext|>


<commit_before>/*global angular */

(function () {
    'use strict';

    angular.module('centers', [])
        .factory('centers', function ($resource) {
            return $resource('/api/centers.json');
        });
}());
<commit_msg>Source formatting / making DI explicit<commit_after>/*global angular */

(function () {
    'use strict';

    angular.module('centers', [])
        .factory('centers', ['$resource', function ($resource) {
            return $resource('/api/centers.json');
        }]);
}());
<|endoftext|>