const buildColumn = col => {
      const { parent, columns, height, name, property, sortable } = col;

      this.columnIndex[name] = col;
      
      col.property = normalizeProperty(property, col);
      col.sortable = normalizeSortable(sortable, col);

      if (!_.isFunction(col.template)) {
        col.template = defaultCellTemplate;
      }
      col.height  = _.isNumber(height) ? height : 1;
      col.rowIndex = parent ? parent.rowIndex + parent.height : 0;
      col.columns = _.map(columns, c => buildColumn(_.extend({ parent: col }, c)));
      col.treeHeight = col.height;
      col.treeWidth = 1;
      if (!_.isEmpty(col.columns)) {
        col.treeHeight += _.chain(col.columns)
          .map(_.property('treeHeight')).max().value();
        col.treeWidth = _.chain(col.columns)
          .map(_.property('treeWidth')).reduce((a, b) => a + b, 0).value();
      } else {
        this.leafColumns.push(col);
      }

      return col;
    };
function filterTaskByAgency ( agency, task ) {
  var getAbbr = _.property( 'abbr' );

  if ( _.isUndefined( agency ) ) {
    return task;
  }

  if ( getAbbr( agency.data ) === getAbbr( task.restrict ) ) {
    return _.property( 'restrictToAgency' )( task.restrict ) || _.property( 'projectNetwork' )( task.restrict );
  }

}
Example #3
0
    columns: function (rows, cfg_) {
        if (rows.length === 0) {
            return [] }
        else {
            
            /*  convert column data to string, taking first line
             */
            var rowsToStr       = rows.map (_.map.tails2 (function (col) { return (col + '').split ('\n')[0] }))

            /*  compute column widths (per row) and max widths (per column)
             */
            var columnWidths    = rowsToStr.map (_.map.tails2 (_.property ('length')))
            var maxWidths       = columnWidths.zip (_.largest)

            /*  default config
             */
            var cfg             = cfg_ || { minColumnWidths: maxWidths, maxTotalWidth: 0 }

            /*  project desired column widths, taking maxTotalWidth and minColumnWidths in account
             */
            var totalWidth      = _.reduce (maxWidths, _.sum, 0)
            var relativeWidths  = _.map (maxWidths, _.muls (1.0 / totalWidth))
            var excessWidth     = Math.max (0, totalWidth - cfg.maxTotalWidth)
            var computedWidths  = _.map (maxWidths, function (w, i) {
                                                        return Math.max (cfg.minColumnWidths[i], Math.floor (w - excessWidth * relativeWidths[i])) })

            /*  this is how many symbols we should pad or cut (per column)
             */
            var restWidths      = columnWidths.map (function (widths) { return [computedWidths, widths].zip (_.subtract) })

            /*  perform final composition
             */
            return [rowsToStr, restWidths].zip (
                 _.zap.tails (function (str, w) { return w >= 0 ? (str + ' '.repeats (w)) : (_.initial (str, -w).join ('')) })
                 .then (_.joinsWith ('  ')) ) } }
Example #4
0
    this.findOne({}, function (err, result){
        
        var modules = [];
        
        if (err) {
            return next(err);
        }

        if (result) {

            if (req.body.module) {
                if (result.modules) {
                    var modules_length = result.modules.length;
                    for (var index = 0; index < modules_length; index ++) {
                        if (result.modules[index].name == req.body.module) {
                            var changes = false;
                            for (var property in req.body) {
                                if (_.property(result.modules[index], property)) {
                                    result.modules[index][property] = req.body[property];
                                    changes = true;
                                }
                            }
                            if (changes) {
                                // With this "tells" to Mongoose that the value has changed
                                result.markModified('modules');
                                result.save();
                            }
                        }
                    }
                }
            }
        }
        return next();
    });
Example #5
0
    function configureDiskConfig(command) {
        var serverData = command.serversData;
        var diskConfig = _.chain(serverData).map(_.property("disks")).flatten().value();

        //disk config provided as array - no conversion needed
        if (!(command.disks instanceof Array)) {
            var newDiskCfg = command.disks;

            if (newDiskCfg.add) {
                var toAdd = _.asArray(newDiskCfg.add);
                diskConfig = diskConfig.concat(toAdd);
            }

            if (newDiskCfg.remove) {
                var toRemove = _.asArray(newDiskCfg.remove);
                diskConfig = _.filter(diskConfig, function(disk) {
                    return toRemove.indexOf(disk.id) === -1;
                });
            }

            if (newDiskCfg.edit) {
                var toEdit = _.asArray(newDiskCfg.edit);

                _.each(diskConfig, function(srvDisk) {
                    var diskCfg = _.findWhere(toEdit, {id: srvDisk.id});

                    if (diskCfg) {
                        srvDisk.size = diskCfg.size;
                    }
                });
            }
        }

        return diskConfig;
    }
Example #6
0
 var strings = convertEntity(fields, function (value, field) {
     if (field.fieldType.id == 'reference' && value) {
         return value.name && value.name.toString() || undefined;
     } else if (field.fieldType.id == 'multiReference' && value) {
         return value.map(_.property('name')).join(' ');
     }
     return value && value.toString() || undefined;
 }, entity);
Example #7
0
File: api.js Project: NealRame/mbac
function get_field(data, key, transform) {
    transform = transform || _.identity;
    return transform(
        _.chain(data)
            .filter((part) => !!part && part.field === key)
            .map(_.property('value'))
            .value()
    );
}
Example #8
0
                var propsFound = _.filter(propLevel, function (propPart) {
                    if (_.has(objToCheck, propPart)) {
                        objToCheck = _.property(propPart)(objToCheck);
                        return true;
                    }

                    log.warn(util.format('Plugin at [%s] property [%s] is not defined', filePath, prop));
                    return false;
                });
Example #9
0
    asTable: function (arrayOfObjects) {
        var columnsDef  = arrayOfObjects.map (_.keys.arity1).reduce (_.union.arity2, []) // makes ['col1', 'col2', 'col3'] by unifying objects keys
        var lines       = log.columns ( [columnsDef].concat (
                                            _.map (arrayOfObjects, function (object) {
                                                                        return columnsDef.map (_.propertyOf (object)) })), {
                                        maxTotalWidth: 120,
                                        minColumnWidths: columnsDef.map (_.property ('length')) })

        return [lines[0], log.thinLine[0].repeats (lines[0].length), _.rest (lines)].flat.join ('\n') },
    vcr.it('Should return correct credentials of created server', function (done) {
        this.timeout(15 * 60 * 1000);

        serverBuilder
            .createCentOsVm({password: '******'})
            .then(servers.findCredentials)
            .then(_.property('password'))
            .then(_.partial(assert.equal, '1qa@WS3ed'))
            .then(serverBuilder.deleteServer(done));
    });
Example #11
0
 File.list(folder.path, function(files) {
   var childrenIds = _.map(folder.children, _.property('id'));
   var newFiles = _.filter(files, function(file) { return !_.contains(childrenIds, file.id); });
   folder.children = folder.children.concat(newFiles);
   if (!folder.watching) {
     folder.watching = true;
     self.$root.watch(folder.path);
   }
   if (typeof cb === 'function') cb();
 });
Example #12
0
 handleFetch: function (cb, er, res) {
   if (er) return cb(er);
   var newsPosts = _.chain(this.state.newsPosts.concat(res.data))
     .unique(_.property('id'))
     .map(function (newsPost) { return _.extend({comments: []}, newsPost); })
     .sortBy('created_at')
     .value()
     .reverse();
   this.update({newsPosts: {$set: newsPosts}});
   cb(null, res.data.length < PER_PAGE);
 },
Example #13
0
        .then(function(contacts) {
          // If you have a home place make sure its at the top
          if (usersHomePlace) {
            var homeIndex = _.findIndex(contacts, function(contact) {
              return contact._id === usersHomePlace._id;
            });

            additionalListItem =
              !$scope.filters.search &&
              !$scope.filters.simprintsIdentities &&
              (additionalListItem || !$scope.appending) &&
              homeIndex === -1;

            if (!$scope.appending) {
              if (homeIndex !== -1) {
                // move it to the top
                contacts.splice(homeIndex, 1);
                contacts.unshift(usersHomePlace);
              } else if (
                !$scope.filters.search &&
                !$scope.filters.simprintsIdentities
              ) {
                contacts.unshift(usersHomePlace);
              }
              if ($scope.filters.simprintsIdentities) {
                contacts.forEach(function(contact) {
                  var identity = $scope.filters.simprintsIdentities.find(
                    function(identity) {
                      return identity.id === contact.simprints_id;
                    }
                  );
                  contact.simprints = identity || {
                    confidence: 0,
                    tierNumber: 5,
                  };
                });
              }
            }
          }

          $scope.moreItems = liveList.moreItems =
            contacts.length >= options.limit;

          const mergedList = options.paginating ?
            _.uniq(contacts.concat(liveList.getList()), false, _.property('_id'))
            : contacts;
          liveList.set(mergedList, !!options.reuseExistingDom);

          _initScroll();
          $scope.loading = false;
          $scope.appending = false;
          $scope.hasContacts = liveList.count() > 0;
          setActionBarData();
        })
Example #14
0
    messageUtil.getMessage = function(key, languageType) {

        var _ = require('underscore');
        var languageUtil = require('components/util/languageUtil');
        var message = '';

        switch (languageType) {
            case languageUtil.languageTypes.en:
                message = _.property(key)(messageEn);
                break;
            case languageUtil.languageTypes.zh:
                message = _.property(key)(messageZh);
                break;
            default :
                message = _.property(key)(messageEn);
                break;
        }

        return messageUtil.formatMessage(key, message);
    };
    self.await = function (timeout) {
        if (jobInfo && jobInfo.isQueued === false) {
            reject(makeJobFailedMessage("notQueued"));
        } else {
            queueClient
                .getStatus(jobInfo.findStatusId())
                .then(_.property('status'))
                .then(onStatusReceived(timeout));
        }

        return self;
    };
Example #16
0
	_.each(docConfigs, function(doc) {
		var versions = _.map(doc.versions, function(ver) {
			var docVersion = {
				name : doc.name,
				description : doc.description,
				version : ver.version,
				configPath : ver.configPath,
				engineConfig : loadEngineConfig(ver.configPath),
				staticTemplatePath : ver.staticTemplatePath,
				templateEngineVersion : ver.templateEngineVersion || doc.templateEngineVersion,
				isDynamic : ver.configPath ? true : false,				
			};
			addAssets(docVersion, this);
			addStaticTemplate(docVersion, this);
			checkVersion(docVersion, this);
			return docVersion;
		}, this);
		this.config[doc.name] = { 
				versions : _.indexBy(versions, _.property('version')),
				maxVersion : _.max(_.map(versions, _.property('version')))
			};
	}, this);
        _attachTypeFilter: function(listOptions, activityType) {
            var typeChoices = _.mapObject(listOptions, _.property('label'));

            this.typeFilter = new MultiSelectFilter({
                showLabel: false,
                choices: typeChoices,
                widgetOptions: {
                    refreshNotOpened: true
                }
            });
            this.typeFilter.setValue(activityType);
            this.$(this.options.typeChoiceContainerSelector).append(this.typeFilter.render().$el);
            this.listenTo(this.typeFilter, 'update', this._onTypeFilterUpdate);
        },
Example #18
0
    function reduceAndGetStationName(rawParsedData, log) {
        if (!rawParsedData) {
            log.warn('Could not attempt to parse raw json from xml, as the object was null');
            return null;
        }

        assert(rawParsedData.conds, 'Response was missing conds attribute');
        var determinedStationId = _.first(_.keys(rawParsedData.conds));

        return {
            stationId: determinedStationId,
            currentConditionsRaw: _.property(determinedStationId)(rawParsedData.conds)
        }
    }
Example #19
0
        _getCriteriaHint: function() {
            var value = this._getDisplayValue();
            var option = null;

            if (!_.isUndefined(value.type)) {
                var type = value.type;
                option = this._getChoiceOption(type);

                if (this.isEmptyType(type)) {
                    return option ? option.label : this.placeholder;
                }
            }

            if (!value.value || value.value.length === 0) {
                return this.placeholder;
            }

            var data = this.$(this.elementSelector).inputWidget('data');
            if (!data || !data.length) {
                data = this.previousData.length ? this.previousData : this.initialData;
            }

            if (this.valueIsLoaded(value.value)) {
                var self = this;

                var hintRawValue = _.isObject(_.first(value.value)) ?
                    _.map(value.value, _.property('text')) :
                    _.chain(value.value)
                        .map(function(id) {
                            var item =  _.find(self.selectedData, function(item) {
                                return item.id === id;
                            });

                            return item ? item.text : item;
                        })
                        .filter(_.negate(_.isUndefined))
                        .value();

                var hintValue = this.wrapHintValue ? ('"' + hintRawValue + '"') : hintRawValue;

                return (option ? option.label + ' ' : '') + hintValue;
            } else {
                return this.placeholder;
            }
        },
Example #20
0
seneca.add({role: 'engagement', resource:'products', cmd: 'GET'}, (args, callback) => {

  if (args.cartId == null){
    callback("Missing cart Id");
  }

  if (args.engagement == null){
    callback("Missing engagement token");
  }
  //TODO validate token is valid client and store ids

  act({role: 'cart', cmd: 'read', type:'id'}, {id: args.cartId})
    .then(_.property('products'))
    .then(cartProducts => {
      const productIds = _.map(cartProducts, 'productId');
      const params = {
        where: {_id: {$in: productIds}},
        select: 'name description img'
      };
      return Promise.props({
        cartProducts,
        productDetails: act({role: 'products', cmd: 'read'}, params)
      });
    })
    .then(result => {
      const cartProducts = result.cartProducts;
      const productDetails = result.productDetails;
      const productsWithDetail = _.map(cartProducts, cartProduct => {
        const productId = cartProduct.productId;
        const cartProductWithDetail = _.omit(cartProduct, 'productId');
        cartProductWithDetail.product = _.find(productDetails, {_id: productId});
        return cartProductWithDetail;
      });

      callback(null, productsWithDetail);
    })
    .catch(callback);

});
    it("a publish engine should be able to find out which are the most urgent late subscriptions to serve ", function () {

        var publish_server = new ServerSidePublishEngine();
        publish_server.pendingPublishRequestCount.should.eql(0, " No PublishRequest in queue");


        var subscription1 = new Subscription({
            id: 1,
            publishingInterval: 1000,
            lifeTimeCount:        60,
            maxKeepAliveCount:    20,
            publishingEnabled: true,
            publishEngine: publish_server
        });
        subscription1.publishingInterval.should.eql(1000);
        subscription1.lifeTimeCount.should.eql(60);
        subscription1.maxKeepAliveCount.should.eql(20);

        publish_server.add_subscription(subscription1);

        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());
        publish_server._on_PublishRequest(new subscription_service.PublishRequest());


        var subscription2 = new Subscription({
            id: 2,
            publishingInterval: 100,
            lifeTimeCount:      120,
            maxKeepAliveCount:   20,
            publishingEnabled: true,
            publishEngine: publish_server
        });
        subscription2.publishingInterval.should.eql(100);
        subscription2.lifeTimeCount.should.eql(120);
        subscription2.maxKeepAliveCount.should.eql(20);
        publish_server.add_subscription(subscription2);

        var subscription3 = new Subscription({
            id: 3,
            publishingInterval:  50,
            lifeTimeCount:     1000,
            maxKeepAliveCount:   20,
            publishingEnabled: true,
            publishEngine: publish_server
        });
        subscription3.publishingInterval.should.eql(100); // !! Note that publishingInterval has been clamped in constructor
        subscription3.lifeTimeCount.should.eql(1000);
        subscription3.maxKeepAliveCount.should.eql(20);

        publish_server.add_subscription(subscription3);

        var monitoredItem1  =add_mock_monitored_item(subscription1);
        var monitoredItem2  =add_mock_monitored_item(subscription2);
        var monitoredItem3  =add_mock_monitored_item(subscription3);


        subscription1.lifeTimeCount.should.eql(60);
        subscription2.lifeTimeCount.should.eql(120);
        subscription3.lifeTimeCount.should.eql(1000);


        subscription1.timeToExpiration.should.eql(1000 *  60);
        subscription2.timeToExpiration.should.eql(100  * 120);
        subscription3.timeToExpiration.should.eql(100   * 1000);

        // add some notification we want to process
        monitoredItem1.simulateMonitoredItemAddingNotification();
        monitoredItem2.simulateMonitoredItemAddingNotification();
        monitoredItem3.simulateMonitoredItemAddingNotification();

        // let move in time so that subscriptions starts
        this.clock.tick(Math.max(subscription1.publishingInterval, subscription2.publishingInterval, subscription3.publishingInterval));

        subscription1.state.should.eql(SubscriptionState.NORMAL);
        subscription2.state.should.eql(SubscriptionState.NORMAL);
        subscription3.state.should.eql(SubscriptionState.NORMAL);

        publish_server.findLateSubscriptionsSortedByAge().should.eql([]);


        // let move in time so that all subscriptions get late (without expiring)
        this.clock.tick(1000 * 20);
        subscription1.state.should.eql(SubscriptionState.LATE);
        subscription2.state.should.eql(SubscriptionState.LATE);
        subscription3.state.should.eql(SubscriptionState.LATE);


        publish_server.findLateSubscriptionsSortedByAge().map(_.property("id")).should.eql([2, 1, 3]);

        this.clock.tick(1100);
        subscription1.state.should.eql(SubscriptionState.LATE);
        subscription2.state.should.eql(SubscriptionState.CLOSED);
        subscription3.state.should.eql(SubscriptionState.LATE);

        publish_server.findLateSubscriptionsSortedByAge().map(_.property("id")).should.eql([1, 3]);

        subscription1.terminate();

        subscription2.terminate();

        subscription3.terminate();

        publish_server.shutdown();
    });
Example #22
0
 * @des 完善链式的方法
 */
var func = function () {};
_.tap(obj, func);
// obj作为参数 调用func

/**
 * @Function _.has
 * @des 是否拥有指定键名  等价于Object.hasOwnProperty
 */

/**
 * @Function _.property
 * @des 传入某个键名 返回一个方法 再传入某个对象 返回该对象对应键名的键值
 */
_.property('name')(obj);
// => 12

/**
 * @Function _.propertyOf
 * @des 纯粹有病 和property一个娘的
 */
_.propertyOf(obj)('name');
// => 12

/**
 * @Function _.isEqual
 * @des 对象之间的相等比较 本不会返回true 这里算是弱化了
 */
var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone  = {name: 'moe', luckyNumbers: [13, 27, 34]};
Example #23
0
 _.iteratee = function(value, context, argCount) {
   if (value == null) return _.identity;
   if (_.isFunction(value)) return createCallback(value, context, argCount);
   if (_.isObject(value)) return _.matches(value);
   return _.property(value);
 };
"use strict";define("pages/open-course/assessment/clients/contentRequesterAssessmentClient",["require","exports","module","underscore","js/lib/path"],function(require,exports,module){function buildSessionUrl(){return"session"}function buildActionUrl(e,n){return t.join(buildSessionUrl(),e,"action",n)}var _=require("underscore"),t=require("js/lib/path"),e=function ContentRequesterAssessmentClient(e){this.contentRequester=e};e.prototype.callAction=function(t,n,e){var r={argument:e||[]};return this.contentRequester.request(buildActionUrl(t,n,e),r).then(function(e){return{result:e["return"]}})},e.prototype.getOrCreateSession=function(){return this.contentRequester.request(buildSessionUrl(),[]).then(_.property("session")).then(_.property("id"))},module.exports=e});
Example #25
0
}

let gridConfig = {
  el: '#container',
  dataSource: {
    type: 'memory',
    data: memoryData,
    primaryKey: 'UserName',
  },
  rows: {
    headRows: [{
      html: '<div class="head-rows-html">head rows html</div>',
      payload: 'Custom Row',
      attributes: {
        'data-type': 'html',
        'data-payload': _.property('payload'),
      },
    }, 'column-header-rows'],
    bodyRows: [
      {
        type: 'data-rows',
        classes: {
          male: row => (row.Gender === 'Male'),
          female: row => (row.Gender === 'Female'),
        },
        attributes: {
          'data-type': 'data',
          'data-first-name': _.property('FirstName'),
        },
      },
    ],
//////////////////////////////////////////////////////////////////////
// カーリルから返却されてきた複数本情報json object解析
// カーリルから取得した結果はグローバル変数のbooklistとcalil_books_statusにセットする
//
// return: jsonのcontinueフィールドが1(失敗なら)sessionの文字列を返す。
//         0(成功)なら空文字""を返す
//         エラーなら"error"を返す
//////////////////////////////////////////////////////////////////////
function parseCalil( json ) {
    

    var CALIL_BOOKS = "books";
    var CALIL_NARA_IKOMA = "Nara_Ikoma";    //他地域はここを変更要
    var CALIL_LIBKEY = "libkey";
    var CALIL_RESERVE_URL = "reserveurl";
    var CALIL_STATUS = "status";
    var CALIL_CONTINUE = "continue";
    var CALIL_SESSION = "session";
    var ERROR_CODE = "error";
    
    
    if (json == null) {
        if(DEBUG) console.log("json is null");
        return ERROR_CODE;
    }
    
    /* ★★★★★
    http://www.red.oit-net.jp/tatsuya/js/string.htm 
    http://www.underscorejs.org
    ★★★★★
    */
    
    try {
        //continue=1の場合は続きがあるので取り直す必要がある
 
        if ( _.has( json, CALIL_CONTINUE) ) {
            var isContinue = _.property( CALIL_CONTINUE )(json);
        	if(DEBUG) console.log("retry continue = "+ isContinue);
                
        	if (isContinue == 1) {
        		var session = "";
                
                if( _.has( json, CALIL_SESSION )){
                    session = _.property( CALIL_SESSION )(json);
        
                    if(DEBUG) console.log("retry session = "+ session);
        		}
        		return session;
        	}
        }

        //continue=0の場合はparseしてOK
        if( _.has( json, CALIL_BOOKS )){

            var books = _.property( CALIL_BOOKS )(json);

            
            for( var Isbn_by_calil in books ){  //本の数だけ取得する(ここから)

                //Isbn_by_calil がISBN条件に合っているかcheck
                
                
            
            //if( BookInfo.Isbn ){
            
                var bookByIsbn = _.property( Isbn_by_calil )(books);

                if( _.has( bookByIsbn, CALIL_NARA_IKOMA)){
                    var naraIkoma = _.property( CALIL_NARA_IKOMA )(bookByIsbn);
                    
                    if( _.has( naraIkoma, CALIL_LIBKEY)){
                        
                        var libkey = _.property( CALIL_LIBKEY )(naraIkoma);
                        
                        var libraries = _.keys( libkey );
                        
                        if ( libraries.length != 0 ) {
                            var name = _.values( libkey );
                            
                            setBookLibRentaledInfo( Isbn_by_calil, Setting, libraries, name );
                            
                            /*
                            if(DEBUG){
                                for( var i=0; i < libraries.length; i++){
                                    console.log(libraries[i] +"=" + name[i]);
                                }
                            } */
                        }
                        
                        if( _.has( naraIkoma, CALIL_STATUS )){  
                            //statusは"OK", "Cache", "Running", "Error"のいづれか
                            //"Cache"は"OK"と同様(カーリルサーバーのキャッシュを利用)
                            var status = _.property( CALIL_STATUS )(naraIkoma);
                            
                            if(status != "Running"){
                                set_calil_books_status( Isbn_by_calil, status );
                            }
                            
                        }
                        if( _.has( naraIkoma, CALIL_RESERVE_URL)){
                        
                        //if (naraIkoma.has(CALIL_RESERVE_URL)) {
                            var reserveUrl = _.property( CALIL_RESERVE_URL )(naraIkoma);

                            setBookLibCityURL( Isbn_by_calil, reserveUrl );

                        }
                    }
                }
            //}
            }   //本の数だけ取得(Isbn_by_calilへの代入for文ここまで)
            
            return "";  //成功
        }
    }catch (e) {
         if(DEBUG) console.log("Json Exception!" + e);
         return ERROR_CODE;
    }
    
}
Example #27
0
 })).then(_.flatten).then(function (items) {
   return _.unique(items, _.property('name'));
 });
Example #28
0
 _.pluck = function(obj, key) {
   return _.map(obj, _.property(key));
 };
Example #29
0
 var lookupIterator = function(value) {
   if (value == null) return _.identity;
   if (_.isFunction(value)) return value;
   return _.property(value);
 };
    it("a publish engine should be able to find out which are the most urgent late subscriptions to serve ", function () {

        var publish_server = new ServerSidePublishEngine();
        publish_server.pendingPublishRequestCount.should.eql(0, " No PublishRequest in queue");


        var subscription1 = new Subscription({
            id: 1,
            publishingInterval: 1000, lifeTimeCount: 10, maxKeepAliveCount: 2,
            publishEngine: publish_server
        });
        subscription1.publishingInterval.should.eql(1000);
        subscription1.lifeTimeCount.should.eql(10);
        subscription1.maxKeepAliveCount.should.eql(2);

        publish_server.add_subscription(subscription1);

        var subscription2 = new Subscription({
            id: 2,
            publishingInterval: 100, lifeTimeCount: 20, maxKeepAliveCount: 2,
            publishEngine: publish_server
        });
        subscription2.publishingInterval.should.eql(100);
        subscription2.lifeTimeCount.should.eql(20);
        subscription2.maxKeepAliveCount.should.eql(2);
        publish_server.add_subscription(subscription2);

        var subscription3 = new Subscription({
            id: 3,
            publishingInterval: 50, lifeTimeCount: 1000, maxKeepAliveCount: 2,
            publishEngine: publish_server
        });
        subscription3.publishingInterval.should.eql(100); // !! Note that publishingInterval has been clamped in constructor
        subscription3.lifeTimeCount.should.eql(1000);
        subscription3.maxKeepAliveCount.should.eql(2);

        publish_server.add_subscription(subscription3);

        subscription1.lifeTimeCount.should.eql(10);
        subscription2.lifeTimeCount.should.eql(20);
        subscription3.lifeTimeCount.should.eql(1000);


        subscription1.timeToExpiration.should.eql(10000);
        subscription2.timeToExpiration.should.eql(2000);
        subscription3.timeToExpiration.should.eql(100000);

        // let move in time so that subscriptions starts
        this.clock.tick(10);

        subscription1.state.should.eql(SubscriptionState.NORMAL);
        subscription2.state.should.eql(SubscriptionState.NORMAL);
        subscription3.state.should.eql(SubscriptionState.NORMAL);

        publish_server.findLateSubscriptionsSortedByAge().should.eql([]);


        // add some notification we want to process
        subscription1.addNotificationMessage(fakeNotificationData);
        subscription2.addNotificationMessage(fakeNotificationData);
        subscription3.addNotificationMessage(fakeNotificationData);


        // let move in time so that all subscriptions get late (without expiring)
        this.clock.tick(1100);
        subscription1.state.should.eql(SubscriptionState.LATE);
        subscription2.state.should.eql(SubscriptionState.LATE);
        subscription3.state.should.eql(SubscriptionState.LATE);


        publish_server.findLateSubscriptionsSortedByAge().map(_.property("id")).should.eql([2, 1, 3]);

        this.clock.tick(1100);
        subscription1.state.should.eql(SubscriptionState.LATE);
        subscription2.state.should.eql(SubscriptionState.CLOSED);
        subscription3.state.should.eql(SubscriptionState.LATE);

        publish_server.findLateSubscriptionsSortedByAge().map(_.property("id")).should.eql([1, 3]);

        subscription1.terminate();

        subscription2.terminate();

        subscription3.terminate();

        publish_server.shutdown();
    });