Пример #1
0
/**
 * Upgrade a dependencies collection based on latest available versions
 * @param currentDependencies current dependencies collection object
 * @param latestVersions latest available versions collection object
 * @returns {{}} upgraded dependency collection object
 */
function upgradeDependencies(currentDependencies, latestVersions) {

    // filter out dependencies with empty values
    currentDependencies = cint.filterObject(currentDependencies, function (key, value) {
        return value;
    });

    // get the preferred wildcard and bind it to upgradeDependencyDeclaration
    var wildcard = getPreferredWildcard(currentDependencies) || DEFAULT_WILDCARD;
    var upgradeDep = _.partialRight(upgradeDependencyDeclaration, {
        wildcard: wildcard
    });

    return _(currentDependencies)
        // only include packages for which a latest version was fetched
        .pickBy(function (current, packageName) {
            return packageName in latestVersions;
        })
        // combine the current and latest dependency objects into a single object keyed by packageName and containing
        // both versions in an array: [current, latest]
        .mapValues(function (current, packageName) {
            var latest = latestVersions[packageName];
            return [current, latest];
        })
        // pick the packages that are upgradeable
        // we can use spread because isUpgradeable and upgradeDependencyDeclaration both take current and latest as
        // arguments
        .pickBy(_.spread(isUpgradeable))
        .mapValues(_.spread(upgradeDep))
        .value();
}
Пример #2
0
const test_logged_in = function (t) {
  _get_secret().then(_.spread(function (resp, body) {
    t.equal(resp.statusCode, 200, "gives 200 status code");
    t.equal(body.some_secret, "sssh!", "secret in response body");
    t.end();
  })).catch(t.end);
};
Пример #3
0
describe('hasDescription(matcherOrValue)', function () {
	_.forEach([
		[__.hasSize(3), __.containsString('WILL NEVER MATCH'), false],
		[__.hasSize(3), __.containsString('size <3>'), true],
		[__.hasSize(3), 'a collection or string with size <3>', true]
	], _.spread(function (actualMatcher, expectedDescription, matchResult) {
		it('should only match if the description of the actual matcher is as expected: ' + [__.describe(actualMatcher), __.describe(expectedDescription), matchResult].join(' / '), function () {
			var sut = __.hasDescription(expectedDescription);

			__.assertThat(sut.matches(actualMatcher), __.is(matchResult));
		});
	}));

	describe('description', function () {
		var description;
		beforeEach(function () {
			description = new __.Description();
		});

		it('should contain given description matcher\'s description', function () {
			var sut = __.hasDescription(__.containsString('X'));

			sut.describeTo(description);

			__.assertThat(description.get(), __.equalTo('a matcher with description: a string containing \"X\"'));
		});

		it('should contain description of the given matcher if the description differs', function () {
			var sut = __.hasDescription(__.containsString('WILL NEVER MATCH'));

			__.assertThat(sut, __.failsToMatch(__.hasSize(3), 'matcher description was "a collection or string with size <3>"'));
		});
	});
});
Пример #4
0
// Compare two interactions, returns 0 if they are equal
function compare(a, b) {
  if (a.type !== 'InteractionSimple' || b.type !== 'InteractionSimple') {
    if(a.type==="InteractionNative" && b.type === "InteractionNative") {
      return ((_.isEqual(a.code,b.code))?(0):(1));
    }
    return -1;
  }
  if (a.operator > b.operator) {
    return 1;
  } else {
    if (a.operator < b.operator) {
      return -1;
    } else {
      if ((a.operand.length - b.operand.length) !== 0) {
        return (a.operand.length - b.operand.length);
      } else {
        var x = _.zip(a.operand, b.operand);
        var f = _.spread(compare);
        for (var i = 0; i < x.length; i++) {
          var res = f(x[i]);
          if (res !== 0) return res;
        }
        return 0;
      }
    }
  }
}
module.exports = function getZipWithConfigAsBuffer(properties) {
  if (typeof properties.Code !== 'object') {
    return bluebird.reject('Mandatory Code resource property is missing');
  }

  var s3Region = properties.Code.S3Region;
  var s3Bucket = properties.Code.S3Bucket;
  var s3Key = properties.Code.S3Key;

  var hashIndex = s3Key.indexOf('#');
  var afterDownload = _.identity;
  if (hashIndex >= 0) {
    var tarFilePath = s3Key.substring(hashIndex + 1);
    afterDownload = function (tarFile) {
      return extractFileFromTarball(tarFile, tarFilePath);
    };
    s3Key = s3Key.substring(0, hashIndex);
  }

  logDownload(s3Region, s3Bucket, s3Key);
  return bluebird.all([
      download(s3Region, s3Bucket, s3Key).then(afterDownload),
      createConfigFile(properties.Config)
    ])
    .then(_.spread(insertFileInZip))
    .then(fs.readFileAsync);
};
Пример #6
0
	describe('appendDescriptionOf(matcherOrValue)', function () {
		it('should append matcher description', function () {
			var matcher = _.create(new Matcher(), {
				describeTo: function (description) {
					description.append('a matcher description');
				}
			});

			sut.appendDescriptionOf(matcher);

			assertEquals(sut.get(), 'a matcher description');
		});

		_.forEach([
			[5, '<5>'],
			['XX', '"XX"']
		], _.spread(function (value, expectedDescription) {
			it('should append value of simple types:' + value, function () {

				sut.appendDescriptionOf(value);

				assertEquals(sut.get(), expectedDescription);
			});
		}));
	});
Пример #7
0
 _.forOwn(methods, function (routeFn, method) {
     if(_.isArray(routeFn)){
         _.spread(route[method])(route)
         route[method].apply(route, [routeFn]);
     }
     route[method].apply(route, [routeFn]);
 });
Пример #8
0
const test_logged_out = function (t) {
  _get_secret().then(_.spread(function (resp, body) {
    t.equal(resp.statusCode, 401, "gives 401 status code");
    t.notOk(body.secret, "secret not in response body");
    t.end();
  })).catch(t.end);
};
Пример #9
0
  const analyseSegments = (fix) => {
    let result = [];
    const traversed = traverseSegments(fix);
    if (!_.isEmpty(traversed)) {
      let nodes;
      if (latestPassedNode) {
        nodes = [latestPassedNode].concat(traversed);
      } else {
        nodes = traversed;
      }

      const segments = _(nodes)
        .initial()
        .zip(_.rest(nodes))
        .value();
      const analyses = _.map(segments, _.spread(analyse));
      result = _(segments)
        .zip(analyses)
        .map(([[start, end], oneAnalysis]) => {
          let segment = {
            start,
            end
          };
          segment[analysisName] = oneAnalysis;
          return segment;
        })
        .value();
      latestPassedNode = _.last(traversed);
    }
    return result;
  };
Пример #10
0
  (value, key) => chai.Assertion.addMethod(key, function() {
      var args = Array.from(arguments);

      // jscs:disable disallowDanglingUnderscores
      args.unshift(this._obj);// eslint-disable-line no-underscore-dangle
      // jscs:enable disallowDanglingUnderscores
      return _.spread(value)(args);
    })
Пример #11
0
 .spread((metrics, logo) => {
   var badges = [
     ['APIs in collection' , metrics.numAPIs, 'orange'],
     ['Endpoints', metrics.numEndpoints, 'red'],
     ['OpenAPI specs', metrics.numSpecs, 'yellow'],
     ['Tested on', metrics.numSpecs + ' specs', 'green', logo]
   ];
   return Promise.mapSeries(badges, _.spread(saveShield));
 }
Пример #12
0
function queryYouTube (url, data) {
  return Promise.all([getBaseUrl(), authStore.getApiKey()])
    .then(_.spread((baseUrl, apiKey) => {
      return req({
        url: `${baseUrl}${url}`,
        data: _.extend({ key: apiKey }, data),
      })
    }))
}
Пример #13
0
    var bindEvents = function (events, handler, binder) {
        var changeEvents = _.reduce(events, function (result, event) {
            result.push(event);
            result.push(handler);
            return result;
        }, []);

        _.spread(binder)(changeEvents);
    };
Пример #14
0
  _.each(swagger.paths, function (path) {
    var intersection = _.spread(_.partialRight(_.intersectionWith, _.isEqual));
    var pathArgs = _(path).pick(SwaggerMethods).map('parameters').value();
    pathArgs = intersection(pathArgs);

    if (_.isNull(globalArgs)) {
      globalArgs = pathArgs;
      return;
    }
    globalArgs = intersection([globalArgs, pathArgs]);
  });
Пример #15
0
var option = function(name, argumentRequired) {
    return base.cons(
        text.string(name)
      , ((argumentRequired)
          ? parse.choice(
                parse.attempt(parse.next(text.string('='), argument.name))
              , parse.attempt(parse.next(text.string(' '), argument.name)))
          : parse.of(null))).map(_.spread(function(__, value) {
                return value;
            }));
};
Пример #16
0
 , _.spread(function(desc, defs) {
       return (desc !== undefined
           || defs  !== undefined
       )
         ? self.chain(_.spread(function(desc1, defs1) {
               return parse.of([
                   desc + desc1
                 , defs.concat(defs1)
               ]);
           }))
         : parse.of(['', []]);
   })
 var streams = _.map(analysisStreams, function(analysisStream) {
   var streamObjects = _.map(analysisStream.data, function() { return new stream.PassThrough({ objectMode: true }); });
   var mockAnalysisStream = jasmine.createSpy('analysisStream');
   var stubAnalysis = _.spread(mockAnalysisStream.and.returnValues).bind(mockAnalysisStream.and);
   return _.extend({}, analysisStream, {
     streamObjects: streamObjects,
     mockAnalyser: {
       isSupported: function() { return _.includes(supportedAnalyses, analysisStream.codeMaatInstruction); },
       fileAnalysisStream: stubAnalysis(streamObjects)
     }
   });
 });
Пример #18
0
  init: function () {
    this.campaigns = []
    this.dashboards = []
    this.custom_dashboards = []
    this.custom_charts = []
    this.loaded = false

    Promise.all([
      CampaignStore.getCampaignsPromise(),
      api.get_dashboard(),
      Office.getOffices()
    ]).then(_.spread(this._loadDashboards))
  },
Пример #19
0
 .spread((account, created) => {
     logger('sso').debug('found or created account %s in directory %s from SAML response', account.id, req.swagger.params.id.value);
     const providerData = _.defaults({providerId: 'saml'}, _.mapValues(samlResponse.user.attributes, _.head));
     const application = hrefHelper.resolveHref(req.authInfo.app_href);
     return BluebirdPromise.join(
         account.update(
             //'_.fromPairs' doesn't support property paths (customData.xxx), so we use zipObjectDeep(zip) instead
             _.spread(_.zipObjectDeep)(_.spread(_.zip)(
                 _(mappingRules.items)
                 //get account attribute lists and their new value
                     .map(_.over(_.property('accountAttributes'), _.flow(_.property('name'), _.propertyOf(providerData))))
                     //make pairs of account attribute/value (obviously)
                     .flatMap(_.spread(_.overArgs(_.map, [_.identity, _.flow(_.constant, _.partial(_.over, _.identity))])))
                     //add provider data
                     .tap(_.method('push', ['providerData', providerData]))
                     .value()
             ))
         )
             .then(account => accountHelper.getLinkedAccount(account, application.id)),
         created,
         application.getLookupAccountStore(req.authInfo.onk)
     );
 });
Пример #20
0
 .map(_.spread(function(usage, rest) {
     console.log(rest);
     try {
     return { usage: usage, tests: parse.run(
         parse.eager(parse.many1(
             parse.either(
                 parse.attempt(parse.next(
                     parse.many(text.space)
                   , base.cons(
                         base.join(base.cons(
                             text.string('$ prog')
                           , parse.eager(parse.many(text.match(/ /)))
                           , parse.optional('', parse.attempt(
                                 base.join(parse.eager(parse.many(
                                     text.noneOf('\n'))))))
                         ))
                       , parse.either(
                             parse.attempt(parse.next(
                                 parse.many(text.space)
                               , text.string('"user-error"')))
                           , parse.next(
                                 parse.many(text.space)
                               , lang.between(
                                     text.string('{')
                                   , text.string('}')
                                   , base.join(
                                         parse.eager(parse.many(
                                             text.noneOf('}')))))
                                 .map(function(x) {
                                     return JSON.parse(
                                         '{' + x + '}'
                                     );
                                 })
                             )
                         )
                     )
                 )).map(_.spread(function(input, output) {
                     return { input: input, output: output };
                 }))
               , parse.eof)
         ))
       , rest
     ) };
     } catch(e) {
         console.log('>', rest.replace(/\n/g, ' '));
         console.log('>', _.repeat(' ', 12) + _.repeat('^', 3));
         console.log(e.toString());
         throw e;
     }
 }))
Пример #21
0
  onInitData: function () {
    let self = this

    // self.data.entryFormDefinitions = self.entryFormDefinitions
    // self.data.formIdSelected = self.entryFormDefinitions[0]

    Promise.all([
      api.campaign(null, null, {'cache-control': 'no-cache'}),
      api.locations(),
      api.indicators({ read_write: 'w' }, null, {'cache-control': 'no-cache'})])
    .then(_.spread(function (campaigns, locations, indicators) {
        // campains
      let campaignResult = _(campaigns.objects)
          .map(campaign => {
            return {
              'id': campaign.id,
              'name': campaign.name
            }
          }).value()

      self.data.campaigns = campaignResult
      self.data.campaignIdSelected = campaignResult[0].id

      // locations
      let locationResult = _(locations.objects)
          .map(location => {
            return {
              'title': location.name,
              'value': location.id,
              'parent': location.parent_location_id
            }
          })
          .sortBy('title')
          .reverse()
          .thru(_.curryRight(treeify)('value'))
          .map(ancestryString)
          .value()

      self.locationList = locationResult
      self.data.filterLocations = locationResult
      self.data.locationMap = _.indexBy(locations.objects, 'id')

        // Indicators
      self.data.indicatorMap = _.indexBy(indicators.objects, 'id')
        // self._filterLocationsByCampaign()
      self.trigger(self.data)
    })
    )
  },
Пример #22
0
            new Promise((resolve, reject) => {
                const structured = _.zip(entry.args, passed).map(_.spread((arg, pass) =>
                    ({ [arg.name]: arg.serialize(pass) })
                ));

                const args = _.merge.apply(null, structured);

                axios.post(`http://${client.host}:${client.port}/${entry.location.replace(/\./g, '/')}`, args)
                    .then(res => {
                        resolve(res.data.result.data);
                    })
                    .catch(res => {
                        reject(res.data.error);
                    });
            })
Пример #23
0
function battlegroundData() {

  if (battlegroundDataCache.expiry > Date.now()) {
    return Promise.resolve(battlegroundDataCache.response);
  }

  var promises = battlegroundSpreadsheets.map(request.bind(request));
  return Promise.all(promises)
                .then(_.spread(slopeDataParse))
                .then(function(response) {
                  battlegroundDataCache.response = response;
                  battlegroundDataCache.expiry = Date.now() + 5000;
                  return response;
                });
}
Пример #24
0
const setup = function (t) {
  tmp_file_sqlite = tmp.fileSync();
  Promise.resolve().then(function () {
    return app.run_server(
      APP_PORT, dir_client_build, tmp_file_sqlite.name);
  }).then(function (run_server_ret) {
    return _.at(run_server_ret, ['server', 'close_db']);
  }).then(_.spread(function (new_server, close_db) {
    t.ok(new_server, "got server instance");
    t.equal(typeof close_db, 'function', "got close database callback");
    cb_close_db = close_db;
    app_server = new_server;
    return wd_client.init();
  })).then(function () {
    t.end();
  }).catch(t.end);
};
Пример #25
0
function forecastData(item) {

  var source = {
    name:'electionforecast.co.uk',
    link:'http://www.electionforecast.co.uk'
  };

  return Promise.all([
    request({uri: forecast[item], transform: tsv, maxAge: shortMaxAge}),
    request({uri: forecast.updated, json: true, maxAge: shortMaxAge})
  ])
  .then(_.spread(function(data, updated) {
    return {
      data: data,
      updated: new Date(updated.updated),
      source: source
    };
  }));
}
Пример #26
0
export default function solid_from_slices(solids){

        let polygons = collect_polygons(solids)

        let builder = new Builder()
        let detector = new Detector(polygons)

        //
        // Build walls between every consecutive pair of 2D polygons
        //

        // create a list of pairs of polygons
        let pairs = _.zip(_.initial(polygons), _.rest(polygons))

        // for each pair, build wallls between
        _.forEach(pairs, _.spread( (poly1, poly2) => {
                builder.addWallsBetween(poly1, poly2)
        }))

        //
        // Build the last section depending on whether it is a torus
        //

        let startPolygon = _.first(polygons)
        let endPolygon = _.last(polygons)
        if (detector.isTorus()){

            builder.addWallsBetween(endPolygon, startPolygon)

        } else {

            builder.addPolygon(startPolygon)
            builder.addPolygonFlipped(endPolygon)
        }

        if (detector.isInverted()){
            builder.flip()
        }

        let csg = new CSG.fromPolygons(builder.build())
        return csg
}
Пример #27
0
var leadingFlags = parse.getParserState.chain(function(state) {
    return parse.choice(
        parse.attempt(base.cons(
            option.short
          , parse.next(
                parse.either(
                  text.string(', ')
                , text.string(' '))
              , option.long)
        ))
        .chain(_.spread(function(short, long) {
            return (
            (short.arg && long.arg && short.arg !== long.arg)
              ? parse.fail(util.mstr('\
                    Short and long arguments differ.    \n\
                    Please either use the same argument \n\
                    for both or only specify on one.    \
                '))
              : parse.of({
                    short: _.assign(short, { arg: short.arg || long.arg })
                  , long: _.assign(long,  { arg: short.arg || long.arg })
                  , arg: short.arg || long.arg
                }));
        }))
      , parse.attempt(option.short)
            .map(function(short) {
                return { short: short };
            })
      , parse.attempt(option.long)
            .map(function(long) {
                return { long: long };
            })
    )
    .chain(function(flags) {
        return parse.modifyState(function(userState) {
            return _.assign(userState || {}, {
                flagStart: state.position.index
            });
        }).chain(_.constant(parse.of(flags)));
    });
});
Пример #28
0
function* caller() {
	for(;;) {

        // get next request, when available
		var requests = yield csp.take(chQuip);
		if (requests === csp.CLOSED) break;

        if (failing) {
            yield csp.timeout(20000);
            failing = false;
		}

        // convert [fn, arg, arg, arg ...] and execute
		var fn = requests[0];
		var args = requests.slice(1);
		_.spread(fn)(args);
		yield csp.timeout(3000);
	}

	console.log('Calls Processed');
}
Пример #29
0
StackTraceMapper.prototype.loadMaps = function (mapUrls) {
  mapUrls = _.clone(mapUrls || {});

  let maps = this.maps;

  $('script[src][src-map]').each(function () {
    let $el = $(this);
    mapUrls[$el.attr('src')] = $el.attr('src-map');
  });

  return resolve(_.pairs(mapUrls))
  .map(
    _.spread(function (url, mapUrl) {
      return fetch(mapUrl)
      .then(function (resp) { return resp.json(); })
      .then(function (map) {
        maps.push(new SourceMapReader(url, map));
      });
    })
  );
};
Пример #30
0
)).chain(_.spread(function(state, userState) {
    return (userState
        && userState.flagStart
        && userState.flagStart != state.position.index)
      ? base.fail(
            'Flag start not aligned! '
          + 'Expected leading white space of `'
          + (userState.flagStart)
          + '` spaces'
        )
      : base.cons(
            leadingFlags
          , description
        ).map(_.spread(function(flags, optText) {
            return {
                flags: flags
              , defaults: optText.defaults
              , description: optText.description
              , initialOffet: state.position.index
            };
        }))
    ;
}));