this.api.get('*', (req, res) => { const pathKeys = splitRoute(req.path) const pathKeysButLast = initial(pathKeys) const pathKeysButTwoLast = initial(pathKeysButLast) // TODO: with the current ordering, we allow "actions" and "info" to be keys in state; should we? if (hasIn(this.state, pathKeys)) { const item = get(this.state, pathKeys) return res.send(get(this.state, pathKeys)) } else if (last(pathKeys) === 'info' && hasIn(this.state, pathKeysButLast)) { const item = get(this.state, pathKeysButLast) return res.send(normalInfo(item)) } else if (last(pathKeys) === 'info' && penultimate(pathKeys) === 'actions' && hasIn(this.state, pathKeysButTwoLast)) { const item = get(this.state, pathKeysButTwoLast) return res.send(actionInfo(item, req.feanorActions)) } else { return res.status(404).send("We cannot find your item.") } })
export const getSingleFetcher = (state, fetcher) => { if(!_.hasIn(getConfigFetchers(), fetcher)) { throw new Error(`${fetcher} is not a known fetcher !`); } return _.get(getFetchers(state), fetcher); };
isConflictExtend: function(objSource, objInject) { var keys = _.keys(objInject); var i = 0; for (; i < keys.length; i++) { if (_.hasIn(objSource, keys[i])) { return keys[i]; } } return false; },
export const getRequestHeaders = function(method, serviceDesc) { const capsMethod = method.toUpperCase() if ( _.hasIn(serviceDesc.methods, [capsMethod, 'request', 'headers']) && _.isArray(serviceDesc.methods[capsMethod].request.headers) ) { return mkHeadersMap(serviceDesc.methods[capsMethod].request.headers) } return [] }
const findResponseDesc = function(method, serviceDesc, nameOfResponse) { const capsMethod = method.toUpperCase() if ( _.hasIn(serviceDesc.methods, [capsMethod, 'responses']) && _.isArray(serviceDesc.methods[capsMethod].responses) ) { const respIdx = _.findIndex(serviceDesc.methods[capsMethod].responses, function(response) { return response.name === nameOfResponse }) if (respIdx >= 0) { return serviceDesc.methods[capsMethod].responses[respIdx] } } return null }
const instance = Promise.join(wire({$ref: ref}), args).spread(function(referencedModule, resolvedArgs) { if (!_.hasIn(referencedModule, path)) { return Promise.reject(`Sub module not found: ${referencedModule} ... ${path}`); } const subModule = _.get(referencedModule, path); if (options.factory === 'function') { if (!_.isFunction(subModule)) { return Promise.reject(`Sub module is not a function (factory expected): ${referencedModule} ... ${path}`); } return subModule(...resolvedArgs); } else if (options.factory === 'factoryOf') { return Utils.applyAwares(wire, new subModule(...resolvedArgs), Promise, logger); } else if (options.factory === 'factoryOfFactory') { return () => Utils.applyAwares(wire, new subModule(...resolvedArgs), Promise, logger); } else { return subModule; } });
Selector.prototype.compile = function (selector) { if (_.isNil(selector)) { this.logger.debug("selector -> null"); selector = {}; } else { this.logger.debug("selector -> not null"); if (!selector || (_.hasIn(selector, "_id") && !selector._id)) { this.logger.debug("selector -> false value || { _id: false value }"); selector = { _id: false }; } } if (_.isFunction(selector)) { this.logger.debug("selector -> function(doc) { ... }"); //_initFunction.call(matcher, selector); this.clauses = [{ kind: "function", value: selector }]; this.logger.debug("clauses created: " + JSON.stringify(this.clauses)); } else if (_.isString(selector) || _.isNumber(selector)) { this.logger.debug("selector -> \"123456789\" || 123456798"); selector = { _id: selector }; //_initObject.call(matcher, selector); this.clauses = this.__buildSelector(selector); this.logger.debug("clauses created: " + JSON.stringify(this.clauses)); } else { this.logger.debug("selector -> { field: value }"); //_initObject.call(matcher, selector); this.clauses = this.__buildSelector(selector); this.logger.debug("clauses created: " + JSON.stringify(this.clauses)); } var matcher = new SelectorMatcher_1.SelectorMatcher(this); return matcher; };
(function(param) { if (_.hasIn(_controller.class.ioc, param)) { param_builder.push(function(req, res) { return _controller.class.ioc[param]; }) } else if (param && param[0] === "$") { param_builder.push(function(req, res) { param = param.substring(1); if (req.body && req.body[param]) { return req.body[param]; } else { return null; } }); } else { url = `${url}:${param}/`; param_builder.push(function(req, res) { return req.params[param]; }); } })(param);
isFunctor: function (obj) { return _.hasIn(obj, [ 'map' ]); },
Selector.prototype.compileFields = function (spec, aggregation) { var projection = {}; if (_.isNil(spec)) return projection; if (_.isString(spec)) { // trim surrounding and inner spaces spec = spec.replace(/( )+/ig, " ").trim(); // Replace the commas by spaces if (spec.indexOf(",") !== -1) { // Replace commas by spaces, and treat it as a spaced-separated string return this.compileFields(spec.replace(/,/ig, " "), aggregation); } else if (spec.indexOf(" ") !== -1) { var fields = spec.split(" "); for (var i = 0; i < fields.length; i++) { // Get the field from the spec (we will be working with pairs) var field = fields[i].trim(); // If the first is not a field, throw error if ((field === "-1" || field === "1") || (field === "false" || field === "true")) { this.logger.throw("Bad fields specification: %s", JSON.stringify(spec)); } else { // Get the next item of the pair var next = _.toString(fields[i + 1]); if (next === "-1" || next === "1") { if (next === "-1") { for (var _key in projection) { if (field !== "_id" && projection[_key] === 1) { this.logger.throw("A projection cannot contain both include and exclude specifications"); } } projection[field] = -1; } else { projection[field] = 1; } i++; } else if (next === "false" || next === "true") { if (next === "false") { if (field === "_id") { projection[field] = -1; } else { this.logger.throw("A projection cannot contain both include and exclude specifications"); } } else { projection[field] = 1; } i++; } else if (aggregation && next.indexOf("$") === 0) { projection[field] = next.replace("$", ""); i++; } else { projection[field] = 1; } } } } else if (spec.length > 0) { //.find({}, "field1") projection[spec] = 1; } } else if (_.isArray(spec)) { // Join the array with spaces, and treat it as a spaced-separated string return this.compileFields(spec.join(" "), aggregation); } else if (_.isPlainObject(spec)) { // TODO Nested path -> .find({}, { "field1.field12": "asc" }) var _spec = []; for (var key in spec) { if (_.hasIn(spec, key)) { _spec.push(key); _spec.push(spec[key]); } } return this.compileFields(_spec, aggregation); } else { this.logger.throw("Bad fields specification: %s", JSON.stringify(spec)); } return projection; };
TulingWXBot.prototype.handleMsgAll = function(msg, cb) { var self = this; var promise = Q(); debug('Handler msg All. msg=%o', msg); if (msg.msgTypeId === 1 && msg.content.type === 0) { // reply to self } else if (msg.msgTypeId === 4 && msg.content.type === 0) { promise = promise.then(function() { return Q.nfcall(self.tulingAutoReply.bind(self), msg.user.id, msg.content.data); }) .then(function(tmsg) { tmsg = '[机器人值班中]' + tmsg; return Q.nfcall(self.sendMsgByUid.bind(self), tmsg, msg.user.id); }); } else if (msg.msgTypeId === 3 && msg.content.type === 0) { // group text message var myName; if (_.hasIn(msg, 'content.detail')) { myName = self.getGroupMemberName(self.myAccount.UserName, msg.user.id); } debug('myName=%o', myName); if (!myName) myName = {}; if (self.myAccount.NickName) myName.nickName2 = self.myAccount.NickName; if (self.myAccount.RemarkName) myName.remarkName2 = self.myAccount.RemarkName; var isAtMe = false; for(var i = 0; i < msg.content.detail.length; i++) { var detail = msg.content.detail[i]; debug('detail[%s]=%o', i, detail); if (detail.type === 'at') { for (var k in myName) { if (myName[k] === detail.value) { isAtMe = true; break; } } } } if (isAtMe) { var srcName = msg.content.user.name; debug('srcName=%s', srcName); var reply = 'to ' + srcName + ': '; if (msg.content.type === 0) { promise = promise.then(function () { return Q.nfcall(self.tulingAutoReply.bind(self), msg.content.user.id, msg.content.desc); }) .then(function (tmsg) { reply += tmsg; }) } else { reply += '对不起,只认字,其他杂七杂八的我都不认识0.0'; } promise = promise.then(function() { debug('reply=%s', reply); return Q.nfcall(self.sendMsgByUid.bind(self), reply, msg.user.id); }) } } promise.then(function() { cb(); }) .catch(cb); }
function($scope, $stateParams, executionDetailsSectionService) { $scope.configSections = ['deploymentConfig', 'taskStatus', 'artifactStatus']; function areJarDiffsEmpty() { let result = true; const jarDiffs = $scope.stage.context.jarDiffs; if (!_.isEmpty(jarDiffs)) { result = !Object.keys(jarDiffs).some(key => Array.isArray(jarDiffs[key]) && jarDiffs[key].length); } return result; } function evaluateSections() { $scope.configSections = ['deploymentConfig', 'taskStatus', 'artifactStatus']; if ($scope.stage.context) { if ( ($scope.stage.context.commits && $scope.stage.context.commits.length > 0) || !areJarDiffsEmpty($scope.stage.context.jarDiffs) ) { $scope.configSections.push('changes'); } } } evaluateSections(); let initialized = () => { evaluateSections(); $scope.detailsSection = $stateParams.details; var context = $scope.stage.context || {}, results = []; function addDeployedArtifacts(key) { var deployedArtifacts = _.find(resultObjects, key); if (deployedArtifacts) { _.forEach(deployedArtifacts[key], function(serverGroupName, region) { var result = { type: 'serverGroups', application: context.application, serverGroup: serverGroupName, account: context.account, region: region, provider: context.providerType || context.cloudProvider || 'aws', cloudProvider: context.providerType || context.cloudProvider || 'aws', project: $stateParams.project, }; result.href = UrlBuilder.buildFromMetadata(result); results.push(result); }); } } if (context && context['kato.tasks'] && context['kato.tasks'].length) { var resultObjects = context['kato.tasks'][0].resultObjects; if (resultObjects && resultObjects.length) { results = []; addDeployedArtifacts('serverGroupNameByRegion'); } } $scope.deployed = results; configureWaitingMessages(results); $scope.provider = context.cloudProvider || context.providerType || 'aws'; $scope.changeConfig = { buildInfo: context.buildInfo || {}, commits: $scope.stage.context.commits, jarDiffs: $scope.stage.context.jarDiffs, }; $scope.customStuckDeployGuide = HelpContentsRegistry.getHelpField('execution.stuckDeploy.guide'); if (_.has(context, 'source.region') && context['deploy.server.groups']) { const serverGroupName = context['deploy.server.groups'][context.source.region][0]; ServerGroupReader.getServerGroup(context.application, context.account, context.source.region, serverGroupName) .then(serverGroup => { if (_.has(serverGroup, 'buildInfo.jenkins')) { $scope.changeConfig.buildInfo.jenkins = serverGroup.buildInfo.jenkins; } }) .catch(() => {}); } }; function configureWaitingMessages(deployedArtifacts) { $scope.showWaitingMessage = false; $scope.waitingForUpInstances = false; $scope.showScalingActivitiesLink = false; $scope.showPlatformHealthOverrideMessage = false; if (!deployedArtifacts.length) { return; } const deployed = deployedArtifacts[0]; const stage = $scope.stage; const activeWaitTask = (stage.tasks || []).find( t => ['RUNNING', 'TERMINAL'].includes(t.status) && t.name === 'waitForUpInstances', ); if (activeWaitTask && stage.context.lastCapacityCheck) { $scope.showWaitingMessage = true; $scope.waitingForUpInstances = activeWaitTask.status === 'RUNNING'; const lastCapacity = stage.context.lastCapacityCheck; const waitDurationExceeded = activeWaitTask.runningTimeInMs > Duration.fromObject({ minutes: 5 }).as('milliseconds'); lastCapacity.total = lastCapacity.up + lastCapacity.down + lastCapacity.outOfService + lastCapacity.unknown + lastCapacity.succeeded + lastCapacity.failed; if (CloudProviderRegistry.getValue(stage.context.cloudProvider, 'serverGroup.scalingActivitiesEnabled')) { // after three minutes, if desired capacity is less than total number of instances, // show the scaling activities link if (waitDurationExceeded && lastCapacity.total < stage.context.capacity.desired) { $scope.showScalingActivitiesLink = true; $scope.scalingActivitiesTarget = { name: deployed.serverGroup, app: deployed.application, account: deployed.account, region: deployed.region, cluster: NameUtils.getClusterNameFromServerGroupName(deployed.serverGroup), cloudProvider: deployed.cloudProvider, }; } } // Also show platform health warning after three minutes if instances are in an unknown state if ( waitDurationExceeded && stage.context.lastCapacityCheck.unknown > 0 && stage.context.lastCapacityCheck.unknown === stage.context.lastCapacityCheck.total && !stage.context.interestingHealthProviderNames && !_.get($scope.application.attributes, 'platformHealthOverride', false) ) { $scope.showPlatformHealthOverrideMessage = true; } } } this.overrideFiltersForUrl = r => ClusterState.filterService.overrideFiltersForUrl(r); let initialize = () => executionDetailsSectionService.synchronizeSection($scope.configSections, initialized); initialize(); $scope.$on('$stateChangeSuccess', initialize); if (_.hasIn($scope.application, 'executions.onRefresh')) { $scope.application.executions.onRefresh($scope, initialize); } },
export default (req, key, defaultValue, modifier = _.identity) => ( _.hasIn(req, ['query', key]) ? modifier(_.get(req, ['query', key])) : defaultValue );
update (userId, apiBackendDoc) { // Get API with ID const api = Apis.findOne(apiBackendDoc._id); // If a user can manage api then the user can edit that return api && api.currentUserCanManage(); }, remove (userId, apiBackendDoc) { // Get API with ID const api = Apis.findOne(apiBackendDoc._id); // If a user can manage api then the user can remove that return api && api.currentUserCanManage(); }, }); Apis.deny({ insert (fields) { // Don't allow user to set average rating or bookmark count fields if (_.hasIn(fields, 'averageRating') || _.hasIn(fields, 'bookmarkCount')) { return true; } return false; }, update (fields) { // Don't allow user to set average rating or bookmark count fields if (_.hasIn(fields, 'averageRating') || _.hasIn(fields, 'bookmarkCount')) { return true; } return false; }, });
props.forEach(function (prop) { if (!_.hasIn(config, prop)) { throw new Error(`'${prop}' is required`); } });
.map(prop => _.hasIn(obj, prop))
Selector.prototype.compileSort = function (spec) { if (_.isNil(spec)) { return function () { return 0; }; } var keys = []; var asc = []; if (_.isString(spec)) { spec = spec.replace(/( )+/ig, " ").trim(); if (spec.indexOf(",") !== -1) { // Replace commas by spaces, and treat it as a spaced-separated string return this.compileSort(spec.replace(/,/ig, " ")); } else if (spec.indexOf(" ") !== -1) { var fields = spec.split(" "); for (var i = 0; i < fields.length; i++) { var field = fields[i].trim(); if ((field === "desc" || field === "asc") || (field === "-1" || field === "1") || (field === "false" || field === "true")) { this.logger.throw("Bad sort specification: %s", JSON.stringify(spec)); } else { var next = _.toString(fields[i + 1]); if (next === "desc" || next === "asc") { keys.push(field); asc.push((next === "asc") ? true : false); i++; } else if (next === "-1" || next === "1") { keys.push(field); asc.push((next === "1") ? true : false); i++; } else if (next === "false" || next === "true") { keys.push(field); asc.push((next === "true") ? true : false); i++; } else { keys.push(field); asc.push(true); // Default sort } } } } else { //.sort("field1") keys.push(spec); asc.push(true); } } else if (_.isArray(spec)) { // Join the array with spaces, and treat it as a spaced-separated string return this.compileSort(spec.join(" ")); // for (var i = 0; i < spec.length; i++) { // if (_.isString(spec[i])) { // keys.push(spec[i]); // asc.push(true); // } else { // keys.push(spec[i][0]); // asc.push(spec[i][1] !== "desc"); // } // } } else if (_.isPlainObject(spec)) { // TODO Nested path -> .sort({ "field1.field12": "asc" }) var _spec = []; for (var key in spec) { if (_.hasIn(spec, key)) { _spec.push(key); _spec.push(spec[key]); } } return this.compileSort(_spec); } else { this.logger.throw("Bad sort specification: %s", JSON.stringify(spec)); } // return {keys: keys, asc: asc}; return function (a, b) { var x = 0; for (var i = 0; i < keys.length; i++) { if (i !== 0 && x !== 0) return x; // Non reachable? // x = Selector._f._cmp(a[JSON.stringify(keys[i])], b[JSON.stringify(keys[i])]); x = SelectorMatcher_1.SelectorMatcher.cmp(a[keys[i]], b[keys[i]]); if (!asc[i]) { x *= -1; } } return x; }; // eval() does not return a value in IE8, nor does the spec say it // should. Assign to a local to get the value, instead. // var _func; // var code = "_func = (function(c){return function(a,b){var x;"; // for (var i = 0; i < keys.length; i++) { // if (i !== 0) { // code += "if(x!==0)return x;"; // } // code += "x=" + (asc[i] ? "" : "-") + "c(a[" + JSON.stringify(keys[i]) + "],b[" + JSON.stringify(keys[i]) + "]);"; // } // code += "return x;};})"; // eval(code); // return _func(Selector._f._cmp); };
.controller('DeployExecutionDetailsCtrl', function ($scope, $stateParams, executionDetailsSectionService, urlBuilderService, clusterFilterService, cloudProviderRegistry, namingService) { $scope.configSections = ['deploymentConfig', 'taskStatus']; if ($scope.stage.context) { if ($scope.stage.context.commits && $scope.stage.context.commits.length > 0) { $scope.configSections.push('codeChanges'); } if (!_.isEmpty($scope.stage.context.jarDiffs)) { $scope.configSections.push('JARChanges'); } } let initialized = () => { $scope.detailsSection = $stateParams.details; var context = $scope.stage.context || {}, results = []; function addDeployedArtifacts(key) { var deployedArtifacts = _.find(resultObjects, key); if (deployedArtifacts) { _.forEach(deployedArtifacts[key], function (serverGroupName, region) { var result = { type: 'serverGroups', application: context.application, serverGroup: serverGroupName, account: context.account, region: region, provider: context.providerType || context.cloudProvider || 'aws', cloudProvider: context.providerType || context.cloudProvider || 'aws', project: $stateParams.project, }; result.href = urlBuilderService.buildFromMetadata(result); results.push(result); }); } } if (context && context['kato.tasks'] && context['kato.tasks'].length) { var resultObjects = context['kato.tasks'][0].resultObjects; if (resultObjects && resultObjects.length) { results = []; addDeployedArtifacts('serverGroupNameByRegion'); } } $scope.deployed = results; configureWaitingMessages(results); $scope.provider = context.cloudProvider || context.providerType || 'aws'; }; function configureWaitingMessages(deployedArtifacts) { $scope.showWaitingMessage = false; $scope.waitingForUpInstances = false; $scope.showScalingActivitiesLink = false; $scope.showPlatformHealthOverrideMessage = false; if (!deployedArtifacts.length) { return; } const deployed = deployedArtifacts[0]; const stage = $scope.stage; const activeWaitTask = (stage.tasks || []).find(t => ['RUNNING', 'TERMINAL'].includes(t.status) && t.name === 'waitForUpInstances'); if (activeWaitTask && stage.context.lastCapacityCheck) { $scope.showWaitingMessage = true; $scope.waitingForUpInstances = activeWaitTask.status === 'RUNNING'; const lastCapacity = stage.context.lastCapacityCheck; const waitDurationExceeded = activeWaitTask.runningTimeInMs > moment.duration(5, 'minutes').asMilliseconds(); lastCapacity.total = lastCapacity.up + lastCapacity.down + lastCapacity.outOfService + lastCapacity.unknown + lastCapacity.succeeded + lastCapacity.failed; if (cloudProviderRegistry.getValue(stage.context.cloudProvider, 'serverGroup.scalingActivitiesEnabled')) { // after three minutes, if desired capacity is less than total number of instances, // show the scaling activities link if (waitDurationExceeded && lastCapacity.total < stage.context.capacity.desired) { $scope.showScalingActivitiesLink = true; $scope.scalingActivitiesTarget = { name: deployed.serverGroup, app: deployed.application, account: deployed.account, region: deployed.region, cluster: namingService.getClusterNameFromServerGroupName(deployed.serverGroup), cloudProvider: deployed.cloudProvider, }; } } // Also show platform health warning after three minutes if instances are in an unknown state if (waitDurationExceeded && stage.context.lastCapacityCheck.unknown > 0 && stage.context.lastCapacityCheck.unknown === stage.context.lastCapacityCheck.total && !stage.context.interestingHealthProviderNames && !_.get($scope.application.attributes, 'platformHealthOverride', false)) { $scope.showPlatformHealthOverrideMessage = true; } } } this.overrideFiltersForUrl = r => clusterFilterService.overrideFiltersForUrl(r); let initialize = () => executionDetailsSectionService.synchronizeSection($scope.configSections, initialized); initialize(); $scope.$on('$stateChangeSuccess', initialize); if (_.hasIn($scope.application, 'executions.onRefresh')) { $scope.application.executions.onRefresh($scope, initialize); } });